diff --git "a/6239.jsonl" "b/6239.jsonl"
new file mode 100644--- /dev/null
+++ "b/6239.jsonl"
@@ -0,0 +1,2068 @@
+{"seq_id":"74210938248","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport __init__\nimport src.load_data.loader as data_loader\n\nif __name__ == \"__main__\":\n url = 'https://raw.githubusercontent.com/jvns/pandas-cookbook/master/data/weather_2012.csv'\n dest_folder = 'weather/'\n #data_loader.fetch_data(url, dest_folder)\n data_file = 'weather_2012.csv'\n local_path = data_loader.dataset_path(dest_folder, data_file)\n weather_2012_final = pd.read_csv(local_path, index_col='Date/Time', parse_dates=True)\n temperatures = weather_2012_final[[u'Temp (C)']].copy()\n print(temperatures.head())\n temperatures.loc[:,'Hour'] = weather_2012_final.index.hour\n print(temperatures.head())\n temperatures.groupby('Hour').aggregate(np.median).plot()\n plt.show()\n temperatures.groupby('Hour').aggregate(np.mean).plot()\n plt.show()\n\n\n","repo_name":"gaborchris/tutorials","sub_path":"pandas_tutorial/chap5.py","file_name":"chap5.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"20340973188","text":"#!/usr/bin/env python3\nimport time\nfrom smbus import SMBus\nimport requests\nprint(\"Starting PH Probe\")\nbus = SMBus(1)\n\ndef readChannel(params):\n global bus\n bus.write_byte(0x48, params & 0x03)\n bus.write_byte(0x48, 0)\n return bus.read_byte(0x48)\n\ndef analogOut(out):\n global bus\n bus.write_byte(0x48, 0x40)\n bus.write_byte(0x48, out & 0xFF)\n bus.write_byte(0x48, 0x00)\n\ndef readAll():\n global bus\n bus.write_byte(0x48, 0x04)\n data = []\n for _ in range(4):\n data.append(bus.read_byte(0x48))\n return data\n\nurl = \"https://beer.tanger.dev/ph\"\nheaders = {'Content-type': 'application/json'}\nwhile(True):\n print('channel 1 is:')\n print(readChannel(1))\n print('check AOUT, should be about 2.5v')\n print(analogOut(127))\n val = readChannel(1)\n val = (val / 10.0)\n try:\n response = requests.post(url, json={\"ph\": (val / 10.0), \"data\": \"Test\"}, headers=headers)\n if response.status_code == 200:\n print(f\"PH request sent with data: {val}\")\n print(\n f\"PH request NOT sent successfully with data: {val} and response code: {response.status_code}: {response.content}\"\n )\n except requests.ConnectionError:\n print(\n f\"PH request NOT sent successfully with data: {val} and response code: {response.status_code}: {response.content}\"\n )\n time.sleep(3)\n","repo_name":"Tangdongle/InFermneter","sub_path":"ph_probe.py","file_name":"ph_probe.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"1755340766","text":"# https://www.hackerrank.com/challenges/defaultdict-tutorial\n\nfrom collections import defaultdict\n\ndef readn(n):\n\tl = []\n\tfor i in range(0, n):\n\t\tl.append(input().strip())\n\treturn l\n\nn, m = map(int, list(input().split(' ')))\nA = readn(n)\nB = readn(m)\nd = defaultdict(list)\nfor i in B:\n\tif d[i] == []:\n\t\tfor j in range(0,len(A)):\n\t\t\tif i == A[j]:\n\t\t\t\td[i].append(j + 1)\n\tif d[i] == []:\n\t\td[i].append(-1)\n\tprint(' '.join(map(str, d[i])))\n\n\n\n\n\n","repo_name":"tamarit/hackerrank_phyton","sub_path":"defaultdict-tutorial/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"3608460339","text":"import datetime\nimport json\nimport os\nfrom time import sleep\nimport requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\n\n\nclass ShopDetails:\n def __init__(self, order_number, url):\n\n # initialized a dictionary to store the dara\n\n self.order_number = order_number\n self.DATA_DICT = {\"Shop Name\": [], \"ShopAddress\": [], \"Phone Number\": [], \"Shop URL\": [],\n \"Description\": []}\n\n self.URL = f\"{url}\"\n self.BaseURL = \"https://www.northpointcity.com.sg/\"\n\n def appendingDataInJSONfile(self):\n\n self.getShopDescription()\n names = self.DATA_DICT['Shop Name']\n locations = self.DATA_DICT['ShopAddress']\n urls = self.DATA_DICT['Shop URL']\n phone_numbers = self.DATA_DICT['Phone Number']\n descriptions = self.DATA_DICT['Description']\n\n data = {\n \"Shops\": []\n }\n\n for name, location, url, phone_number, description in zip(names, locations, urls, phone_numbers, descriptions):\n data['Shops'].append(\n {\n 'Shop Name': name,\n 'Shop Address': location,\n 'Shop URL': url,\n 'Phone Number': phone_number,\n 'Description': description\n\n }\n )\n order_id = self.order_number\n folder_path = 'Data'\n current_utc_datetime = datetime.datetime.utcnow()\n file_name = f\"{order_id} - {current_utc_datetime.strftime('%Y-%m-%d__%H-%M')}.json\"\n file_path = os.path.join(folder_path, file_name)\n if not os.path.exists('Data'):\n os.mkdir(folder_path)\n with open(file_path, 'w', encoding=\"utf-8\") as json_file:\n json.dump(data, json_file, indent=4, ensure_ascii=False)\n\n print(\"All Data Scrapped Successfully\")\n\n def getShopDescription(self):\n\n # in this function getting description of Shops\n shop_description_list = []\n # getting Shops URLs by calling the url extractor Description\n data = self.getShopData()\n res_urls = data[0]\n names = data[1]\n for url, name in zip(res_urls, names):\n print(f'Scrapping data of \"{name}\"')\n response = requests.get(url)\n # making soap of every url page getting from Description of Shops\n\n urlSoap = BeautifulSoup(response.text, 'html.parser')\n # print(urlSoap)\n if urlSoap is not None:\n\n # Finding Description of Restaurants\n\n description_div = urlSoap.find('div', class_=\"textbody\")\n\n if description_div is not None:\n\n description = description_div.text.replace(\"\\n\", \" \").replace(\" \", \"\").replace('\\u00a0',\n \" \").replace('\\r',\n \"\").replace(\n \"\\\"\", \"\")\n\n shop_description_list.append(description)\n else:\n shop_description_list.append(\"Not available\")\n else:\n\n shop_description_list.append(\"Not Available\")\n\n self.DATA_DICT['Description'] = shop_description_list\n\n def getShopData(self):\n\n soap = self.getShopSoap()\n\n shop_urls_list = []\n shop_name_list = []\n shop_address_list = []\n shop_number_list = []\n # Shop URLs\n if soap is not None:\n list_of_restaurants = soap.findAll('div', class_=\"storename\")\n for index, shopurl in enumerate(list_of_restaurants):\n url = shopurl.find('a')\n if url is not None:\n shop_urls_list.append(self.BaseURL + url['href'])\n # print(f\"{index} Scrapping Details FOR {self.BaseURL + url['href']}\")\n else:\n shop_urls_list.append(\"Not Available\")\n print(\"Info Not Available\")\n # Shop Names\n shop_name = shopurl.text.replace('\\n', \"\")\n if shop_name is not None:\n shop_name_list.append(shop_name)\n else:\n shop_name_list.append(\"Not Available\")\n # print(len(shop_name_list))\n # Shop Address\n list_of_shop_address = soap.findAll('div', class_=\"col findus\")\n for shopAddress in list_of_shop_address:\n if shopAddress is not None:\n shop_address_list.append(shopAddress.findNext('div', class_='info').text)\n else:\n shop_address_list.append(\"Not Available\")\n list_of_shop_number = soap.findAll('div', class_='col callus')\n for shopNumbar in list_of_shop_number:\n if shopNumbar is not None:\n shop_number_list.append(shopNumbar.findNext('div', class_=\"info\").text)\n else:\n shop_number_list.append(\"Not Available\")\n else:\n shop_address_list.append(\"Not Available\")\n shop_urls_list.append(\"Not Available\")\n shop_name_list.append(\"Not Available\")\n\n self.DATA_DICT['Shop Name'] = shop_name_list\n self.DATA_DICT['ShopAddress'] = shop_address_list\n self.DATA_DICT['Phone Number'] = shop_number_list\n self.DATA_DICT['Shop URL'] = shop_urls_list\n return shop_urls_list, shop_name_list\n\n def getShopSoap(self):\n print(\"Scrapping Process start\")\n chrome_options = Options()\n chrome_options.add_argument(\"--disable-extensions\")\n chrome_options.add_argument(\"--disable-gpu\")\n chrome_options.add_argument(\"--no-sandbox\")\n chrome_options.add_argument(\"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36\")\n chrome_options.add_argument(\"--headless\")\n driver = webdriver.Chrome(options=chrome_options)\n driver.get(self.URL)\n print(\"Loading....\")\n print(\"Loading website All data\")\n while True:\n driver.implicitly_wait(10)\n try:\n driver.find_element(By.XPATH, \"/html/body/div[2]/section/a\").click()\n except:\n break\n driver.implicitly_wait(10)\n sleep(5)\n html = driver.page_source\n soup = BeautifulSoup(html, \"html.parser\")\n driver.close()\n return soup\n","repo_name":"Mask02/Data_Graber_For_AWS_Remote_Server","sub_path":"Data_Graber(Beautiful Soap)/NORTH_POINT_CITY/NORTH_POINT_CITY.py","file_name":"NORTH_POINT_CITY.py","file_ext":"py","file_size_in_byte":6671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"17203036989","text":"import sys\nimport requests\nfrom io import BytesIO\nfrom PIL import Image\nfrom params import get_scale_params\n\n\n# python main.py Москва, ул. Ак. Королева, 12\ntoponym_to_find = \" \".join(sys.argv[1:])\n\ngeocoder_api_server = \"http://geocode-maps.yandex.ru/1.x/\"\n\ngeocoder_params = {\n \"apikey\": \"40d1649f-0493-4b70-98ba-98533de7710b\",\n \"geocode\": toponym_to_find,\n \"format\": \"json\"}\n\nresponse = requests.get(geocoder_api_server, params=geocoder_params)\n\nif not response:\n print('ERROR')\n pass\n\n# Преобразуем ответ в json-объект\njson_response = response.json()\n\n# Собираем параметры для запроса к StaticMapsAPI:\nmap_params = {\n \"ll\": ','.join([get_scale_params(json_response)['longitude'], get_scale_params(json_response)['latitude']]),\n \"spn\": get_scale_params(json_response)[\"spn\"],\n \"l\": \"map\",\n \"pt\": f\"{','.join([get_scale_params(json_response)['longitude'], get_scale_params(json_response)['latitude']])},pm2rdm1\"\n}\n\nmap_api_server = \"http://static-maps.yandex.ru/1.x/\"\nresponse = requests.get(map_api_server, params=map_params)\n\nImage.open(BytesIO(\n response.content)).show()\n","repo_name":"HotCucumber1/Full-search","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"1756642731","text":"#-*- coding:utf-8 -*-\r\n\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\nfrom __future__ import absolute_import\r\n\r\nimport os\r\nimport cv2\r\nimport numpy as np\r\nimport time\r\nfrom torch.multiprocessing import Pool\r\nfrom utils.nms_wrapper import nms\r\nfrom utils.timer import Timer\r\nfrom configs.CC import Config\r\nimport argparse\r\nfrom layers.functions import Detect, PriorBox\r\nfrom peleenet import build_net\r\nfrom data import BaseTransform, VOC_CLASSES\r\nfrom utils.core import *\r\nfrom utils.pycocotools.coco import COCO\r\n\r\n\r\nparser = argparse.ArgumentParser(description='Pelee Testing')\r\nparser.add_argument('-c', '--config', default='configs/Pelee_VOC.py')\r\nparser.add_argument('-d', '--dataset', default='VOC',\r\n help='VOC or COCO dataset')\r\nparser.add_argument('-m', '--trained_model', default=None,\r\n type=str, help='Trained state_dict file path to open')\r\nparser.add_argument('-t', '--thresh', default=0.5, type=float,\r\n help='visidutation threshold')\r\nparser.add_argument('--show', action='store_true',\r\n help='Whether to display the images')\r\nargs = parser.parse_args()\r\n\r\nprint_info(' ----------------------------------------------------------------------\\n'\r\n '| Pelee Demo Program |\\n'\r\n ' ----------------------------------------------------------------------', ['yellow', 'bold'])\r\n\r\nglobal cfg\r\ncfg = Config.fromfile(args.config)\r\nanchor_config = anchors(cfg.model)\r\nprint_info('The Anchor info: \\n{}'.format(anchor_config))\r\npriorbox = PriorBox(anchor_config)\r\nnet = build_net('test', cfg.model.input_size, cfg.model)\r\ninit_net(net, cfg, args.trained_model)\r\nprint_info('===> Finished constructing and loading model', ['yellow', 'bold'])\r\nnet.eval()\r\n\r\nnum_classes = cfg.model.num_classes\r\n\r\nimgs_path_dict = {'VOC': 'imgs/VOC', 'COCO': 'imgs/COCO'}\r\nim_path = imgs_path_dict[args.dataset]\r\n\r\nimgs_result_path = os.path.join(im_path, 'im_res')\r\nif not os.path.exists(imgs_result_path):\r\n os.makedirs(imgs_result_path)\r\n\r\nwith torch.no_grad():\r\n priors = priorbox.forward()\r\n if cfg.test_cfg.cuda:\r\n net = net.cuda()\r\n priors = priors.cuda()\r\n cudnn.benchmark = True\r\n else:\r\n net = net.cpu()\r\n_preprocess = BaseTransform(\r\n cfg.model.input_size, cfg.model.rgb_means, (2, 0, 1))\r\ndetector = Detect(num_classes,\r\n cfg.loss.bkg_label, anchor_config)\r\n\r\n\r\ndef _to_color(indx, base):\r\n \"\"\" return (b, r, g) tuple\"\"\"\r\n base2 = base * base\r\n b = 2 - indx / base2\r\n r = 2 - (indx % base2) / base\r\n g = 2 - (indx % base2) % base\r\n return b * 127, r * 127, g * 127\r\nbase = int(np.ceil(pow(num_classes, 1. / 3)))\r\ncolors = [_to_color(x, base)\r\n for x in range(num_classes)]\r\ncats = [_.strip().split(',')[-1]\r\n for _ in open('data/coco_labels.txt', 'r').readlines()]\r\nlabel_config = {'VOC': VOC_CLASSES, 'COCO': tuple(['__background__'] + cats)}\r\nlabels = label_config[args.dataset]\r\n\r\n\r\ndef draw_detection(im, bboxes, scores, cls_inds, fps, thr=0.2):\r\n imgcv = np.copy(im)\r\n h, w, _ = imgcv.shape\r\n for i, box in enumerate(bboxes):\r\n if scores[i] < thr:\r\n continue\r\n cls_indx = int(cls_inds[i])\r\n box = [int(_) for _ in box]\r\n thick = int((h + w) / 300)\r\n cv2.rectangle(imgcv,\r\n (box[0], box[1]), (box[2], box[3]),\r\n colors[cls_indx], thick)\r\n mess = '%s: %.3f' % (labels[cls_indx], scores[i])\r\n cv2.putText(imgcv, mess, (box[0], box[1] - 7),\r\n 0, 1e-3 * h, colors[cls_indx], thick // 3)\r\n if fps >= 0:\r\n cv2.putText(imgcv, '%.2f' % fps + ' fps', (w - 160, h - 15),\r\n 0, 2e-3 * h, (255, 255, 255), thick // 2)\r\n\r\n return imgcv\r\n\r\nim_fnames = sorted((fname for fname in os.listdir(im_path)\r\n if os.path.splitext(fname)[-1] == '.jpg'))\r\nim_fnames = (os.path.join(im_path, fname) for fname in im_fnames)\r\nim_iter = iter(im_fnames)\r\n\r\nfor fname in im_fnames:\r\n image = cv2.imread(fname, cv2.IMREAD_COLOR)\r\n loop_start = time.time()\r\n w, h = image.shape[1], image.shape[0]\r\n img = _preprocess(image).unsqueeze(0)\r\n if cfg.test_cfg.cuda:\r\n img = img.cuda()\r\n scale = torch.Tensor([w, h, w, h])\r\n out = net(img)\r\n boxes, scores = detector.forward(out, priors)\r\n boxes = (boxes[0] * scale).cpu().numpy()\r\n scores = scores[0].cpu().numpy()\r\n allboxes = []\r\n for j in range(1, num_classes):\r\n inds = np.where(scores[:, j] > cfg.test_cfg.score_threshold)[0]\r\n if len(inds) == 0:\r\n continue\r\n c_bboxes = boxes[inds]\r\n c_scores = scores[inds, j]\r\n c_dets = np.hstack((c_bboxes, c_scores[:, np.newaxis])).astype(\r\n np.float32, copy=False)\r\n soft_nms = cfg.test_cfg.soft_nms\r\n # min_thresh, device_id=0 if cfg.test_cfg.cuda else None)\r\n keep = nms(c_dets, cfg.test_cfg.iou, force_cpu=soft_nms)\r\n keep = keep[:cfg.test_cfg.keep_per_class]\r\n c_dets = c_dets[keep, :]\r\n allboxes.extend([_.tolist() + [j] for _ in c_dets])\r\n\r\n loop_time = time.time() - loop_start\r\n allboxes = np.array(allboxes)\r\n boxes = allboxes[:, :4]\r\n scores = allboxes[:, 4]\r\n cls_inds = allboxes[:, 5]\r\n im2show = draw_detection(image, boxes, scores, cls_inds, -1, args.thresh)\r\n if im2show.shape[0] > 1100:\r\n im2show = cv2.resize(im2show,\r\n (int(1000. * float(im2show.shape[1]) / im2show.shape[0]), 1000))\r\n if args.show:\r\n cv2.imshow('test', im2show)\r\n cv2.waitKey(2000)\r\n\r\n filename = os.path.join(imgs_result_path, '{}_stdn.jpg'.format(\r\n os.path.basename(fname).split('.')[0]))\r\n cv2.imwrite(filename, im2show)\r\n","repo_name":"Tessellate-Imaging/Monk_Object_Detection","sub_path":"15_pytorch_peleenet/lib/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":5856,"program_lang":"python","lang":"en","doc_type":"code","stars":608,"dataset":"github-code","pt":"16"}
+{"seq_id":"35220121586","text":"import os\nimport sys\n\n# dont do this in production code, this is bad practice it would seem, only for tests\nsys.path.append(os.path.abspath(os.path.dirname(__file__) + \"/../../servicemanager\"))\n\nfrom servicemanager.actions import actions\nfrom servicemanager.serviceresolver import ServiceResolver\nfrom servicemanager.smcontext import SmApplication, SmContext\n\nimport time\nimport shutil\nimport unittest\nimport subprocess\n\n\nclass TestBase(unittest.TestCase):\n\n config_dir_override = os.path.join(os.path.dirname(__file__), \"../conf\")\n default_time_out = 10\n\n def setUp(self):\n self.set_up_and_clean_workspace()\n self.setup_local_git()\n self.bintrayContext = None\n self.artifactoryContext = None\n self.nexusContext = None\n\n def tearDown(self):\n self.stopFakeBintray()\n self.stopFakeArtifactory()\n self.stopFakeNexus()\n self.tear_down_local_git()\n\n def set_up_and_clean_workspace(self):\n workspace_dir = os.path.join(os.path.dirname(__file__), \"workspace\")\n if os.path.exists(workspace_dir):\n shutil.rmtree(workspace_dir)\n os.mkdir(workspace_dir)\n os.environ[\"WORKSPACE\"] = workspace_dir\n os.chdir(workspace_dir)\n\n def setup_local_git(self):\n workspace_dir = os.path.join(os.path.dirname(__file__), \"workspace\")\n testapp_dir = os.path.join(os.path.dirname(__file__), \"../testapps/basicplayapp\")\n os.makedirs(os.path.join(workspace_dir, \"git\"))\n shutil.copytree(testapp_dir, os.path.join(workspace_dir, \"git\", \"basicplayapp\"))\n os.chdir(os.path.join(workspace_dir, \"git\", \"basicplayapp\"))\n command = \"git init && git add . && git commit -m 'test'\"\n ps_command = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, universal_newlines=True)\n ps_command.communicate()\n os.chdir(workspace_dir)\n\n def tear_down_local_git(self):\n workspace_dir = os.path.join(os.path.dirname(__file__), \"workspace\")\n git_dir = os.path.join(workspace_dir, \"git\", \"basicplayapp\")\n if os.path.exists(git_dir):\n shutil.rmtree(git_dir)\n\n def createContext(self):\n return SmContext(SmApplication(self.config_dir_override), None, False, False)\n\n def start_service_and_wait(self, context, servicetostart):\n sm_application = SmApplication(self.config_dir_override)\n service_resolver = ServiceResolver(sm_application)\n actions.start_and_wait(\n service_resolver,\n context,\n [servicetostart],\n source=False,\n fatjar=True,\n release=False,\n proxy=None,\n port=None,\n seconds_to_wait=5,\n append_args=None,\n )\n\n def startFakeBintray(self):\n self.bintrayContext = self.createContext()\n self.start_service_and_wait(self.bintrayContext, \"FAKE_BINTRAY\")\n self.assertIsNotNone(self.bintrayContext.get_service(\"FAKE_BINTRAY\").status())\n\n def startFakeArtifactory(self):\n self.artifactoryContext = self.createContext()\n self.start_service_and_wait(self.artifactoryContext, \"FAKE_ARTIFACTORY\")\n self.assertIsNotNone(self.artifactoryContext.get_service(\"FAKE_ARTIFACTORY\").status())\n\n def startFakeNexus(self):\n self.nexusContext = self.createContext()\n self.start_service_and_wait(self.nexusContext, \"FAKE_NEXUS\")\n self.assertIsNotNone(self.nexusContext.get_service(\"FAKE_NEXUS\").status())\n\n def stopFakeNexus(self):\n if self.nexusContext is not None:\n self.nexusContext.kill(\"FAKE_NEXUS\", True)\n self.assertEqual(self.nexusContext.get_service(\"FAKE_NEXUS\").status(), [])\n\n def stopFakeBintray(self):\n if self.bintrayContext is not None:\n self.bintrayContext.kill(\"FAKE_BINTRAY\", True)\n self.assertEqual(self.bintrayContext.get_service(\"FAKE_BINTRAY\").status(), [])\n\n def stopFakeArtifactory(self):\n if self.artifactoryContext is not None:\n self.artifactoryContext.kill(\"FAKE_ARTIFACTORY\", True)\n self.assertEqual(self.artifactoryContext.get_service(\"FAKE_ARTIFACTORY\").status(), [])\n\n def waitForCondition(self, f, expected, time_out_secs=default_time_out):\n dead_line = time.time() + time_out_secs\n value = None\n while time.time() < dead_line:\n value = f()\n if value == expected:\n return\n time.sleep(0.1)\n\n command = \"ps -eo ppid,pid,etime,rss,args\"\n ps_command = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, universal_newlines=True)\n stdout, _ = ps_command.communicate()\n print(stdout)\n\n self.assertEqual(value, expected)\n","repo_name":"hmrc/service-manager","sub_path":"test/it/testbase.py","file_name":"testbase.py","file_ext":"py","file_size_in_byte":4753,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"16"}
+{"seq_id":"72353348167","text":"# Create a function that will take unlimited arguments and should add all the\n# arguments which are passed.\n\ndef sum(*args):\n Sum = 0\n lst1 = []\n for arg in args:\n lst1.append(arg)\n Sum += arg\n print(\"Result: \", Sum)\n\n\nlst = list(map(int, input(\"Please enter the arguments to be taken: \").split()))\nsum(*tuple(lst))\n","repo_name":"zeciljain8197/SBS_Python_Postgres_Training_Repo","sub_path":"python_ex1/Que18.py","file_name":"Que18.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"17660939545","text":"from logging import Logger\n\nfrom botocore.exceptions import ClientError, NoCredentialsError\n\n\ndef boto_client_error(logger: Logger, message: str = \"\"):\n def decorator(func):\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except ClientError as error:\n if error.response['Error']['Code'] == 'InternalError': # Generic error\n # We grab the message, request ID, and HTTP code to give to customer support\n logger.error('Error Message: {}'.format(error.response['Error']['Message']))\n logger.error('Request ID: {}'.format(error.response['ResponseMetadata']['RequestId']))\n logger.error('Http code: {}'.format(error.response['ResponseMetadata']['HTTPStatusCode']))\n else:\n logger.error(f\"boto3 clientError raised in function {func.__name__}\" + repr(error) + message)\n raise\n except NoCredentialsError as error:\n logger.error(f\"boto3 NoCredentialsError raised in function {func.__name__}: {repr(error)}\"\n f\"Check if the IAM role has the right permission or if you need to increase IMDS retry.\")\n raise\n\n return wrapper\n return decorator\n","repo_name":"awslabs/aws-glue-libs","sub_path":"awsglue/scripts/connector_activation_util.py","file_name":"connector_activation_util.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","stars":592,"dataset":"github-code","pt":"16"}
+{"seq_id":"32805278993","text":"from aiogram.types import ReplyKeyboardRemove, \\\n ReplyKeyboardMarkup, KeyboardButton, \\\n InlineKeyboardMarkup, InlineKeyboardButton\n\nfrom models import Database\ndb = Database()\n\nmain_menu = ReplyKeyboardMarkup(resize_keyboard = True)\nmain_menu.add(\n KeyboardButton(\"🛍 Каталог\"),\n KeyboardButton(\"🛒 Корзина\")\n )\nmain_menu.add(\n KeyboardButton('👥Партнёрская программа'),\n KeyboardButton(\"💼 Личный кабинет\")\n )\nmain_menu.add(\n KeyboardButton('🏪 О магазине'),\n KeyboardButton(\"📨 Техподдержка\")\n )\nadmin_main_menu = ReplyKeyboardMarkup(resize_keyboard = True)\nadmin_main_menu.add(\n KeyboardButton(\"🛍 Каталог\"),\n KeyboardButton(\"🛒 Корзина\")\n )\nadmin_main_menu.add(\n KeyboardButton('👥Партнёрская программа'),\n KeyboardButton(\"💼 Личный кабинет\")\n )\nadmin_main_menu.add(\n KeyboardButton('🏪 О магазине'),\n KeyboardButton(\"📨 Техподдержка\")\n )\nadmin_main_menu.add(\n KeyboardButton('🔐Административная панель')\n )\nadmin_menu = ReplyKeyboardMarkup(resize_keyboard = True)\nadmin_menu.add(\n KeyboardButton('📩Рассылка'),\n KeyboardButton('📊Статистика')\n \n )\n \nadmin_menu.add(\n KeyboardButton('ℹ️Пробить по базе'),\n KeyboardButton('👤Доб. Админа')\n ) \n \nadmin_menu.add(\n KeyboardButton('🛒 История покупок'),\n KeyboardButton('🖋Написать юзеру')\n )\nadmin_menu.add(\n \"◀️Назад\"\n ) \nall_categories_menu = InlineKeyboardMarkup()\nall_categories_menu.add(\n InlineKeyboardButton(\n text = '👕Футболки',\n callback_data = \"category_t-shirts_1\"\n ),\n InlineKeyboardButton(\n text = '🧢 Кепки',\n callback_data = \"category_caps_1\"\n ), \n )\nall_categories_menu.add(\n InlineKeyboardButton(\n text = '👖Джинсы',\n callback_data = \"category_jeans_1\"\n ),\n InlineKeyboardButton(\n text = '👟Кросовки',\n callback_data = \"category_sneakers_1\"\n ), \n )\n \nall_categories_menu.add(\n InlineKeyboardButton(\n text = '🧦Носки',\n callback_data = \"category_socks_1\"\n )\n ) \n \nasync def get_item_navigation_menu(category_name,item_name, pos):\n menu = InlineKeyboardMarkup()\n back_pos = pos - 1\n if pos == 1:\n back_pos = 5\n next_pos = pos+1 \n if pos == 5:\n next_pos = 1\n menu.add(\n InlineKeyboardButton(\n text = \"◀️\" ,\n callback_data = f\"category_{category_name}_{back_pos}\"\n ),\n InlineKeyboardButton(\n text = \"▶️\" ,\n callback_data = f\"category_{category_name}_{next_pos}\"\n ) \n )\n menu.add(\n InlineKeyboardButton(\n text = '🛒 Добавить в корзину',\n callback_data = f'add_to_cart_{item_name}'\n )\n )\n return menu\n\nchoose_sex_menu = InlineKeyboardMarkup()\nchoose_sex_menu.add(\n InlineKeyboardButton(\n text = 'Мужской',\n callback_data = 'sex_Мужской'\n ),\n InlineKeyboardButton(\n text = 'Женский',\n callback_data = 'sex_Женский'\n ) \n )\n \nchoose_age_menu = InlineKeyboardMarkup()\nchoose_age_menu.add(\n InlineKeyboardButton(\n text = 'до 20',\n callback_data = 'age_до 20'\n ),\n InlineKeyboardButton(\n text = '20-30',\n callback_data = 'age_30-20'\n ),\n InlineKeyboardButton(\n text = 'более 30',\n callback_data = 'age_более 30'\n ) \n ) \nasync def choose_color_menu(choosen_color = []): \n menu = InlineKeyboardMarkup(row_width = 4)\n colors = [['⚫️', 'Черный'],['🔴', 'Красный'],['⚪️', 'Белый'],['🟢', 'Зеленый']]\n finaly_menu = []\n for color in colors:\n if color[1] in choosen_color:\n finaly_menu.append(\n InlineKeyboardButton(\n text = '☑️',\n callback_data = 'pass'\n ) \n )\n else:\n finaly_menu.append(\n InlineKeyboardButton(\n text = color[0],\n callback_data = f'color_{color[1]}'\n )\n )\n menu.add(\n *finaly_menu\n )\n menu.add(\n InlineKeyboardButton(\n text = '✅ Подтвердить',\n callback_data = 'set_colors'\n )\n )\n return menu\n\nasync def basket_navigation_menu(item_name, pos, id):\n last_pos = await db.get_last_position_bascket(id)\n sum = await db.get_sum_cost_bascket(id)\n next_pos = pos+1\n back_pos = pos-1\n print(last_pos)\n if pos == last_pos:\n next_pos = 1\n elif pos <=1:\n \n back_pos = last_pos\n menu = InlineKeyboardMarkup()\n menu.add(\n InlineKeyboardButton(\n text = '🔺',\n callback_data = f'add_qty_item_{item_name}_{pos}'\n ),\n InlineKeyboardButton(\n text = '❌',\n callback_data = f'delete_from_bascket_{item_name}'\n ),\n InlineKeyboardButton(\n text = '🔻',\n callback_data = f'take_away_qty_item_{item_name}_{pos}'\n ), \n \n )\n menu.add(\n InlineKeyboardButton(\n text = '◀️',\n callback_data = f'bascket_item_pos_{back_pos}'\n ),\n InlineKeyboardButton(\n text = '1/2',\n callback_data = 'test'\n ),\n InlineKeyboardButton(\n text = '▶️',\n callback_data = f'bascket_item_pos_{next_pos}'\n ), \n ) \n menu.add(\n InlineKeyboardButton(\n text =f'✅ Оформить заказ нa {sum}?',\n callback_data = 'order'\n )\n )\n menu.add(\n InlineKeyboardButton(\n text ='🛍 Проложить покупки',\n callback_data = 'catalog'\n )\n )\n return menu\n\n\ncalncel = ReplyKeyboardMarkup(resize_keyboard = True)\ncalncel.add(\n KeyboardButton('🚫 Отмена')\n \n )\n \nget_lacation_menu = ReplyKeyboardMarkup(resize_keyboard = True)\nget_lacation_menu.add(\n KeyboardButton('📍 Отправить геолокация',request_location = True)\n \n )\nget_lacation_menu.add(\n KeyboardButton('🚫 Отмена')\n \n )\n \nadd_buttons = ReplyKeyboardMarkup(resize_keyboard = True)\nadd_buttons.add(\n KeyboardButton('📤 Отправить сообщение'),\n)\nadd_buttons.add(\n KeyboardButton('☑️ Добвить инлайн кнопки'),\n )\n\nadd_buttons.add(\n KeyboardButton('🚫 Отмена')\n )\n \n \nasync def create_markup(markpus):\n menu = InlineKeyboardMarkup()\n for markpup in markpus:\n \n ii = [markpup.split(' | ')]\n num = 0\n for i in ii:\n if len(i) > 1:\n markup1 = i[0].split(' - ')\n markup2 = i[1].split(' - ')\n menu.add(\n InlineKeyboardButton(\n text = markup1[0],\n url = markup1[1]\n ),\n InlineKeyboardButton(\n text = markup2[0],\n url = markup2[1]\n )\n )\n else:\n markup1 = i[0].split(' - ')\n \n menu.add(\n InlineKeyboardButton(\n text = markup1[0],\n url = markup1[1]\n ),\n )\n \n \n \n return menu\ninline_back_button = InlineKeyboardMarkup()\ninline_back_button.add(\n InlineKeyboardButton(\n text = '🔙 Назад',\n callback_data = 'back'\n )\n \n )\n \n\nget_actions = ReplyKeyboardMarkup(resize_keyboard = True)\n\n\nget_actions.add(\n KeyboardButton('✅ Подтверждаю')\n )\n\nget_actions.add(\n KeyboardButton('🚫 Отмена')\n ) \n \ncancel = ReplyKeyboardMarkup(resize_keyboard = True)\ncancel.add(\n KeyboardButton('🚫 ��тмена')\n ) \n \n \nconfim_order = ReplyKeyboardMarkup(resize_keyboard = True)\nconfim_order.add('✅ Подтверждаю')\n\n","repo_name":"ceoaleksandr/test-shop-bot","sub_path":"markup.py","file_name":"markup.py","file_ext":"py","file_size_in_byte":9239,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"12165425470","text":"#!/usr/bin/env python3\n\nimport urllib.request\nimport urllib.error\n\n\ndef get_link(ip, port, path):\n return \"http://{}:{}/{}\".format(ip, port, path)\n\n\ndef make_get_request(ip, port, path):\n contents = ''\n try:\n contents = urllib.request.urlopen(get_link(ip, port, path)).read()\n except urllib.error.HTTPError as e:\n print(\"Error during GET request:\", e)\n finally:\n return contents\n\n\ndef make_post_request(ip, port, path, data):\n contents = ''\n try:\n contents = urllib.request.urlopen(get_link(ip, port, path),\n data=data).read()\n except urllib.error.HTTPError as e:\n print(\"Error during POST request:\", e)\n finally:\n return contents\n","repo_name":"sakshamsharma/distributed-control-panel","sub_path":"dcp/http_client.py","file_name":"http_client.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"16982685730","text":"import json\nfrom abc import ABC, abstractmethod\nfrom datetime import timedelta\nfrom typing import Optional, Union, Dict, Tuple, List, cast\n\n\nclass BaseStorageClient(ABC):\n \"\"\"\n The base class for storage clients with operations to list, read, write files and generate signed urls.\n \"\"\"\n\n _GZIP_MAGIC_NUMBER = (\n b\"\\x1f\\x8b\" # Hex signature used to identify a gzip compressed files\n )\n\n class GenericError(Exception):\n pass\n\n class PermissionsError(GenericError):\n pass\n\n class NotFoundError(GenericError):\n pass\n\n def __init__(self, prefix: Optional[str] = None):\n self._prefix = prefix or \"\"\n if self._prefix and not self._prefix.endswith(\"/\"):\n self._prefix = f\"{self._prefix}/\"\n\n @property\n @abstractmethod\n def bucket_name(self) -> str:\n \"\"\"\n Returns the bucket name referenced by this client\n \"\"\"\n pass\n\n @abstractmethod\n def write(self, key: str, obj_to_write: Union[bytes, str]) -> None:\n \"\"\"\n Writes a file in the given key, contents are included as bytes or string.\n :param key: path to the file, for example /dir/name.ext\n :param obj_to_write: contents for the file, specified as a bytes array or string\n \"\"\"\n raise NotImplementedError()\n\n @abstractmethod\n def read(\n self,\n key: str,\n decompress: Optional[bool] = False,\n encoding: Optional[str] = None,\n ) -> Union[bytes, str]:\n \"\"\"\n Returns the contents of the specified file.\n :param key: path to the file, for example /dir/name.ext\n :param decompress: flag indicating if `gzip` contents should be decompressed automatically\n :param encoding: if set binary content will be decoded using this encoding and a string will be returned\n :return: a bytes object, unless encoding is set, in which case it returns a string.\n \"\"\"\n raise NotImplementedError()\n\n @abstractmethod\n def delete(self, key: str) -> None:\n \"\"\"\n Deletes the file at `key`\n :param key: path to the file, for example /dir/name.ext\n \"\"\"\n raise NotImplementedError()\n\n @abstractmethod\n def download_file(self, key: str, download_path: str) -> None:\n \"\"\"\n Downloads the file at `key` to the local file indicated by `download_path`.\n :param key: path to the file, for example /dir/name.ext\n :param download_path: local path to the file where the contents of `key` will be stored.\n \"\"\"\n raise NotImplementedError()\n\n @abstractmethod\n def upload_file(self, key: str, local_file_path: str) -> None:\n \"\"\"\n Uploads the file at `local_file_path` to `key` in the associated bucket.\n :param key: path to the file, for example /dir/name.ext\n :param local_file_path: local path to the file to upload.\n \"\"\"\n raise NotImplementedError()\n\n def read_json(self, key: str) -> Dict:\n \"\"\"\n Returns the contents as a dictionary of the JSON file at `key`.\n :param key: path to the file, for example /dir/name.ext\n :return: a Dictionary loaded from the JSON document.\n \"\"\"\n data = self.read(key)\n return json.loads(data.decode(\"utf-8\") if isinstance(data, bytes) else data)\n\n @abstractmethod\n def read_many_json(self, prefix: str) -> Dict:\n \"\"\"\n Reads all JSON files under `prefix` and returns a dictionary where the key is the file path and the value\n is the dictionary loaded from the JSON file.\n :param prefix: Prefix for the files to load, for example: `/dir/`\n :return: a dictionary where the key is the file path and the value is the dictionary loaded from the JSON file.\n \"\"\"\n raise NotImplementedError()\n\n @abstractmethod\n def managed_download(self, key: str, download_path: str):\n \"\"\"\n Performs a managed transfer that might be multipart, downloads the file at `key` to the local file at\n `download_path`.\n :param key: path to the file, for example /dir/name.ext\n :param download_path: local path to the file where the contents of `key` will be stored.\n \"\"\"\n raise NotImplementedError()\n\n @abstractmethod\n def list_objects(\n self,\n prefix: Optional[str] = None,\n batch_size: Optional[int] = None,\n continuation_token: Optional[str] = None,\n delimiter: Optional[str] = None,\n *args, # type: ignore\n **kwargs, # type: ignore\n ) -> Tuple[Union[List, None], Union[str, None]]:\n \"\"\"\n List objects (files and folder) under the specified prefix.\n Delimiter is set to \"/\" to return sub-folders, this works for all storage providers as it works for S3.\n Documentation about delimiter in S3 requests available here:\n https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html#API_ListObjectsV2_RequestSyntax\n Prefix can be used to return contents of folders.\n :param prefix: Prefix to use for listing, it can be used to list folders, for example: `prefix=/dir/`\n :param batch_size: Used to page the result\n :param continuation_token: Used to page the result, the second value in the resulting tuple is the continuation\n token for the next call.\n :param delimiter: Set to \"/\" to return sub-folders, when set the result will include the list of prefixes\n returned by the storage provider instead of metadata for the objects.\n :return: A tuple with the result list and the continuation token. The result list includes the following\n attributes (when no delimiter is set): ETag, Key, Size, LastModified, StorageClass. If delimiter is\n specified only Prefix is included in the result for each listed folder.\n \"\"\"\n raise NotImplementedError()\n\n @abstractmethod\n def generate_presigned_url(self, key: str, expiration: timedelta) -> str:\n \"\"\"\n Generates a pre-signed url for the given file with the specified expiration.\n :param key: path to the file, for example /dir/name.ext\n :param expiration: time for the generated link to expire, expressed as a timedelta object.\n :return: a pre-signed url to access the specified file.\n \"\"\"\n raise NotImplementedError()\n\n @abstractmethod\n def is_bucket_private(self) -> bool:\n \"\"\"\n Checks if the bucket is configured with public access disabled.\n\n :return: True if public access is disabled for the bucket and False if the bucket is publicly available.\n \"\"\"\n raise NotImplementedError()\n\n def _is_gzip(self, content: bytes) -> bool:\n return content[:2] == self._GZIP_MAGIC_NUMBER\n\n def _apply_prefix(self, key: Optional[str]) -> Optional[str]:\n if not key:\n return self._prefix\n if self._prefix:\n return f\"{self._prefix}{key}\"\n else:\n return key\n\n def _remove_prefix(self, key: str) -> str:\n if self._prefix and key.startswith(self._prefix):\n return key[len(self._prefix) :]\n else:\n return key\n\n def _remove_prefix_from_prefixes(\n self, entries: Optional[List[Dict]]\n ) -> Optional[List[Dict]]:\n if not entries or not self._prefix:\n return entries\n return [\n {\"Prefix\": self._remove_prefix(cast(str, entry.get(\"Prefix\")))}\n for entry in entries\n ]\n\n def _remove_prefix_from_entries(\n self, entries: Optional[List[Dict]]\n ) -> Optional[List[Dict]]:\n if not entries or not self._prefix:\n return entries\n return [\n {**entry, \"Key\": self._remove_prefix(cast(str, entry.get(\"Key\")))}\n for entry in entries\n ]\n","repo_name":"monte-carlo-data/apollo-agent","sub_path":"apollo/integrations/storage/base_storage_client.py","file_name":"base_storage_client.py","file_ext":"py","file_size_in_byte":7839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"33778230569","text":"class Solution:\n def minOperations(self, boxes: str) -> List[int]:\n posB = list()\n res = list()\n for i, element in enumerate(boxes):\n if element=='1':\n posB.append(i)\n \n for i in range(len(boxes)):\n count = 0\n for x in posB:\n count += abs(x-i) \n res.append(count)\n return res","repo_name":"bzlee-bio/coding-study","sub_path":"modulabs/week4/problem5.py","file_name":"problem5.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"22352194640","text":"from selenium.common import StaleElementReferenceException\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\nclass wait_for_value_to_start_with(object):\n def __init__(self, locator, text_):\n self.locator = locator\n self.text = text_\n\n def __call__(self, driver):\n try:\n element_text = driver.find_element(*self.locator).get_attribute('value')\n return element_text.startswith(self.text)\n except StaleElementReferenceException:\n return False\n\n\nplaylist = \"\"\nprint(\"Keep in mind that the playlist must be public.\")\nwhile True:\n print(\"Enter the link of the playlist you want to download: \")\n playlist = str(input())\n if not playlist.startswith(\"https://www.deezer.com/\") or \"/playlist/\" not in playlist:\n print(\"You entered the wrong link\")\n continue\n else:\n break\nopen('links_file.txt', 'w').close()\ndriver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))\ndriver.get(playlist)\nlistoflinks = []\nprint(\"Make sure you expand your browser window!\")\nprint(\"Links to every track from playlist: \")\ntry:\n try:\n refuse_button = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.ID, \"gdpr-btn-refuse-all\"))\n )\n refuse_button.click()\n except:\n print(\"Refuse button didn't pop up!\")\n numberoftracks = driver.find_element(By.CSS_SELECTOR, \"#page_naboo_playlist > div.catalog-content > div > div._5BJsj > div > div._2yyo6 > ul > li:nth-child(1)\").text\n numberoftracks = numberoftracks[0:len(numberoftracks)-7]\n numberoftracks = int(numberoftracks)\n for x in range(1, numberoftracks + 1):\n try:\n button = driver.find_element(By.CSS_SELECTOR,\n \"div._2OACy[aria-rowindex=\\'\" + str(x) + \"\\'] .popper-wrapper button\")\n button.click()\n div = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.CLASS_NAME, \"_2ZkBf\"))\n )\n share_button = div.find_element(By.XPATH, \"//*[contains(text(), 'Share')]\")\n share_button.click()\n except Exception as e:\n print(e)\n driver.execute_script(\n \"document.querySelector(\\\"div._2OACy[aria-rowindex=\\'\" + str(x) + \"\\']\\\").scrollIntoView()\")\n continue\n WebDriverWait(driver, 10).until(wait_for_value_to_start_with((By.CSS_SELECTOR,\n \"#modal_sharebox > div.modal-body > div.share-content.share-infos > div.share-thumbnail-infos > div.share-action > div > div.control-input > input\"),\n \"https:\"))\n input = driver.find_element(By.CSS_SELECTOR,\n \"#modal_sharebox > div.modal-body > div.share-content.share-infos > div.share-thumbnail-infos > div.share-action > div > div.control-input > input\")\n link = input.get_attribute('value')\n listoflinks.append(link)\n print(str(x) + \". track: \" + link)\n close_button = driver.find_element(By.ID, \"modal-close\")\n close_button.click()\n driver.execute_script(\n \"document.querySelector(\\\"div._2OACy[aria-rowindex=\\'\" + str(x) + \"\\']\\\").scrollIntoView()\")\nexcept Exception as e:\n print(e)\n driver.quit()\ndriver.quit()\nwith open(\"links_file.txt\", \"w\") as f:\n for element in listoflinks:\n f.write(str(element) + \"\\n\")\nprint(\"Links to all \" + str(len(listoflinks)) + \" tracks are in the \\\"links_file.txt\\\"\")","repo_name":"djordjije11/DeezerPlaylistsDownload","sub_path":"deezer_main.py","file_name":"deezer_main.py","file_ext":"py","file_size_in_byte":3855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"15916140894","text":"def decor(fanc):\n def check(name):\n if not name.isalpha():\n print('Please enter valid data')\n else:\n fanc(name)\n return check\n\n\n@decor\ndef wish(name):\n print(f'Best of luck {name}')\n\n\nwish('John')\nwish('1234')\n\ndecorfanction = decor(wish)\ndecorfanction('Shubham')\ndecorfanction('1111')\n\n\n\n\n","repo_name":"shubhampaanchal/Python","sub_path":"Decorator/Decorator.py","file_name":"Decorator.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"8181293379","text":"#!/usr/bin/env python3\n\"\"\"Load paths to sound files.\"\"\"\n\nimport os\nimport sys\n\n\ndef load_sound_paths():\n \"\"\"meh.\"\"\"\n sound_dir = os.path.join(os.path.dirname(__file__), 'sound_files')\n\n for f in os.listdir(sound_dir):\n name = os.path.splitext(os.path.basename(f))[0]\n path = os.path.join(sound_dir, f)\n setattr(sys.modules[__name__], name, path)\n\n\nload_sound_paths()\n","repo_name":"muppetjones/remgame","sub_path":"gamelib/sounds.py","file_name":"sounds.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"7438361292","text":"#!/usr/bin/env python\n\nimport zmq\nfrom sys import argv\nfrom pprint import pprint\n\ndef main():\n context = zmq.Context()\n\n request = context.socket(zmq.REQ)\n request.connect('tcp://localhost:3333')\n\n # Statistics\n # cache_stats / config / all_services\n request.send_json({\n \t'version' : 1,\n 'action': 'all_services'\n })\n\n pprint(request.recv_json())\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"sguzwf/lsd","sub_path":"misc/stats_watcher.py","file_name":"stats_watcher.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"72053587209","text":"# Enter your code here. Read input from STDIN. Print output to STDOUT\n\ndef doormat(r, c):\n for i in range(r//2):\n print((\".|.\"*(i*2+1)).center(c, \"-\"))\n print(\"WELCOME\".center(c, \"-\"))\n for i in range(r//2-1, -1, -1):\n print((\".|.\"*(i*2+1)).center(c, \"-\"))\n\n\ndef main():\n rows, columns = [int(s) for s in input().strip().split()]\n doormat(rows, columns)\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"hideyukikanazawa/Challenges","sub_path":"hackerrank/python/10. printDoormat.py","file_name":"10. printDoormat.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"7126732772","text":"import ee\nimport geemap\n\n# Create a map centered at (lat, lon).\nMap = geemap.Map(center=[40, -100], zoom=4)\n\n# Add some data to the Map\ndem = ee.Image(\"JAXA/ALOS/AW3D30_V1_1\").select('MED')\nMap.addLayer(dem, {'min': 0, 'max': 5000, 'palette': ['000000', 'ffffff'] }, 'DEM', True)\n\n# TEST Map.setCenter\nMap.setCenter(0, 28, 2.5)\n\n# Display the map.\nMap\n","repo_name":"giswqs/earthengine-py-examples","sub_path":"Gena/map_set_center.py","file_name":"map_set_center.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":114,"dataset":"github-code","pt":"16"}
+{"seq_id":"31818073393","text":"from __future__ import annotations\n\nimport os\nimport sys\nimport pickle\nimport csv\nimport datetime as dt\nfrom secrets import token_hex\nfrom typing import List, Dict, Tuple, IO, Optional\n\nimport discord\nfrom discord.ext import commands\nfrom bidict import bidict\nfrom bidict._exc import *\n\nfrom comp3000bot import config\nfrom comp3000bot.singleton import Singleton\nfrom comp3000bot.logger import get_logger\nfrom comp3000bot.utils import (\n generate_file,\n generate_csv_file,\n get_text_channel,\n get_guild,\n get_role,\n get_text_channel_or_curr,\n)\n\nlogger = get_logger()\n\n\nclass StudentInformation:\n def __init__(self, name: str, number: int, email: str):\n self.name = name\n self.number = number\n self.email = email\n self.discord_name = None # type: str\n self.discord_id = None # type: int\n self.is_registered = False\n self.generate_new_secret()\n\n def __repr__(self):\n return f'Student(name={self.name})'\n\n def __hash__(self):\n return hash(self.number)\n\n def __eq__(self, other):\n return self.number == other.number\n\n def generate_new_secret(self):\n self.secret = token_hex(32)\n\n def register(self, member: discord.Member):\n self.discord_name = member.name\n self.discord_id = member.id\n self.is_registered = True\n\n def reset(self):\n self.discord_name = None\n self.discord_id = None\n self.is_registered = False\n\n @classmethod\n def csv_header(cls) -> Tuple[str, str, str, str, str]:\n return ('name', 'number', 'email', 'discord_name', 'secret')\n\n def csv_row(self) -> Tuple[str, int, str, str, str]:\n return (self.name, self.number, self.email, self.discord_name, self.secret)\n\n def to_csv_file(self) -> discord.File:\n return generate_csv_file(\n f'{self.name}_{self.number}.csv', self.csv_header(), [self.csv_row()]\n )\n\n\nclass Students(metaclass=Singleton):\n __FILE_NAME = os.path.join(config.STUDENTS_DIR, f'students_{config.GUILD_ID}.dat')\n\n def __init__(self):\n self.students = bidict({}) # type: bidict[str, StudentInformation]\n self.registered_students = bidict({}) # type: bidict[int, StudentInformation]\n\n @staticmethod\n def factory():\n \"\"\"\n Load students from disk or create an empty Students class.\n \"\"\"\n try:\n return Singleton._instances[Students]\n except Exception:\n pass\n try:\n Students._from_disk()\n except FileNotFoundError as e:\n logger.warn(f\"Unable to load students from disk: {repr(e)}\")\n return Students()\n\n @staticmethod\n def _from_disk() -> Students:\n \"\"\"\n Load Students from a file saved on disk. Don't call this directly. Use Students.factory() instead.\n \"\"\"\n fname = Students.__FILE_NAME\n logger.info(f'Loading {fname}...')\n with open(fname, 'rb') as f:\n obj = pickle.load(f)\n if not isinstance(obj, Students):\n raise TypeError(\"Unpicked object is not of type Students\")\n Singleton._instances[Students] = obj\n logger.info(f'Loaded {fname}')\n return obj\n\n def add_student(\n self, name: str, number: int, email: str, overwrite: bool = False\n ) -> StudentInformation:\n \"\"\"\n Add a new student to the collection of students.\n \"\"\"\n student = StudentInformation(name, number, email)\n if overwrite:\n self.students.forceput(student.secret, student)\n else:\n try:\n self.students[student.secret] = student\n except ValueDuplicationError:\n raise Exception(\n f'Refusing to update existing {repr(student)}. You may wish to set overwrite to True.'\n )\n return student\n\n def remove_student(self, number: int):\n secret = self.students.inverse[StudentInformation('', number, '')]\n try:\n _id = self.registered_students.inverse[StudentInformation('', number, '')]\n self.registered_students.pop(_id)\n except Exception:\n pass\n return self.students.pop(secret)\n\n def reset_student(self, number: int):\n secret = self.students.inverse[StudentInformation('', number, '')]\n student = self.students[secret]\n student.reset()\n return student\n\n def register_student(self, student: StudentInformation, member: discord.Member):\n student.register(member)\n self.registered_students[member.id] = student\n return student\n\n def student_by_secret(self, secret: str) -> StudentInformation:\n \"\"\"\n Get a student by their secret.\n \"\"\"\n try:\n return self.students[secret]\n except KeyError:\n raise KeyError(f'No student with secret {secret}') from None\n\n def student_by_member(self, member: discord.Member) -> StudentInformation:\n \"\"\"\n Get a student by their discord member.\n \"\"\"\n try:\n return self.registered_students[member.id]\n except KeyError:\n raise KeyError(f'No student associated with {member.name}') from None\n\n def to_csv_file(self) -> discord.File:\n return generate_csv_file(\n f'student_information.csv',\n StudentInformation.csv_header(),\n [student.csv_row() for student in self.students.values()],\n )\n\n def to_disk(self):\n \"\"\"\n Write Students to disk.\n \"\"\"\n fname = Students.__FILE_NAME\n logger.info(f'Saving {fname}...')\n with open(fname, 'wb+') as f:\n pickle.dump(self, f)\n\n async def populate_from_csv_file(\n self,\n ctx: commands.Context,\n fp: IO[str],\n has_header: bool,\n overwrite: bool = False,\n ) -> 'StudentInformation':\n \"\"\"\n Populate this student manager from an open CSV file.\n The format should be as follows:\n fname, lname, email, number\n \"\"\"\n reader = csv.reader(fp)\n failed_count = 0\n success_count = 0\n if has_header:\n reader = reader[1:]\n for fname, lname, email, number in reader:\n name = f'{fname} {lname}'\n try:\n self.add_student(name, int(number), email, overwrite)\n success_count += 1\n except Exception as e:\n logger.error(f'Unable to add student ({name}, {number})', exc_info=e)\n failed_count += 1\n if failed_count:\n await ctx.send(f'Failed to add {failed_count} students')\n else:\n await ctx.send(f'Added {success_count} students successfully')\n","repo_name":"willfindlay/comp3000bot","sub_path":"comp3000bot/students.py","file_name":"students.py","file_ext":"py","file_size_in_byte":6745,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"16"}
+{"seq_id":"48074749260","text":"import itertools\nfrom logging import getLogger\n\nimport matplotlib\nimport numpy as np\n\nmatplotlib.use('Agg')\nimport pylab as plt\n\nfrom omnium import Analyser\nfrom omnium.utils import get_cube\nfrom omnium.consts import L, cp, Lf\n\nlogger = getLogger('scaf.dump_entr')\n\nSCALARS = ['MSE', 'FMSE']\nCLD_OPTS = ['scaffold', 'scaffold_plus', 'scaffold_plus_strong', 'SS2012', 'swann_ud', 'swann_core']\nMETHODS = ['normal', 'acc']\n\nclass DumpEntr(Analyser):\n analysis_name = 'dump_entr'\n multi_expt = True\n\n input_dir = 'share/data/history/{expt}'\n input_filename_glob = '{input_dir}/atmosa_da480.nc'\n output_dir = 'omnium_output/{version_dir}/suite_{expts}'\n output_filenames = ['{output_dir}/atmos.dump_entr.dummy']\n\n def load(self):\n self.load_cubes()\n\n def run(self):\n pass\n\n def save(self, state, suite):\n with open(self.task.output_filenames[0], 'w') as f:\n f.write('done')\n\n def display_results(self):\n self._plot_entrainment()\n plt.close('all')\n\n def _plot_entrainment(self):\n opts = []\n for p in itertools.product(SCALARS, CLD_OPTS, METHODS):\n opt = {'SCALAR': p[0],\n 'CLD_DEF': p[1],\n 'METHOD': p[2]}\n opts.append(opt)\n\n for i, expt in enumerate(self.task.expts):\n da = self.expt_cubes[expt]\n\n theta_cube = get_cube(da, 0, 4)\n q_cube = get_cube(da, 0, 10)\n\n qcl_cube = get_cube(da, 0, 254)\n qcf_cube = get_cube(da, 0, 12)\n qcf2_cube = get_cube(da, 0, 271)\n qgr_cube = get_cube(da, 0, 273)\n w_cube = get_cube(da, 0, 150)\n\n z = theta_cube.coord('atmosphere_hybrid_height_coordinate').points\n\n # Calc MSE (h), FMSE (h2)\n theta = theta_cube.data\n q = q_cube.data\n qcf = qcf_cube.data\n qcf2 = qcf2_cube.data\n qgr = qgr_cube.data\n h = theta + L / cp * q\n h2 = theta + L / cp * q - Lf / cp * (qcf + qcf2 + qgr)\n\n w = w_cube.data\n qcl = qcl_cube.data\n qcf = qcf_cube.data\n qcf2 = qcf2_cube.data\n theta = theta_cube.data\n\n for opt in opts:\n logger.debug('entr for {}: {}', expt, opt)\n if opt['CLD_DEF'] == 'SS2012':\n # Using def from Stirling and Stratton 2012:\n # qcl or qcf (or qcf2) > 1e-5 kg/kg\n # w > 0\n # +ve buoyancy (here defined as theta > theta.mean())\n qcl_thresh = 1e-5\n w_thresh = 0\n env_mask = (((qcl > qcl_thresh) | (qcf > qcl_thresh) | (qcf2 > qcl_thresh))\n & (w > w_thresh)\n & (theta > theta.mean(axis=(1, 2))[:, None, None]))\n elif opt['CLD_DEF'] == 'swann_ud':\n qcl_thresh = 1e-6\n w_thresh = 0\n env_mask = (((qcl > qcl_thresh) | (qcf > qcl_thresh) | (qcf2 > qcl_thresh))\n & (w > w_thresh))\n elif opt['CLD_DEF'] == 'swann_core':\n qcl_thresh = 1e-6\n w_thresh = 0\n env_mask = (((qcl > qcl_thresh) | (qcf > qcl_thresh) | (qcf2 > qcl_thresh))\n & (w > w_thresh)\n & (theta > theta.mean(axis=(1, 2))[:, None, None]))\n elif opt['CLD_DEF'] == 'scaffold':\n qcl_thresh = 5e-6\n w_thresh = 1\n env_mask = (qcl > qcl_thresh) & (w > w_thresh)\n elif opt['CLD_DEF'] == 'scaffold_plus':\n qcl_thresh = 5e-6\n w_thresh = 1\n env_mask = (((qcl > qcl_thresh) | (qcf > qcl_thresh) | (qcf2 > qcl_thresh))\n & (w > w_thresh))\n elif opt['CLD_DEF'] == 'scaffold_plus_strong':\n qcl_thresh = 5e-6\n w_thresh = 5\n env_mask = (((qcl > qcl_thresh) | (qcf > qcl_thresh) | (qcf2 > qcl_thresh))\n & (w > w_thresh))\n cld_mask = ~env_mask\n\n # Calc entr.\n if opt['SCALAR'] == 'MSE':\n scalar = h\n elif opt['SCALAR'] == 'FMSE':\n scalar = h2\n # Can't do without knowing source terms of qt.\n # elif opt['SCALAR'] == 'qt':\n # scalar = (expt_res['q_cube'].data +\n # expt_res['qcl_cube'].data +\n # expt_res['qcf_cube'].data +\n # expt_res['qcf2_cube'].data)\n\n if opt['METHOD'] == 'acc':\n scalar_c = (np.ma.masked_array(scalar * w, cld_mask).mean(axis=(1, 2))\n / np.ma.masked_array(w, cld_mask).mean(axis=(1, 2)))\n scalar_e = np.ma.masked_array(scalar, env_mask).mean(axis=(1, 2))\n\n dscalar_c_dz = (scalar_c[2:] - scalar_c[:-2])/(z[2:] - z[:-2])\n entr = dscalar_c_dz / (scalar_e[1:-1] - scalar_c[1:-1])\n\n elif opt['METHOD'] == 'normal':\n scalar_c = np.ma.masked_array(scalar, cld_mask).mean(axis=(1, 2))\n scalar_e = np.ma.masked_array(scalar, env_mask).mean(axis=(1, 2))\n\n dscalar_c_dz = (scalar_c[2:] - scalar_c[:-2]) / (z[2:] - z[:-2])\n entr = dscalar_c_dz / (scalar_e[1:-1] - scalar_c[1:-1])\n\n # Plot results\n z_km = z / 1000\n\n figname = 'entr_{}_{}_{}_{}'.format(expt,\n opt['SCALAR'],\n opt['CLD_DEF'],\n opt['METHOD'])\n fig = plt.figure(figname)\n plt.clf()\n fig, axgrid = plt.subplots(1, 5, fig=fig, sharey=True, num=figname, figsize=(15, 12))\n ax0, ax1, ax2, ax3, ax4 = axgrid\n\n # ~10 km\n # ztop_index = 55\n ztop_index = 75\n # full.\n # ztop_index = 98\n ax0.plot(scalar_c[1:ztop_index], z_km[1:ztop_index], label='cld')\n ax0.plot(scalar_e[1:ztop_index], z_km[1:ztop_index], label='env')\n ax0.legend()\n\n ax1.plot(dscalar_c_dz[:ztop_index - 1] * 1000, z_km[1:ztop_index])\n\n ax2.plot(scalar_e[1:ztop_index] - scalar_c[1:ztop_index], z_km[1:ztop_index])\n\n ax3.plot(env_mask.sum(axis=(1, 2)) / (env_mask.shape[1] * env_mask.shape[2]), z_km)\n ax3.set_xlim((0, 0.1))\n\n ax4.plot(entr[:ztop_index - 1] * 1000, z_km[1:ztop_index])\n ax4.set_xlim((-1, 1))\n ax4.axvline(x=0, color='k', linestyle='--')\n\n ax0.set_ylabel('height (km)')\n ax0.set_ylim((0, 15))\n ax0.set_xlabel('{}'.format(opt['SCALAR']))\n ax1.set_xlabel('$\\\\frac{{d{}_c}}{{dz}}$'.format(opt['SCALAR']))\n ax2.set_xlabel('${0}_e - {0}_c$'.format(opt['SCALAR']))\n ax3.set_xlabel('$\\\\sigma$')\n ax4.set_xlabel('$\\\\epsilon$ (km$^{-1}$)')\n\n plt.savefig(self.file_path('entr_' + figname + '.png'))\n","repo_name":"markmuetz/scaffold_analysis","sub_path":"scaffold/suite/dump_entr.py","file_name":"dump_entr.py","file_ext":"py","file_size_in_byte":7484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"35803219623","text":"# -*- coding: utf-8 -*-\n#BEGIN_HEADER\n# The header block is where all import statements should live\nimport os\nimport uuid\nimport json\nimport shutil\nfrom KBaseReport.KBaseReportClient import KBaseReport\nfrom Workspace.WorkspaceClient import Workspace\nfrom taxaspec.filter import filter_file\nfrom taxaspec import acquire\nimport zipfile\n#END_HEADER\n\n\nclass MetabolomicsTools:\n '''\n Module Name:\n MetabolomicsTools\n\n Module Description:\n A KBase module: MetabolomicsTools\n '''\n\n ######## WARNING FOR GEVENT USERS ####### noqa\n # Since asynchronous IO can lead to methods - even the same method -\n # interrupting each other, you must be *very* careful when using global\n # state. A method could easily clobber the state set by another while\n # the latter method is running.\n ######################################### noqa\n VERSION = \"1.0.0\"\n GIT_URL = \"git@github.com:JamesJeffryes/MetabolomicsTools.git\"\n GIT_COMMIT_HASH = \"c76fc0898314fad8a852c976f5d6d0ca5082fcf0\"\n\n #BEGIN_CLASS_HEADER\n # Class variables and functions can be defined in this block\n #END_CLASS_HEADER\n\n # config contains contents of config file in a hash or None if it couldn't\n # be found\n def __init__(self, config):\n #BEGIN_CONSTRUCTOR\n \n # Any configuration parameters that are important should be parsed and\n # saved in the constructor.\n self.callback_url = os.environ['SDK_CALLBACK_URL']\n self.workspaceURL = config['workspace-url']\n self.shared_folder = config['scratch']\n\n #END_CONSTRUCTOR\n pass\n\n\n def get_mona_spectra(self, ctx, params):\n \"\"\"\n :param params: instance of type \"GetSpectraParams\" -> structure:\n parameter \"workspace_name\" of String, parameter \"metabolic_model\"\n of type \"model_ref\" (A reference to a kbase metabolic model),\n parameter \"spectra_source\" of String, parameter \"spectra_query\" of\n String\n :returns: instance of type \"SpectraResults\" -> structure: parameter\n \"report_name\" of String, parameter \"report_ref\" of String\n \"\"\"\n # ctx is the context object\n # return variables are: output\n #BEGIN get_mona_spectra\n # Parse/examine the parameters and catch any errors\n print('Validating parameters.')\n for val in ('workspace_name', 'metabolic_model', 'spectra_source',\n 'spectra_query'):\n if val not in params:\n raise ValueError('Parameter %s is not set in input arguments'\n % val)\n\n uuid_string = str(uuid.uuid4())\n scratch = self.shared_folder + \"/\" + uuid_string\n os.mkdir(scratch)\n token = ctx['token']\n ws_client = Workspace(self.workspaceURL, token=token)\n with open('/kb/module/data/Compound_Data.json') as infile:\n comp_data = json.load(infile)\n # acquire metabolic model from the workspace and get inchikeys & names\n try:\n kb_model = ws_client.get_objects(\n [{'name': params['metabolic_model'],\n 'workspace': params['workspace_name']}])[0]\n except Exception as e:\n raise ValueError(\n 'Unable to get metabolic model object from workspace: (' +\n params['workspace_name'] + '/' +\n params['metabolic_model'] + ')' + str(e))\n kb_ids = [x['id'].replace('_c0', '')\n for x in kb_model['data']['modelcompounds']]\n names, inchis = set(), set()\n for cid in kb_ids:\n if cid in comp_data:\n names.update(comp_data[cid].get('names', None))\n inchis.add(comp_data[cid].get('inchikey', None))\n\n # Acquire Spectral Library\n if params['spectra_source'] == 'MoNA-API':\n spec_file = acquire.from_mona(params['spectra_query'],\n '/kb/module/data/')\n else:\n spec_file = '/kb/module/data/%s' % params['spectra_source']\n try:\n z = zipfile.ZipFile(spec_file + \".zip\")\n z.extractall('/kb/module/data/')\n except ValueError:\n raise ValueError('%s is not a supported spectra source'\n % params['spectra_source'])\n\n # Filter Spectral Library\n n_in_spectra, n_out_spectra, output_file = filter_file(spec_file, None,\n inchis, names)\n print(n_in_spectra, n_out_spectra)\n if not n_out_spectra:\n raise RuntimeError(\"No matching spectra found\")\n\n new_path = \"%s/%s%s.msp\" % (scratch, os.path.basename(output_file)[:-8],\n params['metabolic_model'])\n shutil.move(output_file, new_path)\n\n # Package report\n report_files = [{'path': new_path,\n 'name': os.path.basename(new_path),\n 'label': os.path.basename(new_path),\n 'description': 'Spectral Library filtered with '\n 'supplied metabolic model'}]\n report_params = {\n 'objects_created': [],\n 'message': 'Acquired %s matching spectra and filtered library to '\n '%s spectra which match the %s model' % (\n n_in_spectra, n_out_spectra, params['metabolic_model']),\n 'file_links': report_files,\n 'workspace_name': params['workspace_name'],\n 'report_object_name': 'mass_spectra_report_' + uuid_string\n }\n\n # Construct the output to send back\n report_client = KBaseReport(self.callback_url)\n report_info = report_client.create_extended_report(report_params)\n output = {'report_name': report_info['name'],\n 'report_ref': report_info['ref'],\n }\n #END get_mona_spectra\n\n # At some point might do deeper type checking...\n if not isinstance(output, dict):\n raise ValueError('Method get_mona_spectra return value ' +\n 'output is not type dict as required.')\n # return the results\n return [output]\n def status(self, ctx):\n #BEGIN_STATUS\n returnVal = {'state': \"OK\",\n 'message': \"\",\n 'version': self.VERSION,\n 'git_url': self.GIT_URL,\n 'git_commit_hash': self.GIT_COMMIT_HASH}\n #END_STATUS\n return [returnVal]\n","repo_name":"kbaseapps/MetabolomicsTools","sub_path":"lib/MetabolomicsTools/MetabolomicsToolsImpl.py","file_name":"MetabolomicsToolsImpl.py","file_ext":"py","file_size_in_byte":6591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"3350715117","text":"\"\"\"A collection of function for doing my project.\"\"\"\n\nimport random\n\ndef greeting():\n \"\"\"Greets user and asks for the inputs that will be used all throughour the project. \"\"\"\n \n # Get name, temperature, top and color from the user\n name = input('Hi, What is your name? ')\n temperature = input('What is the temperature in farenheit? ')\n top = input('What kind of top do you want to wear? ')\n color = input('What color is the top? ')\n \n return name, int(temperature), top, color\n\n#Function on weather\ndef weather(temperature):\n \"\"\"Given a temperature value it decides if the weather is going to feel chilly, hot or cold. \n \n Parameters\n ----------\n temperature : int\n The number to be compared. \n \n Returns\n -------\n output : str\n The way that the weather is going to feel like. \n \"\"\"\n \n # Use if/elif/else statements to know how the temperature is going to feel like\n if temperature > 60 and temperature < 72:\n temp = 'chilly'\n elif temperature >= 72 and temperature < 100:\n temp = 'hot'\n elif temperature <= 60:\n temp = 'cold'\n else:\n temp = None\n \n return temp\n\n#Function on type of bottoms\n#I can use random function to choose any of the choices in either of the lists\n\ndef bottoms_shoes(temp):\n \"\"\"Given the temperature returns the bottoms and shoes for it. \n \n Parameters\n ----------\n temp : str\n The temperature to be compared to check what kind of bottoms. \n \n Returns\n -------\n choice_1 : str\n The bottoms that the student should use. \n choice_2 : str\n The shoes that the student should use.\n \"\"\"\n\n bottoms_chilly = ['jeans', 'long overalls']\n bottoms_hot = ['shorts', 'skirt', 'short overalls']\n bottoms_cold = ['leggings', 'leather pants', 'joggers']\n shoes_chilly = ['sneakers', 'loafers']\n shoes_cold = ['ankle boots', 'over the knee boots', 'knee high boots']\n shoes_hot = ['sandals', 'slides']\n \n # The if/elif/else loop, using random from ramdon package chooses a bottom from the list that temp belongs to.\n if temp == 'chilly':\n choice_1 = random.choice(bottoms_chilly)\n choice_2 = random.choice(shoes_chilly)\n elif temp == 'hot':\n choice_1 = random.choice(bottoms_hot)\n choice_2 = random.choice(shoes_hot)\n elif temp == 'cold':\n choice_1 = random.choice(bottoms_cold)\n choice_2 = random.choice(bottoms_cold)\n else:\n choice_1 = None\n choice_2 = None\n \n return choice_1, choice_2\n\n#Function on mix of colors\n#How about two colors come back\n\ndef colors_mix(color):\n \"\"\"Given a primary color it randomly chooses a color that matches. \n \n Parameters\n ----------\n color : str\n The color of the top the student wants to wear. \n \n Returns\n -------\n choice : str\n The color that matches the given color of the top. \n \"\"\"\n \n lst_primary = ['black', 'white', 'red', 'yellow', 'blue']\n white_mix = ['black', 'red', 'yellow', 'blue', 'cyan', 'orange', 'pink','violet', 'indigo','chartreuse', 'orange']\n black_mix = ['white', 'red', 'yellow', 'blue', 'cyan', 'orange', 'pink','violet', 'indigo','chartreuse', 'orange']\n red_mix = ['cyan', 'orange', 'pink']\n blue_mix = ['yellow', 'violet', 'indigo']\n yellow_mix = ['blue', 'chartreuse', 'orange']\n \n # Makes the string all lowercase\n color = color.lower()\n \n #The first if/elif/else loop checks that the lowercase primary color is in our list to then assign a color that matches\n if color in lst_primary:\n # Then this loop uses random from the random package to choose a color from our list\n if color == 'black':\n choice = random.choice(black_mix)\n elif color == 'white':\n choice = random.choice(white_mix)\n elif color == 'red':\n choice = random.choice(red_mix)\n elif color == 'blue':\n choice = random.choice(blue_mix)\n elif color == 'yellow':\n choice = random.choice(yellow_mix)\n else:\n choice = None \n else:\n choice = 'color should be primary: black, white, red, blue or yellow'\n \n return choice\n\n#final function \n#should say goodbye \n\ndef farewell():\n \n name, temperature, top, color = greeting()\n feels_like_temp = weather(temperature)\n outfit = bottoms_shoes(feels_like_temp)\n final_color = colors_mix(color)\n \n print('Hello ' + name + ' your outfit is ' + outfit[0] + ' and ' + outfit[1])\n print('The color that matches with ' + color + ' is ' + final_color)\n \nfarewell()","repo_name":"avenerio/COGS18_Project","sub_path":"My_project/my_module/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":4660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"6062146532","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Sep 21 20:30:21 2019\r\n\r\n@author: x00423910\r\n\"\"\"\r\n\r\n\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport pandas as pd\r\nimport os\r\nimport random\r\n\r\n\r\ndef preProcessDataForOffLineInfer(fileName):\r\n #导入测试数据\r\n with open(fileName, \"r\") as rf:\r\n file_data = pd.read_csv(rf)\r\n file_data = np.array(file_data.get_values(), dtype=np.float32)\r\n print(\"fileName:\", fileName, \" shape of file data:\", file_data.shape)\r\n \r\n #至此,我们把fileName文件里的数据都读到file_test_set_data中了\r\n #此时的file_test_set_data是个维度为[XXX, 18]的数组\r\n #开始对每个数据样本构造数据特征\r\n test_xs = []\r\n for i in range(len(file_data)):\r\n org_data = file_data[i]\r\n #和训练代码中预处理一致地,我们需要构建之前的3个数据特征\r\n feature_dis_2d = np.sqrt(np.power(org_data[12]-org_data[1],2)+np.power(org_data[13]-org_data[2],2)) \r\n feature_RS_Power = org_data[8]\r\n feature_dis_3d = np.sqrt(np.power(org_data[12]-org_data[1],2)\r\n +np.power(org_data[13]-org_data[2],2)\r\n +np.power(org_data[14]-org_data[9],2))\r\n tmp_test_xs = [feature_dis_2d/100, feature_RS_Power, feature_dis_3d/100]\r\n test_xs.append(tmp_test_xs)\r\n #将test_xs转换为numpy数组类型\r\n test_xs = np.array(test_xs) \r\n print(\"shape of test_xs:\", test_xs.shape) \r\n return test_xs\r\n\r\n\r\ndef infer(fileName):\r\n test_xs = preProcessDataForOffLineInfer(fileName)\r\n \r\n #从保存的模型文件中将模型加载回来\r\n with tf.Session(graph=tf.Graph()) as sess:\r\n tf.saved_model.loader.load(sess, [\"serve\"], \"./model_0922\")\r\n graph = tf.get_default_graph()\r\n x = sess.graph.get_tensor_by_name('haha_input_x:0')\r\n y = sess.graph.get_tensor_by_name('haha_output_y:0')\r\n infer_y_value = sess.run(y, feed_dict={x: test_xs})\r\n print(\"shape of infer_y_value:\", infer_y_value.shape)\r\n #保存结果为csv文件 \r\n np.savetxt(fileName+\"_infer_res.csv\", infer_y_value, delimiter=',')\r\n \r\n\r\n#test_xs = preProcessDataForOffLineInfer(os.path.join(\"test_set\",\"test_112501.csv\"))\r\ninfer(os.path.join(\"test_set\",\"test_112501.csv\"))\r\n","repo_name":"Aplicity/Huawei_shumo_LSTM","sub_path":"shumo_Demo/off_line_infer_code/off_line_infer_code.py","file_name":"off_line_infer_code.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"16"}
+{"seq_id":"32444668448","text":"\nimport grid2op\nimport warnings\nimport unittest\nimport pdb\n\n\nclass Issue533Tester(unittest.TestCase):\n def setUp(self) -> None:\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\")\n self.env = grid2op.make('l2rpn_neurips_2020_track1',\n test=True,\n _add_to_name=type(self).__name__,\n )\n self.env.seed(0)\n return super().setUp()\n \n def tearDown(self):\n self.env.close()\n \n def test_issue_as_serializable_dict(self):\n actions = self.env.action_space.get_all_unitary_topologies_set(self.env.action_space, sub_id=1) \n actions[1].as_serializable_dict()\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"rte-france/Grid2Op","sub_path":"grid2op/tests/test_issue_533.py","file_name":"test_issue_533.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","stars":240,"dataset":"github-code","pt":"16"}
+{"seq_id":"38189510462","text":"# AND function calculation between an odd number of XOR masked data shares\r\n# for every i this algorithm calculates:\r\n# Ci = [XOR(k!=i: Ak) AND XOR(j!=i: Bj)] XOR (Ai AND Bi)\r\n\r\n# The generic parameters enable arbitrary wide words to be AND-ed which consist of arbitrary odd\r\n# number masked shares. The algorithm does not work with an even number of shares due to its math\r\n# properties!\r\n\r\ndef masked_AND_rolled_out(am, bm):\r\n #any non-zero offset creates non-completeness, can even be random\r\n offset = 1\r\n #calculate AND between masked values\r\n cm = [am[i] & bm[i] for i in range(r)]\r\n #calculating correction terms\r\n for i in range(r):\r\n summa = 0\r\n #calculating no parities between all but 1 Ak and Bj bits which could cause unmasking\r\n for j in range(r):\r\n if i==j:\r\n continue\r\n summa ^= am[i] & bm[j]\r\n #addig correction term to the particular output share\r\n #which is the \"AND\" between the parities\r\n cm[i-offset] ^= summa\r\n return cm\r\n\r\n# BEGIN TESTING\r\n\r\na = 0x76857f6f\r\nb = 0x5432f1f2\r\nprint(\"A: \", hex(a))\r\nprint(\"B: \", hex(b))\r\nprint(\"AND: \", hex(a & b))\r\n\r\n# preparing odd pieces of random numbers for masking\r\n# the algorithm doesn't work with an even number of shares!\r\n\r\nr = 7 #6 #uncomment to test even number of shares\r\n\r\nra =[0x67978544,\r\n 0xa6f328ab,\r\n 0x68979586,\r\n 0xa76ef4bc,\r\n 0xc9876d3e, # comment to test even number of shares\r\n 0xa7656b36] \r\n\r\nrb =[0x6abdc744,\r\n 0x895728ab,\r\n 0xfe45c8d6,\r\n 0xc9876d3e,\r\n 0xe346a867, # comment to test even number of shares\r\n 0x86f675ed] \r\n\r\n# the sum of the masks has to be zero at first...*1\r\nrasum = 0\r\nfor ma in ra:\r\n rasum ^= ma\r\nra.append(rasum)\r\nrbsum = 0\r\nfor mb in rb:\r\n rbsum ^= mb\r\nrb.append(rbsum)\r\n\r\n# *1...so that adding a and b to any arbitrary random number yields valid shares\r\nam = ra\r\nam[2] ^= a #index is arbitrary\r\nbm = rb\r\nbm[r-2] ^= b #index is arbitrary\r\n\r\n# test vectors for VHDL code\r\n#for s in am:\r\n# print(hex(s))# test vectors for VHDL code\r\n#for s in bm:\r\n# print(hex(s))\r\n\r\n# double checking the sum of shares\r\na = 0\r\nb = 0\r\nfor i in range(r):\r\n a ^= am[i]\r\n b ^= bm[i]\r\nprint(\"A sum: \", hex(a))\r\nprint(\"B sum: \", hex(b))\r\n\r\n# AND calculation between masked shares\r\ncm = masked_AND_rolled_out(am, bm)\r\n\r\n# test vectors for VHDL code\r\n#for s in cm:\r\n# print(hex(s))\r\n\r\n#summing up the result shares\r\nc = 0\r\nfor k in range(len(cm)):\r\n c ^= cm[k]\r\nprint(\"Result: \", hex(c))\r\nprint(\"Correct: \", c == a&b)","repo_name":"InfamousTechnician/Side_channel_attack_countermeasures","sub_path":"masked_AND_by_me/rolled_out_masked_and.py","file_name":"rolled_out_masked_and.py","file_ext":"py","file_size_in_byte":2572,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"6780018669","text":"# improvements:\n# use kellylist dataset to use more frequently used words as this shit comes up with some weird ass words\n\nimport json\n\nwith open(\"svenska-ord.json\",\"r\") as f:\n data = json.load(f)\n\ndef generate5WordFile(data):\n newData = [word.lower() for word in data if len(word) == 5 and (\" \" not in word) and (\"-\" not in word)]\n with open(\"sample.json\", \"w\") as outfile:\n json.dump(newData, outfile, ensure_ascii=False)\n\n","repo_name":"theojohnhenry/ordle","sub_path":"json/dataprocess.py","file_name":"dataprocess.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"74152213449","text":"from datetime import datetime, timedelta\nimport os\nfrom airflow import DAG\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom airflow.operators import (StageToRedshiftOperator, LoadFactDimensionOperator,\n DataQualityOperator)\nfrom helpers import SqlQueries\nfrom airflow.models import Variable\n\n\n#/opt/airflow/start.sh\n\ndefault_args = {\n 'owner': 'udacity',\n 'start_date': datetime(2022, 5, 29),\n 'depends_on_past': False,\n 'retries': 3,\n 'retry_delay': 300,\n 'catchup': False,\n 'email_on_retry': False\n}\n\ndag = DAG('election_data_dag',\n default_args=default_args,\n description='Load and transform brazil election data in Redshift',\n schedule_interval='0 * * * *',\n max_active_runs=1\n )\n\nstart_operator = DummyOperator(task_id='Begin_execution', dag=dag)\n\nwait_operator = DummyOperator(task_id='Load_complete', dag=dag)\n\n\nstage_candidates_data_to_redshift = StageToRedshiftOperator(\n task_id='stage_candidates_data_task',\n dag=dag,\n redshift_conn_id='redshift',\n create_table_query=SqlQueries.create_staging_candidates,\n destination_schema='raw_data',\n destination_table='election_candidates',\n s3_path='s3://udacity-brazil-election-votes/consulta_cand/',\n file_format= 'csv',\n copy_parameters=\" delimiter as ',' truncatecolumns IGNOREHEADER 1 blanksasnull emptyasnull\",\n aws_credentials='aws_credentials'\n)\n\nstage_votes_data_to_redshift = StageToRedshiftOperator(\n task_id='stage_votes_data_task',\n dag=dag,\n redshift_conn_id='redshift',\n create_table_query=SqlQueries.create_staging_votes,\n destination_schema='raw_data',\n destination_table='election_votes',\n s3_path='s3://udacity-brazil-election-votes/votacao_secao/',\n file_format= 'csv',\n copy_parameters=\"delimiter as ',' truncatecolumns IGNOREHEADER 1 blanksasnull emptyasnull\",\n aws_credentials='aws_credentials'\n)\n\n\nload_dim_candidate_table = LoadFactDimensionOperator(\n task_id='load_dim_candidate_table_task',\n dag=dag,\n redshift_conn_id=\"redshift\",\n destination_schema=\"dim\",\n destination_table=\"candidate\",\n create_table_query=SqlQueries.create_dim_candidate,\n insert_table_query=SqlQueries.insert_dim_candidate\n)\n\nload_dim_date_table = LoadFactDimensionOperator(\n task_id='load_dim_date_table_task',\n dag=dag,\n redshift_conn_id=\"redshift\",\n destination_schema=\"dim\",\n destination_table=\"date\",\n create_table_query=SqlQueries.create_dim_date,\n insert_table_query=SqlQueries.insert_dim_date\n)\n\nload_dim_election_table = LoadFactDimensionOperator(\n task_id='load_dim_election_table_task',\n dag=dag,\n redshift_conn_id=\"redshift\",\n destination_schema=\"dim\",\n destination_table=\"election\",\n create_table_query=SqlQueries.create_dim_election,\n insert_table_query=SqlQueries.insert_dim_election\n)\n\nload_dim_party_table = LoadFactDimensionOperator(\n task_id='load_dim_party_table_task',\n dag=dag,\n redshift_conn_id=\"redshift\",\n destination_schema=\"dim\",\n destination_table=\"party\",\n create_table_query=SqlQueries.create_dim_party,\n insert_table_query=SqlQueries.insert_dim_party\n)\n\nload_dim_location_table = LoadFactDimensionOperator(\n task_id='load_dim_location_table_task',\n dag=dag,\n redshift_conn_id=\"redshift\",\n destination_schema=\"dim\",\n destination_table=\"location\",\n create_table_query=SqlQueries.create_dim_location,\n insert_table_query=SqlQueries.insert_dim_location\n)\n\nload_fact_votes_table = LoadFactDimensionOperator(\n task_id='load_fact_votes_table_task',\n dag=dag,\n redshift_conn_id=\"redshift\",\n destination_schema=\"fact\",\n destination_table=\"votes\",\n create_table_query=SqlQueries.create_fact_votes,\n insert_table_query=SqlQueries.insert_fact_votes\n)\n\nrun_quality_checks_dim_location = DataQualityOperator(\n task_id='run_quality_checks_dim_location_task',\n dag=dag,\n redshift_conn_id='redshift',\n table_schema='dim',\n table='location',\n id_column='id',\n checks=['unique_key',\n 'load_successful']\n)\n\nrun_quality_checks_dim_date = DataQualityOperator(\n task_id='run_quality_checks_dim_date_task',\n dag=dag,\n redshift_conn_id='redshift',\n table_schema='dim',\n table='date',\n id_column='date',\n checks=['unique_key',\n 'load_successful']\n)\n\nrun_quality_checks_dim_election = DataQualityOperator(\n task_id='run_quality_checks_dim_election_task',\n dag=dag,\n redshift_conn_id='redshift',\n table_schema='dim',\n table='election',\n id_column='id',\n checks=['unique_key',\n 'load_successful']\n)\n\nrun_quality_checks_dim_candidate = DataQualityOperator(\n task_id='run_quality_checks_dim_candidate_task',\n dag=dag,\n redshift_conn_id='redshift',\n table_schema='dim',\n table='candidate',\n id_column='cpf_number',\n checks=['unique_key',\n 'load_successful']\n)\n\nrun_quality_checks_dim_party = DataQualityOperator(\n task_id='run_quality_checks_dim_party_task',\n dag=dag,\n redshift_conn_id='redshift',\n table_schema='dim',\n table='party',\n id_column='id',\n checks=['unique_key',\n 'load_successful']\n)\n\nrun_quality_checks_fact_votes = DataQualityOperator(\n task_id='run_quality_checks_fact_votes_task',\n dag=dag,\n redshift_conn_id='redshift',\n table_schema='fact',\n table='votes',\n checks=['load_successful']\n)\n\nend_operator = DummyOperator(task_id='Stop_execution', dag=dag)\n\nstart_operator >> stage_candidates_data_to_redshift >> wait_operator\nstart_operator >> stage_votes_data_to_redshift >> wait_operator\n\nwait_operator >> load_dim_candidate_table >> run_quality_checks_dim_candidate >> end_operator\nwait_operator >> load_dim_date_table >> run_quality_checks_dim_date >> end_operator\nwait_operator >> load_dim_party_table >> run_quality_checks_dim_party >> end_operator\nwait_operator >> load_dim_location_table >> run_quality_checks_dim_location >> end_operator\nwait_operator >> load_dim_election_table >> run_quality_checks_dim_election >> end_operator\nwait_operator >> load_fact_votes_table >> run_quality_checks_fact_votes >> end_operator\n\n\n\n","repo_name":"betinamehl/udacity_de_nanodegree","sub_path":"capstone_project/airflow/dags/election_data_dag.py","file_name":"election_data_dag.py","file_ext":"py","file_size_in_byte":6171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"18710593687","text":"import sys\n\nn, l = map(int, input().split())\n\ns = [input() for i in range(n)]\n\ns.sort()\n\nmin_str = \"\"\n\nfor item in s:\n min_str += item\n\nprint(\"{}\".format(min_str))","repo_name":"shio408/AtCoderBeginnerContest-practice","sub_path":"question32.py","file_name":"question32.py","file_ext":"py","file_size_in_byte":166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"17549977051","text":"import requests\r\nimport yaml\r\n\r\nyaml_path = './config.yaml'\r\n\r\ndef map_get(center, markers=None):\r\n with open(yaml_path, 'r') as f:\r\n cfg = yaml.load(f.read(), Loader = yaml.FullLoader)\r\n ak = cfg['API']['ak']\r\n map_get_url = cfg['API']['map_get_url']\r\n zoom = cfg['API']['zoom']\r\n width = cfg['API']['width']\r\n height = cfg['API']['height']\r\n markerStyles = cfg['API']['markerStyles']\r\n scale = cfg['API']['scale']\r\n \r\n params = { # 参考文档:https://lbsyun.baidu.com/index.php?title=static\r\n 'ak': ak,\r\n 'center': center,\r\n 'zoom': zoom,\r\n 'width': width,\r\n 'height': height,\r\n 'markerStyles': markerStyles,\r\n 'scale': scale,\r\n }\r\n\r\n params['markers'] = markers if markers else center # 显示中心点位置或者船的位置\r\n # print(params)\r\n\r\n response = requests.get(map_get_url, params=params)\r\n # with open('D:/project/original_map/map.html', 'wb') as f:\r\n # f.write(response.content)\r\n with open('./original_map/current_map.png', 'wb') as f:\r\n f.write(response.content)","repo_name":"NicerY/plant_seg_demo","sub_path":"map/map_get.py","file_name":"map_get.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"18675389659","text":"from suds.client import Client\nfrom suds.xsd.doctor import ImportDoctor, Import\nimport requests\nimport json\nimport pytest\nimport datetime\n\nurl = \"http://www.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx?wsdl\"\n\nimp = Import('http://www.w3.org/2001/XMLSchema', location='http://www.w3.org/2001/XMLSchema.xsd')\n\nimp.filter.add('http://WebXml.com.cn')\n\n# doctor = ImportDoctor(imp)\n# client = Client(url,doctor=doctor)\n# print(client.service.getCountryCityByIp(\"117.28.35.18\"))\n# rsp = requests.get(url)\n\n# print(rsp.text)\n\ndata = '''\n\n \n \n \n \n 117.75.179.13\n \n \n'''\n\n# rsp = requests.post(url=url,data=data.encode(\"utf-8\"))\n# print(rsp.text)\n\n\n'''\ndata = [\"13588620187\",\"135886236187\",\"13188620187\"]\n@pytest.fixture(params=data,scope=\"module\")\ndef getuse(request):\n data = request.param\n url1 =\"https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel={}\".format(data)\n#data1 = json.dumps(data1)\n session = requests.Session()\n rsp = session.get(url = url1)\n\n yield rsp\n with open('1.txt','a') as f:\n f.write(rsp.text)\n\ndef test_case(getuse):\n assert \"mts\" in getuse.text ,\"mts 不存在\"\ndef test_case1(getuse):\n assert getuse.status_code ==200 ,\"访问失败\"\ndef test_case2(getuse):\n assert \"province\" in getuse.text, \"province 不存在\"\ndef test_case3(getuse):\n assert \"catName\" in getuse.text, \"catName 不存在\"\n\n\nif __name__ == '__main__':\n pytest.main([\"C:/Users/Administrator/PycharmProjects/untitled/123test/lianxi02.py\"])\n'''\nimport itertools\n\n\ndef A(l):\n for i in l:\n if i % 2 == 0:\n yield i\n\n\nl = [1, 2, 3, 4, 5, 6, 7, 9]\nl1 = [1, 2, 3, 4, 5, 6, 7, 9]\n\n\ndef B(l):\n n = 0\n for i in A(l):\n n += i\n return n\n\n\n# print(B(l))\nz = sum(i for i in l if i % 2 == 0)\n# print(z)\n\nfor a, b in itertools.product(l, l1):\n if a + b == 10:\n pass\n #print(a, b)\n# print(a,b)\nfor i in itertools.islice(l,0,None,2):\n print(i)\n","repo_name":"shiqinghuana/Python","sub_path":"123test/lianxi02.py","file_name":"lianxi02.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"10250734585","text":"import skimage\n\nimport numpy as np\nimport scipy\nimport skimage\n\nimport numba\nimport pandas as pd\n\nfrom glob import glob\nimport os\n\nfrom ._tqdm import tqdm\n\ndef lowres_image_iterator(path, img_as_float=True):\n\t\"\"\"\n\tIterator over all of a scene's low-resolution images (LR*.png) and their\n\tcorresponding status maps (QM*.png).\n\t\n\tReturns at each iteration a `(l, c)` tuple, where:\n\t* `l`: matrix with the loaded low-resolution image (values as np.uint16 or\n\t np.float64 depending on `img_as_float`),\n\t* `c`: the image's corresponding \"clear pixel?\" boolean mask.\n\t\n\tScenes' image files are described at:\n\thttps://kelvins.esa.int/proba-v-super-resolution/data/\n\t\"\"\"\n\tpath = path if path[-1] in {'/', '\\\\'} else (path + '/')\n\tfor f in glob(path + 'LR*.png'):\n\t\tq = f.replace('LR', 'QM')\n\t\tl = skimage.io.imread(f, dtype=np.uint16)\n\t\tc = skimage.io.imread(q, dtype=np.bool)\n\t\tif img_as_float:\n\t\t\tl = skimage.img_as_float64(l)\n\t\tyield (l, c)\n\n\ndef bicubic_upscaling(img):\n \"\"\"\n Compute a bicubic upscaling by a factor of 3.\n \"\"\"\n r = skimage.transform.rescale(img, scale=3, order=3, mode='edge',\n anti_aliasing=False, multichannel=False)\n # NOTE: Don't change these options. They're required by `baseline_upscale`.\n # http://scikit-image.org/docs/dev/api/skimage.transform.html#skimage.transform.rescale\n # http://scikit-image.org/docs/dev/api/skimage.transform.html#skimage.transform.warp\n return r\n\n\ndef baseline_upscale(path):\n\t\"\"\"\n\tReimplementation of the image enhancement operation performed by the\n\tbaseline code (`generate_sample_submission.py`) provided in:\n\thttps://kelvins.esa.int/proba-v-super-resolution/submission-rules/\n\t\n\t\t\"takes all low resolution images that have the maximum amount of clear\n\t\tpixels, computes a bicubic upscaling by a factor of 3 and averages their\n\t\tpixel intensities.\"\n\t\n\tThis function takes as argument the `path` to a single scene, and returns\n\tthe matrix with the scene's enhanced image.\n\t\"\"\"\n\tclearance = {}\n\tfor (l, c) in lowres_image_iterator(path, img_as_float=True):\n\t\tclearance.setdefault(c.sum(), []).append(l)\n\t\n\t# take all the images that have the same maximum clearance\n\timgs = max(clearance.items(), key=lambda i: i[0])[1]\n\t\n\tsr = np.mean([\n\t\tbicubic_upscaling(i)\n\t\tfor i in imgs\n\t\t], axis=0)\n\t\n\treturn sr\n\n\n\ndef central_tendency(images, agg_with='median',\n\t only_clear=False, fill_obscured=False,\n\t img_as_float=True):\n\t\"\"\"\n\tAggregate the given `images` through a statistical central tendency measure,\n\tchosen by setting `agg_with` to either 'mean', 'median' or 'mode'.\n\t\n\tExpects `images` to be a list of `(image, status map)` tuples.\n\tShould `images` be a string, it's interpreted as the path to a scene's\n\tfiles. The code will then aggregate that scene's low resolution images\n\t(LR*.png), while taking also into account their status maps (QM*.png).\n\t\n\tWill optionally aggregate only images' clear pixels (if `only_clear=True`)\n\tby using the information in images' corresponding status maps.\n\t\n\tIn some scenes, some pixels are obscured in all of the low-resolution\n\timages. Aggregation with mean/median will return np.nan for those pixels,\n\tand aggregation with mode will return 0.0.\n\tIf called with `fill_obscured=True` those pixels will be filled with the\n\t`agg_with` aggregate of the values at all those obscured pixels. Setting\n\t`fill_obscured` to one of 'mean', 'median' or 'mode' will indicate that is\n\tthe measure that should be used to aggregate obscured pixels.\n\t\"\"\"\n\tagg_opts = {\n\t\t'mean' : lambda i: np.nanmean(i, axis=0),\n\t\t'median' : lambda i: np.nanmedian(i, axis=0),\n\t\t'mode' : lambda i: scipy.stats.mode(i, axis=0, nan_policy='omit').mode[0],\n\t\t}\n\tagg = agg_opts[agg_with]\n\t\n\timgs = []\n\tobsc = []\n\t\n\tif isinstance(images, str):\n\t\timages = lowres_image_iterator(images, img_as_float or only_clear)\n\telif only_clear:\n\t\t# Images were given by the caller, rather than loaded here.\n\t\t# Because `only_clear=True`, we generate copies of all lr images, so the\n\t\t# function will have no unintended side-effects on the caller's side.\n\t\timages = [(l.copy(), c) for (l,c) in images]\n\t\n\tfor (l, c) in images:\n\t\t\n\t\tif only_clear:\n\t\t\t\n\t\t\t# keep track of the values at obscured pixels\n\t\t\tif fill_obscured != False:\n\t\t\t\to = l.copy()\n\t\t\t\to[c] = np.nan\n\t\t\t\tobsc.append(o)\n\t\t\t\n\t\t\t# replace values at obscured pixels with NaNs\n\t\t\tl[~c] = np.nan\n\t\t\n\t\timgs.append(l)\n\t\n\t# aggregate the images\n\twith np.warnings.catch_warnings(): ## https://stackoverflow.com/a/29348184\n\t\t# suppress the warnings that originate when `only_clear=True`\n\t\t# but some pixels are never clear in any of the images\n\t\tnp.warnings.filterwarnings('ignore', r'All-NaN (slice|axis) encountered')\n\t\tnp.warnings.filterwarnings('ignore', r'Mean of empty slice')\n\t\t\n\t\tagg_img = agg(imgs)\n\t\t\n\t\tif only_clear and fill_obscured != False:\n\t\t\tif isinstance(fill_obscured, str):\n\t\t\t\tagg = agg_opts[fill_obscured]\n\t\t\tsome_clear = np.isnan(obsc).any(axis=0)\n\t\t\tobsc = agg(obsc)\n\t\t\tobsc[some_clear] = 0.0\n\t\t\tnp.nan_to_num(agg_img, copy=False)\n\t\t\tagg_img += obsc\n\t\n\treturn agg_img\n\n\ndef highres_image(path, img_as_float=True):\n\t\"\"\"\n\tLoad a scene's high resolution image and its corresponding status map.\n\t\n\tReturns a `(hr, sm)` tuple, where:\n\t* `hr`: matrix with the loaded high-resolution image (values as np.uint16 or\n\t np.float64 depending on `img_as_float`),\n\t* `sm`: the image's corresponding \"clear pixel?\" boolean mask.\n\t\n\tScenes' image files are described at:\n\thttps://kelvins.esa.int/proba-v-super-resolution/data/\n\t\"\"\"\n\tpath = path if path[-1] in {'/', '\\\\'} else (path + '/')\n\thr = skimage.io.imread(path + 'HR.png')\n\tsm = skimage.io.imread(path + 'SM.png')\n\tif img_as_float:\n\t\thr = skimage.img_as_float64(hr)\n\treturn (hr, sm)\n\t\n\n\ndef lowres_image_iterator(path, img_as_float=True):\n\t\"\"\"\n\tIterator over all of a scene's low-resolution images (LR*.png) and their\n\tcorresponding status maps (QM*.png).\n\t\n\tReturns at each iteration a `(l, c)` tuple, where:\n\t* `l`: matrix with the loaded low-resolution image (values as np.uint16 or\n\t np.float64 depending on `img_as_float`),\n\t* `c`: the image's corresponding \"clear pixel?\" boolean mask.\n\t\n\tScenes' image files are described at:\n\thttps://kelvins.esa.int/proba-v-super-resolution/data/\n\t\"\"\"\n\tpath = path if path[-1] in {'/', '\\\\'} else (path + '/')\n\tfor f in glob(path + 'LR*.png'):\n\t\tq = f.replace('LR', 'QM')\n\t\tl = skimage.io.imread(f)\n\t\tc = skimage.io.imread(q)\n\t\tif img_as_float:\n\t\t\tl = skimage.img_as_float64(l)\n\t\tyield (l, c)\n\t\n\n\n# [============================================================================]\n\n\ndef check_img_as_float(img, validate=True):\n\t\"\"\"\n\tEnsure `img` is a matrix of values in floating point format in [0.0, 1.0].\n\tReturns `img` if it already obeys those requirements, otherwise converts it.\n\t\"\"\"\n\tif not issubclass(img.dtype.type, np.floating):\n\t\timg = skimage.img_as_float64(img)\n\t# https://scikit-image.org/docs/dev/api/skimage.html#img-as-float64\n\t\n\tif validate:\n\t\t# safeguard against unwanted conversions to values outside the\n\t\t# [0.0, 1.0] range (would happen if `img` had signed values).\n\t\tassert img.min() >= 0.0 and img.max() <= 1.0\n\t\n\treturn img\n\t\n\n\n# [============================================================================]\n\n\ndef all_scenes_paths(base_path):\n\t\"\"\"\n\tGenerate a list of the paths to all scenes available under `base_path`.\n\t\"\"\"\n\tbase_path = base_path if base_path[-1] in {'/', '\\\\'} else (base_path + '/')\n\treturn [\n\t\tbase_path + c + s\n\t\tfor c in ['RED/', 'NIR/']\n\t\tfor s in sorted(os.listdir(base_path + c))\n\t\t]\n\t\n\n\ndef scene_id(scene_path, incl_channel=False):\n\t\"\"\"\n\tExtract from a scene's path its unique identifier.\n\t\n\tExamples\n\t--------\n\t>>> scene_id('probav/train/RED/imgset0559/')\n\t'imgset0559'\n\t>>> scene_id('probav/train/RED/imgset0559', incl_channel=True)\n\t'RED/imgset0559'\n\t\"\"\"\n\tsep = os.path.normpath(scene_path).split(os.sep)\n\tif incl_channel:\n\t\treturn '/'.join(sep[-2:])\n\telse:\n\t\treturn sep[-1]\n\t\n\n# [============================================================================]\n\ndef prepare_submission(images, scenes, subm_fname='submission.zip'):\n\t\"\"\"\n\tPrepare a set of images for submission.\n\t\n\tGiven a list of `images` (as matrices of shape (384, 384)), and the paths\n\tto the `scenes` to which they correspond, write a zip file containing all\n\timages as .png files, named after their scene's identification\n\t(example: imgset1160.png).\n\t\"\"\"\n\tassert len(images) == 290, '%d images provided, 290 expected.' % len(images)\n\tassert len(images) == len(scenes), \"Mismatch in number of images and scenes.\"\n\tassert subm_fname[-4:] == '.zip'\n\t\n\t# specific warnings we wish to ignore\n\twarns = [\n\t\t'tmp.png is a low contrast image',\n\t\t'Possible precision loss when converting from float64 to uint16']\n\t\n\twith np.warnings.catch_warnings():\n\t\tfor w in warns:\n\t\t\tnp.warnings.filterwarnings('ignore', w)\n\t\t\n\t\tprint('Preparing submission. Writing to \"%s\".' % subm_fname)\n\t\t\n\t\twith ZipFile(subm_fname, mode='w') as zf:\n\t\t\t\n\t\t\tfor img, scene in zip(tqdm(images), scenes):\n\t\t\t\tassert img.shape == (384, 384), \\\n\t\t\t\t\t'Wrong dimensions in image for scene %s.' % scene\n\t\t\t\t\n\t\t\t\tskimage.io.imsave('tmp.png', img)\n\t\t\t\tzf.write('tmp.png', arcname=scene_id(scene) + '.png')\n\t\t\n\t\tos.remove('tmp.png')\n \n \n# [============================================================================]\n\n\n# Baseline cPSNR values for the dataset's images. Used for normalizing scores.\n# (provided by the competition's organizers)\nbaseline_cPSNR = pd.read_csv(\n os.path.dirname(os.path.abspath(__file__)) + '/norm.csv',\n names = ['scene', 'cPSNR'],\n index_col = 'scene',\n sep = ' ')\n\n\ndef score_images(imgs, scenes_paths, *args):\n\t\"\"\"\n\tMeasure the overall (mean) score across multiple super-resolved images.\n\t\n\tTakes as input a sequence of images (`imgs`), a sequence with the paths to\n\tthe corresponding scenes (`scenes_paths`), and optionally a sequence of\n\t(hr, sm) tuples with the pre-loaded high-resolution images of those scenes.\n\t\"\"\"\n\treturn np.mean([\n#\t\tscore_image(*i)\n\t\tscore_image_fast(*i)\n\t\tfor i in zip(tqdm(imgs), scenes_paths, *args)\n\t\t])\n\n\ndef score_image(sr, scene_path, hr_sm=None):\n\t\"\"\"\n\tCalculate the individual score (cPSNR, clear Peak Signal to Noise Ratio) for\n\t`sr`, a super-resolved image from the scene at `scene_path`.\n\t\n\tParameters\n\t----------\n\tsr : matrix of shape 384x384\n\t\tsuper-resolved image.\n\tscene_path : str\n\t\tpath where the scene's corresponding high-resolution image can be found.\n\thr_sm : tuple, optional\n\t\tthe scene's high resolution image and its status map. Loaded if `None`.\n\t\"\"\"\n\thr, sm = highres_image(scene_path) if hr_sm is None else hr_sm\n\t\n\t# \"We assume that the pixel-intensities are represented\n\t# as real numbers ∈ [0,1] for any given image.\"\n\t#sr = check_img_as_float(sr)\n\t#hr = check_img_as_float(hr, validate=False)\n\t\n\t# \"Let N(HR) be the baseline cPSNR of image HR as found in the file norm.csv.\"\n\tN = baseline_cPSNR.loc[scene_id(scene_path)][0]\n\t\n\t# \"To compensate for pixel-shifts, the submitted images are\n\t# cropped by a 3 pixel border, resulting in a 378x378 format.\"\n\tsr_crop = sr[3 : -3, 3 : -3]\n\t\n\tcrop_scores = []\n\t\n\tfor (hr_crop, sm_crop) in hr_crops(hr, sm):\n\t\t# values at the cropped versions of each image that\n\t\t# fall in clear pixels of the cropped `hr` image\n\t\t_hr = hr_crop[sm_crop]\n\t\t_sr = sr_crop[sm_crop]\n\t\t\n\t\t# \"we first compute the bias in brightness b\"\n\t\tpixel_diff = _hr - _sr\n\t\tb = np.mean(pixel_diff)\n\t\t\n\t\t# \"Next, we compute the corrected clear mean-square\n\t\t# error cMSE of SR w.r.t. HR_{u,v}\"\n\t\tpixel_diff -= b\n\t\tcMSE = np.mean(pixel_diff * pixel_diff)\n\t\t\n\t\t# \"which results in a clear Peak Signal to Noise Ratio of\"\n\t\tcPSNR = -10. * np.log10(cMSE)\n\t\t\n\t\t# normalized cPSNR\n\t\tcrop_scores.append(N / cPSNR)\n#\t\tcrop_scores.append(cMSE)\n\t\n\t# \"The individual score for image SR is\"\n\tsr_score = min(crop_scores)\n#\tsr_score = N / (-10. * np.log10(min(crop_scores)))\n\t\n\treturn sr_score\n\n\n# [===================================]\n\n\ndef hr_crops(hr, sm):\n\t\"\"\"\n\t\"We denote the cropped 378x378 images as follows: for all u,v ∈ {0,…,6},\n\tHR_{u,v} is the subimage of HR with its upper left corner at coordinates\n\t(u,v) and its lower right corner at (378+u, 378+v).\"\n\t-- https://kelvins.esa.int/proba-v-super-resolution/scoring/\n\t\"\"\"\n\tnum_cropped = 6\n\tmax_u, max_v = np.array(hr.shape) - num_cropped\n\t\n\tfor u in range(num_cropped + 1):\n\t\tfor v in range(num_cropped + 1):\n\t\t\tyield hr[u : max_u + u, v : max_v + v], \\\n\t\t\t\t sm[u : max_u + u, v : max_v + v]\n\t\n\n \n# [============================================================================]\n\n\ndef score_image_fast(sr, scene_path, hr_sm=None):\n \"\"\"\n Calculate the individual score (cPSNR, clear Peak Signal to Noise Ratio) for\n `sr`, a super-resolved image from the scene at `scene_path`.\n\n Parameters\n ----------\n sr : matrix of shape 384x384\n super-resolved image.\n scene_path : str\n path where the scene's corresponding high-resolution image can be found.\n hr_sm : tuple, optional\n the scene's high resolution image and its status map. Loaded if `None`.\n \"\"\"\n\n hr, sm = highres_image(scene_path) if hr_sm is None else hr_sm\n\n # \"We assume that the pixel-intensities are represented\n # as real numbers ∈ [0,1] for any given image.\"\n #sr = check_img_as_float(sr)\n #hr = check_img_as_float(hr, validate=False)\n\n # \"Let N(HR) be the baseline cPSNR of image HR as found in the file norm.csv.\"\n N = baseline_cPSNR.loc[scene_id(scene_path)][0]\n\n return score_against_hr(sr, hr, sm, N)\n\ndef score_image_fast_normalized(sr, hr, scene_path):\n \"\"\"\n Calculate the individual score (cPSNR, clear Peak Signal to Noise Ratio) for\n `sr`, a super-resolved image from the scene at `scene_path`.\n\n Parameters\n ----------\n sr : matrix of shape 384x384\n super-resolved image.\n scene_path : str\n path where the scene's corresponding high-resolution image can be found.\n hr_sm : tuple, optional\n the scene's high resolution image and its status map. Loaded if `None`.\n \"\"\"\n\n # \"We assume that the pixel-intensities are represented\n # as real numbers ∈ [0,1] for any given image.\"\n #sr = check_img_as_float(sr)\n #hr = check_img_as_float(hr, validate=False)\n\n # \"Let N(HR) be the baseline cPSNR of image HR as found in the file norm.csv.\"\n N = baseline_cPSNR.loc[scene_id(scene_path)][0]\n\n return score_against_hr_normalized(sr, hr, N)\n\n\n@numba.jit(nopython=True, parallel=True)\ndef score_against_hr_normalized(sr, hr, N):\n \"\"\"\n Numba-compiled version of the scoring function.\n \"\"\"\n num_cropped = 6\n max_u, max_v = np.array(hr.shape) - num_cropped\n\n # \"To compensate for pixel-shifts, the submitted images are\n # cropped by a 3 pixel border, resulting in a 378x378 format.\"\n c = num_cropped // 2\n sr_crop = sr[c : -c, c : -c].ravel()\n\n #crop_scores = []\n cMSEs = np.zeros((num_cropped + 1, num_cropped + 1), np.float64)\n\n for u in numba.prange(num_cropped + 1):\n for v in numba.prange(num_cropped + 1):\n\n # \"We denote the cropped 378x378 images as follows: for all u,v ∈\n # {0,…,6}, HR_{u,v} is the subimage of HR with its upper left corner\n # at coordinates (u,v) and its lower right corner at (378+u, 378+v)\"\n hr_crop = hr[u : max_u + u, v : max_v + v].ravel()\n\n # \"we first compute the bias in brightness b\"\n pixel_diff = hr_crop - sr_crop\n b = np.nanmean(pixel_diff)\n\n # \"Next, we compute the corrected clear mean-square\n # error cMSE of SR w.r.t. HR_{u,v}\"\n pixel_diff -= b\n pixel_diff *= pixel_diff\n cMSE = np.nanmean(pixel_diff)\n\n # \"which results in a clear Peak Signal to Noise Ratio of\"\n #cPSNR = -10. * np.log10(cMSE)\n\n # normalized cPSNR\n #crop_scores.append(N / cPSNR)\n\n cMSEs[u, v] = cMSE\n\n # \"The individual score for image SR is\"\n #sr_score = min(crop_scores)\n sr_score = N / (-10. * np.log10(cMSEs.min()))\n\n return sr_score\n\n\n\n#@numba.jit('f8(f8[:,:], f8[:,:], b1[:,:], f8)', nopython=True, parallel=True)\n@numba.jit(nopython=True, parallel=True)\ndef score_against_hr(sr, hr, sm, N):\n \"\"\"\n Numba-compiled version of the scoring function.\n \"\"\"\n num_cropped = 6\n max_u, max_v = np.array(hr.shape) - num_cropped\n\n # \"To compensate for pixel-shifts, the submitted images are\n # cropped by a 3 pixel border, resulting in a 378x378 format.\"\n c = num_cropped // 2\n sr_crop = sr[c : -c, c : -c].ravel()\n\n # create a copy of `hr` with NaNs at obscured pixels\n # (`flatten` used to bypass numba's indexing limitations)\n hr_ = hr.flatten()\n hr_[(~sm).ravel()] = np.nan\n hr = hr_.reshape(hr.shape)\n\n #crop_scores = []\n cMSEs = np.zeros((num_cropped + 1, num_cropped + 1), np.float64)\n\n for u in numba.prange(num_cropped + 1):\n for v in numba.prange(num_cropped + 1):\n\n # \"We denote the cropped 378x378 images as follows: for all u,v ∈\n # {0,…,6}, HR_{u,v} is the subimage of HR with its upper left corner\n # at coordinates (u,v) and its lower right corner at (378+u, 378+v)\"\n hr_crop = hr[u : max_u + u, v : max_v + v].ravel()\n\n # \"we first compute the bias in brightness b\"\n pixel_diff = hr_crop - sr_crop\n b = np.nanmean(pixel_diff)\n\n # \"Next, we compute the corrected clear mean-square\n # error cMSE of SR w.r.t. HR_{u,v}\"\n pixel_diff -= b\n pixel_diff *= pixel_diff\n cMSE = np.nanmean(pixel_diff)\n\n # \"which results in a clear Peak Signal to Noise Ratio of\"\n #cPSNR = -10. * np.log10(cMSE)\n\n # normalized cPSNR\n #crop_scores.append(N / cPSNR)\n\n cMSEs[u, v] = cMSE\n\n # \"The individual score for image SR is\"\n #sr_score = min(crop_scores)\n sr_score = N / (-10. * np.log10(cMSEs.min()))\n\n return sr_score\n\n\n# [============================================================================]\n\n\nclass scorer(object):\n\t\n\tdef __init__(self, scene_paths, preload_hr=True):\n\t\t\"\"\"\n\t\tWrapper to `score_image()` that simplifies the scoring of multiple\n\t\tsuper-resolved images.\n\t\t\n\t\tThe scenes over which the scorer will operate should be given in\n\t\t`scene_paths`. This is either a sequence of paths to a subset of scenes\n\t\tor a string with a single path. In this case, it is interpreted as the\n\t\tbase path to the full dataset, and `all_scenes_paths()` will be used to\n\t\tlocate all the scenes it contains.\n\t\t\n\t\tScene paths are stored in the object's `.paths` variable.\n\t\tWhen scoring, only the super-resolved images need to be provided.\n\t\tThey are assumed to be in the same order as the scenes in `.paths`.\n\t\t\n\t\tIf the object is instantiated with `preload_hr=True` (the default),\n\t\tall scene's high-resolution images and their status maps will be\n\t\tpreloaded. When scoring they will be sent to `score_image()`, thus\n\t\tsaving computation time in repeated scoring, at the expense of memory.\n\t\t\"\"\"\n\t\tif isinstance(scene_paths, str):\n\t\t\tself.paths = all_scenes_paths(scene_paths)\n\t\telse:\n\t\t\tself.paths = scene_paths\n\t\t\n\t\tself.hr_sm = [] if not preload_hr else [\n\t\t\thighres_image(scn_path, img_as_float=True)\n\t\t\tfor scn_path in tqdm(self.paths, desc='Preloading hi-res images')]\n\t\t\n\t\tself.scores = []\n\t\t\n\t\n\tdef __call__(self, sr_imgs, per_image=False, progbar=True, desc=''):\n\t\t\"\"\"\n\t\tScore all the given super-resolved images (`sr_imgs`), which correspond\n\t\tto the scenes at the matching positions of the object's `.paths`.\n\t\t\n\t\tReturns the overall score (mean normalized cPSNR).\n\t\t\n\t\tAn additional value is returned if `per_image=True`: a list with each\n\t\timage's individual cPSNR score. In either case, this list remains\n\t\tavailable in the object's `.scores` variable until the next call.\n\t\t\"\"\"\n\t\tscenes_paths = tqdm(self.paths, desc=desc) if progbar else self.paths\n\t\thr_sm = [] if self.hr_sm == [] else [self.hr_sm]\n\t\t\n\t\tself.scores = [\n#\t\t\tscore_image(*i)\n\t\t\tscore_image_fast(*i)\n\t\t\tfor i in zip(sr_imgs, scenes_paths, *hr_sm)]\n\t\t\n\t\tassert len(self.scores) == len(self.paths)\n\t\t\n\t\tscore = np.mean(self.scores)\n\t\t\n\t\tif per_image:\n\t\t\treturn score, self.scores\n\t\telse:\n\t\t\treturn score\n \n","repo_name":"Ahaeflig/probaVSuperRes","sub_path":"supreshelper/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":20240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"23330953824","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"cpick\",\n version=\"0.1.3\",\n author=\"Toby Slight\",\n author_email=\"tslight@pm.me\",\n description=\"Curses List Picker\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/tslight/cpick\",\n install_requires=[\"columns\"],\n packages=setuptools.find_packages(),\n classifiers=(\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: ISC License (ISCL)\",\n \"Operating System :: OS Independent\",\n ),\n entry_points={\"console_scripts\": [\"cpick = cpick.__main__:main\"]},\n)\n","repo_name":"tslight/cpick","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"16"}
+{"seq_id":"32441529313","text":"import requests\nfrom bs4 import BeautifulSoup\nimport boto3\nimport json\n\ndef scrape_aruodas(event, context):\n page = requests.get('https://en.aruodas.lt/butai/vilniuje/puslapis/2/')\n soup = BeautifulSoup(page.content, 'html.parser')\n s3 = boto3.resource('s3', region_name='eu-west-2')\n\n for row in soup.select('tr.list-row td.list-adress h3 a'):\n place = {'website': 'aruodas'}\n headers = {\n 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'\n }\n\n print(row.attrs['href'])\n\n single_page = requests.get(row.attrs['href'], headers=headers)\n single_soup = BeautifulSoup(single_page.content, 'html.parser')\n name = single_soup.select('h1.obj-header-text')[0]\n place['name'] = name.text.strip()\n\n stats = single_soup.select('div.obj-stats dl dd')\n place['href'] = stats[0].text.strip()\n\n path = place['href'].split('lt/')[1].split('-')\n place['id'] = path[1]\n\n if path[0] == '1':\n place['house'] = False\n else:\n place['house'] = True\n\n place['created_at'] = stats[1].text.strip()\n place['updated_at'] = stats[2].text.strip()\n\n price = single_soup.select('.price-block .price-left .price-eur')[0].text.strip()\n place['price'] = int(price.replace(' ', '').replace('€', ''))\n\n for r in single_soup.select('.obj-details dt'):\n rt = r.text.strip()\n if rt == 'Plotas:':\n area = r.find_next().text.strip()\n place['area'] = float(area.replace(' m²', '').replace(',', '.'))\n if rt == 'Kambarių sk.:':\n place['rooms'] = int(r.find_next().text.strip())\n if rt == 'Metai:':\n place['year'] = int(r.find_next().text.strip())\n if rt == 'Įrengimas:':\n place['equipment'] = r.find_next().contents[0].strip()\n\n map_url = 'https://www.aruodas.lt/map/?id=' + place['href'].split('lt/')[1] + '&position=popup'\n map_page = requests.get(map_url, headers=headers)\n map_soup = BeautifulSoup(map_page.content, 'html.parser')\n\n for line in map_soup.prettify().splitlines():\n if 'var locationCoordinate =' in line:\n location = line.split('var locationCoordinate = ')[1].replace(\"'\", '').replace(';', '').split(',')\n place['lat'] = float(location[0])\n place['lng'] = float(location[1])\n\n s3.Object('chum-buket', place['id'] + \".json\").put(Body=json.dumps(place))\n\n return {\n 'message': 'Scrape those houses!',\n 'event': event\n }\n\n\nscrape_aruodas(1, 1)\n","repo_name":"Rhymond/home-scrape","sub_path":"handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":2728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"28079452212","text":"import random\nfrom tkinter import *\n\n\n# ================= Roll the dice ==============================\ndef roll(d, n, m):\n if n != 0:\n str1 = f\"{n} d{d}'s.\\n\"\n total = 0\n log = \"\"\n for i in range(n):\n roll = random.randint(1, d)\n total += roll + m\n if m > 0:\n log += f\"{roll}(+{m}) \"\n elif m < 0:\n log += f\"{roll}({m}) \"\n else:\n log += f\"{roll} \"\n str1 += \"Rolls: \" + log + \"\\n\"\n return total, str1\n return 0, \"\"\n\n# four - twenty (type of dice)\n# modDice - modifier per dice // modTotal - modifier at the end of the result\ndef dice_roller(four=0, six=0, eight=0, ten=0, twelve=0, hundred=0, twenty=0, modDice=0, modTotal=0):\n if four < 0 or six < 0 or eight < 0 or ten < 0 or twelve < 0 or hundred < 0 or twenty < 0:\n strEnd = \"Invalid number of dice!\"\n return strEnd\n else:\n result = 0\n stringResult = \"\\nRolling...\\n\"\n dice = [4, 6, 8, 10, 12, 100, 20]\n nDice = [four, six, eight, ten, twelve, hundred, twenty]\n for i in range(7):\n rolled = roll(dice[i], nDice[i], modDice)\n result += rolled[0]\n stringResult += rolled[1]\n if modTotal > 0:\n result += modTotal\n stringResult += f\"Modifier: +{modTotal}\\n\"\n elif modTotal < 0:\n result += modTotal\n stringResult += f\"Modifier: {modTotal}\"\n stringResult += f\"Total: {result}.\"\n return stringResult\n\n\n# ================= Interface ===================================\n# main\nwindow = Tk()\nwindow.title(\"Dice Roller v1.0\")\n\n# functions\ndef clickRoll():\n four = int(nFour.get()) # returns the value in the text box\n six = int(nSix.get())\n eight = int(nEight.get())\n ten = int(nTen.get())\n twelve = int(nTwelve.get())\n hundred = int(nHundred.get())\n twenty = int(nTwenty.get())\n dMod = int(modDie.get())\n tMod = int(modTotal.get())\n output.configure(state=\"normal\")\n output.insert(END, dice_roller(four, six, eight, ten,\n twelve, hundred, twenty, dMod, tMod))\n output.configure(state=\"disabled\")\n\n\ndef clickClear():\n nFour.delete(0, END)\n nFour.insert(0, 0)\n nSix.delete(0, END)\n nSix.insert(0, 0)\n nEight.delete(0, END)\n nEight.insert(0, 0)\n nTen.delete(0, END)\n nTen.insert(0, 0)\n nTwelve.delete(0, END)\n nTwelve.insert(0, 0)\n nHundred.delete(0, END)\n nHundred.insert(0, 0)\n nTwenty.delete(0, END)\n nTwenty.insert(0, 0)\n modDie.delete(0, END)\n modDie.insert(0, 0)\n modTotal.delete(0, END)\n modTotal.insert(0, 0)\n output.configure(state=\"normal\")\n output.delete(0.0, END)\n output.configure(state=\"disabled\")\n\n\n# text labels\nLabel(window, text=\"D4\", width=5).grid(row=1, column=0, sticky=W)\nLabel(window, text=\"D6\", width=5).grid(row=2, column=0, sticky=W)\nLabel(window, text=\"D8\", width=5).grid(row=3, column=0, sticky=W)\nLabel(window, text=\"D10\", width=5).grid(row=4, column=0, sticky=W)\nLabel(window, text=\"D12\", width=5).grid(row=5, column=0, sticky=W)\nLabel(window, text=\"D100\", width=5).grid(row=6, column=0, sticky=W)\nLabel(window, text=\"D20\", width=5).grid(row=7, column=0, sticky=W)\n\nLabel(window, text=\"Number\").grid(row=0, column=1)\nLabel(window, text=\"Dice Mod\").grid(row=0, column=2)\nLabel(window, text=\"Result\").grid(row=0, column=3, columnspan=2)\n\n# input\n# d4\nnFour = Entry(window, width=10)\nnFour.grid(row=1, column=1, sticky=W)\nnFour.insert(0, 0)\n\n# d6\nnSix = Entry(window, width=10)\nnSix.grid(row=2, column=1, sticky=W)\nnSix.insert(0, 0)\n\n# d8\nnEight = Entry(window, width=10)\nnEight.grid(row=3, column=1, sticky=W)\nnEight.insert(0, 0)\n\n# d10\nnTen = Entry(window, width=10)\nnTen.grid(row=4, column=1, sticky=W)\nnTen.insert(0, 0)\n\n# d12\nnTwelve = Entry(window, width=10)\nnTwelve.grid(row=5, column=1, sticky=W)\nnTwelve.insert(0, 0)\n\n# d100\nnHundred = Entry(window, width=10)\nnHundred.grid(row=6, column=1, sticky=W)\nnHundred.insert(0, 0)\n\n# d20\nnTwenty = Entry(window, width=10)\nnTwenty.grid(row=7, column=1, sticky=W)\nnTwenty.insert(0, 0)\n\n# mod\nLabel(window, text=\"Per Die\").grid(row=2, column=2, padx=10)\nmodDie = Entry(window, width=10)\nmodDie.insert(0, 0)\nmodDie.grid(row=3, column=2, sticky=W, padx=10)\n\nLabel(window, text=\"Total\").grid(row=5, column=2, padx=10)\nmodTotal = Entry(window, width=10)\nmodTotal.insert(0, 0)\nmodTotal.grid(row=6, column=2, sticky=W, padx=10)\n\n# roll button\nButton(window, text=\"Roll\", command=clickRoll).grid(row=7, column=3)\nButton(window, text=\"Clear\", command=clickClear).grid(row=7, column=4)\n\n# output\noutput = Text(window, wrap=WORD, width=20)\noutput.grid(row=1, column=3, rowspan=6, columnspan=2, sticky=W)\noutput.insert(END, \"Select your Dice!\\n\")\noutput.configure(state=\"disabled\")\n\n# run the main loop\nwindow.mainloop()\n\n\n# = TEST ========================================================\n# print(dice_roller(six=1,eight=2))\n","repo_name":"tomasteicol19452/DnD-Py","sub_path":"DiceRoller/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"17113277165","text":"import math \nimport numpy as np\nimport random\nimport sys\n\n#Helper Methods ------------------------------------------------------------------------\n# Finds the mean/centroid of a cluster.\ndef centerOfCluster(cluster):\n cluster = np.asarray(cluster)\n center =np.array([0,0])\n\n result = np.array([0,0])\n for i in range(len(cluster)):\n result = np.sum([cluster[i], result], axis = 0)\n\n numberOfPoints = len(cluster)\n if numberOfPoints > 0:\n result = result * (1 / numberOfPoints)\n return result\n else: \n print (\"A cluster is empty\")\n sys.exit()\n\n\n# Calculates the distance between 2 2d vectors. \ndef distVector(vectorA, vectorB):\n vectorA = np.asarray(vectorA)\n vectorB = np.asarray(vectorB)\n\n tem1 = np.subtract(vectorA[0], vectorB[0])\n tem2 = np.subtract(vectorA[1], vectorB[1])\n tem1 = np.power(tem1,2)\n tem2 = np.power(tem2,2)\n \n result = np.add(tem1,tem2)\n result = math.sqrt(result)\n \n return result\n\n\n# Calculates the sum of distance for all points in a clusters to its center.\ndef distClustSum(cluster):\n cluster = np.asarray(cluster)\n center = centerOfCluster(cluster)\n\n dist = 0\n for i in range(len(cluster)):\n temp = pow(distVector(center,cluster[i]),2)\n dist = temp + dist\n return dist\n\n#End helper methods\n#---------------------------------------------------------------------------------------\n\n#Calculates the TD2 measure for\ndef TD2(data):\n result = 0\n data = np.asarray(data)\n\n\n for i in range(len(data)):\n result = distClustSum(data[i]) + result\n return result\n\n# Is this forgy / Lloyd or not?\ndef kMeans(data):\n points = [item for sublist in data for item in sublist]\n k = len(data)\n clusters=[[]for i in range(k)]\n \n centroids = []\n for i in range(len(data)):\n centroids.append(centerOfCluster(data[i]))\n\n for x in points:\n lengths = []\n\n for i in centroids:\n lengths.append(distVector(x,i))\n # Find the centroid that are clossest to the point\n minimum = min(lengths)\n\n # Assign that point to the cluster, that centroid belongs too. \n cluster =lengths.index(minimum)\n \n for j in range(k):\n if cluster==j:\n clusters[j].append(x)\n \n return clusters\n\n#kMeansAlgo tager imod data og et k\n#data: En liste af lister af 2d punkter.\n#k: En liste af antal cluster vi gerne vil prøve at finde. \ndef kMeansAlgo(data,k):\n # points takes the list from data, anc uses list comprehension on it. \n points = [item for sublist in data for item in sublist]\n \n TD=[] # TD2squared soloutions for clusters\n for i in k:\n # lav k antal tomme clusters\n clusters=[[]for j in range(i)]\n for x in points:\n # tildel alle punkterne i vores data, tilfædigt i de k antal lister. \n random.choice(clusters).append(x)\n # As long as there are changes for kMeans update, otherwise calcule TD2 and end.\n while kMeans(clusters)!=clusters:\n clusters= kMeans(clusters)\n \n temptTD = TD2(clusters)\n #TD.append(TD2(clusters))\n print(\"Clusters with k =\", i,\"is:\", clusters, \"and TD2 =\", temptTD)\n TD.append(temptTD)\n #return TD # Har jeg udkommenteret fordi jeg ikke bruger den. Det er bare en liste af TD2 for \n # de forskellige clusters. \n\n\nsquares = [[1],[2]]\ntriangle = [[4],[6]]\ncircle = [[8],[9],[10]]\n\ndata = [squares,triangle,circle] \n\n#Her kører vi med værdierne som de er i grafen\nprint (\"k-means with initialie values set = \",kMeans(data), \"TD2 = \", TD2(kMeans(data)))\n\nkMeansAlgo(data, [1,2,3])","repo_name":"RuneSemey/course-help","sub_path":"DM566 - Machine Learning/Clustering/kMeans.py","file_name":"kMeans.py","file_ext":"py","file_size_in_byte":3662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"16"}
+{"seq_id":"14803909470","text":"\"\"\"\nProcesses data for the button analysis\n\"\"\"\nimport logging as log\nimport os\nimport csv\n\nfrom dirs import DIR_PROCESSED, DIR_DATA_SIMU\nfrom utils import read_csv_line\nfrom split_raw_simu_data import str2time\n\n\n# ADAS in the name\n\n\ndef main():\n # log.basicConfig(format='%(asctime)-15s [%(levelname)-10s][%(subject)-10s][%(scenario)-50s]: %(message)s',\n # level=log.INFO)\n log.basicConfig(format='%(subject)s,%(scenario)s,%(message)s', level=log.INFO)\n results = []\n buttons_map = {'down': 'brake',\n 'space': 'left',\n 'b': 'right'}\n for root, dirs, files in os.walk(DIR_DATA_SIMU):\n # Only ADAS scenarios\n if not \"adas\" in root.lower():\n continue\n # No stop and go scenarios\n if \"LCB_B1_Long_Alt\" in root:\n continue\n\n # Getting scenario and subject\n _, scenario = os.path.split(root)\n _, subject = os.path.split(_)\n\n d = {'subject': subject, 'scenario': scenario}\n button_file_path = os.path.join(root, \"keyboardvalues.csv\")\n if not os.path.exists(button_file_path):\n log.warning(\"No button data\".format(subject=subject, scenario=scenario), extra=d)\n continue\n\n button = None\n t = None\n start_time = None\n time_to_answer = None\n for l in read_csv_line(button_file_path):\n action = l[1].lower()\n if action == 'start':\n start_time = str2time(l[0])\n if action not in ['start', 'stop']:\n if action not in buttons_map:\n log.warning(\"Pressed the unhandled button '{b}'\".format(b=action), extra=d)\n continue\n if button is None:\n button = buttons_map[action]\n t = str2time(l[0])\n time_to_answer = (t - start_time).total_seconds()\n elif button != buttons_map[action]:\n log.fatal(\n \"Pressed too many handled buttons ({b1}, {b2})\".format(b1=button, b2=buttons_map[action]),\n extra=d)\n return\n\n if button is None:\n log.warning(\"Pressed no button\", extra=d)\n button = \"---\"\n t = \"---\"\n time_to_answer = \"---\"\n\n results.append([scenario, subject, t, button, time_to_answer])\n\n header = [\"scenario\",\n \"subject\",\n \"timecode\",\n \"answer\",\n \"time_to_answer\",\n ]\n\n assert (len(header) == len(results[0]))\n\n res_fn = os.path.join(DIR_PROCESSED, \"button_answers.csv\")\n with open(res_fn, 'w+') as subject_res:\n subject_res_writer = csv.writer(subject_res, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL,\n lineterminator='\\n')\n subject_res_writer.writerow(header)\n for r in results:\n subject_res_writer.writerow(r)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Anais-Hoarau/BING_GUI_Plugins","sub_path":"pynd/scripts/Matt/button_process.py","file_name":"button_process.py","file_ext":"py","file_size_in_byte":3038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"8969130005","text":"import csv\nimport datetime\nimport operator\n\nCSV_FILE = './overtime.csv'\nCSV_SEP = \",\"\nDATETIME_FORMAT = \"%m/%d/%Y %H:%M\"\nWORKING_HOURS = 9\nDATE_ROW = 0\nENTRY_ROW = 1\nEXIT_ROW = 2\n\n\nclass CalculateOverTime(object):\n def __init__(self):\n self.csv_file = CSV_FILE\n self.dt_format = DATETIME_FORMAT\n self.working_hours = WORKING_HOURS\n self.date_row = DATE_ROW\n self.entry_row = ENTRY_ROW\n self.exit_row = EXIT_ROW\n self.csv_sep = CSV_SEP\n self.weekly_overtime_dict = {}\n self.weekly_overtime = datetime.timedelta(0)\n self.current_week = -1\n self.total_overtime = datetime.timedelta(0)\n\n def get_minus_time(self, td):\n td = datetime.timedelta(days=1) - td\n sign = \"-\"\n return \"{}{}:{}\".format(sign, (td.seconds) // 3600, td.seconds // 60 % 60)\n\n def get_plus_time(self, td):\n sign = \"+\"\n return \"{}{}:{}\".format(sign, (td.days*86400 + td.seconds) // 3600, td.seconds // 60 % 60)\n\n def get_hour_minutes(self, td, return_type=\"str\"):\n if return_type == \"str\":\n sign = \"+\"\n if td.days <= -1:\n return self.get_minus_time(td)\n else:\n return self.get_plus_time(td)\n else:\n return (td.days*86400 + td.seconds)//3600, (td.seconds//60) % 60\n\n def get_overtime(self, start_time, end_time):\n current_time = end_time - start_time\n overtime = current_time - datetime.timedelta(hours=WORKING_HOURS)\n return overtime\n\n def generate_daily_report(self, date, start, end, overtime):\n overtime = self.get_hour_minutes(overtime)\n print(\"Date: {date: <10}, Start: {start: <5}, End: {end: <5},\"\n \" Overtime: {overtime: <6}\".format(\n date=date,\n start=start,\n end=end,\n overtime=overtime\n ))\n\n def get_datetime(self, date, time):\n time = time.replace(\" \", \"\")\n return datetime.datetime.strptime('{} {}'.format(\n date,\n time\n ), DATETIME_FORMAT\n )\n\n def get_week(self, datetime_obj):\n return datetime_obj.strftime(\"%V\")\n\n def update_weekly_overtime(self, overtime):\n self.weekly_overtime += overtime\n\n def get_weekly_report(self, week_no):\n return self.weekly_overtime_dict.get(week_no, datetime.timedelta(0))\n\n def create_weekly_report(self, overtime):\n return {'overtime': overtime}\n\n def get_updated_overtime(self, week_overtime, overtime):\n return week_overtime + overtime\n\n def update_weekly_report(self, week_no, overtime):\n weekly_overtime = self.get_weekly_report(week_no)\n updated_overtime = self.get_updated_overtime(weekly_overtime, overtime)\n self.weekly_overtime_dict[week_no] = updated_overtime\n\n def update_total_overtime(self, curr_overtime):\n self.total_overtime += curr_overtime\n\n def process_csv(self):\n try:\n self.show_header(\"Daily Overtime\", 61)\n with open(self.csv_file) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=self.csv_sep)\n line = 0\n for row in csv_reader:\n line += 1\n if line == 1:\n continue\n date = row[self.date_row]\n entry = row[self.entry_row]\n end = row[self.exit_row]\n entry_time = self.get_datetime(date, entry)\n exit_time = self.get_datetime(date, end)\n current_week = self.get_week(entry_time)\n if entry_time == exit_time:\n continue\n current_overtime = self.get_overtime(entry_time, exit_time)\n self.update_total_overtime(current_overtime)\n self.update_weekly_report(current_week, current_overtime)\n self.generate_daily_report(\n date, entry, end, current_overtime)\n print('-'*61)\n except IOError:\n print(\"File not found at {}\".format(self.csv_file))\n\n except IndexError:\n print(\"Delimiter '{}' not found\".format(self.csv_sep))\n\n except ValueError as e:\n print(str(e))\n\n except Exception as e:\n print(\"Generic Exception\")\n print(str(e))\n\n def display_weekly_entry(self, week_no, overtime):\n overtime = self.get_hour_minutes(overtime)\n print(\n \"Week {week_no: <3} \"\n \"Overtime: {overtime: <6}\".format(\n week_no=week_no,\n overtime=overtime)\n )\n\n def show_header(self, text=\"\", max_line=24):\n print('-'*max_line)\n print(text.center(max_line))\n print('-'*max_line)\n\n def generate_weekly_report(self):\n max_line = 24\n self.show_header(\"Weekly Report\", max_line)\n total_overtime = datetime.timedelta(0)\n for key, value in sorted(self.weekly_overtime_dict.items(), key=operator.itemgetter(0)):\n self.display_weekly_entry(key, value)\n total_overtime += value\n print('-' * max_line)\n\n def show_total_overtime(self):\n hours, minutes = self.get_hour_minutes(\n self.total_overtime, return_type=\"int\")\n self.show_header(\"Total Overtime\", 22)\n print(\n \"Hours: {hours: <3} Minutes: {minutes: <3}\".format(\n hours=hours,\n minutes=minutes\n )\n )\n print('-'*22)\n\n\nif __name__ == \"__main__\":\n overtime = CalculateOverTime()\n overtime.process_csv()\n overtime.generate_weekly_report()\n overtime.show_total_overtime()\n","repo_name":"ruddra/cefalo-overtime-calculator","sub_path":"overtime.py","file_name":"overtime.py","file_ext":"py","file_size_in_byte":5762,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"16"}
+{"seq_id":"24136651871","text":"import pandas as pd\nimport datetime as dt\nimport oandapyV20.endpoints.accounts as accounts\nimport oandapyV20.endpoints.instruments as instruments\nimport pytz\nfrom oandapyV20 import API\nfrom oandapyV20.contrib.factories import InstrumentsCandlesFactory\nfrom oandapyV20.contrib.requests import MarketOrderRequest\nfrom oandapyV20.contrib.requests import TakeProfitDetails, StopLossDetails\nimport oandapyV20.endpoints.orders as orders\nimport oandapyV20.endpoints.positions as positions\nfrom config.keys import oanda_keys\n\nPRACTICE_API_HOST = 'api-fxpractice.forex.com'\nPRACTICE_STREAM_HOST = 'stream-fxpractice.forex.com'\nLIVE_API_HOST = 'api-fxtrade.forex.com'\nLIVE_STREAM_HOST = 'stream-fxtrade.forex.com'\nPORT = '443'\n\n\nclass OandaBroker2:\n # tz = pytz.timezone('America/New_York')\n\n def __init__(self, account_id, access_token, is_live=False):\n if is_live:\n host = LIVE_API_HOST\n stream_host = LIVE_STREAM_HOST\n else:\n host = PRACTICE_API_HOST\n stream_host = PRACTICE_STREAM_HOST\n\n self.account_id = account_id\n self.access_token = access_token\n self.client = API(access_token=self.access_token)\n self.support = None\n self.resistance = None\n\n def get_positions(self):\n r = positions.OpenPositions(accountID=self.account_id)\n self.client.request(r)\n\n all_positions = r.response.get(\"positions\", [])\n for position in all_positions:\n instrument = position['instrument']\n unrealized_pnl = position['unrealizedPL']\n pnl = position['pl']\n long = position['long']\n short = position['short']\n\n if short['units']:\n self.on_position_event(\n instrument, False, short['units'], unrealized_pnl, pnl)\n elif long['units']:\n self.on_position_event(\n instrument, True, long['units'], unrealized_pnl, pnl)\n else:\n self.on_position_event(\n instrument, None, 0, unrealized_pnl, pnl)\n return all_positions\n\n def send_market_order(self, instrument, quantity, is_buy, take_profit=None, stop_loss=None):\n\n tp = None if take_profit is None else TakeProfitDetails(price=take_profit).data\n\n sl = None if stop_loss is None else StopLossDetails(price=stop_loss).data\n\n if is_buy:\n mkt_order = MarketOrderRequest(instrument=instrument,\n units=quantity,\n takeProfitOnFill=tp,\n stopLossOnFill=sl)\n else:\n mkt_order = MarketOrderRequest(instrument=instrument,\n units=(quantity * -1),\n takeProfitOnFill=tp,\n stopLossOnFill=sl)\n\n r = orders.OrderCreate(self.account_id, data=mkt_order.data)\n self.client.request(r)\n\n if r.status_code != 201:\n self.on_order_event(instrument, quantity, is_buy, None, 'NOT_FILLED')\n return False\n\n if 'orderCancelTransaction' in r.response:\n self.on_order_event(instrument, quantity, is_buy, None, 'NOT_FILLED')\n return False\n\n transaction_id = r.response.get('lastTransactionID', None)\n self.on_order_event(instrument, quantity, is_buy, transaction_id, 'FILLED')\n return r\n\n def get_prices(self, instruments_, params):\n if isinstance(instruments_, list):\n df_list = []\n for instrument in instruments_:\n df_list.append(self.get_prices(instrument, params))\n return pd.concat(df_list)\n\n return self.get_prices_instrument(instruments_, params)\n\n def get_prices_instrument(self, instrument, params):\n \"\"\"\n @param instrument:\n @param params:\n @return: dataframe of live candles data\n \"\"\"\n client = self.client\n r = instruments.InstrumentsCandles(instrument=instrument,\n params=params)\n client.request(r)\n candles = r.response.get(\"candles\")\n instrument = r.response.get(\"instrument\")\n granularity = r.response.get(\"granularity\")\n df1 = pd.DataFrame(candles)[['complete', 'volume', 'time']]\n df2 = pd.DataFrame(list(pd.DataFrame(candles)['mid']))\n df = pd.concat([df1, df2], axis=1)\n df.rename(mapper={'o': 'open', 'h': 'high', 'l': 'low', 'c': 'close'}, inplace=True, axis=1)\n df['time'] = pd.to_datetime(df['time'])\n # df['time'] = df['time'].dt.tz_convert('America/New_York')\n\n df[['open', 'high', 'low', 'close']] = df[['open', 'high', 'low', 'close']].apply(pd.to_numeric,\n errors='coerce')\n df['instrument'] = instrument\n df['granularity'] = granularity\n return df\n\n def on_order_event(self, instrument, quantity, is_buy, transaction_id, status):\n print(\n dt.datetime.now(), '[ORDER]',\n 'account_id:', self.account_id,\n 'transaction_id:', transaction_id,\n 'status:', status,\n 'instrument:', instrument,\n 'quantity:', quantity,\n 'is_buy:', is_buy,\n )\n\n def on_position_event(self, instrument, is_long, units, unrealized_pnl, pnl):\n print(\n dt.datetime.now(), '[POSITION]',\n 'account_id:', self.account_id,\n 'instrument:', instrument,\n 'is_long:', is_long,\n 'units:', units,\n 'upnl:', unrealized_pnl,\n 'pnl:', pnl\n )\n\n\nif __name__ == '__main__':\n broker = OandaBroker2(account_id=oanda_keys['account_id'], access_token=oanda_keys['access_token'])\n # pos = broker.get_positions()\n # print(pos)\n # for p in pos:\n # print(p['instrument'], p['long'])\n # print(p['instrument'], p['short'])\n # order = broker.send_market_order('EUR_USD', 1, True)\n # print(order)\n\n print(broker.get_positions())\n print('end')\n","repo_name":"vhphan/algotrading101","sub_path":"traders/oanda/broker_oanda.py","file_name":"broker_oanda.py","file_ext":"py","file_size_in_byte":6194,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"16"}
+{"seq_id":"32625161971","text":"from collections import defaultdict\n\nclass UnionFind():\n def __init__(self, n):\n self.n = n\n self.parents = [-1] * n\n\n def find(self, x):\n if self.parents[x] < 0:\n return x\n else:\n self.parents[x] = self.find(self.parents[x])\n return self.parents[x]\n\n def union(self, x, y):\n x = self.find(x)\n y = self.find(y)\n\n if x == y:\n return\n\n if self.parents[x] > self.parents[y]:\n x, y = y, x\n\n self.parents[x] += self.parents[y]\n self.parents[y] = x\n\n def size(self, x):\n return -self.parents[self.find(x)]\n\n def same(self, x, y):\n return self.find(x) == self.find(y)\n\n def members(self, x):\n root = self.find(x)\n return [i for i in range(self.n) if self.find(i) == root]\n\n def roots(self):\n return [i for i, x in enumerate(self.parents) if x < 0]\n\n def group_count(self):\n return len(self.roots())\n\n def all_group_members(self):\n group_members = defaultdict(list)\n for member in range(self.n):\n group_members[self.find(member)].append(member)\n return group_members\n\n def __str__(self):\n return '\\n'.join(f'{r}: {m}' for r, m in self.all_group_members().items())\n\nN, M = map(int, input().split())\nC, L, R = [], [], []\nfor _ in range(M):\n c, l, r = map(int, input().split())\n C.append(c)\n L.append(l)\n R.append(r)\n\nuf = UnionFind(N+1)\n\nC, L, R = zip(*sorted(zip(C, L, R)))\n\nans = 0\nmembers = 0\n\nfor i in range(M):\n c, l, r = C[i], L[i], R[i]\n\n if uf.same(l-1, r):\n continue\n\n members += 1\n ans += c\n uf.union(l-1, r)\n if members == N:\n break\n\nif members == N:\n print(ans)\nelse:\n print(-1)\n","repo_name":"tamlog06/Atcoder-Beginner-Contest","sub_path":"problems/Typical/typical90/aw/typical90_aw.py","file_name":"typical90_aw.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"2172850383","text":"class Solution:\n def isGood(self, nums: List[int]) -> bool:\n nums.sort()\n m=max(nums)\n l=len(nums)\n if(nums[l-1]==m and nums.count(m)==2 and l-1==m):\n flag=1\n for i in range(l-2):\n if(nums.count(i)>1):\n flag=0\n break\n if(flag==1):\n return True\n return False\n\n\n","repo_name":"Harsha-vardhan1/Product-Based-Company-Training-By-SRU","sub_path":"day 13/check if array is good.py","file_name":"check if array is good.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"11806393867","text":"from utils import table as table_utils\n\n\"\"\"\n Author: Jaelson Carvalho - 11427671\n Python 3.4.3\n Usage: python binomial_coefficient.py\n\n Resources:\n https://github.com/jcarva/algorithms/blob/dynamic-programming/binomial-coefficient.js\n http://www.geeksforgeeks.org/dynamic-programming-set-9-binomial-coefficient/\n https://en.wikipedia.org/wiki/Binomial_coefficient\n\n Description:\n A binomial coefficient C(n, k) also gives the number of ways, disregarding order, that\n k objects can be chosen from among n objects; more formally, the number of k-element subsets\n (or k-combinations) of an n-element set.\n\n Complexity: O(n*k)\n\n Applications:\n Some modeling chemical systems and solving by numerical approaches uses binomial coefficient\n to generate central difference equations to odd-ordered partial differentials in a single-step\n operation. All finite difference equations to partial differentials shown herein display finite\n series of palindromic coefficients with alternating signs.\n\"\"\"\n\ndef solve(input):\n \"\"\"\n :param input: array that contains two non negatives integers, where the second value should be\n less or equal to the first.\n ex: [50, 3]\n\n :return: integer that represents the calculated binomial coefficient.\n ex: 19600\n \"\"\"\n return _binomial_coefficient(input[0], input[1])\n\n\ndef _binomial_coefficient(n, k):\n if (n >= k) and (k >= 0):\n\n # Create a table to store values that are used to solve shortest problems\n c = table_utils.initialize(1, k + 1, 0)[0]\n\n # Set the first position with 1\n c[0] = 1\n\n for i in range(1, n+1):\n\n # Calculate the current row of pascal triangle using the previous column\n j = min(i, k)\n while j > 0:\n c[j] = c[j] + c[j-1]\n j -= 1\n\n return c[k]\n\n else:\n return -1\n","repo_name":"fernandobrito/algorithms_design_assignments","sub_path":"dynamic_greedy_lib/dynamic/binomial_coefficient.py","file_name":"binomial_coefficient.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"25487846846","text":"# A simple interactive program that alerts consumers of their tax and the minimum tip they can give\r\ncost = int(input('meal cost: '))\r\ntip = float(cost) * 0.18\r\ntax = float(cost) * 0.07\r\n\r\ndef addnumbers (cost, tip, tax):\r\n return (cost + tip + tax)\r\n\r\nsum = float(cost) + float(tip) + float(tax)\r\nresult = (\"The sum of {0}, {1} and {2} is {3}\".format(cost, tip, tax, sum))\r\n\r\nprint('Your tip is ', tip)\r\nprint('Your tax is ', tax)\r\nprint(result)\r\nprint(\"Thank you. See you again!\")","repo_name":"kwakuduah12/Tax-Tip","sub_path":"Tax_Tip.py","file_name":"Tax_Tip.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"34614546279","text":"# $HeadURL: $\n''' TokenAgent\n\n This agent inspect all elements, and resets their tokens if necessary.\n\n'''\n\nimport datetime\n\nfrom DIRAC import S_OK, S_ERROR\nfrom DIRAC.Core.Base.AgentModule import AgentModule\nfrom DIRAC.FrameworkSystem.Client.NotificationClient import NotificationClient\nfrom DIRAC.ResourceStatusSystem.Client.ResourceStatusClient import ResourceStatusClient\nfrom DIRAC.ResourceStatusSystem.Client.ResourceManagementClient import ResourceManagementClient\nfrom DIRAC.ResourceStatusSystem.PolicySystem.PDP import PDP\nfrom DIRAC.ResourceStatusSystem.Utilities import RssConfiguration \n\n__RCSID__ = '$Id: $'\nAGENT_NAME = 'ResourceStatus/TokenAgent'\n\nclass TokenAgent( AgentModule ):\n '''\n TokenAgent is in charge of checking tokens assigned on resources.\n Notifications are sent to those users owning expiring tokens.\n '''\n\n # Too many public methods\n # pylint: disable-msg=R0904\n\n def initialize( self ):\n '''\n TokenAgent initialization\n '''\n \n # Attribute defined outside __init__\n # pylint: disable-msg=W0201\n\n self.notifyHours = self.am_getOption( 'notifyHours', 10 )\n\n try:\n self.rsClient = ResourceStatusClient()\n self.rmClient = ResourceManagementClient()\n self.noClient = NotificationClient()\n\n return S_OK()\n except Exception:\n errorStr = \"TokenAgent initialization\"\n self.log.exception( errorStr )\n return S_ERROR( errorStr )\n\n def execute( self ):\n '''\n The main TokenAgent execution method.\n Checks for tokens owned by users that are expiring, and notifies those users.\n Calls rsClient.setToken() to set 'RS_SVC' as owner for those tokens that expired.\n '''\n\n adminMail = ''\n\n try:\n\n reason = 'Out of date token'\n\n #reAssign the token to RS_SVC\n #for g in self.ELEMENTS:\n\n validElements = RssConfiguration.getValidElements()\n\n for granularity in validElements:\n tokensExpired = self.rsClient.getTokens( granularity, \n tokenExpiration = datetime.datetime.utcnow() )\n\n if tokensExpired[ 'Value' ]:\n adminMail += '\\nLIST OF EXPIRED %s TOKENS\\n' % granularity\n adminMail += '%s|%s|%s\\n' % ( 'user'.ljust(20), 'name'.ljust(15), 'status type')\n\n for token in tokensExpired[ 'Value' ]:\n\n name = token[ 1 ]\n stype = token[ 2 ]\n user = token[ 9 ]\n\n self.rsClient.setToken( granularity, name, stype, reason, 'RS_SVC', \n datetime.datetime( 9999, 12, 31, 23, 59, 59 ) )\n adminMail += ' %s %s %s\\n' %( user.ljust(20), name.ljust(15), stype )\n\n #notify token owners\n inNHours = datetime.datetime.utcnow() + datetime.timedelta( hours = self.notifyHours )\n #for g in self.ELEMENTS:\n for granularity in validElements:\n\n tokensExpiring = self.rsClient.getTokens( granularity, tokenExpiration = inNHours )\n\n if tokensExpiring[ 'Value' ]:\n adminMail += '\\nLIST OF EXPIRING %s TOKENS\\n' % granularity\n adminMail += '%s|%s|%s\\n' % ( 'user'.ljust(20),'name'.ljust(15),'status type')\n\n for token in tokensExpiring[ 'Value' ]:\n\n name = token[ 1 ]\n stype = token[ 2 ]\n user = token[ 9 ]\n\n adminMail += '\\n %s %s %s\\n' %( user.ljust(20), name.ljust(15), stype )\n\n #If user is RS_SVC, we ignore this, whenever the token is out, this\n #agent will set again the token to RS_SVC\n if user == 'RS_SVC':\n continue\n\n pdp = PDP( granularity = granularity, name = name, statusType = stype )\n\n decision = pdp.takeDecision()\n pcresult = decision[ 'PolicyCombinedResult' ]\n spresult = decision[ 'SinglePolicyResults' ]\n\n expiration = token[ 10 ]\n\n mailMessage = \"The token for %s %s ( %s )\" % ( granularity, name, stype )\n mailMessage = mailMessage + \" will expire on %s\\n\\n\" % expiration\n mailMessage = mailMessage + \"You can renew it with command 'dirac-rss-renew-token'.\\n\"\n mailMessage = mailMessage + \"If you don't take any action, RSS will take control of the resource.\\n\\n\"\n\n policyMessage = ''\n\n if pcresult[ 'Action' ]:\n\n policyMessage += \" Policies applied will set status to %s.\\n\" % pcresult[ 'Status' ]\n\n for spr in spresult:\n policyMessage += \" %s Status->%s\\n\" % ( spr[ 'PolicyName' ].ljust(25), spr[ 'Status' ] )\n\n mailMessage += policyMessage\n adminMail += policyMessage\n\n self.noClient.sendMail( self.rmClient.getUserRegistryCache( user )[ 'Value' ][ 0 ][ 2 ],\n 'Token for %s is expiring' % name, mailMessage )\n if adminMail != '':\n #FIXME: 'ubeda' is not generic ;p\n self.noClient.sendMail( self.rmClient.getUserRegistryCache( 'ubeda' )[ 'Value' ][ 0 ][ 2 ],\n \"Token's summary\", adminMail )\n\n return S_OK()\n\n except Exception:\n errorStr = \"TokenAgent execution\"\n self.log.exception( errorStr )\n return S_ERROR( errorStr )\n\n################################################################################\n#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF","repo_name":"dlaur/DIRAC","sub_path":"ResourceStatusSystem/Agent/TokenAgent.py","file_name":"TokenAgent.py","file_ext":"py","file_size_in_byte":5418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"16"}
+{"seq_id":"32623311251","text":"#!/usr/bin/env python3\n# from typing import *\n\n\n# def solve(K: int) -> int:\ndef solve(K):\n see = [False] * K\n\n a = 0\n for i in range(K):\n a = a*10 + 7\n a %= K\n\n if see[a]:\n return -1\n\n see[a] = True\n if a == 0:\n return i+1\n\n return -1\n\n\n# generated by oj-template v4.8.1 (https://github.com/online-judge-tools/template-generator)\ndef main():\n K = int(input())\n a = solve(K)\n print(a)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"tamlog06/Atcoder-Beginner-Contest","sub_path":"problems/ABC/174/c/abc174_c.py","file_name":"abc174_c.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"33398884171","text":"import string\nfrom abc import ABC, abstractmethod\n\nfrom .symboltable import SymbolTable\nfrom .exceptions import (\n NoAddressError, BadVariableError, AddressOutOfBoundsError,\n DestinationError, ComputationError, JumpError, RAMError)\n\n\nclass Instruction(ABC):\n \"\"\"\n An abstract instruction class.\n\n Includes an abstract _check_valid method to ensure created\n instructions are valid on initialisation.\n\n Methods\n -------\n get_line()\n Return number in the file of the line from which the instruction\n was obtained\n get_inst()\n Return full instruction (excluding comments and surrounding\n whitespace) as written in the provided file\n encoded()\n Return the instruction in machine language\n \"\"\"\n\n _symbol_table = SymbolTable()\n _ram_address = 16\n\n def __init__(self, line, inst):\n self._line = line\n self._inst = inst\n self._check_valid()\n self._encoded = self._encode()\n\n def get_line(self):\n return self._line\n\n def get_inst(self):\n return self._inst\n\n def encoded(self):\n return self._encoded\n\n @abstractmethod\n def _check_valid(self):\n pass\n\n @abstractmethod\n def _encode(self):\n pass\n\n @classmethod\n def load_table(cls, symbol_table):\n cls._symbol_table = symbol_table\n\n\nclass AInstruction(Instruction):\n \"\"\"\n An A-Instruction class.\n\n Extends the Instruction class by also containing the value\n provided for the given A-Instruction.\n\n Methods\n -------\n get_line()\n Return number in the file of the line from which the instruction\n was obtained\n get_inst()\n Return full instruction (excluding comments and surrounding\n whitespace) as written in the provided file\n get_value()\n Return value after the '@' in the given A-Instruction\n is_numeric()\n Return true if the given address is numeric, false if symbolic\n encoded()\n Return the instruction in machine language\n \"\"\"\n\n _VALID_CHARS = frozenset(string.ascii_letters + string.digits + \"_.$:\")\n\n def __init__(self, line, inst, value):\n self._value = value\n self._numeric = value.isdigit()\n super().__init__(line, inst)\n\n def get_value(self):\n return self._value\n\n def is_numeric(self):\n return self._numeric\n\n def _check_valid(self):\n if self._value == \"\":\n raise NoAddressError(self)\n if len(self._value.split()) > 1:\n raise BadVariableError(self)\n if self._numeric:\n address = int(self._value)\n if address < 0 or address > 32767:\n raise AddressOutOfBoundsError(self)\n elif self._value[0].isdigit():\n raise BadVariableError(self)\n else:\n for c in self._value:\n if c not in AInstruction._VALID_CHARS:\n raise BadVariableError(self)\n\n def _encode(self):\n if self._numeric:\n address = int(self._value)\n elif Instruction._symbol_table.contains(self._value):\n address = Instruction._symbol_table.get_address(self._value)\n else:\n if Instruction._ram_address == 16383:\n raise RAMError(self)\n address = Instruction._ram_address\n Instruction._symbol_table.add_entry(self._value, address)\n Instruction._ram_address += 1\n bits = bin(address).replace(\"0b\", \"\")\n return \"0\" * (16 - len(bits)) + bits\n\n\nclass CInstruction(Instruction):\n \"\"\"\n A C-Instruction class.\n\n Extends the Instruction class by also containing relevant\n C-Instruction information.\n\n Methods\n -------\n get_line()\n Return number in the file of the line from which the instruction\n was obtained\n get_inst()\n Return full instruction (excluding comments and surrounding\n whitespace) as written in the provided file\n get_dest()\n Return the destination registers for the computation\n get_comp()\n Return the desired computation\n get_jump()\n Return the jump operation\n encoded()\n Return the instruction in machine language\n \"\"\"\n\n DEST = {None: \"000\", \"M\": \"001\", \"D\": \"010\", \"MD\": \"011\", \"A\": \"100\",\n \"AM\": \"101\", \"AD\": \"110\", \"AMD\": \"111\"}\n COMP = {\"0\": \"0101010\", \"1\": \"0111111\", \"-1\": \"0111010\",\n \"D\": \"0001100\", \"A\": \"0110000\", \"M\": \"1110000\",\n \"!D\": \"0001101\", \"!A\": \"0110001\", \"!M\": \"1110001\",\n \"-D\": \"0001111\", \"-A\": \"0110011\", \"-M\": \"1110011\",\n \"D+1\": \"0011111\", \"A+1\": \"0110111\", \"M+1\": \"1110111\",\n \"D-1\": \"0001110\", \"A-1\": \"0110010\", \"M-1\": \"1110010\",\n \"D+A\": \"0000010\", \"D+M\": \"1000010\",\n \"D-A\": \"0010011\", \"D-M\": \"1010011\",\n \"A-D\": \"0000111\", \"M-D\": \"1000111\",\n \"D&A\": \"0000000\", \"D&M\": \"1000000\",\n \"D|A\": \"0010101\", \"D|M\": \"1010101\"}\n JUMP = {None: \"000\", \"JGT\": \"001\", \"JEQ\": \"010\", \"JGE\": \"011\", \"JLT\": \"100\",\n \"JNE\": \"101\", \"JLE\": \"110\", \"JMP\": \"111\"}\n\n def __init__(self, line, inst, dest, comp, jump):\n self._dest = dest\n self._comp = comp\n self._jump = jump\n super().__init__(line, inst)\n \n def get_dest(self):\n return self._dest\n\n def get_comp(self):\n return self._comp\n\n def get_jump(self):\n return self._jump\n\n def _check_valid(self):\n if self._dest not in CInstruction.DEST:\n raise DestinationError(self)\n if self._comp not in CInstruction.COMP:\n raise ComputationError(self)\n if self._jump not in CInstruction.JUMP:\n raise JumpError(self)\n\n def _encode(self):\n return (\"111\" + CInstruction.COMP[self._comp] +\n CInstruction.DEST[self._dest] + CInstruction.JUMP[self._jump])\n\n\ndef prepare_symbol_table(file_path):\n Instruction.load_table(SymbolTable(file_path))\n","repo_name":"AntJamGeo/hack-assembler","sub_path":"asmtools/instruction.py","file_name":"instruction.py","file_ext":"py","file_size_in_byte":5966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"6012854973","text":"from django.shortcuts import render\nimport csv\n\n\ndef inflation_view(request):\n template_name = 'inflation.html'\n # чтение csv-файла и заполнение контекста\n data = []\n year = []\n total = []\n with open('inflation_russia.csv', newline='', encoding=\"utf-8\") as csv_file:\n reader = csv.reader(csv_file, delimiter=';')\n for row in reader:\n data.append(row)\n head = data.pop(0)\n # for i in range(len(data)):\n # print(data[i][0])\n for line in data:\n year.append(line.pop(0))\n total.append(line.pop(len(line)-1))\n\n context = {'data': data, 'head': head, 'year': year, 'total': total }\n\n return render(request, template_name,\n context)\n","repo_name":"maxtv1982/Python","sub_path":"dynamic-templates/task1/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"37631582842","text":"from typing import Tuple, Optional, List, Union\n\nimport torch\nimport logging\nimport torch.nn.functional as F\n\nfrom wenet.transformer.positionwise_feed_forward import PositionwiseFeedForward\nfrom wenet.transformer.embedding import PositionalEncoding\nfrom wenet.transformer.embedding import RelPositionalEncoding\nfrom wenet.transformer.embedding import NoPositionalEncoding\nfrom wenet.transformer.subsampling import Conv2dSubsampling4\nfrom wenet.transformer.subsampling import Conv2dSubsampling6\nfrom wenet.transformer.subsampling import Conv2dSubsampling8\nfrom wenet.transformer.subsampling import LinearNoSubsampling\nfrom wenet.transformer.attention import MultiHeadedAttention\nfrom wenet.transformer.attention import RelPositionMultiHeadedAttention\nfrom wenet.transformer.encoder_layer import ConformerEncoderLayer\n\nfrom wenet.efficient_conformer.subsampling import Conv2dSubsampling2\nfrom wenet.efficient_conformer.convolution import ConvolutionModule\nfrom wenet.efficient_conformer.attention import GroupedRelPositionMultiHeadedAttention\nfrom wenet.efficient_conformer.encoder_layer import StrideConformerEncoderLayer\n\nfrom wenet.utils.common import get_activation\nfrom wenet.utils.mask import make_pad_mask\nfrom wenet.utils.mask import add_optional_chunk_mask\n\n\nclass EfficientConformerEncoder(torch.nn.Module):\n \"\"\"Conformer encoder module.\"\"\"\n def __init__(\n self,\n input_size: int,\n output_size: int = 256,\n attention_heads: int = 4,\n linear_units: int = 2048,\n num_blocks: int = 6,\n dropout_rate: float = 0.1,\n positional_dropout_rate: float = 0.1,\n attention_dropout_rate: float = 0.0,\n input_layer: str = \"conv2d\",\n pos_enc_layer_type: str = \"rel_pos\",\n normalize_before: bool = True,\n static_chunk_size: int = 0,\n use_dynamic_chunk: bool = False,\n global_cmvn: torch.nn.Module = None,\n use_dynamic_left_chunk: bool = False,\n macaron_style: bool = True,\n activation_type: str = \"swish\",\n use_cnn_module: bool = True,\n cnn_module_kernel: int = 15,\n causal: bool = False,\n cnn_module_norm: str = \"batch_norm\",\n stride_layer_idx: Optional[Union[int, List[int]]] = 3,\n stride: Optional[Union[int, List[int]]] = 2,\n group_layer_idx: Optional[Union[int, List[int], tuple]] = (0, 1, 2, 3),\n group_size: int = 3,\n stride_kernel: bool = True,\n **kwargs\n ):\n \"\"\"Construct Efficient Conformer Encoder\n\n Args:\n input_size to use_dynamic_chunk, see in BaseEncoder\n macaron_style (bool): Whether to use macaron style for\n positionwise layer.\n activation_type (str): Encoder activation function type.\n use_cnn_module (bool): Whether to use convolution module.\n cnn_module_kernel (int): Kernel size of convolution module.\n causal (bool): whether to use causal convolution or not.\n stride_layer_idx (list): layer id with StrideConv, start from 0\n stride (list): stride size of each StrideConv in efficient conformer\n group_layer_idx (list): layer id with GroupedAttention, start from 0\n group_size (int): group size of every GroupedAttention layer\n stride_kernel (bool): default True. True: recompute cnn kernels with stride.\n \"\"\"\n super().__init__()\n self._output_size = output_size\n\n if pos_enc_layer_type == \"abs_pos\":\n pos_enc_class = PositionalEncoding\n elif pos_enc_layer_type == \"rel_pos\":\n pos_enc_class = RelPositionalEncoding\n elif pos_enc_layer_type == \"no_pos\":\n pos_enc_class = NoPositionalEncoding\n else:\n raise ValueError(\"unknown pos_enc_layer: \" + pos_enc_layer_type)\n\n if input_layer == \"linear\":\n subsampling_class = LinearNoSubsampling\n elif input_layer == \"conv2d2\":\n subsampling_class = Conv2dSubsampling2\n elif input_layer == \"conv2d\":\n subsampling_class = Conv2dSubsampling4\n elif input_layer == \"conv2d6\":\n subsampling_class = Conv2dSubsampling6\n elif input_layer == \"conv2d8\":\n subsampling_class = Conv2dSubsampling8\n else:\n raise ValueError(\"unknown input_layer: \" + input_layer)\n\n logging.info(f\"input_layer = {input_layer}, \"\n f\"subsampling_class = {subsampling_class}\")\n\n self.global_cmvn = global_cmvn\n self.embed = subsampling_class(\n input_size,\n output_size,\n dropout_rate,\n pos_enc_class(output_size, positional_dropout_rate),\n )\n self.input_layer = input_layer\n self.normalize_before = normalize_before\n self.after_norm = torch.nn.LayerNorm(output_size, eps=1e-5)\n self.static_chunk_size = static_chunk_size\n self.use_dynamic_chunk = use_dynamic_chunk\n self.use_dynamic_left_chunk = use_dynamic_left_chunk\n\n activation = get_activation(activation_type)\n self.num_blocks = num_blocks\n self.attention_heads = attention_heads\n self.cnn_module_kernel = cnn_module_kernel\n self.global_chunk_size = 0\n self.chunk_feature_map = 0\n\n # efficient conformer configs\n self.stride_layer_idx = [stride_layer_idx] \\\n if type(stride_layer_idx) == int else stride_layer_idx\n self.stride = [stride] \\\n if type(stride) == int else stride\n self.group_layer_idx = [group_layer_idx] \\\n if type(group_layer_idx) == int else group_layer_idx\n self.grouped_size = group_size # group size of every GroupedAttention layer\n\n assert len(self.stride) == len(self.stride_layer_idx)\n self.cnn_module_kernels = [cnn_module_kernel] # kernel size of each StridedConv\n for i in self.stride:\n if stride_kernel:\n self.cnn_module_kernels.append(self.cnn_module_kernels[-1] // i)\n else:\n self.cnn_module_kernels.append(self.cnn_module_kernels[-1])\n\n logging.info(f\"stride_layer_idx= {self.stride_layer_idx}, \"\n f\"stride = {self.stride}, \"\n f\"cnn_module_kernel = {self.cnn_module_kernels}, \"\n f\"group_layer_idx = {self.group_layer_idx}, \"\n f\"grouped_size = {self.grouped_size}\")\n\n # feed-forward module definition\n positionwise_layer = PositionwiseFeedForward\n positionwise_layer_args = (\n output_size,\n linear_units,\n dropout_rate,\n activation,\n )\n # convolution module definition\n convolution_layer = ConvolutionModule\n\n # encoder definition\n index = 0\n layers = []\n for i in range(num_blocks):\n # self-attention module definition\n if i in self.group_layer_idx:\n encoder_selfattn_layer = GroupedRelPositionMultiHeadedAttention\n encoder_selfattn_layer_args = (\n attention_heads,\n output_size,\n attention_dropout_rate,\n self.grouped_size)\n else:\n if pos_enc_layer_type == \"no_pos\":\n encoder_selfattn_layer = MultiHeadedAttention\n else:\n encoder_selfattn_layer = RelPositionMultiHeadedAttention\n encoder_selfattn_layer_args = (\n attention_heads,\n output_size,\n attention_dropout_rate)\n\n # conformer module definition\n if i in self.stride_layer_idx:\n # conformer block with downsampling\n convolution_layer_args_stride = (\n output_size, self.cnn_module_kernels[index], activation,\n cnn_module_norm, causal, True, self.stride[index])\n layers.append(StrideConformerEncoderLayer(\n output_size,\n encoder_selfattn_layer(*encoder_selfattn_layer_args),\n positionwise_layer(*positionwise_layer_args),\n positionwise_layer(\n *positionwise_layer_args) if macaron_style else None,\n convolution_layer(\n *convolution_layer_args_stride) if use_cnn_module else None,\n torch.nn.AvgPool1d(\n kernel_size=self.stride[index], stride=self.stride[index],\n padding=0, ceil_mode=True,\n count_include_pad=False), # pointwise_conv_layer\n dropout_rate,\n normalize_before,\n ))\n index = index + 1\n else:\n # conformer block\n convolution_layer_args_normal = (\n output_size, self.cnn_module_kernels[index], activation,\n cnn_module_norm, causal)\n layers.append(ConformerEncoderLayer(\n output_size,\n encoder_selfattn_layer(*encoder_selfattn_layer_args),\n positionwise_layer(*positionwise_layer_args),\n positionwise_layer(\n *positionwise_layer_args) if macaron_style else None,\n convolution_layer(\n *convolution_layer_args_normal) if use_cnn_module else None,\n dropout_rate,\n normalize_before,\n ))\n\n self.encoders = torch.nn.ModuleList(layers)\n\n def set_global_chunk_size(self, chunk_size):\n \"\"\"Used in ONNX export.\n \"\"\"\n logging.info(f\"set global chunk size: {chunk_size}, default is 0.\")\n self.global_chunk_size = chunk_size\n if self.embed.subsampling_rate == 2:\n self.chunk_feature_map = 2 * self.global_chunk_size + 1\n elif self.embed.subsampling_rate == 6:\n self.chunk_feature_map = 6 * self.global_chunk_size + 5\n elif self.embed.subsampling_rate == 8:\n self.chunk_feature_map = 8 * self.global_chunk_size + 7\n else:\n self.chunk_feature_map = 4 * self.global_chunk_size + 3\n\n def output_size(self) -> int:\n return self._output_size\n\n def calculate_downsampling_factor(self, i: int) -> int:\n factor = 1\n for idx, stride_idx in enumerate(self.stride_layer_idx):\n if i > stride_idx:\n factor *= self.stride[idx]\n return factor\n\n def forward(self,\n xs: torch.Tensor,\n xs_lens: torch.Tensor,\n decoding_chunk_size: int = 0,\n num_decoding_left_chunks: int = -1,\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Embed positions in tensor.\n Args:\n xs: padded input tensor (B, T, D)\n xs_lens: input length (B)\n decoding_chunk_size: decoding chunk size for dynamic chunk\n 0: default for training, use random dynamic chunk.\n <0: for decoding, use full chunk.\n >0: for decoding, use fixed chunk size as set.\n num_decoding_left_chunks: number of left chunks, this is for decoding,\n the chunk size is decoding_chunk_size.\n >=0: use num_decoding_left_chunks\n <0: use all left chunks\n Returns:\n encoder output tensor xs, and subsampled masks\n xs: padded output tensor (B, T' ~= T/subsample_rate, D)\n masks: torch.Tensor batch padding mask after subsample\n (B, 1, T' ~= T/subsample_rate)\n \"\"\"\n T = xs.size(1)\n masks = ~make_pad_mask(xs_lens, T).unsqueeze(1) # (B, 1, T)\n if self.global_cmvn is not None:\n xs = self.global_cmvn(xs)\n xs, pos_emb, masks = self.embed(xs, masks)\n mask_pad = masks # (B, 1, T/subsample_rate)\n chunk_masks = add_optional_chunk_mask(xs, masks,\n self.use_dynamic_chunk,\n self.use_dynamic_left_chunk,\n decoding_chunk_size,\n self.static_chunk_size,\n num_decoding_left_chunks)\n index = 0 # traverse stride\n for i, layer in enumerate(self.encoders):\n # layer return : x, mask, new_att_cache, new_cnn_cache\n xs, chunk_masks, _, _ = layer(xs, chunk_masks, pos_emb, mask_pad)\n if i in self.stride_layer_idx:\n masks = masks[:, :, ::self.stride[index]]\n chunk_masks = chunk_masks[:, ::self.stride[index],\n ::self.stride[index]]\n mask_pad = masks\n pos_emb = pos_emb[:, ::self.stride[index], :]\n index = index + 1\n\n if self.normalize_before:\n xs = self.after_norm(xs)\n # Here we assume the mask is not changed in encoder layers, so just\n # return the masks before encoder layers, and the masks will be used\n # for cross attention with decoder later\n return xs, masks\n\n def forward_chunk(\n self,\n xs: torch.Tensor,\n offset: int,\n required_cache_size: int,\n att_cache: torch.Tensor = torch.zeros(0, 0, 0, 0),\n cnn_cache: torch.Tensor = torch.zeros(0, 0, 0, 0),\n att_mask: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool)\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n \"\"\" Forward just one chunk\n\n Args:\n xs (torch.Tensor): chunk input\n offset (int): current offset in encoder output time stamp\n required_cache_size (int): cache size required for next chunk\n compuation\n >=0: actual cache size\n <0: means all history cache is required\n att_cache (torch.Tensor): cache tensor for KEY & VALUE in\n transformer/conformer attention, with shape\n (elayers, head, cache_t1, d_k * 2), where\n `head * d_k == hidden-dim` and\n `cache_t1 == chunk_size * num_decoding_left_chunks`.\n cnn_cache (torch.Tensor): cache tensor for cnn_module in conformer,\n (elayers, b=1, hidden-dim, cache_t2), where\n `cache_t2 == cnn.lorder - 1`\n att_mask : mask matrix of self attention\n\n Returns:\n torch.Tensor: output of current input xs\n torch.Tensor: subsampling cache required for next chunk computation\n List[torch.Tensor]: encoder layers output cache required for next\n chunk computation\n List[torch.Tensor]: conformer cnn cache\n\n \"\"\"\n assert xs.size(0) == 1\n\n # using downsampling factor to recover offset\n offset *= self.calculate_downsampling_factor(self.num_blocks + 1)\n\n chunk_masks = torch.ones(1,\n xs.size(1),\n device=xs.device,\n dtype=torch.bool)\n chunk_masks = chunk_masks.unsqueeze(1) # (1, 1, xs-time)\n\n real_len = 0\n if self.global_chunk_size > 0:\n # for ONNX decode simulation, padding xs to chunk_size\n real_len = xs.size(1)\n pad_len = self.chunk_feature_map - real_len\n xs = F.pad(xs, (0, 0, 0, pad_len), value=0.0)\n chunk_masks = F.pad(chunk_masks, (0, pad_len), value=0.0)\n\n if self.global_cmvn is not None:\n xs = self.global_cmvn(xs)\n\n # NOTE(xcsong): Before embed, shape(xs) is (b=1, time, mel-dim)\n xs, pos_emb, chunk_masks = self.embed(xs, chunk_masks, offset)\n elayers, cache_t1 = att_cache.size(0), att_cache.size(2)\n chunk_size = xs.size(1)\n attention_key_size = cache_t1 + chunk_size\n # NOTE(xcsong): After embed, shape(xs) is (b=1, chunk_size, hidden-dim)\n # shape(pos_emb) = (b=1, chunk_size, emb_size=output_size=hidden-dim)\n\n if required_cache_size < 0:\n next_cache_start = 0\n elif required_cache_size == 0:\n next_cache_start = attention_key_size\n else:\n next_cache_start = max(attention_key_size - required_cache_size, 0)\n\n r_att_cache = []\n r_cnn_cache = []\n mask_pad = torch.ones(1,\n xs.size(1),\n device=xs.device,\n dtype=torch.bool)\n mask_pad = mask_pad.unsqueeze(1) # batchPad (b=1, 1, time=chunk_size)\n\n if self.global_chunk_size > 0:\n # for ONNX decode simulation\n pos_emb = self.embed.position_encoding(\n offset=max(offset - cache_t1, 0),\n size=cache_t1 + self.global_chunk_size)\n att_mask[:, :, -self.global_chunk_size:] = chunk_masks\n mask_pad = chunk_masks.to(torch.bool)\n else:\n pos_emb = self.embed.position_encoding(\n offset=offset - cache_t1, size=attention_key_size)\n\n max_att_len, max_cnn_len = 0, 0 # for repeat_interleave of new_att_cache\n for i, layer in enumerate(self.encoders):\n factor = self.calculate_downsampling_factor(i)\n # NOTE(xcsong): Before layer.forward\n # shape(att_cache[i:i + 1]) is (1, head, cache_t1, d_k * 2),\n # shape(cnn_cache[i]) is (b=1, hidden-dim, cache_t2)\n # shape(new_att_cache) = [ batch, head, time2, outdim//head * 2 ]\n att_cache_trunc = 0\n if xs.size(1) + att_cache.size(2) / factor > pos_emb.size(1):\n # The time step is not divisible by the downsampling multiple\n att_cache_trunc = xs.size(1) + \\\n att_cache.size(2) // factor - pos_emb.size(1) + 1\n xs, _, new_att_cache, new_cnn_cache = layer(\n xs, att_mask, pos_emb,\n mask_pad=mask_pad,\n att_cache=att_cache[i:i + 1, :, ::factor, :][:, :, att_cache_trunc:, :],\n cnn_cache=cnn_cache[i, :, :, :]\n if cnn_cache.size(0) > 0 else cnn_cache\n )\n\n if i in self.stride_layer_idx:\n # compute time dimension for next block\n efficient_index = self.stride_layer_idx.index(i)\n att_mask = att_mask[:, ::self.stride[efficient_index],\n ::self.stride[efficient_index]]\n mask_pad = mask_pad[:, ::self.stride[efficient_index],\n ::self.stride[efficient_index]]\n pos_emb = pos_emb[:, ::self.stride[efficient_index], :]\n\n # shape(new_att_cache) = [batch, head, time2, outdim]\n new_att_cache = new_att_cache[:, :, next_cache_start // factor:, :]\n # shape(new_cnn_cache) = [1, batch, outdim, cache_t2]\n new_cnn_cache = new_cnn_cache.unsqueeze(0)\n\n # use repeat_interleave to new_att_cache\n new_att_cache = new_att_cache.repeat_interleave(repeats=factor, dim=2)\n # padding new_cnn_cache to cnn.lorder for casual convolution\n new_cnn_cache = F.pad(\n new_cnn_cache,\n (self.cnn_module_kernel - 1 - new_cnn_cache.size(3), 0))\n\n if i == 0:\n # record length for the first block as max length\n max_att_len = new_att_cache.size(2)\n max_cnn_len = new_cnn_cache.size(3)\n\n # update real shape of att_cache and cnn_cache\n r_att_cache.append(new_att_cache[:, :, -max_att_len:, :])\n r_cnn_cache.append(new_cnn_cache[:, :, :, -max_cnn_len:])\n\n if self.normalize_before:\n xs = self.after_norm(xs)\n\n # NOTE(xcsong): shape(r_att_cache) is (elayers, head, ?, d_k * 2),\n # ? may be larger than cache_t1, it depends on required_cache_size\n r_att_cache = torch.cat(r_att_cache, dim=0)\n # NOTE(xcsong): shape(r_cnn_cache) is (e, b=1, hidden-dim, cache_t2)\n r_cnn_cache = torch.cat(r_cnn_cache, dim=0)\n\n if self.global_chunk_size > 0 and real_len:\n chunk_real_len = real_len // self.embed.subsampling_rate // \\\n self.calculate_downsampling_factor(self.num_blocks + 1)\n # Keeping 1 more timestep can mitigate information leakage\n # from the encoder caused by the padding\n xs = xs[:, :chunk_real_len + 1, :]\n\n return xs, r_att_cache, r_cnn_cache\n\n def forward_chunk_by_chunk(\n self,\n xs: torch.Tensor,\n decoding_chunk_size: int,\n num_decoding_left_chunks: int = -1,\n use_onnx=False\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\" Forward input chunk by chunk with chunk_size like a streaming\n fashion\n\n Here we should pay special attention to computation cache in the\n streaming style forward chunk by chunk. Three things should be taken\n into account for computation in the current network:\n 1. transformer/conformer encoder layers output cache\n 2. convolution in conformer\n 3. convolution in subsampling\n\n However, we don't implement subsampling cache for:\n 1. We can control subsampling module to output the right result by\n overlapping input instead of cache left context, even though it\n wastes some computation, but subsampling only takes a very\n small fraction of computation in the whole model.\n 2. Typically, there are several covolution layers with subsampling\n in subsampling module, it is tricky and complicated to do cache\n with different convolution layers with different subsampling\n rate.\n 3. Currently, nn.Sequential is used to stack all the convolution\n layers in subsampling, we need to rewrite it to make it work\n with cache, which is not prefered.\n Args:\n xs (torch.Tensor): (1, max_len, dim)\n decoding_chunk_size (int): decoding chunk size\n num_decoding_left_chunks (int):\n use_onnx (bool): True for simulating ONNX model inference.\n \"\"\"\n assert decoding_chunk_size > 0\n # The model is trained by static or dynamic chunk\n assert self.static_chunk_size > 0 or self.use_dynamic_chunk\n subsampling = self.embed.subsampling_rate\n context = self.embed.right_context + 1 # Add current frame\n stride = subsampling * decoding_chunk_size\n decoding_window = (decoding_chunk_size - 1) * subsampling + context\n num_frames = xs.size(1)\n\n outputs = []\n offset = 0\n required_cache_size = decoding_chunk_size * num_decoding_left_chunks\n if use_onnx:\n logging.info(\"Simulating for ONNX runtime ...\")\n att_cache: torch.Tensor = torch.zeros(\n (self.num_blocks, self.attention_heads, required_cache_size,\n self.output_size() // self.attention_heads * 2),\n device=xs.device)\n cnn_cache: torch.Tensor = torch.zeros(\n (self.num_blocks, 1, self.output_size(), self.cnn_module_kernel - 1),\n device=xs.device)\n self.set_global_chunk_size(chunk_size=decoding_chunk_size)\n else:\n logging.info(\"Simulating for JIT runtime ...\")\n att_cache: torch.Tensor = torch.zeros((0, 0, 0, 0), device=xs.device)\n cnn_cache: torch.Tensor = torch.zeros((0, 0, 0, 0), device=xs.device)\n\n # Feed forward overlap input step by step\n for cur in range(0, num_frames - context + 1, stride):\n end = min(cur + decoding_window, num_frames)\n logging.info(f\"-->> frame chunk msg: cur={cur}, \"\n f\"end={end}, num_frames={end-cur}, \"\n f\"decoding_window={decoding_window}\")\n if use_onnx:\n att_mask: torch.Tensor = torch.ones(\n (1, 1, required_cache_size + decoding_chunk_size),\n dtype=torch.bool, device=xs.device)\n if cur == 0:\n att_mask[:, :, :required_cache_size] = 0\n else:\n att_mask: torch.Tensor = torch.ones(\n (0, 0, 0), dtype=torch.bool, device=xs.device)\n\n chunk_xs = xs[:, cur:end, :]\n (y, att_cache, cnn_cache) = \\\n self.forward_chunk(\n chunk_xs, offset, required_cache_size,\n att_cache, cnn_cache, att_mask)\n outputs.append(y)\n offset += y.size(1)\n\n ys = torch.cat(outputs, 1)\n masks = torch.ones(1, 1, ys.size(1), device=ys.device, dtype=torch.bool)\n return ys, masks\n","repo_name":"wenet-e2e/wenet","sub_path":"wenet/efficient_conformer/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":25005,"program_lang":"python","lang":"en","doc_type":"code","stars":3402,"dataset":"github-code","pt":"16"}
+{"seq_id":"26386083671","text":"import argparse\nimport traceback\nfrom loader import read_queries, read_constraints\nfrom config import FileType, get_path, CONNECT_MAP\nfrom extract_rule import ExtractQueryRule\nfrom utils import GlobalExpRecorder, get_valid_queries\nfrom constraint import InclusionConstraint, LengthConstraint, FormatConstraint\n\nname_to_type = {\n 'inclusion': InclusionConstraint,\n 'length': LengthConstraint,\n 'format': FormatConstraint,\n}\n# =====================================================================\n\n\n# ========================== main function ============================\ndef main() -> None:\n parser = argparse.ArgumentParser()\n parser.add_argument('--app', default='redmine')\n parser.add_argument('--cnt', type=int, default=100000, help='number of queries to rewrite')\n parser.add_argument(\"--data_dir\", type=str, help=\"data root dir\", default='data')\n args = parser.parse_args()\n \n recorder = GlobalExpRecorder()\n recorder.record(\"app_name\", args.app)\n \n # load query once for each app\n offset = 0\n queries = read_queries(get_path(FileType.RAW_QUERY, args.app, args.data_dir), offset, args.cnt)\n # queries = get_valid_queries(queries, CONNECT_MAP[args.app])\n \n # count the number of queries with constraints on it\n all_cs = load_cs(args.app, args.data_dir, 'all')\n all_cnt, warning_cnt = count_queries_with_cs(all_cs, queries, verbal=True)\n recorder.record(\"queries_with_cs\", all_cnt)\n recorder.record(\"warning cnt\", warning_cnt)\n\n # count inclusion, length, format constraint query\n for type_name in name_to_type.keys():\n cs_type = name_to_type[type_name]\n filtered_cs = load_cs(args.app, args.data_dir, cs_type)\n cnt, _ = count_queries_with_cs(filtered_cs, queries, verbal=True)\n recorder.record(type_name, cnt)\n recorder.dump(get_path(FileType.BENCH_STR2INT_NUM, args.app, args.data_dir))\n\n#################################\n# helper functions #\n#################################\n# return filtered constraints\ndef load_cs(appname, datadir, cs_type) -> list:\n constraints = read_constraints(get_path(FileType.CONSTRAINT, appname, datadir), include_all=True)\n if cs_type == 'all':\n return constraints\n filtered_cs = [c for c in constraints if isinstance(c, cs_type)]\n return filtered_cs\n\n# return number of queries contains filtered constraints\ndef count_queries_with_cs(filtered_cs, queries, verbal) -> tuple:\n cnt = 0\n rule = ExtractQueryRule(filtered_cs)\n for q in queries:\n try:\n rewrite_q = rule.apply(q.q_obj)\n if extracted(rewrite_q):\n # print(format(rewrite_q[0]))\n cnt += 1\n except (KeyError, TypeError, AttributeError, ValueError):\n print_error(q, verbal)\n return (cnt, rule.warning_cnt)\n\n# return True if query contains inclusion constrains\ndef extracted(q) -> bool:\n # rewrite_q is a list of queries from the rewrite rules\n return len(q) >= 1\n\n# print info about errored query\ndef print_error(q, verbal) -> None:\n if verbal:\n print(q.q_raw)\n print(\"----------------\")\n print(traceback.format_exc())\n print(\"================\")\n else:\n pass\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"LiuXiaoxuanPKU/Coco","sub_path":"rewriter/src/bench_str2int_num.py","file_name":"bench_str2int_num.py","file_ext":"py","file_size_in_byte":3261,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"16"}
+{"seq_id":"27630117115","text":"from bs4 import BeautifulSoup\nimport requests\nimport time\nimport os\n\ndef get_page_html(url):\n headers = {\"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36\"}\n page = requests.get(url, headers=headers)\n return page.content\n\n\ndef check_item_in_stock(page_html, phone, text_to_send, value_sku_item):\n soup = BeautifulSoup(page_html, 'html.parser')\n\n stock_L = soup.find(value=value_sku_item)\n\n if stock_L['data-inventory-status'] == 'Available':\n print(\"In stock!\")\n os.system(\"osascript imessage.scpt %s '%s' \" % (phone, text_to_send))\n elif stock_L['data-inventory-status'] == 'Unavailable':\n print(\"OOS\")\n else:\n print(\"Issue in program\")\n\n\ndef main ():\n phone = XXXX\n #Find sku in the source page\n value_sku_item = \"XXXX\"\n text_to_send = 'message to send'\n url = \"https://www.abercrombie.com/shop/us/XXX\"\n page_html = get_page_html(url)\n\n while True:\n check_item_in_stock(page_html, phone, text_to_send, value_sku_item)\n time.sleep(600)\n\nif __name__ == '__main__':\n main()","repo_name":"egiacomin/inventory_check_stock","sub_path":"check_stock.py","file_name":"check_stock.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"22923520950","text":"from aiogram import types\r\nfrom aiogram.dispatcher import FSMContext\r\nfrom aiogram.dispatcher.filters import Command\r\nfrom keyboards.default.keyboards import markup,back\r\nfrom loader import dp\r\n\r\nfrom states.search import search\r\n\r\nimport requests\r\n\r\n@dp.message_handler(text=\"ℹ️ About\")\r\nasync def answer(message: types.Message, state: FSMContext):\r\n await message.answer(\"Ushbu bot butun dunyodagi eng so'ngi ob havo ma'lumotlarini ko'rsatib beradi\")\r\n@dp.message_handler(text=\"🔍Izlash\")\r\nasync def answer(message: types.Message, state: FSMContext):\r\n await search.search.set()\r\n await message.answer(\"\"\"Marhamat qilib Davlat yoki shahar nomini kiriting\r\nMisol uchun: \"O'zbekiston\" yoki \"Toshkent\"\r\nEslatib o'tamiz biz bilan butun\r\ndunyo ob-havo ma'lumotlarini topishingiz mumkin\"\"\",reply_markup=back)\r\n\r\n@dp.message_handler(state=search.search)\r\nasync def qidiruv(message: types.Message, state: FSMContext):\r\n if message.text== \"Qidiruv bo'limidan chiqish\":\r\n await state.finish()\r\n await message.answer('Siz asosiy menudasiz',reply_markup=markup) \r\n\r\n else:\r\n try:\r\n if message.text== \"Qidiruv bo'limidan chiqish\":\r\n await state.finish()\r\n await message.answer('Siz asosiy menudasiz',reply_markup=markup)\r\n API = 'f441cb7b77702bb2d9648180922cae59'\r\n CITY = message.text\r\n URL = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&units=metric&appid={API}'\r\n response = requests.get(url=URL).json()\r\n city_info = {\r\n 'city': CITY,\r\n 'temp': response['main']['temp'],\r\n 'humidity': response['main']['humidity'],\r\n 'weather': response['weather'][0]['main'],\r\n 'wind': response['wind']['speed'],\r\n 'pressure': response['main']['pressure'],\r\n }\r\n h={'Clear':'ochiq',\r\n \"Clouds\":\"bulutli\",\r\n \"Snow\":\"qorli\",\r\n \"Mist\":\"tumanli\",\r\n \"Smoke\":'tutunli',\r\n \"Haze\":\"tumanli\",\r\n \"Dust\":\"havo changli\",\r\n \"Fog\":\"quyuq tuman mavjud\",\r\n \"Sand\":\"yuqori darajada changlangan\",\r\n \"Ash\":\"havo tarkibida kul miqdori ko'p\",\r\n \"Squall\":\"yomg'irli\",\r\n \"Tornado\":\"Bo'ron bo'lmoqda\",\r\n \"Rain\":\"yomg'irli\",\r\n \"Drizzle\":\"yomg'irli\",\r\n \"Thunderstorm\":\"chaqmoq va momaqaldiroq mavjud\"\r\n }\r\n msg = f\"\"\"{CITY.upper()}\r\n\r\nOb-havo:{h[city_info['weather']]} \r\n------------------------------------\r\n🌡 Harorat: {city_info['temp']} C\r\n💨 Shamol: {city_info['wind']} m/s\r\n💦 Namlik: {city_info['humidity']} %\r\n🧬 Bosim: {city_info['pressure']} hPa\"\"\"\r\n await message.answer(msg, parse_mode='html',reply_markup=back)\r\n\r\n except Exception as e:\r\n msg1 = f\"Ushbu davlat haqida ma'lumotlar mavjud emas\"\r\n await message.answer(msg1, parse_mode='html',reply_markup=back)","repo_name":"Akaikumogo/Ob_havo_bot","sub_path":"handlers/users/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":3053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"9699131351","text":"#importacões de libs\nimport matplotlib.pyplot as plt\n\n#variaveis\nx1 = [1, 2, 3, 4, 5]\ny1 = [3, 4, 7, 2, 4]\n\nx2 = [2, 4, 6, 8, 10]\ny2 = [5, 6, 8, 4, 4]\n\ntitulo = \"Graficos em barras\"\neixox = \"eixo X\"\neixoy = \"eixo Y\"\n\n#legendas\nplt.title(titulo)\nplt.xlabel(eixox)\nplt.ylabel(eixoy)\n\n#utlizando o bar para criar graficos em barras\nplt.bar(x1, y1, label = \"Grupo 1\") # colocando a legenda das cores\nplt.bar(x2, y2, label = \"Grupo 1\")\nplt.legend() #mostrando a leganda no gráfico\n\n#mostrando o grafico\nplt.show()\nplt.savefig(r\"graficos\\grafico_barras.png\", dpi = 300) #imagem em alta resolução","repo_name":"rafaelrossim/DataScience","sub_path":"2_graficosbarras.py","file_name":"2_graficosbarras.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"19949836428","text":"import cv2\nimport os\nimport numpy as np\n\npreview_enabled = True\n\ndef init(set_enabled=True):\n global preview_enabled\n preview_enabled = set_enabled\n if set_enabled:\n if not os.path.exists('data_features_matches'):\n os.makedirs('data_features_matches')\n if not os.path.exists('data_features_preview'):\n os.makedirs('data_features_preview')\n\n\ndef saveImageFeaturePreview(imgFile, kp):\n if not preview_enabled:\n return\n img = cv2.imread(\"data/\" + imgFile)\n for kpit in kp:\n cv2.circle(img, tuple(map(int, kpit.pt)), 1, (0, 0, 255), 4)\n cv2.imwrite(\"data_features_preview/\" + imgFile, img)\n\n\ndef saveFullImageFeaturePreview(kp):\n if not preview_enabled:\n return\n img = cv2.imread(\"input/\" + os.environ.get(\"IFS_PHOTO_FILE\", \"ifs.jpg\"))\n for kpit in kp:\n cv2.circle(img, tuple(map(int, kpit.pt)), 1, (0, 0, 255), 4)\n cv2.imwrite(\"data_features_preview/ifs.jpg\", img)\n\n\ndef saveMatchedCenterMultiple(matchedList):\n if not preview_enabled:\n return\n imgFull = cv2.imread(\n \"input/\" + os.environ.get(\"IFS_PHOTO_FILE\", \"ifs.jpg\"))\n for matched in matchedList:\n for center in matched[\"centers\"]:\n imgFull = cv2.circle(\n imgFull, (center[\"x\"], center[\"y\"]), 5, (0, 255, 255), 8)\n imgFull = cv2.putText(\n imgFull, str(matched[\"portalID\"]), (center[\"x\"], center[\"y\"]), cv2.FONT_HERSHEY_COMPLEX, 3, (0, 0, 255), 8)\n cv2.imwrite(\"data_features_matches/ifs.jpg\", imgFull)\n\n\ndef saveGridInfo(matchedGridList):\n if not preview_enabled:\n return\n imgFull = cv2.imread(\"data_features_matches/ifs.jpg\")\n for idx, colList in enumerate(matchedGridList):\n for center in colList:\n imgFull = cv2.putText(\n imgFull, str(idx), (center[\"x\"], center[\"y\"]), cv2.FONT_HERSHEY_COMPLEX, 4, (0, 0, 255), 15)\n cv2.imwrite(\"data_features_matches/ifs-grid.jpg\", imgFull)\n","repo_name":"UESTC-Ingress/IFSolver","sub_path":"modules/utils/PreviewUtil.py","file_name":"PreviewUtil.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"16"}
+{"seq_id":"14655908266","text":"from Messages import Message as Ms\n\n\nclass ConfigMessage(Ms.Message):\n def __init__(self, public_key: str, message: dict = None):\n try:\n if message is None:\n self.message_info = {\n \"Type\": \"Config\",\n \"PublicKey\": public_key\n }\n elif message[\"Type\"] == \"Config\":\n super(ConfigMessage, self).__init__(message=message)\n except Exception as e:\n print(e)\n","repo_name":"aymanKH9991/PasswordManagerServer","sub_path":"Server/Messages/Configration.py","file_name":"Configration.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"3724124962","text":"from django.db.models import Q\nfrom rest_framework.serializers import ModelSerializer\nfrom modules.account.user.helpers.model_utils import UserModelUtils\nfrom ..models import Member, MemberShip, MemberShipType, BookingService, Device\nfrom modules.account.user.helpers.srs import UserSr\nfrom modules.club_service.service.helpers.srs import ServiceSr\nfrom modules.noti.notification.models import Notification\nfrom django.http.request import QueryDict\nfrom rest_framework.serializers import ValidationError\n\n\nModel = Member\n\n\nclass BookingServiceSr(ModelSerializer):\n class Meta:\n model = BookingService\n exclude = ()\n\n def to_representation(self, obj):\n rep = super().to_representation(obj)\n member = Member.objects.filter(id=obj.member.id).first()\n membership = MemberShip.objects.filter(member=member).first()\n\n rep[\"member_real_name\"] = MemberSr(member).data[\"full_name\"]\n rep[\"member_real_phone_number\"] = UserSr(\n member.user).data[\"phone_number\"]\n rep[\"member_real_email\"] = MemberSr(member).data[\"email\"]\n rep[\"dob\"] = MemberSr(member).data[\"dob\"]\n rep[\"occupation\"] = MemberSr(member).data[\"occupation\"]\n rep[\"address\"] = MemberSr(member).data[\"address\"]\n rep[\"gender\"] = MemberSr(member).data[\"gender\"]\n rep[\"avatar\"] = MemberSr(member).data[\"avatar\"]\n rep[\"membership_type\"] = MemberShipSr(\n membership).data[\"membership_type\"]\n rep[\"register_date\"] = MemberShipSr(membership).data[\"register_date\"]\n rep[\"expire_date\"] = MemberShipSr(membership).data[\"expire_date\"]\n\n return rep\n\n\nclass MemberSr(ModelSerializer):\n class Meta:\n model = Model\n exclude = []\n\n def to_representation(self, obj):\n rep = super().to_representation(obj)\n rep[\"phone_number\"] = UserSr(obj.user).data[\"phone_number\"]\n rep[\"email\"] = UserSr(obj.user).data[\"email\"]\n rep[\"membership_type\"] = MemberShipTypeSr(\n obj.membership.membership_type).data\n rep[\"register_date\"] = MemberShipSr(\n obj.membership).data[\"register_date\"]\n rep[\"expire_date\"] = MemberShipSr(obj.membership).data[\"expire_date\"]\n return rep\n\n\nclass MemberShipSr(ModelSerializer):\n class Meta:\n model = MemberShip\n exclude = []\n\n\nclass MemberShipTypeSr(ModelSerializer):\n class Meta:\n model = MemberShipType\n exclude = []\n\n\nclass DeviceSr(ModelSerializer):\n class Meta:\n model = Device\n exclude = []\n\n\nclass MemberRetrieveSr(MemberSr):\n class Meta(MemberSr.Meta):\n exclude = [\n \"created_at\",\n \"updated_at\",\n \"user\",\n ]\n\n def to_representation(self, obj):\n rep = super().to_representation(obj)\n rep[\"membership_type\"] = MemberShipSr(\n obj.membership).data[\"membership_type\"]\n return rep\n\n\nclass MemberPermissionSr(MemberRetrieveSr):\n class Meta(MemberRetrieveSr.Meta):\n pass\n\n def to_representation(self, obj):\n rep = super().to_representation(obj)\n is_not_read = Notification.objects.filter(\n Q(member=obj) & Q(is_read=False))\n rep[\"unread_notification\"] = bool(is_not_read)\n\n rep[\"phone_number\"] = UserSr(obj.user).data[\"phone_number\"]\n rep[\"email\"] = UserSr(obj.user).data[\"email\"]\n rep[\"membership_type\"] = MemberShipTypeSr(\n obj.membership.membership_type).data\n rep[\"list_services\"] = []\n rep[\"register_date\"] = MemberShipSr(\n obj.membership).data[\"register_date\"]\n rep[\"expire_date\"] = MemberShipSr(obj.membership).data[\"expire_date\"]\n rep[\"permissions\"] = UserModelUtils.get_permissions(obj.user)\n # for service in obj.membership.membership_type.services.all():\n # rep[\"list_services\"].append(ServiceSr(service).data)\n return rep\n\n\nclass MemberOptionSr(MemberSr):\n class Meta(MemberSr.Meta):\n exclude = []\n\n def to_representation(self, obj):\n groups = obj.user.groups.all()\n return {\n \"value\": obj.id,\n \"label\": obj.full_name,\n \"email\": obj.user.email,\n \"phone_number\": str(obj.user.phone_number),\n \"groups\": groups.values_list(\"id\", flat=True),\n \"group_labels\": groups.values_list(\"name\", flat=True),\n }\n","repo_name":"datlt198640/apartment-management","sub_path":"api/modules/account/member/helpers/srs.py","file_name":"srs.py","file_ext":"py","file_size_in_byte":4373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"17739310007","text":"'''\r\n\r\nNetwork Security Group operations for test.\r\n\r\n@author: Youyk\r\n'''\r\n\r\nimport apibinding.api_actions as api_actions\r\nimport zstackwoodpecker.test_util as test_util\r\nimport apibinding.inventory as inventory\r\nimport zstackwoodpecker.operations.account_operations as acc_ops\r\nimport zstackwoodpecker.operations.deploy_operations as dep_ops\r\nimport zstackwoodpecker.operations.resource_operations as res_ops\r\nimport zstacklib.utils.xmlobject as xmlobject\r\n\r\nimport os\r\nimport sys\r\nimport traceback\r\n\r\ndef create_security_group(sg_creation_option):\r\n action = api_actions.CreateSecurityGroupAction()\r\n if not sg_creation_option.get_name():\r\n action.name = 'test_sg'\r\n else:\r\n action.name = sg_creation_option.get_name()\r\n \r\n if not sg_creation_option.get_description():\r\n action.description = 'Test Security Group'\r\n else:\r\n action.description = sg_creation_option.get_description()\r\n\r\n if not sg_creation_option.get_timeout():\r\n action.timeout = 120000\r\n else:\r\n action.timeout = sg_creation_option.get_timeout()\r\n \r\n test_util.action_logger('Create [Security Group]: %s' % action.name)\r\n evt = acc_ops.execute_action_with_session(action, sg_creation_option.get_session_uuid())\r\n test_util.test_logger('[sg:] %s is created.' % evt.inventory.uuid)\r\n return evt.inventory\r\n\r\ndef delete_security_group(sg_uuid, session_uuid=None):\r\n action = api_actions.DeleteSecurityGroupAction()\r\n action.uuid = sg_uuid\r\n action.timeout = 12000\r\n test_util.action_logger('Delete [Security Group:] %s' % sg_uuid)\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n return evt\r\n\r\n#rules = [inventory.SecurityGroupRuleAO()]\r\ndef add_rules_to_security_group(sg_uuid, rules, session_uuid=None):\r\n action = api_actions.AddSecurityGroupRuleAction()\r\n action.securityGroupUuid = sg_uuid\r\n action.timeout = 120000\r\n action.rules = rules\r\n for rule in rules:\r\n test_util.action_logger('Add Security Group [Rule:] type: %s, protocol: %s, startPort: %s, endPort: %s, address: %s in [Security Group:] %s' % (rule.type, rule.protocol, rule.startPort, rule.endPort, rule.allowedCidr, sg_uuid))\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n return evt.inventory\r\n\r\n#rules = [rules_uuid]\r\ndef remove_rules_from_security_group(rules, session_uuid=None):\r\n '''\r\n params: rules is a list includes a list of rules uuids. \r\n '''\r\n action = api_actions.DeleteSecurityGroupRuleAction()\r\n action.timeout = 12000\r\n action.ruleUuids = rules\r\n test_util.action_logger('Delete Security Group [Rules:] %s' % rules)\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n return evt.inventory\r\n\r\ndef add_nic_to_security_group(sg_uuid, vm_nic_list, session_uuid=None):\r\n action = api_actions.AddVmNicToSecurityGroupAction()\r\n action.securityGroupUuid = sg_uuid\r\n action.vmNicUuids = vm_nic_list\r\n action.timeout = 120000\r\n test_util.action_logger('Add [Nics:] %s to [Security Group:] %s' \\\r\n % (vm_nic_list, sg_uuid))\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n return evt\r\n\r\ndef remove_nic_from_security_group(sg_uuid, nic_uuid_list, session_uuid=None):\r\n action = api_actions.DeleteVmNicFromSecurityGroupAction()\r\n action.securityGroupUuid = sg_uuid\r\n action.vmNicUuids = nic_uuid_list\r\n action.timeout = 12000\r\n test_util.action_logger('Delete [Nics:] %s From [Security Group:] %s' \\\r\n % (nic_uuid_list, sg_uuid))\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n return evt\r\n\r\ndef attach_security_group_to_l3(sg_uuid, l3_uuid, session_uuid=None):\r\n action = api_actions.AttachSecurityGroupToL3NetworkAction()\r\n action.securityGroupUuid = sg_uuid\r\n action.l3NetworkUuid = l3_uuid\r\n action.timeout = 12000\r\n test_util.action_logger('Attach [Security Group:] %s to [l3:] %s' % (sg_uuid, l3_uuid))\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n return evt\r\n\r\ndef detach_security_group_from_l3(sg_uuid, l3_uuid, session_uuid=None):\r\n action = api_actions.DetachSecurityGroupFromL3NetworkAction()\r\n action.l3NetworkUuid = l3_uuid\r\n action.securityGroupUuid = sg_uuid\r\n action.timeout = 12000\r\n test_util.action_logger('Detach [Security Group:] %s from [l3:] %s' % (sg_uuid, l3_uuid))\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n return evt\r\n\r\ndef create_vip(vip_creation_option):\r\n action = api_actions.CreateVipAction()\r\n action.l3NetworkUuid = vip_creation_option.get_l3_uuid()\r\n action.allocateStrategy = vip_creation_option.get_allocateStrategy()\r\n action.timeout = vip_creation_option.get_timeout()\r\n #mandatory vip name:\r\n name = vip_creation_option.get_name()\r\n if not name:\r\n action.name = 'vip_test'\r\n else:\r\n action.name = name\r\n\r\n session_uuid = vip_creation_option.get_session_uuid()\r\n action.description = vip_creation_option.get_description()\r\n evt = acc_ops.execute_action_with_session(action, session_uuid).inventory\r\n test_util.action_logger('Create [VIP:] %s [IP:] %s in [l3:] %s' % (evt.uuid, evt.ip, action.l3NetworkUuid))\r\n return evt\r\n\r\ndef delete_vip(vip_uuid, session_uuid=None):\r\n action = api_actions.DeleteVipAction()\r\n action.uuid = vip_uuid\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n test_util.action_logger(\"[VIP]: %s is deleted\" % vip_uuid)\r\n return evt\r\n\r\ndef create_port_forwarding(pf_rule_creation_option):\r\n action = api_actions.CreatePortForwardingRuleAction()\r\n action.name = pf_rule_creation_option.get_name()\r\n if not action.name:\r\n action.name = 'test_port_forwarding_rule'\r\n\r\n action.timeout = pf_rule_creation_option.get_timeout()\r\n if not action.timeout:\r\n action.timeout = 12000\r\n\r\n action.description = pf_rule_creation_option.get_description()\r\n session_uuid = pf_rule_creation_option.get_session_uuid()\r\n\r\n action.vipPortStart, action.vipPortEnd = pf_rule_creation_option.get_vip_ports()\r\n action.privatePortStart, action.privatePortEnd = pf_rule_creation_option.get_private_ports()\r\n if not action.privatePortStart:\r\n action.privatePortStart = action.vipPortStart\r\n action.privatePortEnd = action.vipPortEnd\r\n\r\n action.vipUuid = pf_rule_creation_option.get_vip_uuid()\r\n action.vmNicUuid = pf_rule_creation_option.get_vm_nic_uuid()\r\n action.allowedCidr = pf_rule_creation_option.get_allowedCidr()\r\n action.protocolType = pf_rule_creation_option.get_protocol()\r\n test_util.action_logger(\"Create Port Forwarding Rule: [vipUuid:] %s [vm nic:] %s [vip start:] %s [vip end:] %s [pri start:] %s [pri end:] %s [allowedCidr:] %s\" % (action.vipUuid, action.vmNicUuid, action.vipPortStart, action.vipPortEnd, action.privatePortStart, action.privatePortEnd, action.allowedCidr))\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n return evt.inventory\r\n\r\ndef delete_port_forwarding(pf_rule_uuid, session_uuid=None):\r\n action = api_actions.DeletePortForwardingRuleAction()\r\n action.uuid = pf_rule_uuid\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n test_util.action_logger(\"Port Forwarding Rule [uuid:] %s is deleted\" % pf_rule_uuid)\r\n return evt\r\n\r\ndef attach_port_forwarding(pf_rule_uuid, vm_nic_uuid, session_uuid=None):\r\n action = api_actions.AttachPortForwardingRuleAction()\r\n action.ruleUuid = pf_rule_uuid\r\n action.vmNicUuid = vm_nic_uuid\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n test_util.action_logger(\"Port Forwarding Rule [uuid:] %s is attached to %s\" % (pf_rule_uuid, vm_nic_uuid))\r\n return evt.inventory\r\n\r\ndef detach_port_forwarding(pf_rule_uuid, session_uuid=None):\r\n action = api_actions.DetachPortForwardingRuleAction()\r\n action.uuid = pf_rule_uuid\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n test_util.action_logger(\"Port Forwarding Rule [uuid:] %s is detached\" % pf_rule_uuid)\r\n return evt.inventory\r\n\r\ndef create_eip(eip_creation_option):\r\n action = api_actions.CreateEipAction()\r\n action.vipUuid = eip_creation_option.get_vip_uuid()\r\n action.vmNicUuid = eip_creation_option.get_vm_nic_uuid()\r\n action.name = eip_creation_option.get_name()\r\n if not action.name:\r\n action.name = 'eip test'\r\n action.description = eip_creation_option.get_description()\r\n action.timeout = eip_creation_option.get_timeout()\r\n if not action.timeout:\r\n action.timeout = 12000\r\n\r\n session_uuid = eip_creation_option.get_session_uuid()\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n test_util.action_logger(\"[EIP:] %s is created, with [vip:] %s and [nic:] %s\" % (evt.inventory.uuid, action.vipUuid, action.vmNicUuid))\r\n return evt.inventory\r\n\r\ndef attach_eip(eip_uuid, nic_uuid, session_uuid=None):\r\n action = api_actions.AttachEipAction()\r\n action.eipUuid = eip_uuid\r\n action.vmNicUuid = nic_uuid\r\n action.timeout = 12000\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n test_util.action_logger(\"[EIP:] %s is attached to [nic:] %s\" % (eip_uuid, nic_uuid))\r\n return evt.inventory\r\n\r\ndef detach_eip(eip_uuid, session_uuid=None):\r\n action = api_actions.DetachEipAction()\r\n action.uuid = eip_uuid\r\n action.timeout = 12000\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n test_util.action_logger(\"[EIP:] %s is detached\" % eip_uuid)\r\n return evt.inventory\r\n\r\ndef delete_eip(eip_uuid, session_uuid=None):\r\n action = api_actions.DeleteEipAction()\r\n action.uuid = eip_uuid\r\n action.timeout = 12000\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n test_util.action_logger(\"[EIP:] %s is deleted\" % eip_uuid)\r\n return evt\r\n \r\n\r\ndef delete_l2(l2_uuid, session_uuid = None):\r\n '''\r\n Delete L2 will stop all VMs which is using this L2. When VM started again, \r\n the related L2 NIC will be removed. \r\n '''\r\n action = api_actions.DeleteL2NetworkAction()\r\n action.uuid = l2_uuid\r\n action.timeout = 300000\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n test_util.action_logger(\"[L2:] %s is deleted\" % l2_uuid)\r\n return evt\r\n\r\ndef delete_l3(l3_uuid, session_uuid = None):\r\n '''\r\n Delete L3 will stop all VMs which is using this L3. When VM started again, \r\n the related L3 NIC will be removed. \r\n '''\r\n action = api_actions.DeleteL3NetworkAction()\r\n action.uuid = l3_uuid\r\n action.timeout = 300000\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n test_util.action_logger(\"[L3:] %s is deleted\" % l3_uuid)\r\n return evt\r\n\r\ndef attach_l2(l2_uuid, cluster_uuid, session_uuid = None):\r\n action = api_actions.AttachL2NetworkToClusterAction()\r\n action.clusterUuid = cluster_uuid\r\n action.l2NetworkUuid = l2_uuid\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n test_util.action_logger(\"Attach [L2:] %s to [Cluster:] %s \" \\\r\n % (l2_uuid, cluster_uuid))\r\n return evt\r\n\r\ndef add_l2_resource(deploy_config, l2_name, zone_name = None, \\\r\n session_uuid = None):\r\n session_uuid_flag = True\r\n if not session_uuid:\r\n session_uuid = acc_ops.login_as_admin()\r\n session_uuid_flag = False\r\n try:\r\n dep_ops.add_l2_network(deploy_config, session_uuid, l2_name, \\\r\n zone_name = zone_name)\r\n l2_uuid = res_ops.get_resource(res_ops.L2_NETWORK, session_uuid, \\\r\n name = l2_name)[0].uuid\r\n \r\n for zone in xmlobject.safe_list(deploy_config.zones.zone):\r\n if zone_name and zone_name != zone.name_:\r\n continue\r\n for cluster in xmlobject.safe_list(zone.clusters.cluster):\r\n if xmlobject.has_element(cluster, 'l2NetworkRef'):\r\n for l2ref in xmlobject.safe_list(cluster.l2NetworkRef):\r\n if l2_name != l2ref.text_:\r\n continue\r\n\r\n cluster_uuid = res_ops.get_resource(res_ops.CLUSTER, \\\r\n session_uuid, name=cluster.name_)[0].uuid\r\n attach_l2(l2_uuid, cluster_uuid, session_uuid)\r\n\r\n dep_ops.add_l3_network(deploy_config, session_uuid, l2_name = l2_name, \\\r\n zone_name = zone_name)\r\n cond = res_ops.gen_query_conditions('l2NetworkUuid', '=', l2_uuid)\r\n l3_name = res_ops.query_resource(res_ops.L3_NETWORK, cond, \\\r\n session_uuid)[0].name\r\n dep_ops.add_virtual_router(deploy_config, session_uuid, \\\r\n l3_name = l3_name, zone_name = zone_name)\r\n except Exception as e:\r\n test_util.test_logger('[Error] zstack deployment meets exception when adding l2 resource .')\r\n traceback.print_exc(file=sys.stdout)\r\n raise e\r\n finally:\r\n if not session_uuid_flag:\r\n acc_ops.logout(session_uuid)\r\n\r\n test_util.action_logger('Complete add l2 resources for [uuid:] %s' \\\r\n % l2_uuid)\r\n\r\ndef add_l3_resource(deploy_config, l3_name, l2_name = None, zone_name = None, \\\r\n session_uuid = None):\r\n session_uuid_flag = True\r\n if not session_uuid:\r\n session_uuid = acc_ops.login_as_admin()\r\n session_uuid_flag = False\r\n try:\r\n dep_ops.add_l3_network(deploy_config, session_uuid, l3_name = l3_name, \\\r\n l2_name = l2_name, zone_name = zone_name)\r\n dep_ops.add_virtual_router(deploy_config, session_uuid, \\\r\n l3_name = l3_name, zone_name = zone_name)\r\n l3_uuid = res_ops.get_resource(res_ops.L3_NETWORK, session_uuid, \\\r\n name = l3_name)[0].uuid\r\n except Exception as e:\r\n test_util.test_logger('[Error] zstack deployment meets exception when adding l3 resource .')\r\n traceback.print_exc(file=sys.stdout)\r\n raise e\r\n finally:\r\n if not session_uuid_flag:\r\n acc_ops.logout(session_uuid)\r\n\r\n test_util.action_logger('Complete add l3 resources for [uuid:] %s' \\\r\n % l3_uuid)\r\n\r\ndef delete_ip_range(ip_range_uuid, session_uuid = None):\r\n action = api_actions.DeleteIpRangeAction()\r\n action.sessionUuid = session_uuid\r\n action.uuid = ip_range_uuid\r\n action.timeout = 300000\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n test_util.action_logger(\"[IP Range:] %s is deleted\" % ip_range_uuid)\r\n return evt\r\n\r\ndef add_ip_range(ip_range_option, session_uuid = None):\r\n action = api_actions.AddIpRangeAction()\r\n action.sessionUuid = session_uuid\r\n action.timeout = 30000\r\n action.name = ip_range_option.get_name()\r\n action.startIp = ip_range_option.get_startIp()\r\n action.endIp = ip_range_option.get_endIp()\r\n action.netmask = ip_range_option.get_netmask()\r\n action.gateway = ip_range_option.get_gateway()\r\n action.l3NetworkUuid = ip_range_option.get_l3_uuid()\r\n action.description = ip_range_option.get_description()\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n test_util.action_logger(\"[IP Range:] %s is add\" % evt.inventory.uuid)\r\n return evt.inventory\r\n\r\ndef detach_l2(l2_uuid, cluster_uuid, session_uuid = None):\r\n action = api_actions.DetachL2NetworkFromClusterAction()\r\n action.sessionUuid = session_uuid\r\n action.timeout = 90000\r\n action.l2NetworkUuid = l2_uuid\r\n action.clusterUuid = cluster_uuid\r\n test_util.action_logger('Detach [l2:] %s from [cluster:] %s' % \\\r\n (l2_uuid, cluster_uuid))\r\n evt = acc_ops.execute_action_with_session(action, session_uuid)\r\n return evt\r\n\r\ndef get_ip_capacity_by_l3s(l3_network_list):\r\n action = api_actions.GetIpAddressCapacityAction()\r\n action.l3NetworkUuids = l3_network_list\r\n evt = acc_ops.execute_action_with_session(action, None)\r\n return evt\r\n \r\n","repo_name":"hyhhui/zstack-woodpecker","sub_path":"zstackwoodpecker/zstackwoodpecker/operations/net_operations.py","file_name":"net_operations.py","file_ext":"py","file_size_in_byte":15953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"10510225439","text":"\"\"\"AXL addUser/addLine/addPhone sample script, using the Zeep SOAP library\r\nCopyright (c) 2018 Cisco and/or its affiliates.\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n\"\"\"\r\n# This was tested and used on CUCM 11.5\r\n# Note you must have the schema folder/files and CUCM .pem certs in the same location as script\r\n# AXLAPI.wsdl\r\n# AXLEnums.xsd\r\n# AXLSoap.xsd\r\n\r\nfrom lxml import etree\r\nfrom requests import Session\r\nfrom requests.auth import HTTPBasicAuth\r\nfrom getpass import getpass\r\n\r\nimport keyring\r\n\r\nfrom zeep import Client, Settings, Plugin, xsd\r\nfrom zeep.transports import Transport\r\nfrom zeep.exceptions import Fault\r\nimport sys\r\nimport time\r\nimport logging\r\nfrom progress.spinner import Spinner\r\nimport re\r\n\r\n# Use keyring to store username/passwords in Windows credential manager\r\nresetCredentials = False\r\ncucmusername = ''\r\n\r\n\r\ndef _setup_cucm_username():\r\n global cucmusername\r\n # Change username & password variables as you see fit\r\n cucmusername = keyring.get_password(\"username\", \"username\")\r\n if cucmusername is None or cucmusername == \"\" or resetCredentials is True:\r\n print()\r\n print(\"No CUCM username found in local credential manager. Let's add it.\")\r\n print()\r\n cucmusername = getpass(prompt=\"Please enter your CUCM username: Note: you will not see what's being typed: \")\r\n if cucmusername is None or cucmusername == \"\":\r\n print(\"No username entered. Goodbye.\")\r\n sys.exit(1)\r\n else:\r\n keyring.set_password(\"username\", \"username\", cucmusername)\r\n print('Added AM CUCM username to the local credential manager under \"username.\"')\r\n\r\n\r\n_setup_cucm_username()\r\n\r\n\r\ncucmpassword = ''\r\n\r\n\r\ndef _setup_cucm_pw():\r\n global cucmpassword\r\n global resetCredentials\r\n cucmpassword = keyring.get_password(\"cucmpassword\", \"cucmpassword\")\r\n if cucmpassword is None or cucmpassword == \"\" or resetCredentials is True:\r\n print()\r\n print(\"No CUCM password found in local credential manager. Let's add it.\")\r\n print()\r\n cucmpassword = getpass(prompt=\"Please enter your CUCM password: \")\r\n if cucmpassword is None or cucmpassword == \"\":\r\n print(\"No password entered. Goodbye.\")\r\n sys.exit(1)\r\n else:\r\n keyring.set_password(\"cucmpassword\", \"cucmpassword\", cucmpassword)\r\n resetCredentials = False\r\n print('Added AM CUCM password to the local credential manager under \"cucmpassword.\"')\r\n\r\n\r\n_setup_cucm_pw()\r\n\r\n# Set up logging\r\nlog = \"standard.log\"\r\nlogging.basicConfig(filename='standard.log', level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%d/%m/%Y %H:%M:%S')\r\nlogging.info(cucmusername + ' started running the script')\r\n\r\n# CUCM Menu\r\nsessionCert = ''\r\nserverUrl = ''\r\nuserEnteredRegion = ''\r\nlocationMenu = {}\r\nlocationMenu[\"\\n1\"] = 'US'\r\nlocationMenu[\"2\"] = 'Europe'\r\nlocationMenu[\"3\"] = 'APAC'\r\nwhile True:\r\n options = locationMenu.keys()\r\n for entry in options:\r\n print(entry, locationMenu[entry])\r\n\r\n selection = input(\"Please select regional CUCM you'd like to work with: \")\r\n if selection == \"1\":\r\n userEnteredRegion = 'US'\r\n sessionCert = 'us-cert-chain.pem'\r\n serverUrl = 'https://insertUSCUCMURL:8443/axl/'\r\n break\r\n elif selection == \"2\":\r\n userEnteredRegion = 'Europe'\r\n sessionCert = 'europe-cert-chain.pem'\r\n serverUrl = 'https://insertEuropeCUCMURL:8443/axl/'\r\n break\r\n elif selection == \"3\":\r\n userEnteredRegion = 'APAC'\r\n sessionCert = 'apac-cert-chain.pem'\r\n serverUrl = 'https://insertAPACCUCMURL.net:8443/axl/'\r\n break\r\n\r\n# Location Menu\r\ndevicePoolName = None\r\nlocationName = None\r\ncallingSearchSpaceName = None\r\ncallForwardAll = None\r\nexternalMask = None\r\nif userEnteredRegion == 'US':\r\n # US Location Menu\r\n # Set cluster specific variables\r\n commonDeviceConfigName = 'US-PHONES'\r\n softkeyTemplateName = 'Standard User'\r\n userLocale = 'English United States'\r\n routePartitionName = 'ALL_IPPhones'\r\n locationMenu = {}\r\n locationMenu[\"\\n1\"] = 'Location 1'\r\n locationMenu[\"2\"] = 'Location 2'\r\n # you get the idea\r\n\r\n while True:\r\n options = locationMenu.keys()\r\n for entry in options:\r\n print(entry, locationMenu[entry])\r\n\r\n selection = input(\"Please select the location for this phone setup: \")\r\n if selection == \"1\":\r\n devicePoolName = 'LOCATION1_PHONES'\r\n locationName = 'LOCATION1'\r\n callingSearchSpaceName = 'LOCATION1_INTERNATIONAL'\r\n callForwardAll = {'callingSearchSpaceName': 'LOCATION1_CFA_CSS'}\r\n break\r\n elif selection == \"2\":\r\n devicePoolName = 'LOCATION2_PHONES'\r\n locationName = 'LOCATION2'\r\n callingSearchSpaceName = 'LOCATION2_LONG_DISTANCE'\r\n callForwardAll = {'callingSearchSpaceName': 'LOCATION2_CFA_CSS'}\r\n break\r\n # you get the idea\r\n\r\nelif userEnteredRegion == 'Europe':\r\n # Europe location menu\r\n userLocale = None\r\n softkeyTemplateName = 'Standard User'\r\n routePartitionName = 'CLUSTER-DN'\r\n locationMenu = {}\r\n locationMenu[\"\\n1\"] = 'Denmark'\r\n locationMenu[\"2\"] = 'Germany'\r\n # you get the idea\r\n\r\n while True:\r\n options = locationMenu.keys()\r\n for entry in options:\r\n print(entry, locationMenu[entry])\r\n\r\n selection = input(\"Please select the location for this phone setup: \")\r\n if selection == \"1\":\r\n devicePoolName = 'DENMARK-PHONES'\r\n commonDeviceConfigName = 'DENMARK-PHONES'\r\n locationName = 'DENMARK'\r\n callingSearchSpaceName = 'DEVICE-DENMARK-UNRESTRICTED'\r\n userLocale = 'Danish Denmark'\r\n callForwardAll = {'callingSearchSpaceName': 'CW-INTERNAL'}\r\n print('\\nDenmark set to allow internal forwarding only (Forward All CSS = CW-INTERNAL)')\r\n # networkLocale = 'Denmark' # shouldn't need this as it's set on device pool\r\n break\r\n elif selection == \"2\":\r\n devicePoolName = 'GERMANY-PHONES'\r\n commonDeviceConfigName = 'GERMANY-PHONES'\r\n locationName = 'GERMANY'\r\n callingSearchSpaceName = 'DEVICE-GERMANY-UNRESTRICTED'\r\n userLocale = 'German Germany'\r\n callForwardAll = {'callingSearchSpaceName': 'CW-INTERNAL'}\r\n print('\\nDiamant set to allow internal forwarding only (Forward All CSS = CW-INTERNAL)')\r\n break\r\n # you get the idea\r\n\r\nelif userEnteredRegion == 'APAC':\r\n # APAC menu for agent location\r\n userLocale = None\r\n softkeyTemplateName = 'CUSTOM User'\r\n routePartitionName = 'SYSTEM-CLUSTER-DN'\r\n locationMenu = {}\r\n locationMenu[\"\\n1\"] = 'Australia'\r\n locationMenu[\"2\"] = 'Japan'\r\n # you get the idea\r\n\r\n while True:\r\n options = locationMenu.keys()\r\n for entry in options:\r\n print(entry, locationMenu[entry])\r\n\r\n selection = input(\"Please select the location for this phone setup: \")\r\n if selection == \"1\":\r\n devicePoolName = 'AUSTRALIA-PHONES'\r\n commonDeviceConfigName = 'AUSTRALIA-PHONES'\r\n locationName = 'AUSTRALIA'\r\n callingSearchSpaceName = 'AUSTRALIA-UNRESTRICTED'\r\n userLocale = 'English United States'\r\n softkeyTemplateName = 'CUSTOM AUSTRALIA User'\r\n callForwardAll = {'callingSearchSpaceName': 'SYSTEM-CW-INTERNAL'}\r\n print('\\nAustralia set to allow internal forwarding only (Forward All CSS = SYSTEM-CW-INTERNAL)')\r\n break\r\n elif selection == \"2\":\r\n devicePoolName = 'JAPAN-PHONES'\r\n commonDeviceConfigName = 'JAPAN-PHONES'\r\n locationName = 'JAPAN'\r\n callingSearchSpaceName = 'JAPAN-UNRESTRICTED'\r\n userLocale = 'Japanese Japan'\r\n callForwardAll = {'callingSearchSpaceName': 'SYSTEM-CW-INTERNAL'}\r\n print('\\nJapan set to allow internal forwarding only (Forward All CSS = SYSTEM-CW-INTERNAL)')\r\n break\r\n\r\n\r\ndef _get_Phone_Mac_Address():\r\n global phoneMac\r\n global deskPhoneDeviceName\r\n phoneMac = input(\"\\nPlease enter the MAC address of the desk phone (Quit if there's no desk phone): \")\r\n if re.match(\"[0-9a-f]{2}([-:]?)[0-9a-f]{2}(\\\\1[0-9a-f]{2}){4}$\", phoneMac.lower()):\r\n # regex replacement of - & :\r\n phoneMac = re.sub(r'[:-]', '', phoneMac)\r\n deskPhoneDeviceName = 'SEP' + phoneMac.upper()\r\n else:\r\n print('Invalid MAC address, please try again.')\r\n _get_Phone_Mac_Address()\r\n\r\n\r\n# Get Prereqs / input data\r\nphoneUsername = input(\"\\nPlease enter the username of the person for the phone setup: \")\r\nphoneExt = input(\"\\nPlease enter the extension for the phone setup: \")\r\n# Menu for type of phone build Jabber/Deskphone/CIPC etc.\r\nuserEnteredPhoneModel = ''\r\njabberOnly = False\r\ndeskPhoneOnly = False\r\nphoneMac = None\r\ndeskPhoneDeviceName = None\r\nphoneBuildMenu = {}\r\nphoneBuildMenu[\"\\n1\"] = 'Desk Phone Only'\r\nphoneBuildMenu[\"2\"] = 'Jabber Only'\r\nphoneBuildMenu[\"3\"] = 'Desk Phone & Jabber'\r\nwhile True:\r\n options = phoneBuildMenu.keys()\r\n for entry in options:\r\n print(entry, phoneBuildMenu[entry])\r\n selection = input(\"Please select the type of phone build: \")\r\n if selection == \"1\":\r\n deskPhoneOnly = True\r\n userEnteredPhoneModel = input(\"\\nPlease enter the model of the desk phone (e.g. 7942): \")\r\n # replaced simple input with function to validate mac address\r\n _get_Phone_Mac_Address()\r\n break\r\n elif selection == \"2\":\r\n jabberOnly = True\r\n break\r\n elif selection == \"3\":\r\n userEnteredPhoneModel = input(\"\\nPlease enter the model of the desk phone (e.g. 7942): \")\r\n phoneMac = input(\"\\nPlease enter the MAC address of the desk phone (Quit if there's no desk phone): \")\r\n deskPhoneDeviceName = 'SEP' + phoneMac\r\n break\r\n\r\n\r\ndef _setup_connection():\r\n # Setup SOAP/AXL/HTTPS Connection\r\n global service\r\n # Change to true to enable output of request/response headers and XML\r\n DEBUG = False\r\n\r\n # The WSDL is a local file in the working directory, see README\r\n WSDL_FILE = 'schema/AXLAPI.wsdl'\r\n\r\n # This class lets you view the incoming and outgoing http headers and XML\r\n\r\n class MyLoggingPlugin(Plugin):\r\n\r\n def egress(self, envelope, http_headers, operation, binding_options):\r\n\r\n # Format the request body as pretty printed XML\r\n xml = etree.tostring(envelope, pretty_print=True, encoding='unicode')\r\n\r\n print(f'\\nRequest\\n-------\\nHeaders:\\n{http_headers}\\n\\nBody:\\n{xml}')\r\n\r\n def ingress(self, envelope, http_headers, operation):\r\n\r\n # Format the response body as pretty printed XML\r\n xml = etree.tostring(envelope, pretty_print=True, encoding='unicode')\r\n\r\n print(f'\\nResponse\\n-------\\nHeaders:\\n{http_headers}\\n\\nBody:\\n{xml}')\r\n\r\n\r\n # The first step is to create a SOAP client session\r\n session = Session()\r\n\r\n # We avoid certificate verification by default\r\n # session.verify = False\r\n\r\n # To enabled SSL cert checking (recommended for production)\r\n # place the CUCM Tomcat cert .pem file in the root of the project\r\n # and uncomment the line below\r\n\r\n session.verify = sessionCert\r\n\r\n # Add Basic Auth credentials\r\n session.auth = HTTPBasicAuth(cucmusername, cucmpassword)\r\n\r\n # Create a Zeep transport and set a reasonable timeout value\r\n transport = Transport(session=session, timeout=10)\r\n\r\n # strict=False is not always necessary, but it allows zeep to parse imperfect XML\r\n settings = Settings(strict=False, xml_huge_tree=True)\r\n\r\n # If debug output is requested, add the MyLoggingPlugin callback\r\n plugin = [MyLoggingPlugin()] if DEBUG else [ ]\r\n\r\n # Create the Zeep client with the specified settings\r\n client = Client(WSDL_FILE, settings=settings, transport=transport,\r\n plugins=plugin)\r\n\r\n # FUTURE create CUCM chooser menu\r\n\r\n # Create the Zeep service binding to AXL at the specified CUCM\r\n service = client.create_service('{http://www.cisco.com/AXLAPIService/}AXLAPIBinding', serverUrl)\r\n\r\n\r\n_setup_connection()\r\n\r\n\r\ndef _check_for_existing_setup():\r\n global resetCredentials\r\n global associatedDevices\r\n # Find out if there's an existing phone/extension and if it's associated with the line\r\n try:\r\n lineResp = service.getLine(pattern=phoneExt, routePartitionName=routePartitionName)\r\n # Unpack line dict and get associatedDevices. Format: userDetails = rawresp['return'].user\r\n associatedDevices = lineResp['return'].line.associatedDevices\r\n except Fault as err:\r\n if str(err) == 'Item not valid: The specified Line was not found':\r\n # Extension doesn't exist either error out or ask to create\r\n # print(f'Zeep error: getLine: { err }')\r\n logging.warning(cucmusername + ' Extension does not exist')\r\n userResp = input('\\nThis extension does not exist, would you like to create? (y/n) ')\r\n if userResp == 'y' or userResp == 'Y':\r\n # FUTURE create ext.\r\n input('\\nCode to create new extension has not been implemented, exiting.')\r\n sys.exit(1)\r\n else:\r\n input('\\nPress Enter to quit.')\r\n sys.exit(1)\r\n elif str(err) == 'Unknown fault occured':\r\n # Wrong credentials?\r\n logging.error(cucmusername + ' ' + str(err))\r\n print(f'Zeep error: getLine: { err }')\r\n resetCredentailMenu = {}\r\n resetCredentailMenu[\"\\n1\"] = 'Try username & password again'\r\n resetCredentailMenu[\"2\"] = 'Quit'\r\n while True:\r\n options = resetCredentailMenu.keys()\r\n for entry in options:\r\n print(entry, resetCredentailMenu[entry])\r\n selection = input(\"Error authenticating or unknown error. Choose an option above: \")\r\n if selection == \"1\":\r\n resetCredentials = True\r\n _setup_cucm_username()\r\n _setup_cucm_pw()\r\n _setup_connection()\r\n _check_for_existing_setup()\r\n break\r\n elif selection == \"2\":\r\n sys.exit(1)\r\n break\r\n else:\r\n logging.error(cucmusername + ' ' + str(err))\r\n print(f'Zeep error: getLine: { err }')\r\n input('\\nCheck the error above and consult admin if needed, exiting.')\r\n sys.exit(1)\r\n\r\n\r\n_check_for_existing_setup()\r\n\r\n# Assume extension exists and continuing to create phone/device profile\r\n# Ask if you want to blow it away or quit\r\nif associatedDevices is None or associatedDevices == \"\":\r\n print('\\nNo devices associated with this line, continuing setup...')\r\nelse:\r\n\r\n print(associatedDevices)\r\n existingDeviceMenu = {}\r\n existingDeviceMenu[\"\\n1\"] = 'CONTINUE: I am adding a device to an existing user that already has a phone.'\r\n existingDeviceMenu[\"2\"] = 'DELETE: Remove or re-use this phone (This will delete all phones above. WARNING: All previous configuration will be lost.)'\r\n existingDeviceMenu[\"3\"] = 'QUIT (check the device name/mac address or clean things up manually in CUCM.)'\r\n while True:\r\n options = existingDeviceMenu.keys()\r\n for entry in options:\r\n print(entry, existingDeviceMenu[entry])\r\n selection = input('A device already exists with this extension. What would you like to do? ')\r\n if selection == \"1\":\r\n break\r\n # need to test this code\r\n elif selection == \"2\":\r\n service.removePhone(name=associatedDevices)\r\n print('Deleted these devices:')\r\n print(associatedDevices)\r\n break\r\n elif selection == \"3\":\r\n sys.exit(1)\r\n break\r\n\r\n# Force LDAP Sync to pull name instead of prompting for them\r\ntry:\r\n resp = service.doLdapSync(name='LDAP', sync='true')\r\nexcept Fault as err:\r\n logging.error(cucmusername + ' ' + str(err))\r\n print(f'Zeep error: doLdapSync: { err }')\r\n input('\\n Press Enter to quit.')\r\n sys.exit(1)\r\n# Loop and get status of LDAP sync before proceeding. Wait 1 second or it gets caught before complete\r\nspinner = Spinner('LDAP Syncing. This may take 1-2 minutes... ')\r\ntime.sleep(1)\r\nldapSyncStatus = ''\r\nwhile ldapSyncStatus != 'Sync is performed successfully':\r\n try:\r\n resp = service.getLdapSyncStatus(name='LDAP')\r\n ldapSyncStatus = resp['return']\r\n except Fault as err:\r\n logging.error(cucmusername + ' ' + str(err))\r\n print(f'Zeep error: doLdapSync: { err }')\r\n spinner.next()\r\n time.sleep(1)\r\nprint(' LDAP Sync Successful...\\n')\r\n\r\n# Execute the getUser request\r\ntry:\r\n getUserResponse = service.getUser(userid=phoneUsername)\r\n userDetails = getUserResponse['return'].user\r\n phoneLname = userDetails.lastName\r\n phoneFname = userDetails.firstName\r\nexcept Fault as err:\r\n logging.error(cucmusername + ' ' + str(err))\r\n print(f'Zeep error: getUser: { err }')\r\n input('\\n Press Enter to quit.')\r\n sys.exit(1)\r\n\r\n# Normalize some data\r\njabberDeviceName = 'csf' + phoneUsername\r\nphoneDescription = phoneFname + ' ' + phoneLname + ' - ' + phoneExt\r\nphoneDisplay = phoneLname + ', ' + phoneFname[0]\r\nphoneModel = 'Cisco ' + userEnteredPhoneModel\r\n\r\nlogging.info(cucmusername + ' setting up ' + phoneUsername + ' ' + phoneDescription + ' in ' + locationName)\r\ninput('Continue phone build for ' + phoneDescription + ' in ' + locationName + ' ? (Press Ctrl + C to quit. Press Enter to continue...)')\r\n\r\n\r\ndef _setup_Jabber():\r\n # Create the data for adding Jabber, associating the Line\r\n phone = {\r\n 'name': jabberDeviceName,\r\n 'description': phoneDescription,\r\n 'product': 'Cisco Unified Client Services Framework',\r\n 'model': 'Cisco Unified Client Services Framework',\r\n 'class': 'Phone',\r\n 'protocol': 'SIP',\r\n 'protocolSide': 'User',\r\n 'devicePoolName': devicePoolName,\r\n 'commonDeviceConfigName': commonDeviceConfigName,\r\n 'phoneTemplateName': 'Standard Client Services Framework',\r\n 'commonPhoneConfigName': 'Standard Common Phone Profile',\r\n 'locationName': locationName,\r\n 'useTrustedRelayPoint': 'Default',\r\n 'builtInBridgeStatus': 'Default',\r\n 'deviceMobilityMode': 'Default',\r\n 'callingSearchSpaceName': callingSearchSpaceName,\r\n 'retryVideoCallAsAudio': 'true',\r\n 'allowCtiControlFlag': 'true',\r\n 'hlogStatus': 'On',\r\n 'packetCaptureMode': 'None',\r\n 'certificateOperation': 'No Pending Operation',\r\n 'enableExtensionMobility': 'true',\r\n # Add line\r\n 'lines': {\r\n 'line': [\r\n {\r\n 'index': 1,\r\n 'label': phoneDescription, # Line text label\r\n 'dirn': {\r\n 'pattern': phoneExt,\r\n 'routePartitionName': routePartitionName,\r\n },\r\n 'display': phoneDisplay,\r\n 'displayAscii': phoneDisplay,\r\n 'e164Mask': externalMask, # Used in specific locations\r\n 'associatedEndusers': {\r\n 'enduser': [\r\n {\r\n 'userId': phoneUsername\r\n }\r\n ]\r\n }\r\n }\r\n ]\r\n },\r\n 'securityProfileName': 'Cisco Unified Client Services Framework - Standard SIP Non-Secure Profile'\r\n }\r\n # Execute the addPhone request\r\n try:\r\n resp = service.addPhone(phone)\r\n logging.info(cucmusername + ' created Jabber device ' + jabberDeviceName)\r\n\r\n except Fault as err:\r\n logging.error(cucmusername + ' ' + str(err))\r\n print(f'Zeep error: addPhone: { err }')\r\n input('\\n Press Enter to quit.')\r\n sys.exit(1)\r\n # print('\\naddPhone response:\\n')\r\n # print(resp, '\\n')\r\n input('Jabber creation complete. Press Enter to continue...')\r\n\r\n # Execute the updateLine request\r\n try:\r\n resp = service.updateLine(\r\n pattern=phoneExt,\r\n routePartitionName=routePartitionName,\r\n alertingName=phoneDisplay,\r\n asciiAlertingName=phoneDisplay,\r\n description=phoneDescription,\r\n callForwardAll=callForwardAll\r\n )\r\n\r\n except Fault as err:\r\n logging.error(cucmusername + ' ' + str(err))\r\n print(f'Zeep error: updateLine: { err }')\r\n input('\\n Press Enter to quit.')\r\n sys.exit(1)\r\n # print('\\nupdateLine response:\\n')\r\n # print(resp, '\\n')\r\n input('Line Updated. Press Enter to continue...')\r\n\r\n\r\ndef _setup_desk_phone():\r\n # may need to add more models to diferentiate SIP/SCCP\r\n if phoneModel.startswith('Cisco 78') or phoneModel.startswith('Cisco 88'):\r\n protocol = 'SIP'\r\n securityProfileName = phoneModel + ' - Standard SIP Non-Secure Profile'\r\n else:\r\n protocol = 'SCCP'\r\n securityProfileName = None\r\n if userEnteredPhoneModel == '7942' or userEnteredPhoneModel == '7962':\r\n phoneTemplateName = 'Standard ' + userEnteredPhoneModel + 'G ' + protocol\r\n else:\r\n phoneTemplateName = 'Standard ' + userEnteredPhoneModel + ' ' + protocol\r\n phone = {\r\n 'name': deskPhoneDeviceName,\r\n 'description': phoneDescription,\r\n 'product': phoneModel,\r\n 'model': phoneModel,\r\n 'class': 'Phone',\r\n 'protocol': protocol,\r\n 'protocolSide': 'User',\r\n 'devicePoolName': devicePoolName,\r\n 'commonDeviceConfigName': commonDeviceConfigName,\r\n 'phoneTemplateName': phoneTemplateName,\r\n 'softkeyTemplateName': softkeyTemplateName,\r\n 'commonPhoneConfigName': 'Standard Common Phone Profile',\r\n 'locationName': locationName,\r\n 'useTrustedRelayPoint': 'Default',\r\n 'builtInBridgeStatus': 'Default',\r\n 'deviceMobilityMode': 'Default',\r\n 'callingSearchSpaceName': callingSearchSpaceName,\r\n 'retryVideoCallAsAudio': 'true',\r\n 'allowCtiControlFlag': 'true',\r\n 'hlogStatus': 'On',\r\n 'packetCaptureMode': 'None',\r\n 'certificateOperation': 'No Pending Operation',\r\n 'enableExtensionMobility': 'true',\r\n 'securityProfileName': securityProfileName,\r\n # Add line\r\n 'lines': {\r\n 'line': [\r\n {\r\n 'index': 1,\r\n 'label': phoneDescription, # Line text label\r\n 'dirn': {\r\n 'pattern': phoneExt,\r\n 'routePartitionName': routePartitionName,\r\n },\r\n 'display': phoneDisplay,\r\n 'displayAscii': phoneDisplay,\r\n 'e164Mask': externalMask, # Used in specific locations\r\n 'associatedEndusers': {\r\n 'enduser': [\r\n {\r\n 'userId': phoneUsername\r\n }\r\n ]\r\n }\r\n }\r\n ]\r\n }\r\n }\r\n\r\n # Execute the addPhone request\r\n try:\r\n resp = service.addPhone(phone)\r\n logging.info(cucmusername + ' created desk phone ' + deskPhoneDeviceName + ' ' + userEnteredPhoneModel)\r\n # TODO Future add handling for a device that already exists\r\n # Could not insert new row - duplicate value in a UNIQUE INDEX column (Unique Index:)\r\n except Fault as err:\r\n logging.error(cucmusername + ' ' + str(err))\r\n print(f'Zeep error: addPhone: { err }')\r\n input('\\n Press Enter to quit.')\r\n sys.exit(1)\r\n # print('\\naddPhone response:\\n')\r\n # print(resp, '\\n')\r\n input('Desk phone creation complete. Press Enter to continue...')\r\n\r\n # Execute the updateLine request\r\n try:\r\n resp = service.updateLine(\r\n pattern=phoneExt,\r\n routePartitionName=routePartitionName,\r\n alertingName=phoneDisplay,\r\n asciiAlertingName=phoneDisplay,\r\n description=phoneDescription,\r\n callForwardAll=callForwardAll\r\n )\r\n\r\n except Fault as err:\r\n logging.error(cucmusername + ' ' + str(err))\r\n print(f'Zeep error: updateLine: { err }')\r\n input('\\n Press Enter to quit.')\r\n sys.exit(1)\r\n # print('\\nupdateLine response:\\n')\r\n # print(resp, '\\n')\r\n input('Line Updated. Press Enter to continue...')\r\n\r\n\r\ndef _update_End_User():\r\n # LDAP sync should have occured above\r\n # Set data for UpdateUser Request (only variables with multiple values)\r\n\r\n primaryExtension = {\r\n 'pattern': phoneExt,\r\n 'routePartitionName': routePartitionName\r\n }\r\n associatedGroups = {\r\n 'userGroup': [\r\n {'name': 'Standard CCM End Users'},\r\n {'name': 'Standard CTI Enabled'}\r\n ]\r\n }\r\n if deskPhoneOnly:\r\n # Get existing data and append or it will wipe out existing associations\r\n try:\r\n resp = service.getUser(userid=phoneUsername)\r\n userDetails = resp['return'].user\r\n currentAssociatedDeviceList = userDetails.associatedDevices\r\n except Fault as err:\r\n print(f'Zeep error: getUser: { err }')\r\n input('\\n Press Enter to quit.')\r\n sys.exit(1)\r\n # Append desk phone to list\r\n if currentAssociatedDeviceList is None:\r\n updatedAssociatedDevices = {\r\n 'device': deskPhoneDeviceName\r\n }\r\n else:\r\n unpackedAssociatedDevices = currentAssociatedDeviceList.device\r\n unpackedAssociatedDevices.append(deskPhoneDeviceName)\r\n updatedAssociatedDevices = {\r\n 'device': unpackedAssociatedDevices\r\n }\r\n elif jabberOnly:\r\n # Get existing data and append or it will wipe out existing associations\r\n try:\r\n resp = service.getUser(userid=phoneUsername)\r\n userDetails = resp['return'].user\r\n currentAssociatedDeviceList = userDetails.associatedDevices\r\n except Fault as err:\r\n print(f'Zeep error: getUser: { err }')\r\n input('\\n Press Enter to quit.')\r\n sys.exit(1)\r\n # Append jabber to list\r\n if currentAssociatedDeviceList is None:\r\n updatedAssociatedDevices = {\r\n 'device': jabberDeviceName\r\n }\r\n else:\r\n unpackedAssociatedDevices = currentAssociatedDeviceList.device\r\n unpackedAssociatedDevices.append(jabberDeviceName)\r\n updatedAssociatedDevices = {\r\n 'device': unpackedAssociatedDevices\r\n }\r\n else:\r\n # Get existing data and append or it will wipe out existing associations\r\n try:\r\n resp = service.getUser(userid=phoneUsername)\r\n userDetails = resp['return'].user\r\n currentAssociatedDeviceList = userDetails.associatedDevices\r\n except Fault as err:\r\n print(f'Zeep error: getUser: { err }')\r\n input('\\n Press Enter to quit.')\r\n sys.exit(1)\r\n # Append jabber to list\r\n if currentAssociatedDeviceList is None:\r\n updatedAssociatedDevices = {\r\n 'device': [\r\n jabberDeviceName,\r\n deskPhoneDeviceName\r\n ]\r\n }\r\n else:\r\n unpackedAssociatedDevices = currentAssociatedDeviceList.device\r\n unpackedAssociatedDevices.append(deskPhoneDeviceName)\r\n unpackedAssociatedDevices.append(jabberDeviceName)\r\n updatedAssociatedDevices = {\r\n 'device': unpackedAssociatedDevices\r\n }\r\n # Execute update end user (1st time)\r\n if deskPhoneOnly:\r\n try:\r\n resp = service.updateUser(\r\n userid=phoneUsername,\r\n userLocale=userLocale,\r\n homeCluster=True,\r\n associatedDevices=updatedAssociatedDevices,\r\n enableCti=True,\r\n associatedGroups=associatedGroups\r\n )\r\n logging.info(cucmusername + ' first pass updated end user ' + phoneUsername)\r\n except Fault as err:\r\n logging.error(cucmusername + ' ' + str(err))\r\n print(f'Zeep error: updateUser: { err }')\r\n input('\\n Press Enter to quit.')\r\n sys.exit(1)\r\n else:\r\n try:\r\n resp = service.updateUser(\r\n userid=phoneUsername,\r\n userLocale=userLocale,\r\n homeCluster=True,\r\n imAndPresenceEnable=True,\r\n associatedDevices=updatedAssociatedDevices,\r\n enableCti=True,\r\n associatedGroups=associatedGroups\r\n )\r\n logging.info(cucmusername + ' first pass updated end user ' + phoneUsername)\r\n except Fault as err:\r\n logging.error(cucmusername + ' ' + str(err))\r\n print(f'Zeep error: updateUser: { err }')\r\n input('\\n Press Enter to quit.')\r\n sys.exit(1)\r\n # print('\\nupdateUser response:\\n')\r\n # print(resp, '\\n')\r\n\r\n # Execute update end user (2nd time)\r\n try:\r\n resp = service.updateUser(\r\n userid=phoneUsername,\r\n # Need to update after phone/Jabber is associated\r\n primaryExtension=primaryExtension,\r\n )\r\n logging.info(cucmusername + ' second pass updated end user ' + phoneUsername)\r\n except Fault as err:\r\n logging.error(cucmusername + ' ' + str(err))\r\n print(f'Zeep error: updateUser: { err }')\r\n input('\\n Press Enter to quit.')\r\n sys.exit(1)\r\n print('End User Updated...\\n')\r\n\r\n\r\ndef _update_Desk_Phone_Owner():\r\n try:\r\n resp = service.updatePhone(\r\n name=deskPhoneDeviceName,\r\n ownerUserName=phoneUsername\r\n )\r\n logging.info(cucmusername + ' updated desk phone ' + deskPhoneDeviceName + ' owner to ' + phoneUsername)\r\n except Fault as err:\r\n logging.error(cucmusername + ' ' + str(err))\r\n print(f'Zeep error: updatePhone: { err }')\r\n input('\\n Press Enter to quit.')\r\n sys.exit(1)\r\n print('Desk Phone owner updated...\\n')\r\n\r\n\r\ndef _update_Jabber_Owner():\r\n try:\r\n resp = service.updatePhone(\r\n name=jabberDeviceName,\r\n ownerUserName=phoneUsername\r\n )\r\n logging.info(cucmusername + ' updated jabber ' + jabberDeviceName + ' owner to ' + phoneUsername)\r\n except Fault as err:\r\n logging.error(cucmusername + ' ' + str(err))\r\n print(f'Zeep error: updatePhone: { err }')\r\n input('\\n Press Enter to quit.')\r\n sys.exit(1)\r\n print('Jabber owner updated...\\n')\r\n\r\n\r\n# EXECUTE!\r\nif deskPhoneOnly:\r\n _setup_desk_phone()\r\n _update_End_User()\r\n _update_Desk_Phone_Owner()\r\nelif jabberOnly:\r\n _setup_Jabber()\r\n _update_End_User()\r\n _update_Jabber_Owner()\r\nelse:\r\n _setup_desk_phone()\r\n _setup_Jabber()\r\n _update_End_User()\r\n _update_Desk_Phone_Owner()\r\n _update_Jabber_Owner()\r\n\r\nlogging.info(cucmusername + ' succesfully reached end of script')\r\ninput(\r\n 'Complete. Do the following manual tasks where applicable:'\r\n '\\n1:Setup voicemail (import from LDAP using UCXN GUI)'\r\n '\\nPress Enter to quit.')\r\n","repo_name":"dillonator/cucm-provisoning","sub_path":"StandardPhoneSetup.py","file_name":"StandardPhoneSetup.py","file_ext":"py","file_size_in_byte":32819,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"16"}
+{"seq_id":"11760082920","text":"import turtle\n\nimport pandas as pd\n\nfrom scoreboard import Scoreboard\nfrom get_coor import Get_coor\n\n\nscoreboard=Scoreboard()\nscreen=turtle.Screen()\ncanvas = screen.getcanvas()\nwindow = canvas.create_window((100, 100), width=200, height=100)\nscreen.title(\"US States Game\")\nimage=\"blank_states_img.gif\"\nscreen.addshape(image)\nturtle.shape(image)\n\nscreen.tracer(0)\n\n\n# def get_mouce_click_coor(x,y):\n# print(x,y)\n#\n# turtle.onscreenclick(get_mouce_click_coor)\n\nturtle.penup()\n\nget_coor=Get_coor()\ngameIsOn= True\nwhile gameIsOn:\n correct=scoreboard.score\n userInput=screen.textinput(title=f\"{correct}/50 States Correct\",prompt=\"What's another States?\",)\n coor=(0,0)\n if userInput.title()=='Exit':\n break\n if get_coor.have_available(userInput):\n scoreboard.addScore()\n coor=get_coor.get_location(userInput)\n turtle.goto(coor)\n turtle.write(userInput)\n turtle.goto((0, 0))\n screen.update()\n\n if scoreboard.score==50:\n gameIsOn=False\n\n\n#states to learn.csv\ndic={\n \"Unvisted City\": get_coor.all_city_list\n}\ndf=pd.DataFrame(dic)\ndf.to_csv(\"learn.csv\")\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"mamun464/US_States_Game","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"70970409608","text":"def add_time(start, duration, wday=False):\n\n from math import floor\n\n weekday=[\"saturday\",\"sunday\",\"monday\",\"tuesday\",\"wednesday\",\"thursday\",\"friday\"]\n wd_c=[\"Saturday\",\"Sunday\",\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\"]\n\n st=start.split()\n stt=st[0].split(\":\")\n dtt=duration.split(\":\")\n ampm=st[1]\n if ampm==\"PM\":\n stt_f=[int(stt[0])+12,int(stt[1])]\n else:\n stt_f=[int(stt[0]),int(stt[1])]\n\n dtt_f=[int(dtt[0]),int(dtt[1])]\n \n day=floor(dtt_f[0]/24)\n dtt_f[0]=dtt_f[0]%24\n\n ad=[dtt_f[0]+stt_f[0],dtt_f[1]+stt_f[1]]\n if ad[1]>=60:\n ad[0]=ad[0]+floor(ad[1]/60)\n ad[1]=ad[1]%60\n if ad[0]>=24:\n day=day+floor(ad[0]/24)\n ad[0]=ad[0]%24\n \n if ad[0]>=12:\n ampm=\"PM\"\n ad[0]=ad[0]-12\n else:\n ampm=\"AM\"\n if ad[0]==0:\n ad[0]=12\n\n day_str=''\n if day==0:\n day_str=\"\"\n elif (day==1):\n day_str=\" (next day)\"\n else:\n day_str=\" (\"+str(day)+\" days later)\"\n \n new_time=str(ad[0])+\":\"+str(ad[1]).zfill(2)+\" \"+ampm+day_str \n \n if wday!=False:\n wday=wday.lower()\n wday_n=weekday.index(wday)\n wday_n=((wday_n+day+1)%7)-1\n new_time=str(ad[0])+\":\"+str(ad[1]).zfill(2)+\" \"+ampm+\", \"+wd_c[wday_n]+day_str \n\n return new_time","repo_name":"azminewasi/FreeCodeCamp-Certification-Projects","sub_path":"Scientific Computing with Python Projects/p2-time-calculator/time_calculator.py","file_name":"time_calculator.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"16"}
+{"seq_id":"41881193738","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nPyMLGame - Event\n\"\"\"\n\nfrom pymlgame.locals import E_KEYDOWN, E_KEYUP\n\n\nclass Event(object):\n def __init__(self, uid, type, data=None):\n self.uid = uid\n self.type = type\n if type == E_KEYDOWN or type == E_KEYUP:\n self.button = data\n else:\n self.data = data\n","repo_name":"PyMLGame/pymlgame","sub_path":"pymlgame/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"16"}
+{"seq_id":"26603274358","text":"while True:\n try:\n h = input()\n h = h.split(':')\n\n hora = int(h[0]) + 1\n minuto = int(h[1])\n\n aux = hora - 8\n\n if aux < 0:\n print('Atraso maximo: 0')\n else:\n minuto += 60 * aux\n print(f'Atraso maximo: {minuto}')\n\n except EOFError:\n break\n","repo_name":"EdilsonJr/Uri-Judge-Python","sub_path":"beginner/2003.py","file_name":"2003.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"9258269846","text":"import logging\n\nfrom celery import shared_task\n\nfrom sme_ptrf_apps.core.models import (\n AcaoAssociacao,\n Arquivo,\n Associacao,\n ContaAssociacao,\n FechamentoPeriodo,\n Periodo,\n PrestacaoConta,\n)\n\nfrom sme_ptrf_apps.core.services.enviar_email import enviar_email_html\n\nlogger = logging.getLogger(__name__)\n\n\n@shared_task(\n retry_backoff=2,\n retry_kwargs={'max_retries': 8},\n time_limet=600,\n soft_time_limit=300\n)\ndef concluir_prestacao_de_contas_async(periodo_uuid, associacao_uuid):\n from sme_ptrf_apps.core.services.prestacao_contas_services import _criar_documentos, _criar_fechamentos\n\n periodo = Periodo.by_uuid(periodo_uuid)\n associacao = Associacao.by_uuid(associacao_uuid)\n prestacao = PrestacaoConta.abrir(periodo=periodo, associacao=associacao)\n\n acoes = associacao.acoes.filter(status=AcaoAssociacao.STATUS_ATIVA)\n contas = associacao.contas.filter(status=ContaAssociacao.STATUS_ATIVA)\n\n _criar_fechamentos(acoes, contas, periodo, prestacao)\n logger.info('Fechamentos criados para a prestação de contas %s.', prestacao)\n\n _criar_documentos(acoes, contas, periodo, prestacao)\n logger.info('Documentos gerados para a prestação de contas %s.', prestacao)\n\n prestacao = prestacao.concluir()\n logger.info('Concluída a prestação de contas %s.', prestacao)\n\n\n@shared_task(\n retry_backoff=2,\n retry_kwargs={'max_retries': 8},)\ndef processa_carga_async(arquivo_uuid):\n from sme_ptrf_apps.core.services import processa_carga\n logger.info(\"Processando arquivo %s\", arquivo_uuid)\n arquivo = Arquivo.objects.filter(uuid=arquivo_uuid).first()\n if not arquivo:\n logger.info(\"Arquivo não encontrado %s\", arquivo_uuid)\n else:\n logger.info(\"Arquivo encontrado %s\", arquivo_uuid)\n processa_carga(arquivo)\n\n","repo_name":"ollyvergithub/SME-PTRF-BackEnd","sub_path":"sme_ptrf_apps/core/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"71881250887","text":"file = open(\"trans.test\",\"r\",encoding='utf-8')\r\ncontents = file.readlines()\r\n# print(contents[1:10][:])\r\nadmin = []\r\nfor msg in contents:\r\n msg = msg.strip('\\n')\r\n adm = msg.split(';')\r\n if '\"src_text\":\"\"' in adm[1]:\r\n adm[1] = ''\r\n admin.append(adm)\r\n# print(admin[0:5])\r\nfile.close()\r\n# for i in admin:\r\n # if \r\nwith open('desc_trans.txt','w',encoding='utf-8') as f:\r\n# with open('otomevn_full.txt','w') as f:\r\n for i in admin:\r\n for j in i:\r\n f.write(j)\r\n f.write(';')\r\n f.write('\\n')\r\n f.close()","repo_name":"yunpingwang27/otomegame","sub_path":"deal_trans.py","file_name":"deal_trans.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"73784160009","text":"from flask import Blueprint, request\nfrom task.models import Task\nfrom user.models import User\nfrom db import db\n\ntask_blueprint = Blueprint('task', __name__)\n\n@task_blueprint.route(\"\", methods=[\"POST\"])\ndef create_tasks():\n # check json or not\n if not request.is_json:\n return {\"error\": \"Bukan json!!\"}, 400\n\n data = request.get_json()\n \n # task available in data or not\n if \"title\" not in data:\n return {\"error\": \"Title not available\"}, 400\n \n title = data.get(\"title\")\n user_id = data.get(\"user_id\")\n\n user = User.query.get(user_id)\n if not user:\n return {\"error\": \"User not found!\"}, 404\n \n task = Task(user=user, title=title)\n db.session.add(task)\n db.session.commit()\n\n return {\"message\": \"success\"}\n\n# tasks = [{'task': 'Coding with Flask', 'status': 'in progress'}]\n\n# @task_blueprint.route(\"\", methods=[\"GET\"])\n# def get_tasks_list():\n# return tasks\n\n# allowed_status = [\"in progress\", \"to do\", \"done\"]\n\n# @task_blueprint.route(\"/\", methods=[\"PUT\"])\n# def update_tasks(index):\n# if index > len(tasks):\n# return {\"error\": \"task not found!\"}, 404\n \n# data = request.get_json()\n# task = data.get(\"task\")\n# status = data.get(\"status\") # None\n \n# if status not in allowed_status:\n# return {\"error\": \"status tidak valid!\"}, 400 \n\n# updated_task = tasks[index - 1]\n\n# if task:\n# updated_task[\"task\"] = task\n \n# if status:\n# updated_task[\"status\"] = status\n\n# tasks[index - 1] = updated_task\n\n# return tasks\n\n\n# @task_blueprint.route(\"/\", methods=[\"DELETE\"])\n# def delete_task(index):\n# if index > len(tasks):\n# return {\"error\": \"news not found!\"}, 404\n \n# del tasks[index - 1]\n\n# return tasks","repo_name":"luthfihariz/revou-flask-api","sub_path":"day-2/task/apis.py","file_name":"apis.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"5193830482","text":"from basic_python.basictools import pause\n\n\ndef get_y(a, b):\n return lambda x: a * x + b\n\n\ny1 = get_y(14, 3)\nprint(y1(2)) # 结果为2\n\nprint((lambda x, y: x * 3 + y * 78)(90, 5))\n\n\ndef get_y_normal(a, b):\n def func(x):\n return a * x + b\n\n return func\n\n\ny2 = get_y_normal(12, 3)\nprint(y2)\nprint(y2(4))\npause()\n'''\nCreate a function.\n'''\n\n\ndef quicksort(arr):\n if len(arr) <= 1:\n return arr\n pivot = arr[len(arr) // 2]\n left = [x for x in arr if x < pivot]\n middle = [x for x in arr if x == pivot]\n right = [x for x in arr if x > pivot]\n return quicksort(left) + middle + quicksort(right)\n\n\nprint(quicksort([3, 6, 8, 10, 1, 2, 1]))\n\nanimals = ['cat', 'dog', 'monkey']\nfor idx, animal in enumerate(animals):\n print('#%d: %s' % (idx + 1, animal))\n\n'''\nCreate a class.\n'''\n\n\nclass Greeter(object):\n # Constructor\n def __init__(self, name):\n self.name = name # Create an instance variable\n\n # Instance method\n def greet(self, loud=False):\n if loud:\n print('HELLO, %s!' % self.name.upper())\n else:\n print('Hello, %s' % self.name)\n\n\ng = Greeter('Fred') # Construct an instance of the Greeter class\ng.greet() # Call an instance method; prints \"Hello, Fred\"\ng.greet(loud=True) # Call an instance method; prints \"HELLO, FRED!\"\n","repo_name":"likewind1234/nlp-basic-study","sub_path":"basic_python/python.py","file_name":"python.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"17292479395","text":"import pendulum\nfrom airflow.providers.google.cloud.operators.bigquery import (\n BigQueryCreateExternalTableOperator,\n BigQueryDeleteTableOperator,\n)\n\nfrom airflow import DAG\n\nwith DAG(\n dag_id=\"running-buses-gcs-files-dag\",\n description=\"GCP MANAGER DAG\",\n start_date=pendulum.now(),\n tags=[\"live-buses\"],\n) as dag:\n date = pendulum.now(tz=\"America/Sao_Paulo\")\n day = date.format(\"DD\")\n month = date.format(\"MM\")\n year = date.format(\"YYYY\")\n hour = date.format(\"HH\")\n\n project_id = \"bus-data-389717\"\n bq_dataset_name = \"dbt_busdata_stag\"\n\n delete_table = BigQueryDeleteTableOperator(\n task_id=\"delete_table_running_buses\",\n deletion_dataset_table=f\"{project_id}.{bq_dataset_name}.external_table_running_buses\",\n gcp_conn_id=\"google_cloud_default\",\n ignore_if_missing=True,\n )\n\n gcs_bucket_name = \"data_lake_bus_data_bus-data-389717\"\n gcs_path_name = (\n f\"running_buses/year={year}/month={month}/day={day}/hour={hour}/*.csv\"\n )\n # gcs_path_name = f\"running_buses/year={year}/month={month}/day={day}/hour=14/*.csv\"\n # gcs_path_name = f\"running_buses/year={year}/month={month}/day=22/hour=13/part-00000-29e33fc5-b95e-4f0e-b351-1f131fa0eeac-c000.csv\"\n create_external_table = BigQueryCreateExternalTableOperator(\n task_id=\"create_external_table_running_buses\",\n destination_project_dataset_table=f\"{bq_dataset_name}.external_table_running_buses\",\n bucket=gcs_bucket_name,\n source_objects=[gcs_path_name],\n schema_fields=[\n {\"name\": \"line_name\", \"type\": \"STRING\", \"mode\": \"NULLABLE\"},\n {\"name\": \"line_number\", \"type\": \"INTEGER\", \"mode\": \"NULLABLE\"},\n {\"name\": \"qtd_running_buses\", \"type\": \"INTEGER\", \"mode\": \"NULLABLE\"},\n {\"name\": \"timestamp\", \"type\": \"TIMESTAMP\", \"mode\": \"NULLABLE\"},\n ],\n gcp_conn_id=\"google_cloud_default\",\n )\n\n delete_table >> create_external_table\n","repo_name":"warzinnn/bus-data","sub_path":"airflow/dags/running_buses_gcp_dag.py","file_name":"running_buses_gcp_dag.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"8398788129","text":"import pandas as pd\nimport numpy as np\nimport json\nimport os\nfrom sklearn.model_selection import KFold\n\nclass Davis:\n def __init__(self, train=True, sim_type='sis', d_threshold=0.6, p_threshold=0.6):\n self.train = train\n self.sim_type = sim_type\n self.sim_neighbor_num = 5\n self.d_threshold = d_threshold\n self.p_threshold = p_threshold\n\n self.setting2_path = './data/davis/folds/fold_setting2.json'\n self.setting3_path = './data/davis/folds/fold_setting3.json'\n\n self.ligands_path = './data/davis/ligands_can.json'\n self.d_ecfps_path = './data/davis/drug_ecfps.csv'\n self.d_vecs_path = './data/davis/drug_vec.csv'\n self.d_sim_path = './data/davis/drug-drug_similarities_2D.txt'\n self.p_gos_path = './data/davis/protein_go_vector.csv'\n self.p_sim_path = './data/davis/target-target_similarities_WS.txt'\n\n def _load_data(self, setting, fold):\n self.d_vecs = np.loadtxt(self.d_vecs_path, delimiter=',', dtype=float, comments=None)\n self.d_ecfps = np.loadtxt(self.d_ecfps_path, delimiter=',', dtype=int, comments=None)\n\n d_sim_path = self.d_sim_path\n delimiter = ' '\n if self.sim_type != 'default':\n d_sim_path = './data/davis/drug_{}.csv'.format(self.sim_type)\n delimiter = ','\n self.d_sim = np.loadtxt(d_sim_path, delimiter=delimiter, dtype=float, comments=None)\n\n self.p_gos = pd.read_csv(self.p_gos_path, delimiter=',', header=0, index_col=0).to_numpy(float)\n p_sim = np.loadtxt(self.p_sim_path, delimiter=' ', dtype=float, comments=None)\n p_max, p_min = p_sim.max(axis=0), p_sim.min(axis=0)\n self.p_sim = (p_sim - p_min) / (p_max - p_min)\n\n self.p_embeddings = pd.read_csv('./data/davis/protein_embedding.csv', delimiter=',', header=None,\n index_col=0).to_numpy(float)\n\n self.y = np.loadtxt('./data/davis/Y.txt', delimiter=',', dtype=float, comments=None)\n","repo_name":"HuangStomach/SISDTA","sub_path":"data/davis/davis.py","file_name":"davis.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"40688270379","text":"#!/usr/bin/python3\n\"\"\"defines an integer addition function\"\"\"\n\ndef add_integer(a, b=98):\n \"\"\"\n add_integer: adds two integers\n\n Floats are type casted into ints\n\n Raises:\n TypeError: if either a bor b is non int or non-float\n \"\"\"\n\n if ((not isinstance(a, int) and not isinstance(a, float))):\n raise TypeError(\"a must be an integer\")\n\n if ((not isinstance(b, int) and not isinstance(b, float))):\n raise TypeError(\"b must be an integer\")\n\n return (int(a) + int(b))\n","repo_name":"balagrivine/alx-higher_level_programming","sub_path":"0x07-python-test_driven_development/0-add_integer.py","file_name":"0-add_integer.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"5361861433","text":"from django.urls import path, include\nfrom django.conf.urls.static import static\nfrom django.conf import settings\nfrom .views import RenderCertificate, searchCertificate, FindView, UpdateUserView, IndexView, DashboardView, AddCoupleView, PaymentView, AddWedView, AddDivorseView, SearchDocumentView, CertificateView, updateStatus\n\napp_name = 'certification'\nurlpatterns=[\n path('', IndexView.as_view(), name='home'),\n path('search', searchCertificate, name='search'),\n path('certificate/', CertificateView.as_view(), name='certificates'),\n path('dash/certificate/', RenderCertificate.as_view(), name='render-certificates'),\n path('certificate//payment', PaymentView.as_view(), name='payment'),\n path('dash', DashboardView.as_view(), name='dashboard'),\n path('add-couple', AddCoupleView.as_view(), name='add-couple'),\n path('add-wed', AddWedView.as_view(), name='add-wed'),\n path('add-divorse', AddDivorseView.as_view(), name='add-divorse'),\n path('profile/', UpdateUserView.as_view(), name='profile'),\n path('find', FindView.as_view(), name='find'),\n path('certificate/success', updateStatus, name='updatestatus')\n]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)","repo_name":"Bateyjosue/divorse-certification","sub_path":"certification/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"16"}
+{"seq_id":"38351628596","text":"import torch\nimport torchvision\nimport numpy as np\nfrom PIL import Image\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom torchvision.transforms import Compose, Resize, ToTensor, transforms, functional as TF\n\nMEAN = np.array([0.48145466, 0.4578275, 0.40821073]).reshape(-1, 1, 1)\nSTD = np.array([0.26862954, 0.26130258, 0.27577711]).reshape(-1, 1, 1)\n\n\ndef get_image_grid(images):\n # preprocess images\n image_size = (224, 224)\n image_preprocess = Compose([\n Resize(image_size, interpolation=Image.BICUBIC),\n ToTensor()\n ])\n images = [image_preprocess(img) for img in images]\n\n # stack into a grid and return\n image_stack = torch.tensor(np.stack(images))\n image_grid = torchvision.utils.make_grid(image_stack, nrow=5)\n transform = transforms.ToPILImage()\n image_grid = transform(image_grid)\n\n return image_grid\n\n\ndef get_similarity_heatmap(scores, images, text, transpose_flag):\n count_images = len(images)\n count_text = len(text)\n scores = np.round(scores, 2)\n scores = scores.T if transpose_flag else scores\n\n # create the figure\n fig = plt.figure()\n for i, image in enumerate(images):\n plt.imshow(np.asarray(image), extent=(i, i + 1.0, -1.0, -0.2), origin=\"lower\")\n sns.heatmap(scores, annot=scores, cbar_kws={'label': 'Probaility'}, cmap='viridis')\n plt.xticks([])\n plt.yticks(np.arange(count_text) + 0.5, text, rotation=0, fontsize=10)\n plt.xlabel('Images')\n plt.ylabel('Text')\n plt.xlim([0.0, count_images + 0.5])\n plt.ylim([count_text + 0.5, -1.0])\n plt.title('Predictions', fontweight='bold')\n\n return fig\n\n\ndef prepare_images(images, out_res, device):\n all_image = []\n for img in images:\n # PNGs are RGBA and JPGs are RGB, fix at RGB\n img = img.convert('RGB')\n res = min(img.size)\n out = TF.center_crop(img, (res, res))\n out = TF.resize(out, (out_res, out_res))\n out = TF.to_tensor(out).unsqueeze(0)\n out = (out - MEAN) / STD\n all_image.append(out)\n return torch.cat(all_image, dim = 0).to(device)\n","repo_name":"NimbleBoxAI/NL-Images","sub_path":"clip/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"15347711710","text":"from ast import arg\nimport os\nimport re\nimport string\n\n\nclass CppGenerator():\n CMAKE_FILENAME = \"CMakeLists.txt\"\n SRC_FILE = \"main.cpp\"\n DUMMY_DESCRIPTION = '// DUMMY_DESCRIPTION'\n DUMMY_SNIPPET = '// DUMMY_SNIPPET'\n DUMMY_TESTS = '// DUMMY_TESTS'\n ASSERT_TEMPALTE = \"assert((VAR1) == (VAR2));\"\n CLASS_INSTANCE = 'solution'\n parameterTypes = dict()\n\n def __init__(self, workDir, problemDescription, codeSnippet):\n self.workDir = workDir\n self.code = codeSnippet\n self.description = problemDescription\n self.getRetTypesAndParams()\n\n def generate(self):\n try:\n self.setCmakeProjectName()\n self.configureMain()\n return True\n except:\n return False\n\n def setCmakeProjectName(self):\n cmakeFile = self.workDir + '/' + self.CMAKE_FILENAME\n name = \"project (\" + self.workDir.split(\"/\")[-1] + \")\"\n with open(cmakeFile, 'r') as file:\n filedata = file.read()\n\n filedata = re.sub(r'project \\(.*\\)', name, filedata, 1)\n with open(cmakeFile, 'w') as file:\n file.write(filedata)\n\n def configureMain(self):\n mainFile = self.workDir + '/' + self.SRC_FILE\n with open(mainFile, 'r') as file:\n filedata = file.read()\n # problem description\n filedata = filedata.replace(self.DUMMY_DESCRIPTION, self.description)\n # codeSnippet\n filedata = filedata.replace(self.DUMMY_SNIPPET, self.code)\n # examples & asserts\n assertionBlock = \"Solution \" + self.CLASS_INSTANCE+\";\\n\"\n assertionBlock += self.asserts\n filedata = filedata.replace(self.DUMMY_TESTS, assertionBlock)\n with open(mainFile, 'w') as file:\n file.write(filedata)\n\n def getRetTypesAndParams(self):\n code = self.code\n opBrck = code.find('(')\n clBrck = code.find(')')\n brackets = code[opBrck+1:clBrck]\n for argPair in brackets.split(','):\n argPair = argPair.strip().replace('&', '').split(' ')\n self.parameterTypes[argPair[1]] = argPair[0]\n\n typeFin = code.rfind(' ', 0, opBrck)\n typeStrt = code.rfind(' ', 0, typeFin)\n self.fooName = code[typeFin:opBrck].strip()\n self.returnType = code[typeStrt:typeFin].strip()\n if 'void' in self.returnType:\n self.returnType = 'auto'\n\n def parseExamples(self, examples):\n result = ''\n for example in examples:\n result += '\\n{\\n'\n example.replace(' ', '')\n splited = example.split('\\n')\n for row in splited:\n if 'Input:' in row:\n row = row.replace('Input:', '')\n for arg in row.split(', '):\n argType = self.parameterTypes.get(\n arg.split('=')[0].strip(), 'auto')\n if argType == 'auto':\n print(\"ERROOOORROOO\")\n result += argType + ' ' +\\\n arg.replace('[', '{').replace(']', '}')\n result += ';\\n'\n elif 'Output:' in row:\n row = row.replace('Output:', '')\n result += self.returnType + ' result = ' + \\\n row.replace('[', '{').replace(']', '}')\n result += ';\\n'\n else:\n continue\n fooBrackets = ''\n for k, v, in self.parameterTypes.items():\n fooBrackets += k + ','\n fooBrackets = fooBrackets[0:-1]\n result += self.ASSERT_TEMPALTE.replace('VAR1', 'result').replace(\n 'VAR2', self.CLASS_INSTANCE + '.' + self.fooName + '('+fooBrackets+')')\n result += '\\n}'\n self.asserts = result\n","repo_name":"Stasne/leetcode_helper","sub_path":"cpp_gen.py","file_name":"cpp_gen.py","file_ext":"py","file_size_in_byte":3832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"5363618089","text":"import pygame\nimport random\nimport math\nimport os\nimport sys\nfrom config import *\n# initializing the pygame\npygame.init()\n\n# font classes for score, player name, prommpt\nfont = pygame.font.Font(MESSAGE_FONT, 40) # taking font face from config.py\nfont_ = pygame.font.Font(MESSAGE_FONT, 18)\n\n# Configuration variables\nWIDTH = 1000\nHEIGHT = 1000\nSCREEN = pygame.display.set_mode(\n (WIDTH, HEIGHT))\nJUMP_VEL = 12\ngameOver = False\nSTAGE_WIDTH = WIDTH/STAGES\n\n# loading all the sprites\nexplosion_sound = pygame.mixer.Sound(\"music/explosion.ogg\")\n# background music to be played entire game\npygame.mixer.music.load(\"music/background_music.ogg\")\npygame.mixer.music.play(-1) # loopoijg indefinitely\n# loading the ground where player stands\ngnd = [pygame.image.load(\"images/gnd.png\"),\n pygame.image.load(\"images/gnd-1.png\")]\ngnd_c = 0\n# FIREBALL =[pygame.image.load(\"fireball32x32.png\"),pygame.image.load(\"fireball132x32.png\"),pygame.image.load(\"fireball232x32.png\")]\nEXPLOSION = [\n pygame.image.load(\"images/explosion-0.png\"), pygame.image.load(\n \"images/explosion-2.png\"), pygame.image.load(\"images/explosion-3.png\"),\n pygame.image.load(\"images/explosion-4.png\"), pygame.image.load(\n \"images/explosion-5.png\"), pygame.image.load(\"images/explosion-6.png\"),\n]\n\n# creating the lists/ Groups\ndragon_list = []\nexplosions = pygame.sprite.Group() #this will store explosions\nfireball = pygame.sprite.Group() #this will store fireballs\nall_sprites = pygame.sprite.Group()\ngems = pygame.sprite.Group() #for storing gems\nenemies = pygame.sprite.Group() #for storing bombs\n\n# generic function to check collisions\n\n\ndef check_collision(\n rect1,\n rect2):\n if (rect2.right > rect1.left\n and rect1.right > rect2.left\n and rect1.bottom > rect2.top\n and rect1.top < rect2.bottom):\n return True\n return False\n\n# function to make a new window to start the game\n\n\ndef newGame():\n global dragon_list\n global explosions\n global fireball\n global all_sprites\n global gems\n global enemies\n dragon_list = []\n explosions = pygame.sprite.Group()\n fireball = pygame.sprite.Group()\n all_sprites = pygame.sprite.Group()\n gems = pygame.sprite.Group()\n enemies = pygame.sprite.Group()\n for i in range(STAGES):\n for j in range(5):\n gems.add(Gem(random.randint(40, WIDTH-200), STAGE_WIDTH*i-16, #creating random gems\n random.choice([\"score\", \"score\", \"heart\", \"score\"])))\n for i in range(STAGES):\n for j in range(BOMB_COUNT): #creating random enemies\n enemies.add(Enemy(random.randint(40, WIDTH-200), STAGE_WIDTH*i-32))\n # all_sprites.add(player)\n for i in range(STAGES):\n dragon_list += [Dragon(i)] #creating dragons\n\n# class for creating health and scoring gems\n\n\nclass Gem(pygame.sprite.Sprite):\n def __init__(\n self, x, y,\n name):\n super(Gem, self).__init__()\n self.x = x\n self.y = y\n self.name = name\n if name == \"score\":\n self.surf = pygame.image.load(\"images/gem-black.png\")\n if name == \"heart\":\n self.surf = pygame.image.load(\"images/heart.png\")\n self.rect = self.surf.get_rect(\n center=(\n x,\n y,\n )\n )\n\n def update(self, player):\n if check_collision(player.rect, self.rect):\n self.kill()\n if self.name == \"heart\":\n player.health += 10 #updating health after collectiong health gems\n if player.health > 64:\n player.health = 64\n if self.name == \"score\":\n player.score += 1 #updating player scoring after collecting score gems\n\n# class for creating enemiy bombs\n\n\nclass Enemy(pygame.sprite.Sprite):\n def __init__(self, x, y):\n super(Enemy, self).__init__()\n self.x = x\n self.y = y\n self.surf = pygame.image.load(\"images/death.png\")\n self.rect = self.surf.get_rect(\n center=(\n x,\n y,\n )\n )\n\n def update(self, player):\n if check_collision(self.rect, player.rect):\n # pygame.mixer.Sound.stop(explosion_sound)\n self.kill()\n player.health -= 5 #reducing health after enemy collision\n explosions.add(Explosion(self.rect.centerx, self.rect.centery)) #explosion after collison with enemy\n # pygame.mixer.Sound.play(explosion_sound)\n # explosion_sound.play()/\n\n # player.score +=1\n\n# class for creating players\n\n\nclass Player(pygame.sprite.Sprite):\n rounds = 0\n direc = 1\n alive = True\n score = 0\n time = 0\n # global gameOver\n health = 64\n jumping = False\n stage = 0\n speed = 5\n jump_vel = -JUMP_VEL\n jump_acc = 0.4\n\n def __init__(self, direc, name):\n super(Player, self).__init__()\n self.direc = direc\n self.name = name\n if STAGES > 8:\n self.surf = pygame.image.load(\"images/pikachu.png\")\n else:\n self.surf = pygame.image.load(\"images/pikachu-2.png\")\n if direc == 1:\n self.rect = self.surf.get_rect(\n center=(\n 0,\n HEIGHT-32,\n )\n )\n else:\n self.rect = self.surf.get_rect(\n center=(\n 0,\n STAGE_WIDTH-32\n )\n )\n\n def update(self, pressed_keys):\n if self.direc == 1 and self.rect.bottom < 0 and self.stage != 0:\n self.rounds += 1\n self.stage = 0\n self.rect.bottom = WIDTH\n newGame()\n return\n if self.direc == -1 and self.rect.top > HEIGHT and self.stage != 0:\n self.rounds += 1\n self.stage = 0\n newGame()\n return\n if pressed_keys[pygame.K_LEFT]:\n self.rect.move_ip(-self.speed, 0)\n if pressed_keys[pygame.K_RIGHT]:\n self.rect.move_ip(self.speed, 0)\n if not self.jumping and pressed_keys[pygame.K_SPACE]:\n self.stage += 1\n self.jumping = True\n if self.jumping:\n self.jump_vel += self.jump_acc\n self.rect.move_ip(0, self.jump_vel)\n if self.rect.bottom > HEIGHT-STAGE_WIDTH*self.stage and self.jump_vel > 0 and self.direc == 1:\n self.rect.bottom = HEIGHT-STAGE_WIDTH*self.stage\n self.jump_vel = -JUMP_VEL\n self.jumping = False\n elif self.rect.bottom > HEIGHT-STAGE_WIDTH*(STAGES-1-self.stage) and self.jump_vel > 0 and self.direc == -1:\n self.rect.bottom = HEIGHT-STAGE_WIDTH*(STAGES-1-self.stage)\n self.jump_vel = -JUMP_VEL\n self.jumping = False\n\n if self.rect.left < 0:\n self.rect.left = 0\n if self.rect.right > WIDTH:\n self.rect.right = WIDTH\n if self.health < 0:\n explosions.add(Explosion(self.rect.centerx, self.rect.centery))\n self.alive = False\n # self.kill()\n pygame.draw.rect(SCREEN, (0, 0, 0),\n (self.rect.left, self.rect.top-10, 64, 10))\n pygame.draw.rect(SCREEN, (0, 200, 20), (self.rect.left,\n self.rect.top-10, self.health, 10))\n text = font.render(\n f\":{self.score} Round:{self.rounds+1}\", True, (2, 25, 0))\n SCREEN.blit(pygame.image.load(\"images/gem-black.png\"),(0,0))\n SCREEN.blit(text, (32, 0))\n string = font_.render(f\"{self.name}\", True, (0, 200, 100))\n SCREEN.blit(string, (self.rect.left, self.rect.top-25))\n\n# class for creating the fire breathing dragons\n\n\nclass Dragon(pygame.sprite.Sprite):\n id = 0\n state = 0\n dir = 1\n rand = random.randint(10, 20)\n frame_rate = 20\n frame_count = 0\n # fire = False\n fire_count = 0\n\n def __init__(self, id):\n super(Dragon, self).__init__()\n self.surf = pygame.transform.flip(\n pygame.image.load(\"images/dragon.png\"), 1, 0)\n\n self.rect = self.surf.get_rect(\n center=(\n WIDTH - 32,\n HEIGHT - STAGE_WIDTH*id - STAGE_WIDTH/2,\n )\n )\n self.id = id\n\n def update(self, player):\n # if self.id <= player.stage+2 and self.id> player.stage-1:\n if self.frame_count > self.frame_rate:\n self.frame_count -= self.frame_rate\n self.rect.move_ip(0, 5*self.dir)\n self.dir = -1 * self.dir\n if self.fire_count > self.rand:\n self.rand = random.randint(50, 100)\n self.fire_count -= self.rand\n fireball.add(FireBall(self.id))\n self.fire_count += 1\n if check_collision(self.rect, player.rect):\n player.health -= 0.2\n self.frame_count += 1\n\n# class for creationg fireballs\n\n\nclass FireBall(pygame.sprite.Sprite):\n id = 0\n turn = 0\n\n def __init__(self, id):\n super(FireBall, self).__init__()\n # self.surf = pygame.image.load(\"fireball32x32.png\")\n self.surf = pygame.transform.flip(\n pygame.image.load(\"images/bird.png\"), 1, 0)\n if FIREBALL_SPEED == None:\n self.speed = random.random()*5+1\n else:\n self.speed = FIREBALL_SPEED\n\n self.rect = self.surf.get_rect(\n center=(\n WIDTH-150,\n HEIGHT - STAGE_WIDTH*id-STAGE_WIDTH/2-30,\n )\n )\n self.id = id\n\n def update(self, player):\n if self.rect.left < 0:\n self.kill()\n self.rect.move_ip(-self.speed-3*player.rounds, 0)\n self.turn = (self.turn+1) % 3\n # self.surf= FIREBALL[self.turn]\n # self.surf= FIREBALL[self.turn]\n if check_collision(self.rect, player.rect):\n self.kill()\n explosions.add(Explosion(self.rect.centerx, self.rect.centery))\n player.health -= 10\n\n# class for creating explosions\n\n\nclass Explosion(pygame.sprite.Sprite):\n frames = 6\n frame_id = 0\n frame_count = 0\n frame_rate = 15\n\n def __init__(self, x, y):\n super(Explosion, self).__init__()\n # explosion_sound.play()\n pygame.mixer.music.load(\"images/explosion.ogg\")\n pygame.mixer.music.play()\n # pygame.mixer.music.queue(\"background_music.ogg\")\n pygame.mixer.music.load(\"music/background_music.ogg\")\n pygame.mixer.music.play(-1)\n self.x = x\n self.y = y\n self.surf = EXPLOSION[0]\n self.rect = self.surf.get_rect(\n center=(\n x,\n y,\n )\n )\n\n def update(self, player1):\n self.frame_count += 1\n if self.frame_count < 20:\n return\n self.frame_count -= self.frame_rate\n self.frame_id += 1\n if self.frame_id == 6:\n self.kill()\n return\n self.surf = EXPLOSION[self.frame_id]\n\n\n# creting 2 players\nplayer1 = Player(1, \"player1\")\nplayer2 = Player(-1, \"player2\")\nplayer = None\n\n# the main loop\nwhile not gameOver:\n #checking for the quit presses\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n gameOver = True\n elif event.type == pygame.QUIT:\n gameOver = True\n\n #checking for the player\n if(player == None):\n player = player1\n newGame()\n elif not player1.alive and player == player1:\n player = player2\n newGame()\n elif not player2.alive and player == player2:\n #both the players have played\n #displaying hte necessary message\n text = \"\"\n if(player2.score > player1.score):\n text = f\"Player2 won by {player2.score}-{player1.score}\"\n elif(player1.score > player2.score):\n text = f\"Player1 won by {player1.score}-{player2.score}\"\n else:\n text = f\"IT's a Draw\"\n t = font.render(f\"{text}\", True, MESSAGE_COLOR)\n SCREEN.blit(t, (WIDTH/2-100, HEIGHT/2-20))\n pygame.display.update()\n pygame.time.delay(4000)\n \n #restaring the game automatically\n player = None\n player1 = Player(1, \"player1\")\n player2 = Player(-1, \"player2\")\n continue\n \n #drawing the stages,fireballs, explosions,enemies and the player\n for i in range(STAGES):\n SCREEN.blit(gnd[gnd_c], (0, HEIGHT-STAGE_WIDTH*i-80))\n dragon_list[i].update(player)\n SCREEN.blit(dragon_list[i].surf, dragon_list[i].rect)\n for fireballs in fireball:\n SCREEN.blit(fireballs.surf, fireballs.rect)\n fireballs.update(player)\n for explosion in explosions:\n SCREEN.blit(explosion.surf, explosion.rect)\n explosion.update(player)\n for gem in gems:\n SCREEN.blit(gem.surf, gem.rect)\n gem.update(player)\n for enemy in enemies:\n SCREEN.blit(enemy.surf, enemy.rect)\n enemy.update(player)\n SCREEN.blit(player.surf, player.rect)\n\n # checking key presses\n pressed_keys = pygame.key.get_pressed()\n player.update(pressed_keys)\n\n pygame.display.flip()\n SCREEN.fill((255, 255, 255))\n\n\n# pygame quitting\npygame.quit()\n","repo_name":"ace-spadez/pygame","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"69977496968","text":"import datetime\n\ndef solution(book_time):\n \n Room = []\n time = {}\n\n for time in book_time:\n s_h = int(time[0].split(':')[0])\n s_m = int(time[0].split(':')[1])\n e_h = int(time[1].split(':')[0])\n e_m = int(time[1].split(':')[1])\n \n c_start = s_h*60 + s_m\n c_end = e_h*60 + e_m + 10\n \n Room.append([c_start,1])\n Room.append([c_end,-1])\n\n Room.sort()\n number=0\n max_num = 0\n print(Room)\n \n for i in range(len(Room)-1):\n number += Room[i][1]\n \n if(number>max_num):\n if(Room[i][0] != Room[i+1][0]):\n max_num = number\n \n if(number+Room[-1][1] > max_num):\n max_num = number+Room[-1][1]\n print(max_num)\n \n answer = max_num\n \n \n \n \n \n \n \n \n# Room = []\n# for time in book_time:\n\n# s_h = int(time[0].split(':')[0])\n# s_m = int(time[0].split(':')[1])\n# e_h = int(time[1].split(':')[0])\n# e_m = int(time[1].split(':')[1])\n \n# c_start = datetime.time(s_h, s_m)\n \n# if(e_h==23 and e_m>=50):\n# c_end = datetime.time(23, 59)\n# elif(e_m>=50):\n# c_end = datetime.time(e_h+1, e_m-50)\n# else:\n# c_end = datetime.time(e_h, e_m+10)\n \n# flag = 1\n \n# for room in Room:\n# flag = 1\n# length = len(room)\n\n# #start 찾기\n# start_index = -1\n# end_index = -1\n\n# if(c_start>=room[-1]): # 맨 뒤에 추가\n# room.append(c_start)\n# room.append(c_end)\n# flag = 0\n# break\n# elif(c_end <= room[0]): # 맨 앞에 추가\n# room.insert(0, c_start)\n# room.insert(1, c_end)\n# flag = 0\n# break\n# else:\n# # start 찾기\n# for i in range(1, length):\n# if(c_start>=room[i-1] and c_startroom[i-1] and c_end<=room[i]):\n# end_index = i\n# break\n# # start end index 비교\n# if(start_index == end_index and start_index%2==0):\n# room.insert(start_index, c_start)\n# room.insert(start_index+1, c_end)\n# flag = 0\n# if(flag == 0):\n# break\n# # flag = 0 이면 이미 추가된거고 1이면 아직 추가 안된것\n \n# if(flag == 1): # 새로운 룸에 추가 (아무것도 없을때도 추가)\n# Room.append([c_start, c_end]) \n# print(Room)\n\n# answer = len(Room)\n return answer","repo_name":"dainshon/CODING","sub_path":"프로그래머스/unrated/155651. 호텔 대실/호텔 대실.py","file_name":"호텔 대실.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"35145713495","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport json\nimport numpy as np\nimport pandas as pd\n\nclass Graber: \n \n url = 'https://apteki.su/'\n city = ''\n\n def __init__(self, city = ''):\n if city != '':\n self.city = city\n self.url = f\"https://{city}.apteki.su//catalog//Оземпик\"\n\n def openDriver(self):\n self.driver = webdriver.Chrome()\n self.driver.get(self.url)\n\n def waitLoadElement(self): \n pass\n \n def getCity(self):\n places = None\n city_list = []\n try:\n element = WebDriverWait(self.driver, 30).until(EC.presence_of_element_located(\n (By.XPATH, \"//*[@class='location-window__list location-window__list_city']\")))\n finally:\n while places is None:\n places = self.driver.execute_script(\"return sessionStorage.getItem('places');\")\n\n places_json = json.loads(places)\n \n for place in places_json:\n city_list.append(place['alias'])\n city_list.sort()\n return city_list\n\n def getPrice(self):\n table = self.driver.find_element(By.CLASS_NAME, 'search-select-form__item-list')\n elements = table.find_elements(By.TAG_NAME, 'dl')\n element_array = []\n for element in elements:\n name = element.find_elements(By.TAG_NAME, 'dt')[0].text\n price = element.find_elements(By.TAG_NAME, 'dd')[0].text\n element_array.append([self.city, name, price])\n return element_array\n \n def closeDriver(self):\n self.driver.quit()\n\n#MAIN\n#get all city`s\ngraber = Graber()\ngraber.openDriver()\ncity_list = graber.getCity()\ngraber.closeDriver()\n\n\n#get price in some city\nprices = []\nfor city in city_list:\n try:\n graber = Graber(city)\n graber.openDriver()\n pricesInCity = graber.getPrice()\n for priceInCity in pricesInCity:\n prices.append(priceInCity)\n print (f'{city} --- grabed')\n except:\n prices.append([city, 'nil', 'nil'])\n print (f'{city} --- error')\n \n graber.closeDriver()\n\n\n#save to csv\ndf = pd.DataFrame(prices, columns = ['city', 'name', 'price'])\ndf.to_csv('test.csv', index=False)\n","repo_name":"Zork777/GruberApteki","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"20967129777","text":"total_problemas = int(input())\n\nqtd_certezas = 0\nQTD_AMIGOS = 3\nQTD_MIN_CERTEZAS = 2\n\nfor n in range(total_problemas):\n temp = 0\n certezas_n = input().split(' ')\n for i in range(QTD_AMIGOS):\n temp += int(certezas_n[i])\n if temp >= QTD_MIN_CERTEZAS:\n qtd_certezas += 1\n\nprint(qtd_certezas)","repo_name":"nszchagas/APC-codes","sub_path":"5_iteracoes/questao8.py","file_name":"questao8.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"27952981766","text":"from django.urls import path\r\nfrom . import views\r\nfrom . import apiview\r\n\r\nurlpatterns=[\r\n path('', views.index,name=\"index\"),\r\n path('/', views.task_detail, name='task_detail'),\r\n path('form',views.task_form,name=\"task_form\"),\r\n path('api', apiview.api,name =\"Api_View\"),\r\n path ('api/',apiview.api_task_detail,name= \"Api Task Details\")\r\n]","repo_name":"PizzaMGx/DjangoTodo","sub_path":"tasks/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"22875135923","text":"#! /usr/bin/python\n#-*-coding: utf-8 -*-\n\n\"\"\"\nPython code to use the MPR121 capacitive touch sensor from Adafruit with a Raspberry Pi to count/log touches, while ignoring 'un-touch' events.\nCounting/Logging happens in a threaded callback (using RPi.GPIO.add_event_callback) triggered from the IRQ pin on the MPR121\n\nAdafruit_MPR121 requires the Adafuit MPR121 library which, in turn, requires the Adafuit GPIO library for I2C-bus access:\ngit clone https://github.com/adafruit/Adafruit_Python_MPR121 \ngit clone https://github.com/adafruit/Adafruit_Python_GPIO\n\nNOTE :\nAdafruit_Python_MPR121 has been deprecated. Adafruit has a new module for mpr121 using CircuitPython at github.com/adafruit/Adafruit_CircuitPython_MPR121\nbut this requires the whole CircuitPython install, which is rather large. It may be worth switching to this in the future.\n\"\"\"\n\nfrom Adafruit_MPR121 import MPR121\nimport RPi.GPIO as GPIO\n\nfrom array import array\nfrom time import time, sleep\n\ngTouchDetector = None # global reference to touchDetector for use in touchDetector callback\n\n\nclass TouchDetector (MPR121.MPR121):\n \"\"\"\n ******************* TouchDetector inherits from Adafruit's MPR121 capacitive touch sensor code *************************\n\n mnemonic defines for use in controlling touchDetector callback\n \"\"\"\n callbackCountMode = 1 # callback counts touches on set of pin in touchPins\n callbackTimeMode = 2 # callback records time of each touch for each pin in touchPins \n callbackCustomMode = 4 # callback calls user-supplied custom function with touched pin\n\n @staticmethod\n def touchDetectorCallback (channel):\n \"\"\"\n Touch Detector callback, triggered by IRQ pin. The MPR121 sets the IRQ pin high whenever the touched/untouched state of any of the\n antenna pins changes. Calling MPR121.touched () sets the IRQ pin low again. MPR121.touched() returns a 12-but value\n where each bit represents a pin, with bits set for pins being touched, and un-set for pins not being touched. The callback tracks only touches, \n not un-touches, by keeping track of last touches. The callback counts touches on a set of pins, and/or logs timestamps of touches\n on a set of pinss, and/or calls a user-supplied custom function with the touched pin as the only parameter.\n \"\"\"\n global gTouchDetector\n touches = gTouchDetector.touched ()\n # compare current touches to previous touches to find new touches\n for pin in gTouchDetector.touchPins:\n pin = int(pin)\n pinBits = 2**pin\n if (touches & pinBits) and not (gTouchDetector.prevTouches & pinBits):\n if gTouchDetector.callbackMode & TouchDetector.callbackCountMode:\n gTouchDetector.touchCounts [pin] +=1\n if gTouchDetector.callbackMode & TouchDetector.callbackTimeMode:\n gTouchDetector.touchTimes.get(pin).append (time())\n if gTouchDetector.callbackMode & TouchDetector.callbackCustomMode:\n gTouchDetector.customCallback (pin)\n gTouchDetector.prevTouches = touches\n \n \n def __init__(self, I2Caddr, touchThresh, unTouchThresh, pinTuple, IRQpin):\n \"\"\"\n inits the MPR121 superclass, does MPR121 stuff, then does touchDetector stuff\n \"\"\"\n # MPR121 stuff\n super().__init__()\n self.begin(address =I2Caddr)\n self.set_thresholds (touchThresh, unTouchThresh)\n #touchDetector specific stuff, making data arrays, and installing callback\n # the tuple of pin numbers to monitor, passed in\n self.touchPins = pinTuple\n # an array of ints to count touches for each pin, for callbackCountMode\n # we make an array for all 12 pins, even though we may not be monitoring all of them\n self.touchCounts = array ('i', [0]*12)\n # a dictionary of lists to capture times of each touch on each pin, for callbackTimeMode\n self.touchTimes = {}\n for pin in self.touchPins:\n self.touchTimes.update({pin : []})\n # customCallback will contain reference to custom callback function, when installed\n self.customCallback = None\n # make global gTouchDetector reference this TouchDetector\n global gTouchDetector\n gTouchDetector = self\n # set up IRQ interrupt pin for input with pull-up resistor. Save IRQpin so we can remove event detect when object is deleted\n self.IRQpin = IRQpin\n GPIO.setmode (GPIO.BCM) # GPIO.setmode may already have been called, but call it again anyway\n GPIO.setup(IRQpin, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n # install callback\n GPIO.add_event_detect (self.IRQpin, GPIO.FALLING)\n GPIO.add_event_callback (self.IRQpin, TouchDetector.touchDetectorCallback)\n # callback mode, variable that tracks if we are counting touches, logging touch times, or running custom callback\n # callback is always running, even when callbackMode is 0, but we don't always log the touches\n self.callbackMode = 0\n # initial state of touches, saved from one callback call to next, used in callback to separate touches from untouches\n self.prevTouches = self.touched()\n\n\n def __del__ (self):\n \"\"\"\n Removes the event detect callback and cleans up the GPIO pin used for it\n \"\"\"\n GPIO.remove_event_detect (self.IRQpin)\n GPIO.cleanup (self.IRQpin)\n \n def addCustomCallback (self, customCallBack):\n \"\"\"\n sets the custom callback that will be called on a per-pin basis from main callback\n \"\"\"\n self.customCallback = customCallBack\n\n def startCustomCallback(self):\n \"\"\"\n sets callback mode field so main callback calls custom callback\n \"\"\"\n if self.customCallback is not None:\n self.callbackMode |= TouchDetector.callbackCustomMode\n\n def stopCustomCallback(self):\n \"\"\"\n sets callback mode field so main callback stops calling custom callback\n \"\"\"\n self.callbackMode &= ~TouchDetector.callbackCustomMode\n\n def startCount (self):\n \"\"\"\n Zeros the array that stores counts for each pin, and makes sure callback is filling the array for requested pins\n \"\"\"\n for i in range (0,12):\n self.touchCounts [i] = 0\n self.callbackMode |= TouchDetector.callbackCountMode\n \n def resumeCount(self):\n self.callbackMode |= TouchDetector.callbackCountMode\n \n def getCount (self):\n results = []\n for pin in self.touchPins:\n pin = int(pin)\n results.append ((pin, self.touchCounts [pin]))\n return results\n\n def stopCount (self):\n \"\"\"\n returns a list of tuples where each member is a pin number and the number of touches for that pin\n call startCount, wait a while for some touches, then call stopCount\n \"\"\"\n self.callbackMode &= ~TouchDetector.callbackCountMode\n results = []\n for pin in self.touchPins:\n pin = int(pin)\n results.append ((pin, self.touchCounts [pin]))\n return results\n\n\n def startTimeLog (self):\n \"\"\"\n clears the dictionary of lists used to capture times of each touch on each pin\n \"\"\"\n for pin in self.touchPins:\n pin = int(pin)\n self.touchTimes.update({pin : []})\n self.callbackMode = self.callbackMode | TouchDetector.callbackTimeMode\n\n def stopTimeLog (self):\n \"\"\"\n returns a shallow copy (the lists in the original and copy are the same)\n of the dictionary of lists of touch times for each pin\n \"\"\"\n self.callbackMode &= ~TouchDetector.callbackTimeMode\n return self.touchTimes.copy()\n\n def waitForTouch (self, timeOut_secs, startFromZero=False):\n \"\"\"\n Waits for a touch on any pin. Returns pin that was touched, or 0 if timeout expires with no touch,\n or -1 if startFromZero was True and the detector was touched for entire time\n \"\"\"\n endTime = time() + timeOut_secs\n if self.prevTouches == 0: # no touches now, wait for first touch, or timeout expiry\n while self.prevTouches ==0 and time() < endTime:\n sleep (0.05)\n return self.prevTouches\n else: #touches already registered\n if not startFromZero: # we are done already\n return self.prevTouches\n else: # we first wait till there are no touches, or time has expired\n while self.prevTouches > 0 and time() < endTime:\n sleep (0.05)\n if time() > endTime: # touched till timeout expired\n return -1\n else: # now wait for touch or til timeout expires\n while self.prevTouches == 0 and time() < endTime:\n sleep (0.05)\n return self.prevTouches # will be the pin touched, or 0 if no touches till timeout expires\n\n\n","repo_name":"jamieboyd/TouchDetector","sub_path":"TouchDetectorMPR121.py","file_name":"TouchDetectorMPR121.py","file_ext":"py","file_size_in_byte":9052,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"72320554568","text":"from imageai.Detection.Custom import CustomObjectDetection\n\ndetector = CustomObjectDetection()\ndetector.setModelTypeAsYOLOv3()\ndetector.setModelPath(\"../models/modelo_moedas_igor.h5\") #copiado do models p/ facilitar nome\ndetector.setJsonPath(\"../models/json/detection_config.json\") #como esse n muda o nome, faz ref direta\ndetector.loadModel()\npath_in = \"../images_in/\"\npath_out = \"../images_out/\"\nfilename = \"real-2.jpg\"\ndetections = detector.detectObjectsFromImage(input_image=path_in+filename, output_image_path=path_out+filename)\nfor detection in detections:\n print(detection[\"name\"], \" : \", detection[\"percentage_probability\"], \" : \", detection[\"box_points\"])","repo_name":"gdinn/real-imageai","sub_path":"scripts/img_analysis.py","file_name":"img_analysis.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"30687038588","text":"import time\nlist_words = ['hello', ' day', 'love', 'good', 'hi']\n\nresponse = {\n 'hello': 'hi dear, how are you today',\n 'day': 'going well thank you',\n 'love': 'thanks',\n 'doing good': 'am also doing good, and nice to know'\n}\nuser_input = input('chat with our chat bot :\\n ')\nwhile len(user_input) > 0:\n if list_words[0] in user_input or list_words[4] in user_input:\n print('response processing')\n time.sleep(2)\n print(response['hello'])\n elif list_words[1] in user_input:\n print('response processing')\n time.sleep(2)\n print(response['day'])\n elif list_words[2] in user_input:\n print('response processing')\n time.sleep(2)\n print(response['love'])\n elif list_words[3] in user_input:\n print('response processing')\n time.sleep(2)\n print(response['doing good'])\n elif user_input == 'exit':\n print('pleasure talking to you, hope to talk to you next time')\n time.sleep(2)\n exit()\n elif 'can' and 'question' in user_input:\n print('response processing')\n time.sleep(2)\n print('you can ask your question')\n elif 'question' in user_input and 'can' not in user_input:\n print('response processing')\n time.sleep(2)\n print('sorry am just a bolt but our customer care can assist you better, contact them on 09090240674')\n else:\n print(\"sorry i don't have a response for that question\")\n user_input = input()\n","repo_name":"Esi-meci/chatbot","sub_path":"structure.py","file_name":"structure.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"11810385916","text":"import os\r\n# import requests\r\n# from bs4 import BeautifulSoup as soup\r\nimport pandas as pd\r\n\r\nimport utils as ut\r\nfrom config import Settings\r\n\r\nconfig = Settings()\r\n\r\n\r\ndef Crawl_data(base_url=config.base_url, save_path=config.data_folder, load_time=3):\r\n\r\n return_reviews, return_sentiments = ut.crawl_data_from_url(\r\n base_url,\r\n no_load=load_time,\r\n reviews=[],\r\n sentiments=[]\r\n )\r\n\r\n df = pd.DataFrame({\"Reviews\": return_reviews,\r\n \"sentiment\": return_sentiments})\r\n file_name = f'{len(df)}_crawling_data.csv'\r\n df.save_csv(os.path.join(save_path, file_name))\r\n\r\n\r\ndef main():\r\n\r\n base_url = config.base_url\r\n save_path = config.data_folder\r\n load_time = 1\r\n\r\n Crawl_data(base_url, save_path, load_time)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"gaster08nan/Sentiment-Classification","sub_path":"crawl_data.py","file_name":"crawl_data.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"39275186296","text":"class DoublyLinkedListNode:\n def __init__(self, value):\n self.value = value\n self.next_node = None\n self.prev_node = None\n\n def __repr__(self):\n return f\"DoublyLinkedListNode(value={self.value})\"\n\n\nif __name__ == '__main__':\n a = DoublyLinkedListNode(\"a\")\n b = DoublyLinkedListNode(\"b\")\n c = DoublyLinkedListNode(\"c\")\n d = DoublyLinkedListNode(\"d\")\n\n a.next_node = b\n b.prev_node = a\n b.next_node = c\n c.prev_node = b\n c.next_node = d\n d.prev_node = c\n\n print(c.prev_node, c.next_node)\n","repo_name":"ArtyomKozyrev8/algorithms_training","sub_path":"algorithms/linked_list/doubly_linked_list.py","file_name":"doubly_linked_list.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"70707961927","text":"#!/usr/bin/env Python\r\n#-*-coding:utf-8-*-\r\n\r\n# author :Guido.shu\r\n# datetime :2020/4/20 9:47\r\n# software : PyCharm\r\nimport requests\r\nfrom pyquery import PyQuery as pq\r\nfrom proxyTool import AbuyunSpider\r\nimport time\r\nimport random\r\nimport re\r\nfrom urllib import parse\r\nfrom conf.useragent import random_useragent\r\n\r\n\r\n\"\"\"\r\n土巴兔爬虫\r\n需求:爬取 城市、类型(家装or工装),家庭公司名称、地址、电话、设计案例、装修公司数\r\n\"\"\"\r\n\r\n\r\nclass TubatuSpider(object):\r\n\r\n def __init__(self):\r\n self.requestsProxies = self.reutnRequestsProxies()\r\n self.builtUrl = 'https://sz.to8to.com/'\r\n\r\n def reutnRequestsProxies(self):\r\n \"\"\"\r\n :return: 返回requests的proxies\r\n \"\"\"\r\n return AbuyunSpider.returnRequestProxies()\r\n\r\n def returnBuiltHeaders(self, path, item, RefererUrl=None, page=None):\r\n \"\"\"\r\n 构造headers\r\n\r\n :return:\r\n \"\"\"\r\n city = parse.quote(item['city'])\r\n city_num = item['city_num']\r\n city_type = item['city_type']\r\n\r\n sourceUrl_built_url = 'https%3A%2F%2F{}.to8to.com%2Fcompany%2F'.format(city_num)\r\n firstUrl_built_url = 'https://{city_num}.to8to.com/company/{city_type}/'.format(city_num=city_num,city_type=city_type)\r\n sourceUrl = item['sourceUrl'].replace('://', '%3A%2F%2F').replace('/', \"%2F\") if item.get('sourceUrl') else sourceUrl_built_url\r\n firstUrl = item.get('firstUrl').replace('://', '%3A%2F%2F').replace('/', \"%2F\") if item.get('firstUrl') else firstUrl_built_url.replace(':/', '%3A%2F%2F').replace('/', \"%2F\")\r\n nowpage = item.get('firstUrl').replace('://', '%253A%252F%252F').replace('/','%252F') if item.get('firstUrl') else firstUrl_built_url.replace(':/', '%253A%252F%252F').replace('/', \"%252F\")\r\n if not page:\r\n landpage = 'https%3A//sz.to8to.com/'\r\n else:\r\n landpage = firstUrl\r\n headers = {\r\n # \"accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\",\r\n # \"accept-encoding\": \"gzip, deflate, br\",\r\n # \"accept-language\": \"zh-CN,zh;q=0.9\",\r\n # \"cache-control\": \"no-cache\",\r\n # \"pragma\": \"no-cache\",\r\n # \"sec-fetch-dest\": \"document\",\r\n # \"sec-fetch-mode\": \"navigate\",\r\n # \"sec-fetch-site\": \"cross-site\",\r\n # \"sec-fetch-user\": \"?1\",\r\n # \"upgrade-insecure-requests\": '1',\r\n \"user-agent\": random_useragent()\r\n ,\"cookie\": \"uid=CgoKUF61XAWCtJc0A7vvAg==; \"\r\n \"to8tocookieid=f982c677f999237b9fe9e5ee3947f2cc806225; \"\r\n \"tracker2019session=%7B%22session%22%3A%2217201522ce2109-0c32fb225c0495-14291003-2073600-17201522ce3201%22%7D; \"\r\n \"tracker2019jssdkcross=%7B%22distinct_id%22%3A%2217201522ce612f-03e21b7f111ee1-14291003-2073600-17201522ce71e%22%7D; \"\r\n \"to8to_sourcepage=; to8to_landtime=1589160062; \"\r\n \"to8to_cook=OkOcClPzRWV8ZFJlCIF4Ag==; \"\r\n \"to8to_townid=1103; to8to_tcode=sh; \"\r\n \"to8to_tname=%E4%B8%8A%E6%B5%B7; \"\r\n \"Hm_lvt_dbdd94468cf0ef471455c47f380f58d2=1589160063; \"\r\n \"tender_popup_flag=true;\"\r\n \" ONEAPM_BI_sessionid=9238.924|1589197648127; \"\r\n \"Hm_lpvt_dbdd94468cf0ef471455c47f380f58d2={times}; act=freshen;\"\r\n \"to8to_landpage={landpage}; \"\r\n \"to8to_tcode={city_num}; to8to_tname={city}; \"\r\n \"to8to_cmp_sourceUrl={sourceUrl}; \"\r\n \"to8to_cmp_firstUrl={firstUrl}; \"\r\n \"to8to_nowpage={nowpage}; \".format(city=city,\r\n city_num=item['city_num'],\r\n sourceUrl=sourceUrl,\r\n firstUrl=firstUrl,\r\n nowpage=nowpage,\r\n landpage=landpage,times=now_to_timestamp())\r\n }\r\n if RefererUrl:\r\n headers['Referer'] = RefererUrl\r\n headers['sourceUrl'] = sourceUrl\r\n return headers\r\n\r\n def process_response(self, response, meta, item):\r\n \"\"\"\r\n 处理response\r\n :param response:\r\n :return:\r\n \"\"\"\r\n # print(response)\r\n with open('土巴兔.html','w',encoding='utf-8') as f:\r\n f.write(response.text)\r\n documents = pq(response.text)\r\n li_params = documents('.company__list--content > ul > li')\r\n for li in li_params.items():\r\n bulitDivs = li('.company__info')\r\n href_params = li('a').attr('href')\r\n #todo:公司名称\r\n companyName = bulitDivs('.company__info--top').text()\r\n #todo:评论数量\r\n commentNum = bulitDivs('.company__info--all > .comment-count').text()\r\n #todo:日志数量\r\n logNum = bulitDivs('.company__info--all > .owner-diary').text()\r\n #todo:最近签约\r\n clientStatus = bulitDivs('.company__info--all')('.info-num > .recent-signing').text()\r\n #todo:价格\r\n priceNum = bulitDivs('.company__info--all')('.info-num > .average-price').text()\r\n\r\n print(companyName,commentNum,logNum,clientStatus,priceNum,href_params)\r\n\r\n #下一页\r\n print('ssssss', response.url)\r\n nextPage = documents('#nextpageid').attr('href')\r\n if nextPage:\r\n page = re.search(re.compile('(\\d+)'), nextPage)\r\n item['sourceUrl'] = meta['firstUrl']\r\n item['firstUrl'] = response.url\r\n print('################正在爬取{}页##############'.format(int(page.group(1))-1))\r\n nextUrl = self.builtUrl + nextPage.split('/')[1] + '/' + meta['key_con'] + '-' + nextPage.split('/')[-1] + '/'\r\n\r\n response,meta = self.process_request(nextUrl, meta=meta, Referer=response.url, item=item)\r\n meta['firstUrl'] = response.url\r\n self.process_response(response=response, meta=meta,item=item)\r\n else:\r\n page = re.search(re.compile('page(\\d+)'), response.url)\r\n\r\n print('################正在爬取{}页##############'.format(page.group(1)))\r\n\r\n #todo:处理requests 请求URL\r\n def process_request(self, nextPage, meta, item,Referer=None):\r\n path_params = '/' + '/'.join(nextPage.split('/')[-3:])\r\n \"\"\"\r\n header\r\n \"\"\"\r\n\r\n\r\n\r\n headers = self.returnBuiltHeaders(path=path_params, RefererUrl=Referer, item=item)\r\n meta['firstUrl'] = headers['sourceUrl']\r\n del headers['sourceUrl']\r\n while 1:\r\n try:\r\n first_url = nextPage[:-1]\r\n first_res = requests.get(first_url, headers={'user-agent': random_useragent()})\r\n with open('ss1.html', 'w') as f:\r\n # print(first_res.text)\r\n f.write(first_res.text)\r\n second_res = nextPage.replace('https', 'http')\r\n second_res = requests.get(second_res, headers={'user-agent': random_useragent()})\r\n with open('ss2.html', 'w') as f:\r\n # print(second_res.text)\r\n f.write(second_res.text)\r\n three_yrl = nextPage\r\n response = requests.get(url=three_yrl,\r\n headers=headers,\r\n timeout=3, allow_redirects=False, proxies=self.reutnRequestsProxies())\r\n if response.status_code == 200:\r\n return response,meta\r\n else:\r\n print(response)\r\n except Exception as e:\r\n print(e)\r\n time.sleep(random.randint(2, 5))\r\n\r\n\r\n\r\n #todo:处理url\r\n def process_start(self):\r\n \"\"\"\r\n 处理url\r\n :return:\r\n \"\"\"\r\n url_item = {\r\n 'ht1': \"小户型\",\r\n # 'ht4': \"普通住宅\",\r\n }\r\n city_params = [\r\n {'city': '上海', \"city_num\": \"sh\"},\r\n # {'city': '深圳', \"city_num\": \"sz\"},\r\n ]\r\n for key, value in url_item.items():\r\n for x in city_params:\r\n url = 'https://{city_num}.to8to.com/company/{key}/'.format(city_num=x['city_num'], key=key)\r\n x['city_type'] = key\r\n response = self.process_request(url, meta={'key_con': key, \"value_con\": value}, item=x)\r\n print(response)\r\n self.process_response(response[0], meta=response[1], item=x)\r\n\r\n def start(self):\r\n print('###########################土巴兔爬虫开启##############')\r\n\r\n self.process_start()\r\n\r\ndef now_to_timestamp(digits = 10):\r\n \"\"\"获取13位时间\"\"\"\r\n time_stamp = time.time()\r\n digits = 10 ** (digits -10)\r\n time_stamp = str(round(time_stamp*digits))\r\n return time_stamp\r\n\r\nif __name__ == '__main__':\r\n tubatu = TubatuSpider()\r\n tubatu.start()","repo_name":"917868607/spider_project","sub_path":"spider/Tubatu_spider.py","file_name":"Tubatu_spider.py","file_ext":"py","file_size_in_byte":9273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"15181176588","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom WarpUtils import *\nfrom ProcessEXR import *\nfrom CropPano import *\nfrom Consts import *\n\ndef createDataset():\n exr_files = [f for f in listdir(hdr_dataset_dir) if isfile(join(hdr_dataset_dir,f)) and f.endswith(\".exr\")]\n random.shuffle(exr_files)\n for f in exr_files[:4]:\n name = f[:-4]\n processHDR(name)\n\n\ndef processHDR(name):\n # load HDR & segmap\n count = 16\n hdr_data = exr2array(hdr_dataset_dir+name+\".exr\")\n # segmap = plt.imread(light_masks_dir+name+\"_light_mask.jpg\")\n gray_segmap = plt.imread(light_masks_dir+name+\"_light_semantic_map.jpg\")\n segmap = np.expand_dims(gray_segmap, axis=-1)\n print(np.unique(segmap))\n print(segmap.shape)\n\n # cropped_hdr = []\n converted_ldr = []\n cropped_segmap = []\n for i in range(count):\n c1 = 0.125*(i-1) # (-0.25, 0, 0.25, 0.5, ..., 1.5), total: 8\n # c2 = 0.2\n c2 = np.clip(np.random.normal(loc=CROP_DISTRIB_MU, scale=CROP_DISTRIB_SIGMA), a_min=0.2, a_max=0.55)\n # c2 = np.random.uniform(low=0.2, high=0.5)\n # c2 = np.random.normal(loc=CROP_DISTRIB_MU, scale=CROP_DISTRIB_SIGMA)\n center_point = np.array([c1, c2]) # camera center point (valid range [0,2])\n center_row, center_col = crop_center2row_col(center_point)\n crop_theta, crop_phi = row_col2theta_phi(center_row, center_col, WIDTH, HEIGHT)\n partial_hdr = nfov.toNFOV(hdr_data, center_point, True).astype('float32')\n partial_segmap = nfov.toNFOV(segmap, center_point, False)\n # cropped_hdr.append(partial_hdr)\n cropped_segmap.append(partial_segmap)\n print(np.min(cropped_segmap, axis=(0,1)))\n # print(cropped_segmap[-1].shape)\n ldrDurand = tonemap_drago.process(partial_hdr)\n partial_ldr = np.clip(ldrDurand*255, 0, 255).astype('uint8')\n converted_ldr.append(partial_ldr)\n for i in range(count):\n ldr_img_name = ldr_imgs + name + \"_partial_{}.jpg\".format(i)\n seg_label_name = seg_labels + name + \"_partial_{}_segmap.jpg\".format(i)\n plt.imsave(ldr_img_name, converted_ldr[i])\n plt.imsave(seg_label_name, cropped_segmap[i])\n\n\nif __name__ == '__main__':\n # createDataset()\n processHDR(name=\"9C4A1707-0f4b3a9a59\")","repo_name":"WinterCyan/Gardner2019","sub_path":"DataPreprocess/CreateSegDataset.py","file_name":"CreateSegDataset.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"16"}
+{"seq_id":"22575704143","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport sys\n\ninputFileName = ''\ndelimiter = ','\nhasHeader = False\ntokenizerType = ''\ntokenizedFileName = ''\nremoveDuplicateTokens = False\nrunReplacement = False\nmatrixNumTokenRule = False\nmatrixInitialRule = False\nmu = 0.50\nmuIterate = 0.10\nepsilon = 0.50\nepsilonIterate = 0.00\ncomparator = ''\nbeta = 0\nminBlkTokenLen = 0\nexcludeNumericBlocks = False\nremoveExcludedBlkTokens = False\nsigma = 0\nfatalError = False\ntruthFileName = ''\n\n\ndef convertToBoolean(lineNbr, value):\n if value == 'True':\n return True\n if value == 'False':\n return False\n print('**Error: Invalid Boolean value in Parameter File, line:', lineNbr, '->', value)\n global fatalError\n fatalError = True\n\n\ndef convertToFloat(lineNbr, value):\n try:\n floatValue = float(value)\n except ValueError:\n print('**Error: Invalid floating point value in Parameter File, line:', lineNbr, '->', value)\n global fatalError\n fatalError = True\n else:\n return floatValue\n\n\ndef convertToInteger(lineNbr, value):\n if value.isdigit():\n return int(value)\n else:\n print('**Error: Invalid integer value in Parameter File, line:', lineNbr, '->', value)\n global fatalError\n fatalError = True\n\n\ndef getParms(parmFileName):\n global fatalError\n validParmNames = ['inputFileName', 'delimiter', 'hasHeader', 'tokenizerType', 'removeDuplicateTokens',\n 'runReplacement', 'minFreqStdToken', 'minLenStdToken', 'maxFreqErrToken',\n 'mu', 'muIterate', 'beta', 'minBlkTokenLen', 'sigma', 'epsilon', 'epsilonIterate',\n 'excludeNumericBlocks', 'removeExcludedBlkTokens', 'runClusterMetrics',\n 'createFinalJoin', 'comparator', 'truthFileName', 'matrixNumTokenRule', 'matrixInitialRule']\n parmFile = open(parmFileName, 'r')\n parms = {}\n lineNbr = 0\n while True:\n line = (parmFile.readline()).strip()\n lineNbr += 1\n if line == '':\n break\n # Skip comment lines in parameter file\n if line.startswith('#'):\n continue\n part = line.split('=')\n parmName = part[0].strip()\n if parmName not in validParmNames:\n print('**Error: Invalid Parameter Name in Parameter File, line:', lineNbr, '->', parmName)\n fatalError = True\n parmValue = part[1].strip()\n if parmName == 'inputFileName':\n global inputFileName\n inputFileName = parmValue\n continue\n if parmName == 'delimiter':\n global delimiter\n if ',;:|\\t'.find(parmValue) >= 0:\n delimiter = parmValue\n continue\n else:\n print('**Error: Invalid delimiter in Parameter File, line:', lineNbr, '->', parmName)\n sys.exit()\n if parmName == 'hasHeader':\n global hasHeader\n hasHeader = convertToBoolean(lineNbr, parmValue)\n continue\n if parmName == 'tokenizerType':\n global tokenizerType\n tokenizerType = parmValue\n continue\n if parmName == 'removeDuplicateTokens':\n global removeDuplicateTokens\n removeDuplicateTokens = convertToBoolean(lineNbr, parmValue)\n continue\n if parmName == 'runReplacement':\n global runReplacement\n runReplacement = convertToBoolean(lineNbr, parmValue)\n continue\n if parmName == 'minFreqStdToken':\n global minFreqStdToken\n minFreqStdToken = convertToInteger(lineNbr, parmValue)\n continue\n if parmName == 'minLenStdToken':\n global minLenStdToken\n minLenStdToken = convertToInteger(lineNbr, parmValue)\n continue\n if parmName == 'maxFreqErrToken':\n global maxFreqErrToken\n maxFreqErrToken = convertToInteger(lineNbr, parmValue)\n continue\n if parmName == 'matrixNumTokenRule':\n global matrixNumTokenRule\n matrixNumTokenRule = convertToBoolean(lineNbr, parmValue)\n continue\n if parmName == 'matrixInitialRule':\n global matrixInitialRule\n matrixInitialRule = convertToBoolean(lineNbr, parmValue)\n continue\n if parmName == 'mu':\n global mu\n mu = convertToFloat(lineNbr, parmValue)\n continue\n if parmName == 'muIterate':\n global muIterate\n muIterate = convertToFloat(lineNbr, parmValue)\n continue\n if parmName == 'epsilon':\n global epsilon\n epsilon = convertToFloat(lineNbr, parmValue)\n continue\n if parmName == 'epsilonIterate':\n global epsilonIterate\n epsilonIterate = convertToFloat(lineNbr, parmValue)\n continue\n if parmName == 'comparator':\n global comparator\n comparator = parmValue\n continue\n if parmName == 'beta':\n global beta\n beta = convertToInteger(lineNbr, parmValue)\n continue\n if parmName == 'minBlkTokenLen':\n global minBlkTokenLen\n minBlkTokenLen = convertToInteger(lineNbr, parmValue)\n continue\n if parmName == 'excludeNumericBlocks':\n global excludeNumericBlocks\n excludeNumericBlocks = convertToBoolean(lineNbr, parmValue)\n continue\n if parmName == 'removeExcludedBlkTokens':\n global removeExcludedBlkTokens\n removeExcludedBlkTokens = convertToBoolean(lineNbr, parmValue)\n continue\n if parmName == 'sigma':\n global sigma\n sigma = convertToInteger(lineNbr, parmValue)\n continue\n if parmName == 'truthFileName':\n global truthFileName\n truthFileName = parmValue\n continue\n # End of loop, cross checks\n if beta < 2:\n print('**Error: beta value ', beta, ' must be larger than 2')\n fatalError = True\n if sigma <= beta:\n print('**Error: sigma value ', sigma, ' must be larger than beta value ', beta)\n fatalError = True\n if mu <= 0.0 or mu > 1.00:\n print('**Error: mu value ', mu, ' must be in interval (0.00,1.00]')\n fatalError = True\n if fatalError:\n sys.exit()\n","repo_name":"Adeeba23/CensusBureauNameAddress","sub_path":"Household Graph/oysterer-dwm-graph-8711cd315cf3/GDWM18/DWM10_Parms.py","file_name":"DWM10_Parms.py","file_ext":"py","file_size_in_byte":6422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"16"}
+{"seq_id":"3981953300","text":"def ATMAndStudents(students, money):\n length = len(students)\n maxx = 0\n res = [-1]\n count = money\n i = 0\n j = 0\n while j < length and i < length:\n count += students[j]\n if count >= 0 and maxx < (j - i + 1):\n maxx = j - i + 1\n res = [i + 1, j + 1]\n if count < 0:\n count -= students[i]\n i += 1\n if count >= 0:\n j += 1\n else:\n count -= students[j]\n return res\n\ntests = int(input())\nans = []\nfor _ in range(tests):\n a, b = list(map(int, input().split()))\n students = list(map(int, input().split()))\n ans.append(ATMAndStudents(students, b))\nfor a in ans:\n print(*a)","repo_name":"nattigy/competitive_programming","sub_path":"div3 contest-1/F. ATM and Students.py","file_name":"F. ATM and Students.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"11521011860","text":"###################################################################################################\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Aug 23 22:05:51 2020\r\n\r\n@author: Srikanth Thirumalasetti (Roll #2019900090)\r\n\"\"\"\r\n\r\n\"\"\" This file is part of Main project on 'Learning representations in Financial domain' \"\"\"\r\n\r\n\"\"\" It evaluates a finetuned BERT model (base-uncased) on binary classification task. \"\"\"\r\n\r\n\"\"\" The script uses SimpleTransformers's ClassificationModel for finetuning. \"\"\"\r\n\r\n\"\"\" We use wandb to optimize our hyper params (learning rate and # of epochs) using \"accuracy\" as the key metric\r\n to evaluate the performance and store the best model.\"\"\"\r\n\r\n\"\"\" The model is:\r\n 1. first trained on the train set (self.trainDataFrame), \r\n 2. next, the wandb sweep is evaluated on the validation set (self.evalDataFrame)\r\n \r\n The best model as measured by the maximum accuracy corresponding to the hyper parameter values is saved to folder: self.bestModelOutputDir.\r\n\"\"\"\r\n###################################################################################################\r\nimport glob\r\nimport json\r\nimport logging as log\r\nimport math\r\nimport multiprocessing\r\nimport os\r\nimport pandas\r\nimport re\r\nimport sklearn\r\nimport subprocess\r\nimport sys\r\nimport threading\r\nimport time\r\nimport torch\r\nimport traceback\r\nimport wandb\r\nfrom collections import defaultdict, OrderedDict\r\nfrom filterSourceFilesForTraining import filterAndCopyCorpusFilesUsedToTrainBertOnMLM as filterCorpus\r\nfrom nltk.tokenize import sent_tokenize\r\nfrom preprocess import preprocess_seq # make sure that the pre-process.py file is in the parent folder, else, the script errors out\r\nfrom simpletransformers.classification import (ClassificationModel, ClassificationArgs)\r\n\r\n# This variable is used as header for the train and validation dataframes\r\nglobal HEADER_COLS\r\nHEADER_COLS = [\"tweet\", \"relation\"]\r\n\r\n# This variable is the WandB API key that is used to log training and eval params in real-time to WandB server\r\nglobal WAND_API_KEY, WAND_PROJECT_NAME\r\nWAND_API_KEY = \"01b06361bbf14e2d29e535b7ae84a9f3716365a4\"\r\nWAND_PROJECT_NAME = \"bert-base-finetune-mlm-sec-data-binary-cls\"\r\n\r\n\r\n############################################################################\r\n# This class evaluates a finetuned BERT model on binary classification task.\r\n############################################################################\r\nclass EvalLanguageModelOnBinCls:\r\n def __init__(self, modelNameOrPath, trainFile, evalFile, maxSeqLen, wandb_sweep_config, wandb_sweep_defaults, logLevel):\r\n log.debug(\"Initializing 'EvalLanguageModelOnBinCls' class instance..\")\r\n self.modelType = \"bert\"\r\n self.modelNameOrPath = modelNameOrPath\r\n self.trainFile = trainFile\r\n self.evalFile = evalFile\r\n self.trainDataFrame = None\r\n self.evalDataFrame = None\r\n self.maxSeqLength = maxSeqLen\r\n self.wandbConfig = wandb_sweep_config\r\n self.wandbDefaults = wandb_sweep_defaults\r\n self.modelOutputDir = os.path.join(os.path.split(trainFile)[0], \"finetuned_model_on_bin_cls\")\r\n self.bestModelOutputDir = os.path.join(self.modelOutputDir, \"best_model\")\r\n self.modelCacheDir = os.path.join(self.modelOutputDir, \"cache\")\r\n self.modelFinalEvalResultsFile = os.path.join(self.modelOutputDir, \"model.eval.results\")\r\n self.modelFinalEvalOutputs = os.path.join(self.modelOutputDir, \"model.eval.outputs\")\r\n self.modelFinalWrongPreds = os.path.join(self.modelOutputDir, \"model.predictions.wrong.results\")\r\n self.lock = threading.Lock()\r\n setLogLevel(logLevel)\r\n\r\n def __preprocessSequenceWithoutBreakingSentence(self, sequence):\r\n ##############################################################################################\r\n # This method ensures that if multiple sentences are passed for pre-processing, the sequence\r\n # is pre-processed as individual sentence.\r\n #############################################################################################\r\n try:\r\n seqsPP = []\r\n sequences = sent_tokenize(sequence)\r\n if sequences:\r\n for seq in sequences:\r\n seqsPP.append(preprocess_seq(seq))\r\n if seqsPP:\r\n return \".\".join(seqsPP).strip()\r\n else:\r\n return sequence\r\n except:\r\n exc_type, exc_value, exc_traceback = sys.exc_info()\r\n err = f\"Error occurred while pre-processing the sequence '{sequence}'. Error is: {str(exc_type)}; {str(exc_value)}.\"\r\n log.error(err)\r\n return sequence\r\n\r\n def __buildTrainingAndEvalDataFrames(self):\r\n ##############################################################################################\r\n # This method builds training and eval dataframes from the given input training and dev files.\r\n #############################################################################################\r\n try:\r\n tweetsDictTrain = {}\r\n tweetsDictEval = {}\r\n with open(self.trainFile, \"r\", encoding=\"utf-8\") as fR:\r\n tweetsDictTrain = json.load(fR)\r\n log.debug(f\"Finished building training file.\")\r\n with open(self.evalFile, \"r\", encoding=\"utf-8\") as fD:\r\n tweetsDictEval = json.load(fD)\r\n log.debug(f\"Finished building eval file.\")\r\n\r\n # Columns are: 'tweet', 'target_num', 'offset', 'target_cashtag' and 'relation'\r\n # Our classification task is: Given a tweet, tell whether the relation is 0 or 1\r\n if tweetsDictTrain:\r\n log.debug(f\"Started generating pandas dataframe for training..\")\r\n df = pandas.DataFrame.from_dict(tweetsDictTrain)\r\n self.trainDataFrame = df.iloc[0:len(df.index), [0,4]]\r\n self.trainDataFrame.columns = HEADER_COLS\r\n self.trainDataFrame[HEADER_COLS[0]] = self.trainDataFrame[HEADER_COLS[0]].map(lambda sent: self.__preprocessSequenceWithoutBreakingSentence(sent))\r\n\r\n if tweetsDictEval:\r\n log.debug(f\"Started generating pandas dataframe for evaluation..\")\r\n df = pandas.DataFrame.from_dict(tweetsDictEval)\r\n self.evalDataFrame = df.iloc[0:len(df.index), [0,4]]\r\n self.evalDataFrame.columns = HEADER_COLS\r\n self.evalDataFrame[HEADER_COLS[0]] = self.evalDataFrame[HEADER_COLS[0]].map(lambda sent: self.__preprocessSequenceWithoutBreakingSentence(sent))\r\n except:\r\n exc_type, exc_value, exc_traceback = sys.exc_info()\r\n err = f\"Error occurred while building training and eval dataframes. Error is: {str(exc_type)}; {str(exc_value)}.\"\r\n raise Exception(err)\r\n\r\n def finetuneBertOnBinClsTask(self):\r\n ###############################################################################\r\n # This method evaluates the finetuned BERT model on binary classification task.\r\n ###############################################################################\r\n try:\r\n # Build training and eval dataframes\r\n self.__buildTrainingAndEvalDataFrames()\r\n\r\n # Check to make sure that training and eval data frames are built\r\n if self.trainDataFrame is None or self.evalDataFrame is None:\r\n log.error(f\"Error building training and eval dataframes. Cannot evaluate the finetuned model on binary classification task.\")\r\n return\r\n\r\n # Check if CUDA is available for doing training on a GPU system\r\n if torch.cuda.is_available() is False:\r\n log.warning(f\"CUDA libs not found. It is prefered to do finetuning on on a GPU system with CUDA libs!\")\r\n\r\n # Build WandB sweep params that are used to automatically pick up the hyper-params during training\r\n subprocess.run([\"wandb\", \"login\", WAND_API_KEY])\r\n time.sleep(1)\r\n sweep_defaults = self.wandbDefaults\r\n sweep_id = wandb.sweep(self.wandbConfig, project=WAND_PROJECT_NAME)\r\n\r\n # Start training\r\n startTime = time.time()\r\n def train():\r\n wandb.init(WAND_PROJECT_NAME)\r\n modelArgs = { \"max_seq_length\": self.maxSeqLength, \"output_dir\": self.modelOutputDir, \"overwrite_output_dir\": True, \"best_model_dir\": self.bestModelOutputDir,\r\n \"wandb_project\": WAND_PROJECT_NAME, \"num_training_epochs\": wandb.config.epochs, \"learning_rate\": wandb.config.learning_rate,\r\n \"do_lower_case\": True, \"cache_dir\": self.modelCacheDir, \"encoding\": \"utf-8\", \"train_batch_size\": 5, \"eval_batch_size\": 5,\r\n \"evaluate_during_training_steps\": 50, \"evaluate_during_training_verbose\": True, \"logging_steps\": 5, \"sliding_window\": True,\r\n \"reprocess_input_data\": True, \"evaluate_during_training\": True, \"use_multiprocessing\": True }\r\n\r\n model = ClassificationModel(self.modelType, self.modelNameOrPath, args=modelArgs, sweep_config=wandb.config, use_cuda=torch.cuda.is_available(),)\r\n\r\n # Training and evaluation\r\n try:\r\n log.info(f\"Started training/finetuning BERT on binary classification task..\")\r\n model.train_model(train_df=self.trainDataFrame, eval_df=self.evalDataFrame, show_running_loss=True,\r\n output_dir=self.modelOutputDir,\r\n mcc=sklearn.metrics.matthews_corrcoef,\r\n f1=sklearn.metrics.f1_score,\r\n acc=sklearn.metrics.accuracy_score,\r\n recall_score=sklearn.metrics.recall_score, )\r\n log.info(f\"Finished finetuning and evaluating our fine-tuned model on binary classification task. Check the folder '{self.modelOutputDir}' for finetuned weights.\")\r\n log.info(f\"It took {round((time.time() - startTime) / 3600, 1)} hours to finetune and evaluate ou fine-tuned model on binary classification task.\")\r\n except:\r\n exc_type, exc_value, exc_traceback = sys.exc_info()\r\n err = f\"Error occurred while training and evaluating the finetuned model on binary classification task. Error is: {exc_type}; {exc_value}.\"\r\n log.error(err)\r\n\r\n wandb.join()\r\n\r\n wandb.agent(sweep_id, function=train)\r\n except:\r\n exc_type, exc_value, exc_traceback = sys.exc_info()\r\n err = f\"** ERROR ** occurred while finetuning a pre-trained BERT model and evaluating it on binary classification task. Error is: {exc_type}; {exc_value}.\"\r\n log.error(err)\r\n\r\n\r\ndef setLogLevel(level):\r\n ##########################################################\r\n # This method sets the log level for the default logger.\r\n ##########################################################\r\n # Set log level, if set by the user\r\n # E for Error, D for Debug and I for Info\r\n if level == \"I\":\r\n log.basicConfig(level=log.INFO)\r\n elif level == \"D\":\r\n log.basicConfig(level=log.DEBUG)\r\n else:\r\n level = \"E\"\r\n log.basicConfig(level=log.ERROR) # default to Error\r\n print(f\"Setting log level to {level}\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(\"Total # of arguments passed to main() is {0}\".format(len(sys.argv)))\r\n if len(sys.argv) < 3:\r\n print(\"** ERROR ** 1) Finetuned model directory, 2) Training file, and 3) Dev file are required!\")\r\n print(\"Usage:\\n\\t\")\r\n else:\r\n # Get finetuned model folder as given by the user in the command line\r\n _finetunedModelFolder = sys.argv[1] # set this variable to value: \"bert-base-uncased\" to evaluate using Huggingface's pre-trained BERT embeddings\r\n if os.path.exists(_finetunedModelFolder) is False:\r\n print(f\"** ERROR ** Finetuned model folder '{_finetunedModelFolder}' DOES NOT exist!\")\r\n print(\"Usage:\\n\\t\")\r\n else:\r\n # Convert the path to absolute path\r\n _finetunedModelFolder = os.path.abspath(_finetunedModelFolder)\r\n\r\n # Get the training and dev files\r\n _trainFile = sys.argv[2]\r\n _trainFile = os.path.abspath(_trainFile)\r\n _devFile = sys.argv[3]\r\n _devFile = os.path.abspath(_devFile)\r\n\r\n # Get log level set by the user in the command line\r\n _logLevel = \"E\" # default to log.ERROR\r\n if len(sys.argv) == 5:\r\n _logLevel = sys.argv[4] # over default log level as set by the user\r\n setLogLevel(_logLevel)\r\n\r\n # Evaluate the finetuned model on binary classification task\r\n try:\r\n # Start finetuning with different hyper-parameters\r\n _maxSeqLen = 192 # setting to same sequence value that was used for finetuning the model on MLM objective\r\n _learningRates = [5e-5, 2e-5, 1e-5] # set three diff LRs\r\n _epochs = [3, 5, 10] # set total epochs that we'd like to run\r\n _wandb_sweep_defaults = {'learning_rate': _learningRates[0], 'epochs': _epochs[0]} # set some default values\r\n _wandb_sweep_config = {'method': 'grid', \"metric\": {\"name\": \"mcc\", \"goal\": \"maximize\"},\r\n 'parameters': {'learning_rate': {'values': _learningRates}, 'epochs': {'values': _epochs}},\r\n \"early_terminate\": {\"type\": \"hyperband\", \"min_iter\": 5, },}\r\n\r\n # Initialize training class and start training\r\n cls = EvalLanguageModelOnBinCls(_finetunedModelFolder, _trainFile, _devFile, _maxSeqLen, _wandb_sweep_config, _wandb_sweep_defaults, _logLevel)\r\n cls.finetuneBertOnBinClsTask()\r\n cls = None\r\n except:\r\n exc_type, exc_value, exc_traceback = sys.exc_info()\r\n err = f\"\\n\\t {exc_type}; {exc_value}\"\r\n log.error(err)\r\n","repo_name":"Madhvi19/Representations-in-Financial-Domain","sub_path":"BERT/evalOnBinaryClassificationTask.py","file_name":"evalOnBinaryClassificationTask.py","file_ext":"py","file_size_in_byte":14474,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"9260115186","text":"import json\nfrom unittest.mock import patch\n\nimport pytest\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.models import Permission\nfrom model_bakery import baker\nfrom rest_framework import status\n\nfrom sme_ptrf_apps.core.choices import RepresentacaoCargo\nfrom sme_ptrf_apps.users.models import Grupo\n\npytestmark = pytest.mark.django_db\n\n\n@pytest.fixture\ndef unidade_diferente(dre):\n return baker.make(\n 'Unidade',\n nome='Escola Unidade Diferente',\n tipo_unidade='EMEI',\n codigo_eol='123459',\n dre=dre,\n sigla='ET2',\n cep='5868120',\n tipo_logradouro='Travessa',\n logradouro='dos Testes',\n bairro='COHAB INSTITUTO ADVENTISTA',\n numero='100',\n complemento='fundos',\n telefone='99212627',\n email='emeijopfilho@sme.prefeitura.sp.gov.br',\n diretor_nome='Amaro Pedro',\n dre_cnpj='63.058.286/0001-86',\n dre_diretor_regional_rf='1234567',\n dre_diretor_regional_nome='Anthony Edward Stark',\n dre_designacao_portaria='Portaria nº 0.000',\n dre_designacao_ano='2017',\n )\n\n\n@pytest.fixture\ndef visao_ue():\n return baker.make('Visao', nome='UE')\n\n\n@pytest.fixture\ndef visao_dre():\n return baker.make('Visao', nome='DRE')\n\n\n@pytest.fixture\ndef visao_sme():\n return baker.make('Visao', nome='SME')\n\n\n@pytest.fixture\ndef permissao1():\n return Permission.objects.filter(codename='view_tipodevolucaoaotesouro').first()\n\n\n@pytest.fixture\ndef permissao2():\n return Permission.objects.filter(codename='view_unidade').first()\n\n\n@pytest.fixture\ndef grupo_1(permissao1, visao_ue):\n g = Grupo.objects.create(name=\"grupo1\")\n g.permissions.add(permissao1)\n g.visoes.add(visao_ue)\n g.descricao = \"Descrição grupo 1\"\n g.save()\n return g\n\n\n@pytest.fixture\ndef grupo_2(permissao2, visao_dre):\n g = Grupo.objects.create(name=\"grupo2\")\n g.permissions.add(permissao2)\n g.visoes.add(visao_dre)\n g.descricao = \"Descrição grupo 2\"\n g.save()\n return g\n\n\n@pytest.fixture\ndef grupo_3(permissao1, permissao2, visao_dre, visao_sme):\n g = Grupo.objects.create(name=\"grupo3\")\n g.permissions.add(permissao1, permissao2)\n g.visoes.add(visao_dre, visao_sme)\n g.descricao = \"Descrição grupo 3\"\n g.save()\n return g\n\n\n@pytest.fixture\ndef usuario_para_teste(\n unidade,\n grupo_1,\n visao_ue):\n\n senha = 'Sgp0418'\n login = '7210418'\n email = 'sme@amcom.com.br'\n User = get_user_model()\n user = User.objects.create_user(username=login, password=senha, email=email)\n user.unidades.add(unidade)\n user.groups.add(grupo_1)\n user.visoes.add(visao_ue)\n user.save()\n return user\n\n\n@pytest.fixture\ndef jwt_authenticated_client_u(client, usuario_para_teste):\n from unittest.mock import patch\n\n from rest_framework.test import APIClient\n api_client = APIClient()\n with patch('sme_ptrf_apps.users.api.views.login.AutenticacaoService.autentica') as mock_post:\n data = {\n \"nome\": \"LUCIA HELENA\",\n \"cpf\": \"62085077072\",\n \"email\": \"luh@gmail.com\",\n \"login\": \"7210418\"\n }\n mock_post.return_value.ok = True\n mock_post.return_value.status_code = 200\n mock_post.return_value.json.return_value = data\n resp = api_client.post('/api/login', {'login': usuario_para_teste.username,\n 'senha': usuario_para_teste.password}, format='json')\n resp_data = resp.json()\n api_client.credentials(HTTP_AUTHORIZATION='JWT {0}'.format(resp_data['token']))\n return api_client\n\n\n@pytest.fixture\ndef usuario_2(\n unidade_diferente,\n grupo_2,\n grupo_3,\n visao_dre,\n visao_sme):\n\n senha = 'Sgp1981'\n login = '7211981'\n email = 'sme1981@amcom.com.br'\n User = get_user_model()\n user = User.objects.create_user(username=login, password=senha, email=email)\n user.unidades.add(unidade_diferente)\n user.groups.add(grupo_2, grupo_3)\n user.visoes.add(visao_dre, visao_sme)\n user.save()\n return user\n\n\n@pytest.fixture\ndef usuario_3(\n unidade,\n grupo_2,\n visao_dre,\n visao_ue):\n\n senha = 'Sgp8198'\n login = '7218198'\n email = 'sme8198@amcom.com.br'\n User = get_user_model()\n user = User.objects.create_user(username=login, password=senha, email=email, name=\"Arthur Marques\")\n user.unidades.add(unidade)\n user.groups.add(grupo_2)\n user.visoes.add(visao_dre, visao_ue)\n user.save()\n return user\n\n\n@pytest.fixture\ndef jwt_authenticated_client_u2(client, usuario_2):\n from unittest.mock import patch\n\n from rest_framework.test import APIClient\n api_client = APIClient()\n with patch('sme_ptrf_apps.users.api.views.login.AutenticacaoService.autentica') as mock_post:\n data = {\n \"nome\": \"LUCIA HELENA\",\n \"cpf\": \"62085077072\",\n \"email\": \"luh@gmail.com\",\n \"login\": usuario_2.username\n }\n mock_post.return_value.ok = True\n mock_post.return_value.status_code = 200\n mock_post.return_value.json.return_value = data\n resp = api_client.post('/api/login', {'login': usuario_2.username,\n 'senha': usuario_2.password}, format='json')\n resp_data = resp.json()\n api_client.credentials(HTTP_AUTHORIZATION='JWT {0}'.format(resp_data['token']))\n return api_client\n\n\ndef test_consulta_grupos(\n jwt_authenticated_client_u2,\n usuario_2,\n visao_ue,\n visao_dre,\n visao_sme,\n permissao1,\n permissao2,\n grupo_1,\n grupo_2,\n grupo_3):\n\n response = jwt_authenticated_client_u2.get(\"/api/usuarios/grupos/?visao=DRE\", content_type='application/json')\n result = response.json()\n esperado = [\n {\n \"id\": str(grupo_2.id),\n \"nome\": grupo_2.name,\n \"descricao\": grupo_2.descricao\n },\n {\n \"id\": str(grupo_3.id),\n \"nome\": grupo_3.name,\n \"descricao\": grupo_3.descricao\n }]\n\n assert result == esperado\n\n\ndef test_lista_usuarios(\n jwt_authenticated_client_u,\n usuario_para_teste,\n usuario_3,\n visao_ue,\n visao_dre,\n visao_sme,\n permissao1,\n permissao2,\n grupo_1,\n grupo_2):\n\n response = jwt_authenticated_client_u.get(\"/api/usuarios/?visao=DRE\", content_type='application/json')\n result = response.json()\n esperado = [\n {\n 'id': usuario_3.id,\n 'username': usuario_3.username,\n 'email': usuario_3.email,\n 'name': usuario_3.name,\n 'url': f'http://testserver/api/esqueci-minha-senha/{usuario_3.username}/',\n 'tipo_usuario': usuario_3.tipo_usuario,\n 'groups': [{'id': grupo_2.id, 'name': grupo_2.name, 'descricao': grupo_2.descricao}]\n }\n ]\n assert result == esperado\n\n\ndef test_filtro_por_grupo_lista_usuarios(\n jwt_authenticated_client_u2,\n usuario_2,\n usuario_3,\n visao_ue,\n visao_dre,\n visao_sme,\n permissao1,\n permissao2,\n grupo_1,\n grupo_2):\n\n response = jwt_authenticated_client_u2.get(\n f\"/api/usuarios/?visao=DRE&groups__id={grupo_2.id}\", content_type='application/json')\n result = response.json()\n esperado = [\n {\n 'id': usuario_3.id,\n 'username': '7218198',\n 'email': 'sme8198@amcom.com.br',\n 'name': 'Arthur Marques',\n 'url': 'http://testserver/api/esqueci-minha-senha/7218198/',\n 'tipo_usuario': usuario_3.tipo_usuario,\n 'groups': [\n {\n 'id': grupo_2.id,\n 'name': 'grupo2',\n 'descricao': 'Descrição grupo 2'\n }\n ]\n }\n ]\n assert result == esperado\n\n\ndef test_filtro_por_nome_lista_usuarios(\n jwt_authenticated_client_u2,\n usuario_2,\n usuario_3,\n visao_ue,\n visao_dre,\n visao_sme,\n permissao1,\n permissao2,\n grupo_1,\n grupo_2):\n\n response = jwt_authenticated_client_u2.get(f\"/api/usuarios/?visao=DRE&search=Arth\", content_type='application/json')\n result = response.json()\n esperado = [\n {'id': usuario_3.id,\n 'username': '7218198',\n 'email': 'sme8198@amcom.com.br',\n 'name': 'Arthur Marques',\n 'url': 'http://testserver/api/esqueci-minha-senha/7218198/',\n 'tipo_usuario': usuario_3.tipo_usuario,\n 'groups': [\n {\n 'id': grupo_2.id,\n 'name': 'grupo2',\n 'descricao': 'Descrição grupo 2'}]\n }\n ]\n assert result == esperado\n\n\ndef test_criar_usuario_servidor(\n jwt_authenticated_client_u,\n grupo_1,\n grupo_2,\n visao_dre):\n\n payload = {\n 'tipo_usuario': RepresentacaoCargo.SERVIDOR.name,\n 'username': \"9876543\",\n 'name': \"Lukaku Silva\",\n 'email': 'lukaku@gmail.com',\n 'visao': \"DRE\",\n 'groups': [\n grupo_1.id,\n grupo_2.id\n ]\n }\n response = jwt_authenticated_client_u.post(\n \"/api/usuarios/\", data=json.dumps(payload), content_type='application/json')\n result = response.json()\n\n esperado = {\n 'username': '9876543',\n 'email': 'lukaku@gmail.com',\n 'name': 'Lukaku Silva',\n 'tipo_usuario': RepresentacaoCargo.SERVIDOR.name,\n 'groups': [grupo_1.id, grupo_2.id]\n }\n User = get_user_model()\n u = User.objects.filter(username='9876543').first()\n\n assert len(u.visoes.all()) > 0\n assert response.status_code == status.HTTP_201_CREATED\n assert result == esperado\n\n\ndef test_criar_usuario_servidor_sem_email_e_sem_nome(\n jwt_authenticated_client_u,\n grupo_1,\n grupo_2,\n visao_dre):\n\n payload = {\n 'tipo_usuario': RepresentacaoCargo.SERVIDOR.name,\n 'username': \"9876543\",\n 'name': \"\",\n 'email': \"\",\n 'visao': \"DRE\",\n 'groups': [\n grupo_1.id,\n grupo_2.id\n ]\n }\n response = jwt_authenticated_client_u.post(\n \"/api/usuarios/\", data=json.dumps(payload), content_type='application/json')\n result = response.json()\n esperado = {\n 'username': '9876543',\n 'email': '',\n 'name': '',\n 'tipo_usuario': RepresentacaoCargo.SERVIDOR.name,\n 'groups': [grupo_1.id, grupo_2.id]\n }\n User = get_user_model()\n u = User.objects.filter(username='9876543').first()\n\n assert len(u.visoes.all()) > 0\n assert response.status_code == status.HTTP_201_CREATED\n assert result == esperado\n\n\ndef test_atualizar_usuario_servidor(\n jwt_authenticated_client_u,\n usuario_3,\n usuario_2,\n visao_ue,\n visao_dre,\n visao_sme,\n grupo_1,\n grupo_2):\n\n assert not usuario_2.visoes.filter(nome='UE').first()\n\n payload = {\n 'tipo_usuario': RepresentacaoCargo.SERVIDOR.name,\n 'username': usuario_2.username,\n 'name': usuario_2.name,\n 'email': 'novoEmail@gmail.com',\n 'visao': \"UE\",\n 'groups': [\n grupo_1.id\n ]\n }\n\n response = jwt_authenticated_client_u.put(\n f\"/api/usuarios/{usuario_2.id}/\", data=json.dumps(payload), content_type='application/json')\n result = response.json()\n\n esperado = {\n 'username': usuario_2.username,\n 'email': 'novoEmail@gmail.com',\n 'name': usuario_2.name,\n 'tipo_usuario': RepresentacaoCargo.SERVIDOR.name,\n 'groups': [grupo_1.id]\n }\n\n assert usuario_2.visoes.filter(nome='UE').first()\n assert result == esperado\n\n\ndef test_deletar_usuario_servidor(\n jwt_authenticated_client_u,\n usuario_3\n):\n\n from django.contrib.auth import get_user_model\n\n User = get_user_model()\n assert User.objects.filter(id=usuario_3.id).exists()\n\n response = jwt_authenticated_client_u.delete(\n f\"/api/usuarios/{usuario_3.id}/\", content_type='application/json')\n assert not User.objects.filter(id=usuario_3.id).exists()\n\n\ndef test_consulta_informacao_usuario(jwt_authenticated_client_u):\n path = 'sme_ptrf_apps.users.api.views.user.SmeIntegracaoService.informacao_usuario_sgp'\n with patch(path) as mock_get:\n data = {\n 'cpf': '12808888813',\n 'nome': 'LUCIMARA CARDOSO RODRIGUES',\n 'codigoRf': '7210418',\n 'email': 'tutu@gmail.com',\n 'emailValido': True\n }\n\n mock_get.return_value = data\n\n username = '7210418'\n response = jwt_authenticated_client_u.get(f'/api/usuarios/consultar/?username={7210418}')\n result = json.loads(response.content)\n assert response.status_code == status.HTTP_200_OK\n assert result == data\n\n\ndef test_consulta_informacao_usuario_sem_username(jwt_authenticated_client_u):\n response = jwt_authenticated_client_u.get(f'/api/usuarios/consultar/?username=')\n result = json.loads(response.content)\n assert response.status_code == status.HTTP_400_BAD_REQUEST\n assert result == \"Parâmetro username obrigatório.\"\n\n\ndef test_lista_usuarios_por_unidade(\n jwt_authenticated_client_u,\n usuario_para_teste,\n usuario_2,\n usuario_3,\n associacao,\n grupo_1,\n grupo_2):\n\n response = jwt_authenticated_client_u.get(f\"/api/usuarios/?associacao_uuid={associacao.uuid}\", content_type='application/json')\n result = response.json()\n esperado = [\n {\n 'id': usuario_3.id,\n 'name': 'Arthur Marques',\n 'tipo_usuario': 'Servidor',\n 'url': 'http://testserver/api/esqueci-minha-senha/7218198/',\n 'username': '7218198',\n 'email': 'sme8198@amcom.com.br',\n 'groups': [\n {\n 'descricao': 'Descrição grupo 2',\n 'id': grupo_2.id,\n 'name': 'grupo2'\n }],\n },\n {\n 'id': usuario_para_teste.id,\n 'name': 'LUCIA HELENA',\n 'tipo_usuario': 'Servidor',\n 'url': 'http://testserver/api/esqueci-minha-senha/7210418/',\n 'username': '7210418',\n 'email': 'luh@gmail.com',\n 'groups': [\n {\n 'descricao': 'Descrição grupo 1',\n 'id': grupo_1.id,\n 'name': 'grupo1'\n }],\n }\n\n ]\n print(result)\n assert result == esperado\n","repo_name":"ollyvergithub/SME-PTRF-BackEnd","sub_path":"sme_ptrf_apps/users/tests/test_api_user/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":14682,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"11644009512","text":"import os\nimport sys\nimport json\n\nos_folder = os\ndefault_name = ''\n\n\ndef rename_files(folder_path, extension, new_name):\n os_folder.chdir(folder_path)\n count = 1\n success = False\n for file in os_folder.listdir():\n file_name, file_extension = os_folder.path.splitext(file)\n if file_extension == extension:\n name_to_give = new_name + str(count) + file_extension\n os_folder.rename(file, name_to_give)\n count = int(count) + 1\n success = True\n return success\n\ndef delete_files(folder_path, extension):\n os_folder.chdir(folder_path)\n success = False\n for file in os_folder.listdir():\n file_name, file_extension = os_folder.path.splitext(file)\n if file_extension == extension:\n os_folder.remove(file)\n success = True\n return success\n\nif __name__ == \"__main__\":\n raw_data = sys.argv[1]\n data = eval(raw_data)\n\n # initialize variables\n folder = data['folder']\n action = data['action']\n extension = data['extension']\n name = data['name']\n # folder = folder[2:]\n\n # rename files\n if action == 'rename':\n rename = rename_files(folder, extension, name)\n if rename:\n message = {'message': 'success'}\n print(json.dumps(message))\n\n # delete files\n elif action == 'delete':\n delete = delete_files(folder, extension)\n message = {'message': 'success'}\n print(json.dumps(message))\n\n\n","repo_name":"arhinfulemmanuel/file-renamer","sub_path":"Backend/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"22606612058","text":"# -*- coding: utf-8 -*-\n\nimport cv2\n\nfrom os.path import basename\n\nfrom ..common.configuration import (\n PCT_FIT_BUFFER,\n PCT_HACK_WINDOW_DELAY,\n)\nfrom ..datamanagement.files import (\n get_edited_image_filepath,\n)\nfrom .imageprocessing import (\n crop_image,\n resize_image_width,\n rotate_image,\n compose_images,\n find_dominant_contours,\n collected_extrema,\n)\n\nclass PctComposerResponse:\n\n def get_response(self):\n return self._response\n \n def get_messages(self):\n return self._messages\n \n def get_warnings(self):\n return self._warnings\n \n #\n # Private\n #\n \n def __init__(self, response, messages=[], warnings=[]):\n self._response = response\n self._messages = messages\n self._warnings = warnings\n\nclass BaseComposerError(Exception):\n pass\n\nclass BaseComposer:\n def __init__(self, message_writer=None, debug_writer=None):\n self._debug = False\n self._message_writer = message_writer\n self._debug_writer = debug_writer\n \n def _log(self, msg):\n if self._message_writer:\n self._message_writer.write(msg)\n \n def _log_debug(self, msg):\n if self._debug_writer and self._debug:\n self._debug_writer.write(msg)\n\nclass PctComposerError(BaseComposerError):\n pass\n\nclass PctComposer(BaseComposer):\n \n def prepare(self, debug=False):\n self._debug = debug\n self._log_debug('Preparing images...')\n for image_composer in self._get_composers():\n image_composer.prepare(debug)\n self._log_debug('Image preparation complete.')\n \n def compose(self, debug=False):\n self._debug = debug\n self._log_debug('Composing image...')\n if not self._create_composition():\n self._log('No composition could be created.')\n return False\n return True\n \n def refresh_previews(self, width, startx=0, starty=0, margin=0,\n debug=False):\n self._debug = debug\n self._log_debug('Refreshing previews...')\n x = startx\n y = starty\n for composer in self._get_composers():\n composer.refresh_preview(x, y, width, debug)\n x += width + margin\n\n def refresh_composition(self, width, startx=0, starty=0, debug=False):\n self._debug = debug\n self._log_debug('Refreshing composition...')\n return self._refresh_composition(width, startx, starty)\n\n def reindex_image(self, index_in, index_out, debug=False):\n self._debug = debug\n self._log_debug('Swapping images {} and {}'.format(index_in, index_out))\n if self._check_index(index_in) and self._check_index(index_out):\n return self._reindex_image(index_in, index_out)\n return False\n \n def check_index(self, index, debug=False):\n self._debug = debug\n self._log_debug('Checking index {}'.format(index))\n return self._check_index(index)\n \n def fit(self, index, strength, debug=False):\n self._debug = debug\n self._log_debug('Fitting image {} at {}'.format(index, strength))\n if not self._check_index(index):\n self._log('Invalid index.')\n return False\n return self._get_composer(index).fit(strength, debug)\n \n def fit_all(self, strength, debug=False):\n self._debug = debug\n self._log_debug('Fitting images at {}'.format(strength))\n return self._fit_all(strength)\n \n def rotate(self, index, angle, debug=False):\n self._debug = debug\n self._log_debug('Rotating image {} by {}'.format(index, angle))\n if not self._check_index(index):\n self._log('Invalid index.')\n return False\n return self._get_composer(index).rotate(angle, debug)\n \n def save(self, filepath, metafile=None, debug=False):\n self._debug = debug\n self._log_debug('Saving {}'.format(filepath))\n \n # Composed\n if not self._save_composed(filepath):\n self._log('Unable to save {}'.format(filepath))\n return False\n \n # Edited\n image_files = self._save_changed_images()\n if not image_files:\n self._log('Unable to save edited image files')\n return False\n \n # Metadata\n if metafile is not None:\n if not self._save_metadata(metafile, image_files, filepath):\n self._log('Unable to save {}'.format(metafile))\n return False\n \n return True\n \n def undo(self, index, debug=False):\n self._debug = debug\n self._log_debug('Undoing action on image {}.'.format(index))\n if not self._check_index(index):\n self._log('Invalid index.')\n return False\n return self._get_composer(index).undo(debug)\n \n def redo(self, index, debug=False):\n self._debug = debug\n self._log_debug('Redoing action on image {}.'.format(index))\n if not self._check_index(index):\n self._log('Invalid index.')\n return False\n return self._get_composer(index).redo(debug)\n \n def cleanup(self, debug=False):\n self._debug = debug\n self._log_debug('Cleaning up composer...')\n return self._cleanup()\n \n #\n # Private\n #\n \n def __init__(self, image_files, message_writer=None, debug_writer=None):\n super(PctComposer, self).__init__(message_writer, debug_writer)\n self._init_image_composers(image_files)\n \n self._composition = None\n self._window = None\n\n def _init_image_composers(self, image_files):\n self._indexed_images = {}\n self._image_composers = {}\n for index, image in enumerate(image_files):\n self._indexed_images[index] = image\n self._image_composers[image] = ImgComposer(\n image,\n self._message_writer,\n self._debug_writer,\n )\n return self._image_composers\n\n def _init_window(self, name=None):\n self._destroy_window()\n if name is not None:\n self._window = name\n else:\n self._window = ' + '.join(\n [c.get_window() for c in self._get_composers()]\n )\n cv2.namedWindow(self._window)\n \n def _destroy_window(self):\n if self._window is not None:\n cv2.destroyWindow(self._window)\n self._window = None\n\n def _check_index(self, index):\n if index in self._indexed_images:\n return True\n return False\n\n def _get_composer(self, index):\n return self._image_composers[self._indexed_images[index]]\n \n def _get_composers(self, ordered=True):\n indices = list(self._indexed_images.keys())\n if ordered:\n indices.sort()\n composers = []\n for index in indices:\n composers.append(\n self._image_composers[self._indexed_images[index]]\n )\n return composers\n \n def _reindex_image(self, index_in, index_out):\n temp = self._indexed_images[index_in]\n self._indexed_images[index_in] = self._indexed_images[index_out]\n self._indexed_images[index_out] = temp\n return True\n \n def _create_composition(self):\n images = [c.get_image() for c in self._get_composers()]\n min_height = min([img.shape[0] for img in images])\n self._composition = compose_images(images, min_height)\n return True\n \n def _refresh_composition(self, width, x=0, y=0):\n self._init_window()\n preview = resize_image_width(self._composition, width)\n self._show_image(preview, x, y)\n \n def _show_image(self, image, x=None, y=None):\n cv2.imshow(self._window, image)\n if x is not None and y is not None:\n cv2.moveWindow(self._window, x, y)\n cv2.waitKey(PCT_HACK_WINDOW_DELAY)\n \n def _save_changed_images(self):\n filepaths = []\n for composer in self._get_composers():\n filepaths.append(composer.save(self._debug))\n return filepaths\n \n def _save_composed(self, filepath):\n cv2.imwrite(filepath, self._composition)\n return True\n \n def _save_metadata(self, filepath, image_files, composed_file):\n fp = open(filepath, 'w')\n fp.write(composed_file + '\\n')\n for f in image_files:\n fp.write(f + '\\n')\n fp.close()\n return True\n \n def _fit_all(self, strength):\n for c in self._get_composers():\n if not c.fit(strength, self._debug):\n return False\n return True\n \n def _cleanup(self):\n # Cleans up all of the preview images\n for c in self._get_composers():\n if not c.cleanup(self._debug):\n return False\n \n # Cleans up any composed image\n self._destroy_window()\n \n return True\n \nclass ImgComposerError(BaseComposerError):\n pass\n\nclass ImgComposer(BaseComposer):\n \n def prepare(self, debug=False):\n self._debug = debug\n self._log('Preparing {}'.format(self._image_file))\n self._prepare_image()\n self._prepare_window()\n \n def refresh_preview(self, x, y, width, debug=False):\n self._debug = debug\n preview = resize_image_width(self._current_image(), width)\n self._show_image(preview, x, y)\n \n def get_image(self):\n return self._current_image().copy()\n \n def get_window(self):\n return self._window\n \n def fit(self, strength, debug=False):\n self._debug = debug\n self._log_debug('Fitting {}'.format(self._image_file))\n if self._fit(strength):\n self._init_redo_images()\n return True\n return False\n \n def rotate(self, angle, debug=False):\n self._debug = debug\n self._log_debug('Rotating {}'.format(self._image_file))\n if self._rotate(angle):\n self._init_redo_images()\n return True\n return False\n \n def save(self, debug=False):\n self._debug = debug\n self._log_debug('Saving edited {}'.format(self._image_file))\n filepath = self._get_save_filepath()\n if self._save(filepath):\n return filepath\n return None\n \n def undo(self, debug=False):\n self._debug = debug\n self._log_debug('Undoing action on {}'.format(self._image_file))\n return self._undo()\n \n def redo(self, debug=False):\n self._debug = debug\n self._log_debug('Redoing action on {}'.format(self._image_file))\n return self._redo()\n \n def cleanup(self, debug=False):\n self._debug = debug\n self._log_debug('Cleaning up image composer')\n return self._cleanup()\n \n #\n # Private\n #\n \n def __init__(self, image_file, message_writer=None, debug_writer=None):\n super(ImgComposer, self).__init__(message_writer, debug_writer)\n self._init_images()\n self._init_redo_images()\n \n self._image_file = image_file\n self._window = None\n \n def _init_images(self):\n self._images = []\n \n def _init_redo_images(self):\n self._redo_images = []\n \n def _add_image(self, image):\n self._images.append(image)\n \n def _add_redo_image(self, image):\n self._redo_images.append(image)\n \n def _current_image(self):\n if len(self._images) < 1:\n return None\n return self._images[-1]\n \n def _pop_image(self):\n if len(self._images) < 2:\n return None\n return self._images.pop()\n \n def _pop_redo_image(self):\n if len(self._redo_images) < 1:\n return None\n return self._redo_images.pop()\n \n def _prepare_image(self):\n self._log_debug('Preparing image {}'.format(self._image_file))\n self._add_image(cv2.imread(self._image_file))\n \n def _prepare_window(self):\n self._log_debug('Preparing window for {}'.format(self._image_file))\n self._window = basename(self._image_file)\n cv2.namedWindow(self._window)\n \n def _destroy_window(self):\n if self._window is not None:\n cv2.destroyWindow(self._window)\n self._window = None\n \n def _show_image(self, image=None, x=None, y=None):\n self._log_debug('Showing image {}'.format(self._image_file))\n if image is None:\n cv2.imshow(self._window, self._current_image())\n else:\n cv2.imshow(self._window, image)\n if x is not None and y is not None:\n cv2.moveWindow(self._window, x, y)\n cv2.waitKey(PCT_HACK_WINDOW_DELAY)\n\n def _get_save_filepath(self):\n return get_edited_image_filepath(self._image_file)\n \n def _fit(self, strength):\n contours = find_dominant_contours(self._current_image(), strength)\n if contours is None:\n return False\n left, right, top, bottom = collected_extrema(contours)\n fitted = crop_image(\n self._current_image(),\n left,\n right,\n top,\n bottom,\n PCT_FIT_BUFFER,\n )\n if fitted is None:\n return False\n self._add_image(fitted)\n return True\n \n def _rotate(self, angle):\n rotated = rotate_image(self._current_image(), angle)\n self._add_image(rotated)\n return True\n\n def _save(self, filepath=None):\n cv2.imwrite(filepath, self._current_image())\n return True\n \n def _undo(self):\n image = self._pop_image()\n if image is not None:\n self._add_redo_image(image)\n return True\n return False\n \n def _redo(self):\n image = self._pop_redo_image()\n if image is not None:\n self._add_image(image)\n return True\n return False\n\n def _cleanup(self):\n self._destroy_window()\n return True","repo_name":"jasonbriceno/pct","sub_path":"pct/composer/composer.py","file_name":"composer.py","file_ext":"py","file_size_in_byte":14077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"18727172157","text":"a = False\nb = True\nif(a):\n print(\"A is True\") # indentation is important in python\n if(b):\n print(\"B is also true\")\nelif(9 > 8):\n user = input(\"Enter the message\")\n print(user)\nif(True and True):\n print(\"True\")\n","repo_name":"Ramlala-Yadav-Git/Python","sub_path":"ch9/ifStatement.py","file_name":"ifStatement.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"16"}
+{"seq_id":"34822432081","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 28 09:57:35 2019\n\n@author: Kenton\n\"\"\"\n\nfrom gurobipy import *\n\nfrom .Diet import *\n\ndef farmer_jones():\n # model\n m = Model('Farmer Jones')\n\n # variables\n x_ch = m.addVar()\n x_pl = m.addVar()\n\n # objective\n m.setObjective(4*x_ch + 2*x_pl, GRB.MAXIMIZE)\n\n # constraints\n m.addConstr(20*x_ch + 50*x_pl <= 480) # time\n m.addConstr(4*x_ch + x_pl <= 30) # eggs\n m.addConstr(0.26*x_ch + 0.2*x_pl <= 5) # milk\n\n m.optimize()\n\n print(x_ch.x, x_pl.x)\n\ndef farmer_jones_2():\n C = ['chocolate', 'plain']\n I = ['time', 'eggs', 'milk']\n\n revenue = [4, 2]\n usage = [[20, 50],\n [4, 1],\n [0.25, 0.2]]\n available = [480, 30, 5]\n\n m = Model('Farmer Jones')\n\n X = [m.addVar() for _ in C]\n\n m.setObjective(quicksum(revenue[c]*X[c] for c in range(len(C))),\n GRB.MAXIMIZE)\n\n for i in range(len(I)):\n m.addConstr(quicksum(usage[i][c]*X[c] for c in range(len(C))) <= available[i])\n\n m.optimize()\n\n for x in X:\n print(x.x)\n\ndef stigler():\n m = Model('Stigler Diet')\n\n X = [m.addVar() for f in F]\n\n for n in N:\n m.addConstr(DMIN[n] <= quicksum(NV[f][n]*X[f] for f in F))\n m.addConstr(quicksum(NV[f][n]*X[f] for f in F) <= DMAX[n])\n\n m.setObjective(quicksum(C[f]*X[f] for f in F), GRB.MINIMIZE)\n\n m.optimize()\n\n print('\\n'.join([Food[i] + ': ' + str(x.x) for i, x in enumerate(X)]))\n\nif __name__ == \"__main__\":\n farmer_jones()\n\n","repo_name":"katrinafyi/math3202","sub_path":"tutorials/tutorial_1.py","file_name":"tutorial_1.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"16"}
+{"seq_id":"73963701449","text":"\"\"\"\nPROBLEMA #3:\nThe prime factors of 13195 are 5, 7, 13 and 29.\nWhat is the largest prime factor of the number 600851475143 ?\n\"\"\"\n\n\ndef own_dividers(number):\n dividers = []\n divider = 1\n while divider < number:\n if (number % divider) == 0:\n dividers.append(divider)\n divider += 1\n return dividers\n\n\ndef prime_factor(number):\n sum_result = 0\n for dividers in own_dividers(number):\n sum_result += dividers\n if sum_result == 1:\n return True\n else:\n return False\n\n\nn = 600851475143\nlist_of_prime_factors = []\nfor num in own_dividers(n):\n if prime_factor(num):\n list_of_prime_factors.append(num)\n\nprint(f'The prime factors of {n} are: \\n {list_of_prime_factors}')\n","repo_name":"Edesalher/PyCharm","sub_path":"ChallengeProblems/ChallengeProblem3.py","file_name":"ChallengeProblem3.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"71047072967","text":"#importing modules\r\nimport pygame\r\nimport sys\r\nimport random\r\nimport time\r\nfrom pygame import mixer\r\nfrom pygame.locals import *\r\n\r\n#initializing pygame\r\npygame.init()\r\n\r\n#resolution of the screen\r\nWIDTH=800\r\nHEIGHT=600\r\nscreen=pygame.display.set_mode((WIDTH,HEIGHT))\r\n\r\n#caption and icon\r\npygame.display.set_caption(\"Space Rocket\")\r\nicon=pygame.image.load(\"Images\\\\icon.png\")\r\npygame.display.set_icon(icon)\r\n\r\n#player\r\nplayer_image=pygame.image.load(\"Images\\\\rocket.png\")\r\nplayer_size=30\r\nplayer_pos=[int(WIDTH/2),int(HEIGHT-3*player_size)]\r\n\r\n#enemy\r\nenemy_image=pygame.image.load(\"Images\\\\asteroid.png\")\r\nenemy_size = 50\r\nenemy_pos = [random.randint(0,WIDTH-enemy_size),random.randint(0,HEIGHT)]\r\nenemy_list=[enemy_pos]\r\nenemy_speed=0\r\n\r\n#background image\r\nbackground = pygame.image.load(\"Images\\\\background.png\")\r\n\r\n#background sound\r\nmixer.music.load(\"Sounds\\\\background.ogg\")\r\nmixer.music.play(-1)\r\n\r\n#basic\r\nscore=0\r\ngame_over=False\r\nclock=pygame.time.Clock()\r\n\r\n#fonts\r\nmyFont=pygame.font.SysFont(\"calibri\",35, bold=True, italic=True)\r\ngame_over_font=pygame.font.Font(\"Fonts\\\\font.otf\",60,italic=True)\r\n\r\ndef speed(score, enemy_speed):\r\n if score<10:\r\n enemy_speed=5\r\n elif score<20:\r\n enemy_speed=6\r\n elif score<30:\r\n enemy_speed=9\r\n elif score<50:\r\n enemy_speed=13\r\n elif score<65:\r\n enemy_speed=16\r\n else:\r\n enemy_speed=20\r\n return enemy_speed\r\ndef drop_enemies(enemy_list):\r\n delay = random.random()\r\n if len(enemy_list)<8 and delay<0.06:\r\n x_pos=random.randint(0,WIDTH-enemy_size)\r\n y_pos=0\r\n enemy_list.append([x_pos,y_pos])\r\ndef draw_enemies(enemy_list):\r\n for enemy_pos in enemy_list:\r\n screen.blit(enemy_image,(enemy_pos[0],enemy_pos[1]))\r\ndef new_enemy_pos(enemy_list, score):\r\n for idx, enemy_pos in enumerate(enemy_list):\r\n if enemy_pos[1]>=0 and enemy_pos[1]=p_x and e_x<(p_x+player_size)) or (p_x>=e_x and p_x<(e_x+enemy_size)):\r\n if(e_y>=p_y and e_y<(p_y+player_size)) or (p_y>=e_y and p_y<(e_y+enemy_size)):\r\n explosion=mixer.Sound(\"Sounds\\\\explosion.wav\")\r\n mixer.music.stop()\r\n explosion.play()\r\n return True\r\n return False\r\n\r\ndef gameover(game_over, score):\r\n screen.blit(background,(0,0))\r\n text=\" Game Over !\"\r\n label=game_over_font.render(text, 1, (255, 153, 102))\r\n screen.blit(label,(int(WIDTH/2)-150,int(HEIGHT/2)-30))\r\n text=\"Your Score: \"+str(score)\r\n label=game_over_font.render(text, 1, (255, 153, 102))\r\n screen.blit(label,(int(WIDTH/2)-150,int(HEIGHT/2)+20))\r\n\r\nrunning = True\r\nwhile(running == True):\r\n if game_over==False:\r\n for event in pygame.event.get():\r\n if event.type==pygame.QUIT:\r\n sys.exit()\r\n if event.type==pygame.KEYDOWN:\r\n x=player_pos[0]\r\n y=player_pos[1]\r\n if event.key==pygame.K_LEFT:\r\n \tif (x>0):\r\n \t\tx-=player_size+10\r\n elif event.key==pygame.K_RIGHT:\r\n \tif(x<700):\r\n \t\tx+=player_size+10\r\n elif event.key==pygame.K_UP:\r\n \tif(y>30):\r\n \t\ty-=player_size+10\r\n elif event.key==pygame.K_DOWN:\r\n \tif(y<500):\r\n \t\ty+=player_size+10\r\n player_pos=[x,y]\r\n screen.blit(background,(0,0))\r\n game_over=collision(player_pos,enemy_pos)\r\n drop_enemies(enemy_list)\r\n score=new_enemy_pos(enemy_list, score)\r\n enemy_speed=speed(score, enemy_speed)\r\n text=\"Your Score: \"+str(score)\r\n label=myFont.render(text, 1, (204, 255, 51))\r\n screen.blit(label,(int(WIDTH-250),0))\r\n game_over=multiple_collision(enemy_list,player_pos)\r\n draw_enemies(enemy_list)\r\n screen.blit(player_image,(player_pos[0],player_pos[1]))\r\n clock.tick(30)\r\n pygame.display.update()\r\n elif game_over==True:\r\n gameover(game_over, score)\r\n pygame.display.update()\r\n for event in pygame.event.get():\r\n if event.type==pygame.QUIT:\r\n running = False\r\n pygame.display.quit()\r\n pygame.quit()\r\n sys.exit()\r\n\r\n pygame.display.update()\r\n","repo_name":"DebRC/Space-Rocket","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4727,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"16"}
+{"seq_id":"40094065428","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 14 15:50:27 2019\n@author: matthew\n\nThese functions create the model and all of the custom model metrics we use.\nHeavy use of tensorflow and keras.\n\"\"\"\n\nimport data\n#import max_subarray_tf\nimport tensorflow.keras.models as models\nimport tensorflow.keras.layers as layers\nimport tensorflow.keras.optimizers as kOpt\nfrom tensorflow.keras import backend as keras\nimport tensorflow as tf\n#import tensorflow_probability as tfp\n\n#define a few parameters\nbase_n=5\np=16\n#this function is just shorthand for the base-2 exponential function\ndef f(x):\n return 2**x\n\ndef unet(pretrained_weights = None,input_shape = (224,224,1)):\n #see ronnenberger for architecture description\n \n inputs = layers.Input(input_shape,name='image_input')\n conv1 = layers.Conv2D(f(base_n), 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)\n conv1 = layers.Conv2D(f(base_n), 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1)\n pool1 = layers.MaxPooling2D(pool_size=(2, 2))(conv1)\n #pool1= BatchNormalization(axis=3)(pool1)\n \n conv2 = layers.Conv2D(f(base_n+1), 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool1)\n #conv2= BatchNormalization(axis=3)(conv2)\n conv2 = layers.Conv2D(f(base_n+1), 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv2)\n pool2 = layers.MaxPooling2D(pool_size=(2, 2))(conv2)\n #pool2= BatchNormalization(axis=3)(pool2)\n \n conv3 = layers.Conv2D(f(base_n+2), 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool2)\n #conv3= BatchNormalization(axis=3)(conv3)\n conv3 = layers.Conv2D(f(base_n+2), 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv3)\n pool3 = layers.MaxPooling2D(pool_size=(2, 2))(conv3)\n #pool3= BatchNormalization(axis=3)(pool3)\n \n conv4 = layers.Conv2D(f(base_n+3), 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool3)\n #conv4= BatchNormalization(axis=3)(conv4)\n conv4 = layers.Conv2D(f(base_n+3), 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv4)\n drop4 = layers.Dropout(0.5)(conv4)\n pool4 = layers.MaxPooling2D(pool_size=(2, 2))(drop4)\n #pool4= BatchNormalization(axis=3)(pool4)\n \n conv5 = layers.Conv2D(f(base_n+4), 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool4)\n conv5 = layers.Conv2D(f(base_n+4), 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv5)\n drop5 = layers.Dropout(0.5)(conv5)\n \n up6 = layers.Conv2D(f(base_n+3), 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(layers.UpSampling2D(size = (2,2))(drop5))\n merge6 = layers.concatenate([drop4,up6], axis = 3)\n conv6 = layers.Conv2D(f(base_n+3), 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge6)\n conv6 = layers.Conv2D(f(base_n+3), 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv6)\n \n up7 = layers.Conv2D(f(base_n+2), 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(layers.UpSampling2D(size = (2,2))(conv6))\n merge7 = layers.concatenate([conv3,up7], axis = 3)\n conv7 = layers.Conv2D(f(base_n+2), 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge7)\n conv7 = layers.Conv2D(f(base_n+2), 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv7)\n \n up8 = layers.Conv2D(f(base_n+1), 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(layers.UpSampling2D(size = (2,2))(conv7))\n merge8 = layers.concatenate([conv2,up8], axis = 3)\n conv8 = layers.Conv2D(f(base_n+1), 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge8)\n conv8 = layers.Conv2D(f(base_n+1), 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv8)\n \n up9 = layers.Conv2D(f(base_n), 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(layers.UpSampling2D(size = (2,2))(conv8))\n merge9 = layers.concatenate([conv1,up9], axis = 3)\n conv9 = layers.Conv2D(f(base_n), 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge9)\n #conv9=Dropout(rate=.2)(conv9)\n conv9 = layers.Conv2D(f(base_n), 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)\n conv10 = layers.Conv2D(1, 1 ,activation = 'relu',)(conv9)\n \n model = models.Model(inputs = inputs, outputs = conv10) \n #model.compile(optimizer = kOpt.Adam(lr = 1E-4), loss = mean_squared_error_weighted, metrics = ['mean_absolute_error','mean_squared_error',countErr,countErr_signed,countErr_relative]) \n model.compile(optimizer = kOpt.Adam(lr = 1E-4), loss = mean_squared_error_weighted) \n #decay = 1E-4/100\n #load existing model if provided\n if(pretrained_weights):\n \tmodel.load_weights(pretrained_weights)\n return model\n\n#unused shorthand for batchnorm/conv combo\ndef conv_relu_bn(nFilt,layer):\n conv = layers.Conv2D(nFilt, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(layer)\n conv= layers.BatchNormalization(axis=3)(conv)\n conv = layers.Conv2D(nFilt, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv)\n conv= layers.BatchNormalization(axis=3)(conv)\n return conv\n\n#%% define custom loss functions and metrics for tensorflow. \n \n#structural similarity index. can be useful to look at overall density map quality.\n#see https://scikit-image.org/docs/dev/auto_examples/transform/plot_ssim.html for details \ndef ssim(target,prediction):\n out=tf.image.ssim(target,prediction,2)\n out=-1*out\n return out\n#correlation of gt and predicted count density values, pixelwise\n#def corr2(target,prediction):\n# out=tfp.stats.correlation(tf.reshape(target[0,p:-p,p:-p,0],[192**2,1]),tf.reshape(prediction[0,p:-p,p:-p,0],[192**2,1]))\n# return out\n#not used. implements Lempitsky et al.'s loss function\ndef mesa_dist(target, prediction): \n target=target[0,:,:,0]\n prediction=prediction[0,:,:,0]\n diff1=target-prediction\n diff2=-target+prediction\n dMesa= tf.math.reduce_max(max_subarray_tf.maxSubArray_2D(diff1)[0],max_subarray_tf.maxSubArray_2D(diff2)[0])\n return dMesa\n#weighted mse. not weighted if weight=1\ndef mean_squared_error_weighted(y_true, y_pred):\n #essentially works as MSE with the cropping to remove mirrored regions\n weight=1\n dens = tf.not_equal(y_true, 0)\n sqdiff=keras.square(y_pred - y_true)\n sqdiff=tf.where(dens, weight*sqdiff, sqdiff) #condition, iftrue, iffalse\n return keras.mean(sqdiff[:,p:-p,p:-p,:]) \n\ndef mean_squared_error_bias(y_true, y_pred):\n #combo loss function of MSE and whole image error metric\n weight=1\n dens = tf.not_equal(y_true, 0)\n sqdiff=keras.square(y_pred - y_true)\n sqdiff=tf.where(dens, weight*sqdiff, sqdiff) #condition, iftrue, iffalse\n err=countErr(y_true, y_pred)\n return keras.mean(sqdiff[0,p:-p,p:-p,0])+(.1*tf.square(err))\n\n\ndef mean_squared_error_worst(y_true, y_pred):\n n=.25 #evaluate worst 1/4 of pixels- attempted substitute for max subarray\n \n sqdiff=keras.square(y_pred - y_true)[0,p:-p,p:-p,0]\n sqdiff=tf.reshape(sqdiff,[-1])\n sqdiff=tf.sort(sqdiff) #sorts in ascending order\n sqdiff=sqdiff[int(n*192*192):]\n \n return keras.mean(sqdiff)\n\n\n#evaluate loss only at worst pixel\ndef max_squared_error_weighted(y_true, y_pred):\n dens = tf.not_equal(y_true, 0)\n sqdiff=keras.square(y_pred - y_true)\n sqdiff=tf.where(dens, sqdiff, sqdiff) #condition, iftrue, iffalse\n return keras.max(sqdiff)\n#square of summed error\ndef tot_err(y_true, y_pred):\n #returns total image error squared\n return keras.square(keras.sum(y_true- y_pred)/data.mult)\n#absolute value of total error in image\ndef countErr(target, prediction):\n #target=tf.math.exp(target)-1\n #prediction=tf.math.exp(prediction)-1\n \n a=keras.sum(target)\n b=keras.sum(prediction)\n error = (b-a)\n return tf.math.abs(error/data.mult)\n#relative error over full image\ndef countErr_relative(target, prediction):\n #target=tf.math.exp(target)-1\n #prediction=tf.math.exp(prediction)-1\n #calculates percent error\n \n a=keras.sum(target)+1\n b=keras.sum(prediction)+1\n error = (b-a)/a\n return tf.math.abs(error)\n#signed total error in image\ndef countErr_signed(target, prediction):\n #target=tf.math.exp(target)-1\n #prediction=tf.math.exp(prediction)-1\n \n \n a=keras.sum(target)\n b=keras.sum(prediction)\n error = (b-a)\n return (error/data.mult)\n#get averages for prediciton and target values\ndef targSum(target, prediction):\n a=keras.sum(target)\n return a\ndef predSum(target, prediction):\n a=keras.sum(prediction)\n return a\n\n","repo_name":"ethier-lab/AxoNet","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":8928,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"40964721682","text":"\"\"\" The Hand class instantiates a list of Card objects.\n We add a card to a hand by adding a Card instanse to the cards list.\n To calculate the value, we determine if card is numeric, Ace, or other (a face card).\n Once determined the value is added.\n If the hand is a bust (>21), the value of the Ace is reduced to 1.\n\"\"\"\n\n\nclass Hand:\n # This function when called from the game class creates a empty hand for the player then the dealer.\n def __init__(self, dealer=False):\n self.dealer = dealer\n self.cards = []\n self.rank = 0\n\n # A Card object is added to the cards list.\n def add_card(self, card):\n self.cards.append(card)\n # This function initiates the card at 0 value and not an ace. \n def calculate_rank(self):\n self.rank = 0\n has_ace = False\n # Here we loop througe the Card instances, calculate and add the value.\n for card in self.cards:\n if card.rank.isnumeric():\n self.rank += int(card.rank)\n else:\n if card.rank == \"A\":\n has_ace = True\n self.rank += 11\n else:\n self.rank += 10\n # If over 21 Ace rank drops from 11 to 1\n if has_ace and self.rank > 21: \n self.rank -= 10\n # When called from game.py, this function the calculate_rank function.\n def get_rank(self):\n self.calculate_rank()\n return self.rank\n\n # This function prints players and the dealers 2nd card (hides the first).\n def display(self):\n if self.dealer:\n print(\"Hidden\")\n print(self.cards[1])\n else:\n for card in self.cards: \n print(card)\n print(\"rank:\", self.get_rank())","repo_name":"JEmbry2019/Poker_Python_Project_Tuesday","sub_path":"hand.py","file_name":"hand.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"6343141054","text":"import libreria\n\n\n# Aplicacion para guardar datos de pedir cantidad de productos\n\ndef agregarProductos():\n # 1. Pedir productos\n # 2. Pedir cantidad\n # 3. Guardar los datos en el archivo 5_app.txt\n producto= libreria.pedir_producto(\"Ingrese producto : \")\n cantidad= libreria.pedir_kilogramo(\"Ingrese cantidad : \")\n contenido= producto +\" - \"+str(cantidad)+\" kg\\n\"\n libreria.guardar_datos(\"5_app.txt\", contenido, \"a\")\n print(\"Datos guardados\")\n\ndef leerProductos():\n print(\"Producto Precio\")\n datos= libreria.obtener_datos(\"5_app.txt\")\n if(datos != \"\"):\n print(datos)\n else:\n print(\"Datos no guardados\")\n\nopc=0\nmax=3\nwhile ( opc != max ):\n print(\"##################################################\")\n print(\"############ MENU ###############################\")\n print(\"##################################################\")\n print(\"# 1. Pedir producto y cantidad #\")\n print(\"# 2. Leer producto y cantidad #\")\n print(\"# 3. Salir #\")\n print(\"##################################################\")\n\n opc = libreria.pedir_numero(\"Ingrese opcion : \", 1, 3)\n\n if ( opc == 1 ):\n agregarProductos()\n\n if ( opc == 2):\n leerProductos()\n# fin_menu\n\nprint(\"Fin del programa\")\n","repo_name":"florespadillaunprg/t10_flores.padilla","sub_path":"flores/1_menus/app5.py","file_name":"app5.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"36467762601","text":"# -*- coding:utf-8 -*-\n\nfrom pymongo import MongoClient\n\nconn = MongoClient(\"192.168.200.120\", 27017)\n\ndb = conn[\"products\"]\n\ncol = db[\"jay_loco_amazons\"]\n\nrs = col.find({\"crawlid\": \"5116\"}, {\"images\": 1})\n\nfor i in rs:\n\n print(i)","repo_name":"ShichaoMa/old-spider","sub_path":"test/test_image_exist.py","file_name":"test_image_exist.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"11615449783","text":"import requests\r\nimport random\r\nimport time\r\nimport os\r\nimport pyfiglet\r\nfrom colorama import Fore\r\n\r\nascii_banner = pyfiglet.figlet_format(\"samidbangkit\")\r\nprint(ascii_banner)\r\n\r\ntime.sleep(1)\r\n\r\nchannel_id = input(\"Masukkan ID channel: \")\r\nwaktu1 = int(input(\"Set Waktu Hapus Pesan: \"))\r\nwaktu2 = int(input(\"Set Waktu Kirim Pesan: \"))\r\n\r\ntime.sleep(1)\r\nprint(\"3\")\r\ntime.sleep(1)\r\nprint(\"2\")\r\ntime.sleep(1)\r\nprint(\"1\")\r\ntime.sleep(1)\r\n\r\ndef countdown(t):\r\n \r\n while t:\r\n mins, secs = divmod(t, 60)\r\n timer = '{:02d}:{:02d}'.format(mins, secs)\r\n print(timer, end=\"\\r\")\r\n time.sleep(1)\r\n t -= 1\r\n \r\n print('Fire in the hole!!')\r\n \r\n \r\n# input time in seconds\r\nt = waktu1\r\n\r\n\r\n\r\nos.system('cls' if os.name == 'nt' else 'clear')\r\n\r\nwith open(\"pesan.txt\", \"r\") as f:\r\n words = f.readlines()\r\n\r\nwith open(\"token.txt\", \"r\") as f:\r\n authorization = f.readline().strip()\r\n\r\nwhile True:\r\n channel_id = channel_id.strip()\r\n\r\n payload = {\r\n 'content': random.choice(words).strip()\r\n }\r\n\r\n headers = {\r\n 'Authorization': authorization\r\n }\r\n\r\n r = requests.post(f\"https://discord.com/api/v9/channels/{channel_id}/messages\", data=payload, headers=headers)\r\n print(Fore.WHITE + \"Sent message: \")\r\n print(Fore.YELLOW + payload['content'])\r\n \r\n \r\n# function call\r\n\r\n print(Fore.RED + payload[countdown(int(t))])\r\n\r\n\r\n response = requests.get(f'https://discord.com/api/v9/channels/{channel_id}/messages', headers=headers)\r\n\r\n if response.status_code == 200:\r\n messages = response.json()\r\n if len(messages) == 0:\r\n is_running = False\r\n break\r\n else:\r\n time.sleep(waktu1)\r\n\r\n else:\r\n print(f'Gagal mendapatkan pesan di channel: {response.status_code}')\r\n\r\n time.sleep(waktu2)\r\n","repo_name":"smdbngkt/pushbang","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"32622905061","text":"s = int(input())\n\ndef f(a):\n if a % 2 == 0:\n return a / 2\n else:\n return 3*a + 1\n\na = [s]\ni = 1\nwhile True:\n i += 1\n a_next = f(a[-1])\n if a_next in a:\n print(i)\n break\n else:\n a.append(a_next)","repo_name":"tamlog06/Atcoder-Beginner-Contest","sub_path":"problems/ABC/116/b/abc116_b.py","file_name":"abc116_b.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"14227337376","text":"#This file used to analyze data that exists locally. Data is downloaded seperately. \nfrom numpy import array\nimport csv\nimport os\nimport pickle\n\npath = \"/home/human/WattTime/data/CA-2012\" \npath2= \"/home/human/WattTime/data/CA-2012-Price\"\nplants = {}\npices = {}\n\n#functions for preservation of abstraction\ndef get_name(row):\n try: return float(row[1])\n except: return 0\n\ndef get_ORISPL_code(row):\n try: return float(row[2])\n except: return 0\n\ndef get_unit_id(row):\n try: return float(row[3])\n except: return 0\n\ndef get_date(row):\n try: return row[4]\n except: return 0\n\ndef get_hour(row):\n try: return float(row[5])\n except: return 0\n\ndef get_op_time(row):\n try: return float(row[6])\n except: return 0 \n\ndef get_GLOAD(row):\n try: return float(row[7])\n except: return 0\n\ndef get_SLOAD(row):\n return row[8]\n\ndef get_SO2_MASS(row):\n return row[9]\n\ndef get_SO2_MASS_MEASURE(row):\n return row[10]\n\ndef get_SO2_RATE(row):\n return row[11]\n\ndef get_SO2_RATE_MEASURE(row):\n return row[12]\n\ndef get_CO2_MASS(row):\n try: return row[17]\n except: return 0\n\n#for price data begin\ndef get_LMP_TYPE(row):\n try: return row[6]\n except: return 0\n\ndef get_OPR_DT(row):\n try: return row[0]\n except: return 0\n\ndef get_HE01(row):\n try: return row[11]\n except: return 0\n\ndef get_AVPR(row):\n#returns the average price in a day\n total_price = 0\n for i in range(11,35):\n try: total_price += float(row[i])\n except: total_price += 0\n return total_price/24\n#for price data end\n\ndef get_first(row):\n return row[0] #gets first item in row\n# end of abstraction functions for getting info from csv list object\n\n\"\"\"\n#This is for opening new .csv files. This should now be done by opener.py\n#here for reference only.\n\nfor filename in os.listdir(path):\n with open(\"{0}/{1}\".format(path,filename)) as csv_file:\n data_object = csv.reader(csv_file)\n for row in data_object:\n if \"{0} ID:{d1}\".format(get_name(row),get_unit_id(row)) not in plants:\n plants[\"{0} ID:{1}\".format(get_name(row),get_unit_id(row))] = [row]\n else: \n if get_unit_id(row) == get_unit_id(get_first(plants[\"{0} ID:{1}\".format(get_name(row),get_unit_id(row))])):\n plants[\"{0} ID:{1}\".format(get_name(row),get_unit_id(row))].append(row)\n else:\n plants[\"{0} ID:{1}\".format(get_name(row),get_unit_id(row))] = [row]\n\"\"\"\nwith open(\"/home/human/WattTime/data/plants.pickle\",\"rb\") as pickler:\n plants= pickle.load(pickler) #gets info for plants dictionary from file\n\n\"\"\"\n#This is for generating an \"aggregate plant\", that measures total amount over all plants\n#This should now be done by opener.py. Here for reference only. \n\ndef tryfloat(string):\n try: return float(string)\n except: return 0\n\naggregate_plant ={}\nworklist = []\nfor plant in plants:\n for row in plants[plant]:\n if get_date(row) not in aggregate_plant:\n totalhour = get_op_time(row)\n totalmw = get_GLOAD(row)\n totalCO2 = get_CO2_MASS(row)\n aggregate_plant[get_date(row)] = [tryfloat(totalhour), tryfloat(totalmw), tryfloat(totalCO2)]\n else:\n hour = get_op_time(row)\n mw = get_GLOAD(row)\n CO2 = get_CO2_MASS(row)\n aggregate_plant[get_date(row)][0] += tryfloat(hour)\n aggregate_plant[get_date(row)][1] += tryfloat(mw)\n aggregate_plant[get_date(row)][2] += tryfloat(CO2)\n\"\"\"\nwith open(\"/home/human/WattTime/data/aggregate_plant.pickle\",\"rb\") as pickler:\n aggregate_plant = pickle.load(pickler) #gets info for aggregate_plant dictionary from file\n\n\"\"\"\n#this is a test that displays the contents of the aggregate_plant dictionary\n#uncomment to run\nfor value in sorted(aggregate_plant):\n print(value, aggregate_plant[value])\n\"\"\" \n#this converts the aggregate plant dictionary into a data list.\ndata_list = []\nfor date in sorted(aggregate_plant):\n data_list.append([date] + aggregate_plant[date])\ndata_list.pop()\ndata_list.pop()\n#thisconverts the data_list into a 2-dimmensional numpy array \ndata_array = array([row for row in data_list]) \n\nwith open(\"/home/human/WattTime/data/data_array.pickle\",\"wb\") as pickler:\n pickle.dump(data_array, pickler) #dumps the array for later use by engine\n\n\n\"\"\"\n#this is a test that displays the contents of the data_list list\n#uncomment to run\nfor i in data_list:\n print(i)\n\"\"\"\n\n#these 3 dictionaries exist to make working with their respective variables more convenient\n\"\"\"\naggregate_HOUR = {} \nfor i in aggregate_plant:\n aggregate_HOUR[aggregate_plant[i][0]] = i\n \naggregate_MW = {}\nfor i in aggregate_plant:\n aggregate_MW[aggregate_plant[i][1]] = i\n\naggregate_CO2 = {}\nfor i in aggregate_plant:\n aggregate_CO2[aggregate_plant[i][2]] = i\n\"\"\"\n\"\"\"\n#this is a test that displays the contents of the dictionaries in increasing order\n#uncomment to run\nfor dic in [aggregate_HOUR,aggregate_MW,aggregate_CO2]:\n for value in sorted(dic):\n print(value, dic[value])\n\"\"\"\n\n\"\"\"\n #This is for opening new .csv files for price. This should now be done by opener.py\n #Here for reference only. \n\nfor filename in os.listdir(path2):\n with open(\"{0}/{1}\".format(path2,filename)) as csv_file:\n price_object = csv.reader(csv_file)\n for row in price_object:\n if get_LMP_TYPE(row) == \"LMP\":\n prices[get_OPR_DT(row)] = row\n\"\"\"\n\nwith open(\"/home/human/WattTime/data/prices.pickle\",\"rb\") as pickler:\n prices = pickle.load(pickler) #gets info for prices dictionary from file\n\nav_daily_prices = {}\nfor date in prices:\n av_daily_prices[get_AVPR(prices[date])] = date\n\"\"\"\n#This is a test that prints the average daily prices in increasing order.\n#uncomment to run\nfor price in sorted(av_daily_prices):\n print(price, av_daily_prices[price])\n\"\"\"\nav_daily_prices_bydate = {}\nfor date in prices:\n av_daily_prices_bydate[date] = get_AVPR(prices[date])\n \n\"\"\"\n#Another formatting test\nfor plant in sorted(plants):\n for row in plants[plant]:\n print(\"Plant: {0}; Date: {1} Hour: {2}; Operating Percent: {3}\".format(get_name(row), get_date(row), get_hour(row), get_op_time(row)))\n\nprint(\"Success!\")\n\n\"\"\"\n\ndef count_rows(plants, key):\n count = 0 \n for row in plants[key]:\n count +=1\n\ndef mean(dictionary):\n total = 0\n count = 0\n for value in dictionary.values():\n count +=1\n try: total += value\n except: total += 0\n return total/count\n\ndef avpr_when_on(plants, prices):\n outlist = []\n for plant in sorted(plants):\n for row in plants[plant]:\n outlist.append(\"{0}: {1}\".format(get_date(row), get_hour(row)))\n\ndef operating_time_average(plants, period=24):\n #returns average operating time over all plants in given period\n returndict = {}\n for plant in plants:\n count = 0\n ontime = 0\n for row in plants[plant]:\n count += 1\n try: ontime += float(get_op_time(row))\n except: ontime += 0\n returndict[plant] = (ontime * period)/count\n return mean(returndict)\n\n\ndef average_X(plants, plant, get_X, period=24):\n total = 0 \n count = 0\n for row in plants[plant]:\n if float(get_X(row)) >= 0:\n count += 1\n total += float(get_X(row))\n if count == 0: \n return 0\n return (total * period)/count\n\ndef average_X_dict(plants, get_X, period=24):\n AV_DICT = {}\n for plant in plants:\n AV_DICT[plant] = average_X(plants, plant, get_X, period) \n return AV_DICT\n\ndef op_time_av_plant(plant, period=24):\n ontime = 0\n for row in plant:\n try: ontime += float(get_op_time(row))\n except: ontime += 0\n return (ontime * period)/8784\n\ndef CO2_per_MW(plant, period=1):\n CO2 = 0\n MW = 0\n for row in plant:\n try: CO2 += float(get_CO2_MASS(row))\n except: CO2 += 0 \n for row in plant:\n try: MW += float(get_GLOAD(row))\n except: MW += 0\n if MW == 0:\n return 0\n return (period * (CO2/MW))\n\"\"\"\n#FOR GRAPHING WITH MATPLOTLIB/PYLAB\n\nCO2_DICT = {}\nfor plant in sorted(plants):\n CO2_DICT[CO2_per_MW(plants[plant])] = plant\nfor plant in sorted(CO2_DICT):\n print(plant, CO2_DICT[plant])\nxvals =[]\nyvals =[]\nfor plant in sorted(CO2_DICT):\n xvals.append(CO2_DICT[plant])\n yvals.append(plant)\nimport matplotlib.pyplot as plt\nimport pylab\n\nfig = plt.figure()\ngraph = fig.add_subplot(111)\nfig.subplots_adjust(top=0.85)\ngraph.set_ylabel(\"CO2 per MW/hr\")\ngraph.set_xlabel(\"Plants\")\nfig.suptitle(\"Average CO2 per MW\", fontsize=25, fontweight=\"bold\")\nx = range(len(xvals))\npylab.plot(x, yvals, \"g\")\npylab.show()\n\"\"\"\n \ndef at_least(a, b):\n if a >= b:\n return True\n else:\n return False\n\ndef at_most(a, b):\n if a <= b:\n return True\n else:\n return False\n\ndef on_percent(plants, percent, operator, period=24): \n#returns a list of plants that were operating (on average) at least X percent of a period\n returnlist = []\n for plant in plants:\n if operator(op_time_av_plant(plants[plant], period), percent*period):\n returnlist.append(plant)\n return returnlist\n\"\"\"\n#This is a test that prints all plants on at least half of an average day\n#Uncomment to run\nfor plant in on_percent(plants, .5 , at_least, 24):\n print (plant)\n\"\"\"\ndef similar(plants, operator, threshold, comparer, value, period=24):\n #returns a dictionary of plants greater than or less than(depending on operator) a certain threshold ratio of the output of a value function over a period, compared by some comparer function\n returndict= {}\n finaldict = {}\n for plant in plants:\n returndict[plant] = comparer(plants[plant], period)\n for item in returndict:\n if operator(returndict[item]/value, threshold * value):\n finaldict[item] = returndict[item] \n return finaldict\n\n\"\"\"\"\n#This is a test which displays an example use of \"similar\" function from above.\n#Uncomment to run\n\nsortdict = similar(plants, at_least, 1 , op_time_av_plant, operating_time_average(plants))\nreverse = {}\nfor plant in sorted(sortdict):\n reverse[sortdict[plant]] = plant\nfor i in reverse:\n print(i, reverse[i])\n\"\"\"\ndef similar_days(dict_list, date, radius):\n \"\"\" takes in a list of pairs of dictionaries of format:\n [({average of var1: corresponding-date }, {corresponding-date: average of var1}), ({average of var2: corresponding-date... }...)...]\n as well as a date, and a radius. Returns the most similar days to the given day by minimizing\n the distance between the values recorded in that day and the average values in\n the {radius} amount of days requested. A radius of 5 would return the 10 most\n similar days: 5 days with values greater than the day, and 5 days with lower values\n \"\"\"\n return(\"failure\")\n\ndef similar_days(dict_list, date, amount):\n my_difference =\"nope\" \n print(\"Success!\")\n\n","repo_name":"egeriicw/watttime-grid","sub_path":"regression/2011_REGS/inspector.py","file_name":"inspector.py","file_ext":"py","file_size_in_byte":10999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"36577024933","text":"import json\nfrom queue import Empty\n\nfrom sqlalchemy import and_\n\nfrom flask_restful import Resource\nfrom flask import request\n\nfrom tools import api_tools, auth\nfrom ...models.tests import Test\nfrom ...models.pd.test_parameters import PerformanceTestParam\nfrom ...utils.utils import run_test, parse_test_data, handle_artifact_source\n\n\nclass API(Resource):\n url_params = [\n '',\n ]\n\n def __init__(self, module):\n self.module = module\n\n @auth.decorators.check_api({\n \"permissions\": [\"performance.backend.tests.view\"],\n })\n def get(self, project_id: int):\n total, res = api_tools.get(project_id, request.args, Test)\n rows = []\n for i in res:\n test = i.api_json()\n schedules = test.pop('schedules', [])\n if schedules:\n try:\n test['scheduling'] = self.module.context.rpc_manager.timeout(\n 2).scheduling_backend_performance_load_from_db_by_ids(schedules)\n except Empty:\n test['scheduling'] = []\n rows.append(test)\n return {'total': total, 'rows': rows}, 200\n\n @staticmethod\n def get_schedules_ids(filter_) -> set:\n r = set()\n for i in Test.query.with_entities(Test.schedules).filter(\n filter_\n ).all():\n r.update(set(*i))\n return r\n\n @auth.decorators.check_api({\n \"permissions\": [\"performance.backend.tests.delete\"],\n \"recommended_roles\": {\n \"default\": {\"admin\": True, \"editor\": False, \"viewer\": False},\n \"administration\": {\"admin\": True, \"editor\": False, \"viewer\": False},\n }\n })\n def delete(self, project_id: int):\n project = self.module.context.rpc_manager.call.project_get_or_404(\n project_id=project_id)\n try:\n delete_ids = list(map(int, request.args[\"id[]\"].split(',')))\n except TypeError:\n return 'IDs must be integers', 400\n\n filter_ = and_(\n Test.project_id == project.id,\n Test.id.in_(delete_ids)\n )\n\n try:\n self.module.context.rpc_manager.timeout(3).scheduling_delete_schedules(\n self.get_schedules_ids(filter_)\n )\n except Empty:\n ...\n\n Test.query.filter(\n filter_\n ).delete()\n Test.commit()\n\n return {'ids': delete_ids}, 200\n\n @auth.decorators.check_api({\n \"permissions\": [\"performance.backend.tests.create\"],\n \"recommended_roles\": {\n \"default\": {\"admin\": True, \"editor\": True, \"viewer\": False},\n \"administration\": {\"admin\": True, \"editor\": True, \"viewer\": False},\n }\n })\n def post(self, project_id: int):\n \"\"\"\n Create test and run on demand\n \"\"\"\n data = json.loads(request.form.get('data'))\n run_test_ = data.pop('run_test', False)\n compile_tests_flag = data.pop('compile_tests', False)\n engagement_id = data.get('integrations', {}).get('reporters', {}) \\\n .get('reporter_engagement', {}).get('id')\n\n test_data, errors = parse_test_data(\n project_id=project_id,\n request_data=data,\n rpc=self.module.context.rpc_manager,\n )\n\n if errors:\n return errors, 400\n\n schedules = test_data.pop('scheduling', [])\n\n test_data['test_parameters'].append(\n PerformanceTestParam(\n name=\"test_type\",\n default=test_data.pop('test_type'),\n description='auto-generated from test type'\n ).dict()\n )\n test_data['test_parameters'].append(\n PerformanceTestParam(\n name=\"env_type\",\n default=test_data.pop('env_type'),\n description='auto-generated from environment'\n ).dict()\n )\n\n if test_data['source']['name'] == 'artifact':\n project = self.module.context.rpc_manager.call.project_get_or_404(\n project_id=project_id)\n handle_artifact_source(project, request.files['file'],\n compile_tests_flag=compile_tests_flag,\n runner=test_data[\"runner\"])\n\n test = Test(**test_data)\n test.insert()\n\n test.handle_change_schedules(schedules)\n\n if run_test_:\n resp = run_test(test, engagement_id=engagement_id)\n return resp, resp.get('code', 200)\n return test.api_json(), 200\n","repo_name":"carrier-io/backend_performance","sub_path":"api/v1/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"10087448988","text":"from tkinter import Canvas\n\n\nclass CaseTaquin:\n largeur = 80\n hauteur = 80\n fill = \"grey\"\n activefill = \"green\"\n font = ('Helvetica', '16')\n\n def __init__(self, canevas: Canvas, numero: int, x: int, y: int):\n self.x = x\n self.y = y\n self.numero = numero\n self.canevas = canevas\n self.id = None\n\n def draw(self):\n self.id = self.canevas.create_rectangle(self.x, self.y, self.x + CaseTaquin.largeur,\n self.y + CaseTaquin.hauteur, fill=CaseTaquin.fill,\n activefill=CaseTaquin.activefill)\n self.canevas.create_text(self.x + CaseTaquin.largeur // 2, self.y + CaseTaquin.hauteur // 2,\n text=str(self.numero), font=CaseTaquin.font)\n\n def deplace_droite(self):\n self.x = self.x + CaseTaquin.largeur\n self.canevas.move(self.id, CaseTaquin.largeur, 0)\n self.canevas.move(self.id + 1, CaseTaquin.largeur, 0)\n\n def deplace_gauche(self):\n self.x = self.x - CaseTaquin.largeur\n self.canevas.move(self.id, -CaseTaquin.largeur, 0)\n self.canevas.move(self.id + 1, -CaseTaquin.largeur, 0)\n\n def deplace_haut(self):\n self.y = self.y - CaseTaquin.hauteur\n self.canevas.move(self.id, 0, -CaseTaquin.hauteur)\n self.canevas.move(self.id + 1, 0, -CaseTaquin.hauteur)\n\n def deplace_bas(self):\n self.y = self.y + CaseTaquin.hauteur\n self.canevas.move(self.id, 0, CaseTaquin.hauteur)\n self.canevas.move(self.id + 1, 0, CaseTaquin.hauteur)\n\n def __str__(self):\n return f\"({self.x},{self.y})\"\n","repo_name":"oultetman/taquin","sub_path":"case_taquin.py","file_name":"case_taquin.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"72626219847","text":"from PyGRB.main.fitpulse import PulseFitter\nfrom PyGRB.backend.makemodels import create_model_from_key\n\nGRB = PulseFitter(7475, times = (-2, 60),\n datatype = 'discsc', nSamples = 200, sampler = 'nestle',\n priors_pulse_start = -10, priors_pulse_end = 30, p_type ='docs')\n\nkey = 'F'\nmodel = create_model_from_key(key)\nGRB.main_multi_channel(channels = [0, 1, 2, 3], model = model)\n","repo_name":"JamesPaynter/PyGRB","sub_path":"examples/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"16"}
+{"seq_id":"39639202658","text":"#!/usr/bin/python3\n\"\"\"\nFetches a URL and prints the X-Request-Id header value.\n\"\"\"\n\nimport requests\nimport sys\n\n\ndef main():\n r = sys.argv[1]\n \"\"\"sends a request to the url\"\"\"\n response = requests.get(r)\n if 'X-Request-Id' in response.headers:\n \"\"\"prints the id id variable in the header\"\"\"\n print(response.headers['X-Request-Id'])\n else:\n return None\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"kamerelinda/alx_python","sub_path":"python-network_1/1-hbtn_header.py","file_name":"1-hbtn_header.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"40069427809","text":"# -*- coding: utf-8 -*-\n# cls_mssqlserver.py\t written by Duncan Murray 28/4/2014\n# Simple wrapper for MS SQL Server functionality\n\n# install https://pypi.python.org/pypi/pypyodbc/ \n# extract folder to D:\\install\\python\\pypyodbc-1.3.1\n# shell to folder, run setup.py\n# in your main program:\n# import lib_data_SQLServer as sql\n# sql.CreateAccessDatabase('test.mdb')\n\n\n\ntry:\n import pypyodbc \nexcept ImportError:\n print('you need to install https://pypi.python.org/pypi/pypyodbc/ ')\n exit(1)\n\nfrom if_database import Database\n\n\ndef TEST():\n #testFile = 'D:\\\\database.mdb'\n print('wrapper for MS SQL Server and Access databases')\n \n d = MSSQL_server(['server', 'database', 'username', 'password'])\n d.connect()\n print(d.server)\n \nclass MSSQL_server(Database):\n\n def CreateAccessDatabase(self, fname):\n pypyodbc.win_create_mdb(fname)\n connection = pypyodbc.win_connect_mdb(fname)\n connection.cursor().execute('CREATE TABLE t1 (id COUNTER PRIMARY KEY, name CHAR(25));').commit()\n connection.close()\n\n def CompactAccessDatabase(self, fname):\n pypyodbc.win_compact_mdb(fname,'D:\\\\compacted.mdb')\n\n def SQLServer_to_CSV(self, cred, schema, table, fldr):\n opFile = fldr + table + '.CSV'\n print ('Saving ' + table + ' to ' + opFile)\n #cred = [server, database, username, password]\n connection_string ='Driver={SQL Server Native Client 11.0};Server=' + cred[0] + ';Database=' + cred[1] + ';Uid=' + cred[2] + ';Pwd=' + cred[3] + ';'\n #print(connection_string)\n conn = pypyodbc.connect(connection_string)\n cur = conn.cursor()\t\n sqlToExec = 'SELECT * FROM ' + schema + '.' + table + ';'\n cur.execute(sqlToExec)\n op = open(opFile,'wb') # 'wb'\n # add column headers\n txt = ''\n for col in cur.description:\n txt += '\"' + self.force_string(col[0]) + '\",'\n op.write(txt + '\\n')\n for row_data in cur: # add table rows\t\t\t.encode('utf-8')\n txt = ''\n for col in row_data:\n txt += '\"' + self.force_string(col) + '\",'\n op.write(txt + '\\n')\n op.close()\t\n cur.close()\n conn.close()\n\n def force_string(self, obj):\n if type(obj) is str:\n return obj\n else:\n return str(obj)\n \nif __name__ == '__main__':\n TEST()\t\n ","repo_name":"acutesoftware/AIKIF","sub_path":"aikif/dataTools/if_mssqlserver.py","file_name":"if_mssqlserver.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"16"}
+{"seq_id":"3705122799","text":"import scrapy\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urlparse\n\ncount = 0\n\n\nclass ConcordiaSpider(scrapy.Spider):\n name = \"concordia\"\n start_urls = ['https://www.concordia.ca/ginacody.html']\n\n def parse(self, response):\n soup = BeautifulSoup(response.text, 'lxml')\n page = urlparse(response.url)\n filename = \"test_html/\" + page.path[10:].replace(\"/\", \"_\")\n with open(filename, 'wb') as f:\n f.write(response.body)\n\n # Obeying robots apart from robots.txt Look at tag\n robot_tag = soup.find(\"meta\", attrs={'name': 'robots'})\n\n links = soup.findAll('a', href=True)\n for link in links:\n if link is not None:\n url = link['href']\n if url.startswith(\"/ginacody\") and robot_tag['content'] == \"index,follow\":\n next_link = response.urljoin(url)\n yield {\n 'Next link': next_link,\n 'url': url,\n 'robots_tag': robot_tag['content']\n }\n yield scrapy.Request(url=next_link, callback=self.parse)\n","repo_name":"Gmartinica/COMP-479-projects","sub_path":"p4/concordia/concordia/spiders/concordia_crawler.py","file_name":"concordia_crawler.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"3577331478","text":"'''\nCreated on Oct 25, 2011\n\n@author: Meredith\n'''\n\n'''for loop for counting\nrange (startpoint, end point, update)\\\nstartpoint = includes\nendpoint = does not include\nupdate = number by which to count\n\nrange(0, 10, 2)\noutput- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\n\nrange(0,10,2)\noutput- 0, 2, 4, 6, 8\n\nrange(10, 0, -1)\n10, 9, 8, 7, 6, 5, 4, 3, 2, 1\n\nrange(0, 10)\noutput 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\n\nrange(10)\n0, 1, 2, 3, 4, 5, 6, 7, 8, 9\n\ni,j,k are counting variables'''\n\ns = 'Meredith Hoo'\nfor c in s:\n if c.isalnum():\n print(c)\n elif c.isalph():\n print(c)","repo_name":"zesameri/Beginner-Python-Projects","sub_path":"Basic Concepts/counting.py","file_name":"counting.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"69970209929","text":"from logging import debug\r\nfrom flask import Flask,render_template\r\nfrom flask.globals import request\r\nfrom flask_socketio import SocketIO, emit, join_room, leave_room, send\r\n\r\napp=Flask(__name__)\r\napp.config[\"SECRET_KEY\"]=\"SECRET\"\r\nsocketio = SocketIO(app,async_mode = 'eventlet')\r\n\r\nuser_room_dict={}\r\nsid_user_dict={}\r\n\r\n@socketio.on('message')\r\ndef handle_message(msg):\r\n print(request.sid)\r\n emit(\"message\",msg,broadcast=True)\r\n\r\n@socketio.on('join')\r\ndef join_a_room(data):\r\n print(data)\r\n roomid=data[\"room\"]\r\n join_room(roomid)\r\n\r\n user_room_dict[request.sid]=roomid\r\n\r\n emit(\"Roommessage\",sid_user_dict[request.sid]+\" enter the room\",to=roomid)\r\n\r\n@socketio.on('leave')\r\ndef leave_a_room(data):\r\n print(data)\r\n roomid=data[\"room\"]\r\n leave_room(roomid)\r\n\r\n emit(\"Roommessage\",sid_user_dict[request.sid]+\" leave the room\",to=roomid)\r\n\r\n del user_room_dict[request.sid]\r\n\r\n\r\n\r\n@socketio.on('toSomeRoom')\r\ndef toSomeRoom(Msg):\r\n roomid=user_room_dict[request.sid]\r\n emit('Roommessage',sid_user_dict[request.sid]+\":\"+Msg,to=roomid)\r\n\r\n@socketio.on('changeName')\r\ndef changeName(name):\r\n sid_user_dict[request.sid]=name\r\n\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('broadcast_page.html')\r\n\r\nif __name__==\"__main__\":\r\n socketio.run(app,debug=1)","repo_name":"oFeasl/Flask_SocketIO","sub_path":"test_FlaskSocketIO/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"16064058618","text":"\nimport numpy as np\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport time\n\nclass edge_rec:\n def __init__(self, image): \n self.image = image\n self.PILimg = Image.open(self.image)\n\n self.width = self.PILimg.size[0]\n self.height = self.PILimg.size[1]\n\n self.x_kernel = [[1, 2, 1],\n [0, 0, 0],\n [-1, -2, -1]]\n \n self.y_kernel = [[1, 0, -1],\n [2, 0, -2],\n [1, 0, -1]]\n\n self.kernel_size = len(self.x_kernel[0])\n\n # convert image to gray scale image\n def gray_scale(self):\n lst = []\n for x in range(0, self.height):\n for y in range(0, self.width):\n pixel = (y, x)\n rgb = self.PILimg.getpixel(pixel)\n\n gray_scale = rgb[0] / 255\n lst.append(gray_scale)\n\n gray_im = []\n for i in range(0, len(lst), self.width):\n gray_im.append(lst[i:i + self.width])\n\n return gray_im\n\n # apply convolution on image with a sobel filter\n def convolution(self, kernel):\n matrice = self.gray_scale()\n\n lst = []\n\n for k_j in range(len(matrice) - self.kernel_size + 1):\n for k_i in range(len(matrice[1]) - self.kernel_size + 1):\n scalar = []\n for i in range(self.kernel_size):\n for j in range(self.kernel_size):\n scalar.append(matrice[i + k_j][j + k_i] * kernel[i][j])\n \n lst.append(sum(scalar))\n\n return lst\n\n def main(self):\n # plot original image\n plt.matshow(self.gray_scale(), cmap=\"gray\")\n plt.title(\"original\")\n plt.show()\n \n start = time.time()\n\n # create edges in x-axis\n x_edges = self.convolution(self.x_kernel)\n # create edges in y-axis\n y_edges = self.convolution(self.y_kernel)\n \n # combine x- and y-edges\n for i in range(len(x_edges)):\n x_edges[i] = np.sqrt(pow(x_edges[i], 2) + pow(y_edges[i], 2))\n x_edges[i] = x_edges[i]\n\n edges = x_edges\n \n # reshape to original height - 2 and original width - 2 (the amount of kernels that fit into height and width)\n convolutioned = np.array(edges).reshape(self.height - 2, self.width - 2)\n\n duration = time.time() - start\n print(\"took: \", duration, \" sec\")\n\n plt.matshow(convolutioned)\n plt.title(\"edges\")\n plt.show()\n\n\nif __name__ == \"__main__\":\n edge_rec(\"images/house.png\").main()\n\n","repo_name":"theopfr/edge-detection-from-scratch","sub_path":"python-version/edge_recognition.py","file_name":"edge_recognition.py","file_ext":"py","file_size_in_byte":2642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"11617289647","text":"# hex_map.py\n#\n#\n#\n#\n\nimport tkinter as tk\nimport math\nfrom hex import Hex\n\nCOS_30 = math.cos(math.radians(30))\nSIN_30 = math.sin(math.radians(30))\n\nclass HexMap(tk.Frame):\n\n def __init__(self, master, parent, size, hex_menu_callback):\n super().__init__(master)\n self._master = master\n self._parent = parent\n self.hex_grid = tk.Canvas(self, height=780, width=1275, bg=\"black\")\n self.hex_grid.grid(column=0, row=1)\n self._hex_menu_callback = hex_menu_callback\n\n self._hex_ids = []\n self._hexes = []\n\n self._create_grid(size)\n self._label_grid()\n\n\n def _create_grid(self, size):\n start_x = 50\n curr_x = start_x\n curr_y = 50\n margin = 5\n x_offset = start_x + (COS_30 * start_x) + 3\n for row in range(9):\n print(\"Generating row \" + str(row))\n if row % 2 == 0:\n for hex in range(13):\n next_hex = self._create_hex(curr_x, curr_y, size)\n curr_x = next_hex[0] + margin\n else:\n for hex in range(12):\n next_hex = self._create_hex(curr_x, curr_y, size)\n curr_x = next_hex[0] + margin\n if row % 2 == 0:\n curr_x = x_offset\n else:\n curr_x = start_x\n curr_y = curr_y + (COS_30 * start_x * 2) - 7\n\n\n def _create_hex(self, start_x, start_y, size):\n hex_points = self._calculate_hex_points(start_x, start_y, size)\n hex_id = self.hex_grid.create_polygon(hex_points[0][0], hex_points[0][1], hex_points[1][0], hex_points[1][1], hex_points[2][0], hex_points[2][1], hex_points[3][0], hex_points[3][1], hex_points[4][0], hex_points[4][1], hex_points[5][0], hex_points[5][1], outline=\"white\", activedash=True)\n self._hex_ids.append(hex_id)\n self._hexes.append(Hex(self.hex_grid, self._master, self, hex_id, self._hex_menu_callback))\n return hex_points[2]\n\n\n def _label_grid(self):\n print(\"Laebeling grid...\")\n for hex in self._hex_ids:\n label = str(hex)\n # print(\"Adding label \" + label)\n coords = self.hex_grid.coords(hex)\n self.hex_grid.create_text((coords[0] + coords[4]) / 2, coords[1] - 10, fill=\"white\", text=label, justify=\"center\")\n\n\n def _calculate_hex_points(self, start_x, start_y, size):\n # print(\"Creating hex: \" + str(start_x), str(start_y), str(size))\n p1 = (start_x, start_y)\n p2 = (start_x + (COS_30 * size), (start_y + (SIN_30 * size * -1)))\n p3 = ((p2[0] + (COS_30 * size)), start_y)\n p4 = (p3[0], start_y + size)\n p5 = (p2[0], p4[1] + (SIN_30 * size))\n p6 = (start_x, start_y + size)\n return (p1, p2, p3, p4, p5, p6)\n\n\n def initialize_start_positions(self, player_data):\n start_positions = [1, 7, 13, 101, 107, 113]\n current_player = 1\n for hex in start_positions:\n self._parent._players[current_player-1].set_hq(hex)\n current_player_str = \"p\" + str(current_player)\n current_player_data = player_data[current_player_str]\n self._hexes[hex - 1].change_owner(current_player_data)\n current_player += 1\n","repo_name":"HarrisonMH/smashmap","sub_path":"hex_map_old.py","file_name":"hex_map_old.py","file_ext":"py","file_size_in_byte":3250,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"16"}
+{"seq_id":"14902107831","text":"# Definir una función superposicion() que tome dos listas y\r\n# devuelva True si tienen al menos 1 miembro en común o devuelva False de lo contrario.\r\n# Escribir la función usando el bucle for anidado.\r\n\r\ndef superposicion(array1, array2):\r\n\r\n iguales = True\r\n contador = 0\r\n \r\n for i in array1:\r\n for j in array2:\r\n if i == j:\r\n contador += 1\r\n\r\n if contador > 0:\r\n print(iguales)\r\n else:\r\n iguales = False\r\n print(iguales)\r\n\r\n\r\nlista1 = [1,2]\r\nlista2 = [2,3]\r\n\r\nsuperposicion(lista1, lista2)\r\n","repo_name":"alan199912/Pyhton","sub_path":"Ejercicios 1/07-superposicion.py","file_name":"07-superposicion.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"38620359684","text":"from __future__ import print_function\nimport re\nimport numpy\n\nshifts = []\nguards = dict()\n\nwith open('input.txt', 'rb') as f:\n for line in f:\n shifts.append(line)\n\nshifts.sort()\nprint(shifts)\n\nguard_id = 0\ntimecard = numpy.zeros(60)\ntime_asleep = 0\n\nfor shift in shifts:\n if 'Guard' in shift:\n digits = re.search(r'#\\d+', shift)\n guard_id = int(digits.group()[1:])\n if guard_id in guards:\n guard = guards[guard_id]\n else:\n guards[guard_id] = {\n 'timecard': numpy.zeros(60),\n }\n\n elif 'falls asleep' in shift:\n minutes = re.search(r':\\d+', shift)\n time_asleep = int(minutes.group()[1:])\n elif 'wakes up' in shift:\n minutes = re.search(r':\\d+', shift)\n time_awake = int(minutes.group()[1:])\n for i in range(time_asleep, time_awake):\n guards[guard_id]['timecard'][i] += 1\n\n# part a\ndef most_minutes_asleep():\n max_guard_id = 0\n max_minutes = 0\n max_time = 0\n for i in guards:\n minutes = sum(guards[i]['timecard'])\n if max_minutes < minutes:\n max_guard_id = i\n max_minutes = minutes\n max_time = numpy.argmax(guards[i]['timecard'])\n return max_guard_id * max_time\n\n# part b\ndef minute_most_often_asleep():\n max_guard_id = 0\n max_minutes = 0\n max_time = 0\n for i in guards:\n minutes = max(guards[i]['timecard'])\n if max_minutes < minutes:\n max_guard_id = i\n max_minutes = minutes\n max_time = numpy.argmax(guards[i]['timecard'])\n return max_guard_id * max_time\n\nprint(most_minutes_asleep())\nprint(minute_most_often_asleep())","repo_name":"drewtaylors/Advent_of_Code","sub_path":"day_4/star_4.py","file_name":"star_4.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"38994495741","text":"#Desenvolva um programa que receba 8 números inteiros positivos. Apresente a soma e média aritmética deles.\n\nsoma = 0\nmedia = 0\n\nfor cont in range (1,4):\n num = float(input(\"Digite um número inteiro\"))\n soma = soma + num\n media = soma / 3\n\nprint(soma)\nprint(media)\n\n\n\n","repo_name":"diogomoreirax/computational-thinking-using-python-1-semestre","sub_path":"atividade 7 FOR ESTRUTURAS DE REPETIÇÃO/8soma_arit.py","file_name":"8soma_arit.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"2189197423","text":"import dotenv\nimport hydra\nimport glob\nfrom pathlib import Path\nimport torch\nimport os\nfrom omegaconf import DictConfig\n\n# load environment variables from `.env` file if it exists\n# recursively searches for `.env` in all folders starting from work dir\ndotenv.load_dotenv(override=True)\nfrom src import utils\n\nlog = utils.get_logger(__name__)\n\n@hydra.main(config_path=\"configs/\", config_name=\"test.yaml\")\ndef main(config: DictConfig):\n\n # Imports can be nested inside @hydra.main to optimize tab completion\n # https://github.com/facebookresearch/hydra/issues/934\n from src import utils\n from src.utils import metrics\n from src.testing_pipeline import test\n\n # Applies optional utilities\n utils.extras(config)\n all_preds = []\n os.chdir(\"/Weather-Prediction-NN\")\n # Evaluate model\n chkpts = []\n path = config.ckpt_folder\n for ck in Path(path).rglob(\"*.ckpt\"):\n if not \"last\" in str(ck):\n chkpts.append(ck)\n for c in chkpts:\n config.ckpt_path = c\n preds, all_targets = test(config)\n all_preds.append(preds)\n\n all_preds = torch.stack((all_preds))\n all_preds = torch.mean(all_preds, dim=0)\n rocauc_table, ap_table, f1_table = metrics.metrics_celled(all_targets, all_preds)\n res_rocauc = torch.median(rocauc_table)\n res_ap = torch.median(ap_table)\n res_f1 = torch.median(f1_table)\n log.info(f\"test_ensemble_median_rocauc: {res_rocauc}\")\n log.info(f\"test_ensemble_median_ap: {res_ap}\")\n log.info(f\"test_ensemble_median_f1: {res_f1}\")\n with open(\"ens.txt\", \"a\") as f:\n f.write(config.ckpt_folder + \"\\n\")\n f.write(\"median_rocauc: \" + str(res_rocauc) + \"\\n\")\n f.write(\"\\n\")\n f.write(\"median_ap: \" + str(res_ap) + \"\\n\")\n f.write(\"\\n\")\n f.write(\"median_f1: \" + str(res_f1) + \"\\n\")\n f.write(\"\\n\")\n return\n\n\nif __name__ == \"__main__\":\n \n \n main()\n","repo_name":"VGrabar/Weather-Prediction-NN","sub_path":"test_ensemble.py","file_name":"test_ensemble.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"16"}
+{"seq_id":"13990146622","text":"from django.http import JsonResponse\nfrom django.views import View\nfrom .models import BookInfo, HeroInfo\nfrom .serializers import BookSerializer, HeroSerializer\nfrom .serializers import BookModelSerializer\nimport json\n\n\nclass BooksView(View):\n def post(self, request):\n param_dict = json.loads(request.body.decode())\n\n # 1.将接收的数据赋给data参数\n serializer = BookSerializer(data=param_dict)\n # 2.验证\n if serializer.is_valid():\n # 验证成功===》创建对象\n book = serializer.save()\n\n serializer = BookSerializer(book)\n book_dict = serializer.data\n return JsonResponse(book_dict, status=201)\n else:\n # 验证失败\n return JsonResponse(serializer.errors)\n\n\nclass BookView(View):\n def get(self, request, pk):\n book = BookInfo.objects.get(pk=pk)\n\n # serializer = BookSerializer(book)\n # book_dict = serializer.data\n\n serializer = BookModelSerializer(book)\n book_dict = serializer.data\n\n return JsonResponse(book_dict)\n\n def put(self, request, pk):\n param_dict = json.loads(request.body.decode())\n\n book = BookInfo.objects.get(pk=pk)\n\n serializer = BookSerializer(book, data=param_dict)\n if serializer.is_valid(): ###is_valid() 注意有括号\n book = serializer.save()\n\n serializer = BookSerializer(book)\n book_dict = serializer.data\n return JsonResponse(book_dict, status=201)\n else:\n return JsonResponse(serializer.errors)\n\n\nclass HeroView(View):\n def get(self, request, pk):\n hero = HeroInfo.objects.get(pk=pk)\n\n serializer = HeroSerializer(hero)\n hero_dict = serializer.data\n\n return JsonResponse(hero_dict)\n","repo_name":"yongfang117/pro_useful_code","sub_path":"pro_drf/demo2/booktest/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"12494283540","text":"from data_structure.linked_list import LinkedList\nfrom utils.emojis import chicken_emoji\nfrom food.food import Food\n\n\nchicken_menu_emoji = \"\"\n\nchicken_menu = LinkedList()\n\nchicken_parmesan = Food(\"Chicken Parmesan\", \"Breaded chicken with tomato sauce.\", chicken_emoji)\ngrilled_chicken_salad = Food(\"Grilled Chicken Salad\", \"Greens with grilled chicken slices.\", chicken_emoji)\nchicken_alfredo_pasta = Food(\"Chicken Alfredo Pasta\", \"Pasta with chicken and creamy sauce.\", chicken_emoji)\nbbq_chicken_sandwhich = Food(\"BBQ Chicken Sandwich\", \"Sandwich with BBQ sauce and chicken.\", chicken_emoji)\ncrispy_chicken_strips = Food(\"Crispy Chicken Strips\", \"Fried chicken strips with dipping sauce.\", chicken_emoji)\nchicken_fajitas = Food(\"Chicken Fajitas\", \"Chicken and vegetables in a tortilla.\", chicken_emoji)\nroasted_chicken = Food(\"Roasted Chicken\", \"Whole roasted chicken with vegetables.\", chicken_emoji)\nchicken_noodle_soup = Food(\"Chicken Noodle Soup\", \"Chicken and noodles in broth.\", chicken_emoji)\nlemon_garlic_chicken = Food(\"Lemon Garlic Chicken\", \"Chicken with lemon and garlic flavors.\", chicken_emoji)\nhoney_mustard_chicken = Food(\"Honey Mustard Chicken\", \"Chicken with honey mustard sauce.\", chicken_emoji)\n\nchicken_menu.insert_beginning(chicken_parmesan)\nchicken_menu.insert_end(grilled_chicken_salad)\nchicken_menu.insert_end(chicken_alfredo_pasta)\nchicken_menu.insert_end(bbq_chicken_sandwhich)\nchicken_menu.insert_end(crispy_chicken_strips)\nchicken_menu.insert_end(chicken_fajitas)\nchicken_menu.insert_end(roasted_chicken)\nchicken_menu.insert_end(chicken_noodle_soup)\nchicken_menu.insert_end(lemon_garlic_chicken)\nchicken_menu.insert_end(honey_mustard_chicken)\n\nchicken_menu_emoji = chicken_menu.show_food_emoji()\n","repo_name":"JohnMachado11/Linked-List-Restaurant","sub_path":"src/food/chicken_menu.py","file_name":"chicken_menu.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"24381595194","text":"import json\nimport os\nimport subprocess\nimport uuid\n\nimport pytest\n\nimport quetz\nfrom quetz.db_models import Package, Profile, User\nfrom quetz.rest_models import Channel\nfrom quetz.tasks import indexing\n\n\n@pytest.fixture\ndef user(db):\n user = User(id=uuid.uuid4().bytes, username=\"bartosz\")\n profile = Profile(name=\"Bartosz\", avatar_url=\"http:///avatar\", user=user)\n db.add(user)\n db.add(profile)\n db.commit()\n yield user\n\n\n@pytest.fixture\ndef channel_name():\n return \"my-channel\"\n\n\n@pytest.fixture\ndef package_name():\n return \"mytestpackage\"\n\n\n@pytest.fixture\ndef package_format():\n return 'tarbz2'\n\n\n@pytest.fixture\ndef package_file_name(package_name, package_format):\n if package_format == 'tarbz2':\n return f\"{package_name}-0.1-0.tar.bz2\"\n elif package_format == \"conda\":\n return f\"{package_name}-0.1-0.conda\"\n\n\n@pytest.fixture\ndef channel(dao: \"quetz.dao.Dao\", channel_name, user):\n channel_data = Channel(name=channel_name, private=False)\n channel = dao.create_channel(channel_data, user.id, \"owner\")\n return channel\n\n\n@pytest.fixture\ndef package_subdir():\n return \"noarch\"\n\n\n@pytest.fixture\ndef package_version(\n dao: \"quetz.dao.Dao\",\n user,\n channel,\n package_name,\n db,\n package_file_name,\n package_format,\n package_subdir,\n):\n channel_data = json.dumps({\"subdirs\": [package_subdir]})\n package_data = Package(name=package_name)\n\n package = dao.create_package(channel.name, package_data, user.id, \"owner\")\n package.channeldata = channel_data\n db.commit()\n\n package_info = (\n '{\"run_exports\": {\"weak\": [\"otherpackage > 0.1\"]}, \"size\": 100, \"depends\": []}'\n )\n version = dao.create_version(\n channel.name,\n package_name,\n package_format,\n package_subdir,\n \"0.1\",\n \"0\",\n \"0\",\n package_file_name,\n package_info,\n user.id,\n size=0,\n )\n\n yield version\n\n\n@pytest.fixture\ndef archive_format():\n return \"tarbz2\"\n\n\n@pytest.fixture\ndef pkgstore(config):\n pkgstore = config.get_package_store()\n return pkgstore\n\n\ndef test_repodata_zchunk(\n pkgstore,\n package_version,\n channel_name,\n package_file_name,\n dao,\n db,\n):\n indexing.update_indexes(dao, pkgstore, channel_name)\n\n index_path = os.path.join(\n pkgstore.channels_dir,\n channel_name,\n \"noarch\",\n \"index.html\",\n )\n\n assert os.path.isfile(index_path)\n with open(index_path, 'r') as fid:\n content = fid.read()\n\n assert \"repodata.json\" in content\n assert \"repodata.json.bz2\" in content\n assert \"repodata.json.zck\" in content\n\n for fname in (\"repodata.json\", \"repodata.json.zck\"):\n repodata_path = os.path.join(\n pkgstore.channels_dir, channel_name, \"noarch\", fname\n )\n\n assert os.path.isfile(repodata_path)\n\n if fname.endswith('.zck'):\n subprocess.check_call(['unzck', repodata_path])\n with open('repodata.json') as f:\n repodata_unzck = f.read()\n\n assert repodata == repodata_unzck # NOQA # type: ignore\n else:\n with open(repodata_path) as f:\n repodata = f.read() # NOQA\n","repo_name":"mamba-org/quetz","sub_path":"plugins/quetz_repodata_zchunk/tests/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":3226,"program_lang":"python","lang":"en","doc_type":"code","stars":242,"dataset":"github-code","pt":"16"}
+{"seq_id":"70082936968","text":"#!/usr/bin/env python\nimport numpy as np\nimport cv2\nimport rospy\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\n\nbridge = CvBridge()\nhog = cv2.HOGDescriptor()\n\ndef inside(r, q):\n rx, ry, rw, rh = r\n qx, qy, qw, qh = q\n return rx > qx and ry > qy and rx + rw < qx + qw and ry + rh < qy + qh\n\n\ndef draw_detections(img, rects, thickness = 1):\n for x, y, w, h in rects:\n # the HOG detector returns slightly larger rectangles than the real objects.\n # so we slightly shrink the rectangles to get a nicer output.\n pad_w, pad_h = int(0.15*w), int(0.05*h)\n cv2.rectangle(img, (x+pad_w, y+pad_h), (x+w-pad_w, y+h-pad_h), (0, 255, 0), thickness)\n\ndef callback(data):\n frame = bridge.imgmsg_to_cv2(data, \"bgr8\")\n found,w=hog.detectMultiScale(frame, winStride=(8,8), padding=(32,32), scale=1.05)\n draw_detections(frame,found)\n cv2.imshow('feed',frame)\n cv2.waitKey(3)\n #ch = 0xFF & cv2.waitKey(1)\n #if ch == 27:\n #break\n #cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n hog.setSVMDetector( cv2.HOGDescriptor_getDefaultPeopleDetector() )\n #cap=cv2.VideoCapture('video3.mp4')\n try:\n rospy.init_node('peopledetector_node', anonymous=False)\n rospy.Subscriber('/image_raw', Image, callback)\n rospy.spin()\n except rospy.ROSInterruptException:\n pass\n","repo_name":"jginesclavero/proc_imagen_mj","sub_path":"scripts/peopledetect.py","file_name":"peopledetect.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"34320903189","text":"def add_thousands_separator(fn):\n def wrapper(a, b):\n result = fn(a, b)\n revers_result = str(result)[::-1]\n count = 0\n new_text_num = \"\"\n for i in revers_result:\n if count == 3:\n new_text_num += \"'\" + i\n count = 1\n else:\n new_text_num += i\n count += 1\n return new_text_num[::-1]\n\n return wrapper\n\n\n@add_thousands_separator\ndef multiply(a, b):\n return a * b\n\n\nprint(multiply(9336, 1223))\n","repo_name":"AlitaVitalii/lesson_python","sub_path":"python_basic_28.09.2022/homework/dz30_v1.py","file_name":"dz30_v1.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"4141846806","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n# File : argument.py\n# Author : Jiayuan Mao\n# Email : maojiayuan@gmail.com\n# Date : 03/14/2017\n#\n# This file is part of Jacinle.\n# Distributed under terms of the MIT license.\n\nimport collections\nfrom typing import Any, Optional, Union, Sequence, Tuple, Callable\n\n__all__ = [\n 'get_2dshape', 'get_3dshape', 'get_4dshape',\n 'astuple', 'asshape',\n 'canonize_args_list',\n 'UniqueValueGetter'\n]\n\n\ndef get_2dshape(x: Optional[Union[int, Sequence[int]]], default: Tuple[int, int] = None, type: type = int) -> Tuple[int, int]:\n \"\"\"Convert a value or a tuple to a tuple of length 2.\n\n Args:\n x: a value of type `type`, or a tuple of length 2. If the input is a single value, it will be duplicated to a tuple of length 2.\n default: default value.\n type: expected type of the element.\n\n Returns:\n a tuple of length 2.\n \"\"\"\n if x is None:\n return default\n if isinstance(x, collections.Sequence):\n x = tuple(x)\n if len(x) == 1:\n return x[0], x[0]\n else:\n assert len(x) == 2, '2dshape must be of length 1 or 2'\n return x\n else:\n x = type(x)\n return x, x\n\n\ndef get_3dshape(x: Optional[Union[int, Sequence[int]]], default: Tuple[int, int, int] = None, type: type = int) -> Tuple[int, int, int]:\n \"\"\"Convert a value or a tuple to a tuple of length 3.\n\n Args:\n x: a value of type `type`, or a tuple of length 3. If the input is a single value, it will be duplicated to a tuple of length 3.\n default: default value.\n type: expected type of the element.\n\n Returns:\n a tuple of length 3.\n \"\"\"\n\n if x is None:\n return default\n if isinstance(x, collections.Sequence):\n x = tuple(x)\n if len(x) == 1:\n return x[0], x[0], x[0]\n else:\n assert len(x) == 3, '3dshape must be of length 1 or 3'\n return x\n else:\n x = type(x)\n return x, x, x\n\n\ndef get_4dshape(x: Optional[Union[int, Sequence[int]]], default: Tuple[int, int, int, int] = None, type: type = int) -> Tuple[int, int, int, int]:\n \"\"\"Convert a value or a tuple to a tuple of length 4.\n\n Args:\n x: a value of type `type`, or a tuple of length 4. If there is only one value, it will return (1, x, x, 1).\n If there are two values, it will return (1, x[0], x[1], 1).\n default: default value.\n type: expected type of the element.\n\n Returns:\n a tuple of length 4.\n \"\"\"\n if x is None:\n return default\n if isinstance(x, collections.Sequence):\n x = tuple(x)\n if len(x) == 1:\n return 1, x[0], x[0], 1\n elif len(x) == 2:\n return 1, x[0], x[1], 1\n else:\n assert len(x) == 4, '4dshape must be of length 1, 2, or 4'\n return x\n else:\n x = type(x)\n return 1, x, x, 1\n\n\ndef astuple(arr_like: Any) -> Tuple:\n \"\"\"Convert a sequence or a single value to a tuple. This method differ from the system method `tuple` in that\n a single value (incl. int, string, bytes) will be converted to a tuple of length 1.\n\n Args:\n arr_like: a sequence or a single value.\n\n Returns:\n a tuple.\n \"\"\"\n if type(arr_like) is tuple:\n return arr_like\n elif isinstance(arr_like, collections.Sequence) and not isinstance(arr_like, (str, bytes)):\n return tuple(arr_like)\n else:\n return tuple((arr_like,))\n\n\ndef asshape(arr_like: Optional[Union[int, Sequence[int]]]) -> Optional[Tuple[int, ...]]:\n \"\"\"Convert a sequence or a single value to a tuple of integers. It will return None if the input is None.\n\n Args:\n arr_like: a sequence or a single value.\n\n Returns:\n a tuple of integers.\n \"\"\"\n if type(arr_like) is tuple:\n return arr_like\n elif type(arr_like) is int:\n if arr_like == 0:\n return tuple()\n else:\n return tuple((arr_like,))\n elif arr_like is None:\n return None,\n else:\n return tuple(arr_like)\n\n\ndef canonize_args_list(args: Tuple[Any], *, allow_empty: bool = False, cvt: Optional[Callable[[Any], Any]] = None) -> Tuple[Any]:\n \"\"\"Convert the argument list to a tuple of values. This is useful to make unified interface for shape-related operations.\n\n Example:\n .. code-block:: python\n\n def foo(*args):\n args = canonize_args_list(args, allow_empty=True)\n print(args)\n\n foo(1, 2, 3) # (1, 2, 3)\n foo((1, 2, 3)) # (1, 2, 3)\n foo(1) # (1,)\n foo() # ()\n\n Args:\n args: the argument list.\n allow_empty: whether to allow empty argument list.\n cvt: a function to be applied to each element.\n \"\"\"\n\n if not allow_empty and not args:\n raise TypeError('at least one argument must be provided')\n\n if len(args) == 1 and isinstance(args[0], (list, tuple)):\n args = args[0]\n if cvt is not None:\n args = tuple(map(cvt, args))\n return args\n\n\nclass UniqueValueGetter(object):\n \"\"\"A helper class to ensure that a value is unique.\n\n Example:\n .. code-block:: python\n\n uvg = UniqueValueGetter()\n uvg.set(1)\n uvg.set(2) # will raise ValueError\n uvg.set(1)\n\n print(uvg.get()) # 1\n \"\"\"\n\n def __init__(self, msg: str = 'Unique value checking failed', default: Any = None):\n \"\"\"Initialize the UniqueValueGetter.\n\n Args:\n msg: the error message.\n default: the default value.\n \"\"\"\n self._msg = msg\n self._val = None\n self._default = default\n\n def set(self, v):\n assert self._val is None or self._val == v, self._msg + ': expect={} got={}'.format(self._val, v)\n self._val = v\n\n def get(self):\n return self._val or self._default\n\n","repo_name":"vacancy/Jacinle","sub_path":"jacinle/utils/argument.py","file_name":"argument.py","file_ext":"py","file_size_in_byte":5938,"program_lang":"python","lang":"en","doc_type":"code","stars":122,"dataset":"github-code","pt":"16"}
+{"seq_id":"27340261546","text":"\nimport numpy as np\nimport tensorflow as tf\nimport horovod.tensorflow as hvd\n\nhvd.init()\nsize = hvd.size()\nrank = hvd.rank()\n\ntensor = tf.Variable(np.array([1.0,1.0,1.0], dtype=np.float32) * rank, name = 'tensor')\nassign_op = tf.assign(tensor, np.array([99.0, 99.0, 99.0]))\n\n# An op which broadcasts all tensors on root rank to the same tensors\n# on all other Horovod processes.\nbroadcast_op = hvd.broadcast_global_variables(0)\n\n# The operation will not start until all processes are ready \n# to receive the tensor.\n\nwith tf.Session() as sess:\n\n sess.run(tf.global_variables_initializer())\n print(\"rank %d before broadcast: %s\" % (rank, sess.run(tensor)))\n\n if rank == 0:\n sess.run(assign_op)\n\n sess.run(broadcast_op)\n print(\"rank %d after broadcast: %s\" % (rank, sess.run(tensor)))\n # => [99. 99. 99.]\n","repo_name":"asprenger/distributed-training-patterns","sub_path":"horovod/hvd_broadcast.py","file_name":"hvd_broadcast.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"16"}
+{"seq_id":"36541616551","text":"import logging\nimport threading\nimport time\nimport keyboard\n\nimport activity_log\nimport notification\nimport sound\nimport text_generator\n\nlogging.basicConfig(level=logging.DEBUG, format='%(threadName)s: %(message)s')\n\nstop = False # スレッドの終了用\ninterval = 2 # 記録の間隔\nworking_state_list = [\"start\",\n \"terminate\",\n \"cheer\",\n \"praise\",\n \"idle\"]\nworking_state = \"idle\"\n\n\ndef log_activity_to_file(previous_program_list, current_program_list,\n skip_duplicate=True):\n global working_state\n\n # プログラムの起動と終了を検知\n current_program_list = activity_log.get_all_windows()\n started = activity_log.get_title_of_started_program(\n previous_program_list=previous_program_list,\n current_program_list=current_program_list)\n terminated = activity_log.get_title_of_terminated_program(\n previous_program_list=previous_program_list,\n current_program_list=current_program_list)\n\n if terminated:\n working_state = \"terminate\"\n title = terminated\n state = \"T\"\n activity_log.print_to_file(title, state)\n event_notification.set()\n event_voice.set()\n \n if started:\n working_state = \"start\"\n title = started\n state = \"S\"\n activity_log.print_to_file(title, state)\n activity_log.set_start_word_num(title.split()[0])\n event_voice.set()\n event_notification.set()\n\n working_time = activity_log.get_working_time_on_current_window(interval=2)\n logging.debug(\"working_time: \" + str(working_time))\n thresholds = [3600 for _ in range(8)] # 1~8時間\n for threshold in thresholds:\n if threshold <= working_time < threshold + interval:\n working_state = \"cheer\"\n event_voice.set()\n event_notification.set()\n\n \n # アクティブウィンドウの記録\n title = activity_log.get_title_of_active_window(skip_duplicate)\n state = \"A\"\n if title:\n activity_log.print_to_file(title, state)\n\n title = activity_log.get_active_window_title() \n if len(title.split()) < 2:\n return \n elif \".docx\" in title.split()[0] and title.split()[-1] == \"Word\":\n start_word_num = activity_log.get_start_word_num()\n finish_word_num = activity_log.get_finish_word_num(title.split()[0])\n need_to_notify = notification.need_to_notify(start_word_num,finish_word_num)\n if need_to_notify == True:\n working_state = \"praise\"\n event_notification.set()\n event_voice.set()\n \n\ndef worker_log(event_log):\n \"\"\"ログ記録のためのworker\n \"\"\"\n previous_program_list = activity_log.get_all_windows()\n while not stop:\n # event.set が実行されるまで待機\n event_log.wait()\n event_log.clear()\n logging.debug('logging start')\n\n current_program_list = activity_log.get_all_windows()\n log_activity_to_file(previous_program_list,\n current_program_list)\n previous_program_list = current_program_list\n\n logging.debug('logging end')\n\n\ndef worker_voice(event_voice):\n \"\"\"音声再生のためのworker\n \"\"\"\n while not stop:\n # event.set が実行されるまで待機\n event_voice.wait()\n event_voice.clear()\n logging.debug('voice start')\n text = text_generator.generate_text(working_state)\n # time.sleep(3)\n sound.play_sound(text)\n logging.debug('voice end')\n\n\ndef worker_notification(event_notification):\n \"\"\"通知のためのworker\n \"\"\"\n global working_state\n while not stop:\n # event.set が実行されるまで待機\n event_notification.wait()\n event_notification.clear()\n logging.debug('notify start')\n text = text_generator.generate_text(working_state)\n img_path = notification.generate_path(working_state)\n notification.notify(text, img_path)\n logging.debug('notify end')\n if working_state == \"praise\": \n title = activity_log.get_active_window_title() \n activity_log.set_start_word_num(title.split()[0])\n working_state = \"idle\"\n\ndef worker_main(event_log, event_voice, event_notification):\n \"\"\"処理の中心となるworker\n \"\"\"\n global stop\n global working_state\n\n logging.debug('start')\n print(stop)\n while not stop:\n if keyboard.is_pressed(\"q\"):\n logging.debug(\"q is pressed, program end\")\n exit()\n stop = True\n\n time.sleep(interval)\n event_log.set()\n logging.debug(\"event_log.set()\")\n logging.debug(\"working_state: \" + working_state)\n\n need_to_play_voice = sound.need_to_sound()\n if need_to_play_voice:\n event_voice.set()\n logging.debug(\"event_voice.set()\")\n\n need_to_notify = notification.need_to_notify(-1,-1)\n if need_to_notify:\n event_notification.set()\n logging.debug(\"event_notification.set()\")\n\n\nif __name__ == '__main__':\n event_log = threading.Event()\n event_voice = threading.Event()\n event_notification = threading.Event()\n\n thread_main = threading.Thread(\n name=\"thread_main\",\n target=worker_main,\n args=(event_log, event_voice, event_notification, ))\n\n # メインスレッド以外はすべてデーモン化\n thread_log = threading.Thread(\n name=\"thread_log\",\n target=worker_log,\n args=(event_log,))\n thread_log.setDaemon(True)\n\n thread_voice = threading.Thread(\n name=\"thread_voice\",\n target=worker_voice,\n args=(event_voice,))\n thread_voice.setDaemon(True)\n\n thread_notification = threading.Thread(\n name=\"thread_notification\",\n target=worker_notification,\n args=(event_notification,))\n thread_notification.setDaemon(True)\n\n thread_main.start()\n thread_voice.start()\n thread_notification.start()\n thread_log.start()\n","repo_name":"jphacks/D_2016","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6090,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"16"}
+{"seq_id":"38294186334","text":"import numbers\nimport numpy as np\n\n# import math\n\ndef pcc(x, y):\n\t\"\"\"\nComputes an estimate of the PCC between random variables X and Y\n\nFirst form:\n Args:\n x (list of N floats, N>1): N-points sample of random variable X\n y (list of N floats, N>1): N-points sample of random variable Y\n \n Returns:\n float: PCC estimate of random variables X and Y\n\n Example:\n import tr_pcc\n ...\n x = [0]*N # X sample\n y = [0]*N # Y sample\n p = 0 # PCC estimate\n for n in range (N): # For N draws\n x[n] = draw_X # Draw random variable X\n y[n] = draw_Y # Draw random variable Y\n p = tr_pcc.pcc (x,y) # Compute PCC(X,Y) estimate\n print (\"PCC(X,Y) = %lf\" % p) # Print PCC estimate\n ...\n\nSecond form:\n Args:\n x (list of N floats, N>1): N-points sample of random variable X\n y (list of K lists of N floats, N>1): K different N-points\n samples of random variables Y0,Y1,...,YK-1\n \n Returns:\n list of K floats: PCC estimates of random variables X and Y0,\n X and Y1,..., X and YK-1\n\n Example:\n import tr_pcc\n ...\n x = [0]*N # X sample\n y = [[0]*N for k in range(K)] # Yk samples, 0<=k1): N-points sample of vector random variable X\n y (list of N floats, N>1): N-points sample of random variable Y\n \n Returns:\n list of L floats: PCC estimate of random variables X and Y\n\n Example:\n import tr_pcc\n ...\n x = [[0]*L for n in range(N)] # X sample\n y = [0]*N # Y sample\n p = [0]*L # PCC estimate\n for n in range (N): # For N draws\n for l in range (L): # For L components\n x[n][l] = draw_X (l) # Draw component of random variable X\n y[n] = draw_Y # Draw random variable Y\n p = tr_pcc.pcc (x,y) # Compute PCC(X,Y) estimate\n for l in range (L): # For L components\n\t\t\tprint (\"PCC(X,Y)[%d] = %lf\" % (l,p[l])) # Print component of PCC estimate\n ...\n\nFourth form:\n Args:\n x (list of N lists of L floats, N>1): N-points sample of vector random variable X\n y (list of K lists of N floats, N>1): K different N-points\n samples of random variables Y0,Y1,...,YK-1\n \n Returns:\n list of K lists of L floats: PCC estimates of random variables X and Y0,\n X and Y1,..., X and YK-1\n\n Example:\n import tr_pcc\n ...\n x = [[0]*L for n in range(N)] # X sample\n y = [[0]*N for k in range(K)] # Yk samples, 0<=k[\\-\\w]+)/newsfeeddescription/',newsfeeddescription,name='newsfeeddescription'),\n url(r'^newsapi/',NewsapiViewSet.as_view({'get':'list'}),name='newsapi'),\n url(r'^(?P[\\-\\w]+)/newsfeedsdetail/',newsfeedsdetail,name='newsfeedsdetail'),\n ]","repo_name":"feederfox/FeederFox-Media","sub_path":"NewsFeeds/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"30691662601","text":"import sys\ninput = sys.stdin.readline\nfrom collections import deque\n\nn = int(input())\nlst = []\ncheck = [[0]*n for i in range(n)]\ncheckRG =[[0]*n for i in range(n)]\nanswer = 0\nanswerRG = 0\nfor i in range(n) :\n arr = []\n s = input()\n for j in range(n) :\n if s[j] == 'B' :\n arr.append(0)\n elif s[j] == 'R' :\n arr.append(1)\n else :\n arr.append(2)\n lst.append(arr)\n\ndx = [0, 0, 1, -1]\ndy = [1, -1, 0, 0]\nqueue = deque([])\nqueueRG = deque([])\n\nfor i in range(n) :\n for j in range(n) :\n if check[i][j] == 0 :\n answer += 1\n check[i][j] = answer\n queue.append([i, j])\n\n while queue :\n x, y = queue.popleft()\n # check[x][y] = answer\n for l in range(4) :\n r = x + dx[l]\n c = y + dy[l]\n if r < 0 or r >= n or c < 0 or c >= n :\n continue\n if lst[x][y] == lst[r][c] and check[r][c] == 0:\n check[r][c] = answer\n queue.append([r,c])\n\n if checkRG[i][j] == 0 :\n answerRG += 1\n checkRG[i][j] = answerRG\n queueRG.append([i, j])\n\n while queueRG :\n x, y = queueRG.popleft()\n # checkRG[x][y] = answerRG\n for l in range(4) :\n r = x + dx[l]\n c = y + dy[l]\n if r < 0 or r >= n or c < 0 or c >= n :\n continue\n if checkRG[r][c] == 0:\n if ((lst[x][y] and lst[r][c]) or (not lst[x][y] and not lst[r][c])) :\n checkRG[r][c] = answerRG\n queueRG.append([r,c])\n\nprint(answer, answerRG)","repo_name":"SuperH0ng/algorithm","sub_path":"따로 푼 것/백준/백준 10026(적록색약).py","file_name":"백준 10026(적록색약).py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"34216751681","text":"numeros = []\ncont = 0\nesc = 's'\nwhile True:\n n = int(input('Digite um valor: '))\n if n not in numeros:\n numeros.append(n)\n print('Numero adicionado com sucesso..')\n else:\n print('Valor duplicado! Não vou adicionar.')\n esc = input('Quer o continuar [s]SIM [n]NÃO: ').upper()\n while esc not in 'sn':\n print('Opção inválida!')\n esc = input('Quer o continuar? [s]SIM [n]NÃO: ').upper()\n if esc == 'n':\n break\nprint('-='*20)\nprint(f'Os números validados digitados foram: {sorted(numeros)}')\n","repo_name":"GustaHenriPe/Exercicios-Python","sub_path":"PythonExercicios/ex079.py","file_name":"ex079.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"818873853","text":"from fms_core.template_importer.row_handlers._generic import GenericRowHandler\nfrom fms_core.template_importer._constants import LOAD_ALL\nfrom fms_core.services.sample import get_sample_from_container, prepare_library\nfrom fms_core.services.container import get_container, get_or_create_container\nfrom fms_core.services.index import get_index\nfrom fms_core.services.library import create_library\n\n\n\nclass LibraryRowHandler(GenericRowHandler):\n def __init__(self):\n super().__init__()\n\n def process_row_inner(self, library_batch_info, source_sample, volume_used,\n comment, container, volume, index, strandedness, workflow):\n\n if not library_batch_info:\n self.errors['library_preparation'] = 'No batch is associated with this library.'\n\n # Calling the service creator for Samples in LibraryPreparation\n source_sample_obj, self.errors['container'], self.warnings['container'] = \\\n get_sample_from_container(barcode=source_sample['barcode'], coordinates=source_sample['coordinates'])\n\n if not volume_used:\n self.errors['volume_used'] = f\"Volume used must be entered\"\n\n if source_sample_obj:\n # Set the actual volumed_used in case the load all option was used\n volume_used = source_sample_obj.volume if volume_used == LOAD_ALL else volume_used\n\n if volume_used > source_sample_obj.volume:\n self.errors['volume_used'].append(f\"Volume used ({volume_used}) exceeds the current volume of the sample ({source_sample_obj.volume})\")\n\n # Check if sample is not a library or a pool of libraries\n if source_sample_obj.is_library:\n self.errors['source_sample'] = f\"Source sample can't be a library or a pool of libraries.\"\n\n # Add a warning if the sample has failed qc\n if any([source_sample_obj.quality_flag is False, source_sample_obj.quantity_flag is False]):\n self.warnings[\"qc_flags\"] = (\"Source sample {0} has failed QC.\", [source_sample_obj.name])\n\n # Populate the libraries with the batch and individual information\n protocol = library_batch_info['protocol']\n process_by_protocol = library_batch_info['process_by_protocol']\n\n # Retrieve process\n process_obj = process_by_protocol[protocol.id]\n\n container_coordinates = container['coordinates']\n\n container_parent_obj = None\n if container['parent_barcode']:\n container_parent_obj, self.errors['parent_container'], self.warnings['parent_container'] = \\\n get_container(barcode=container['parent_barcode'])\n\n container_obj, created, self.errors['library_container'], self.warnings['library_container'] = get_or_create_container(\n name=container['name'],\n barcode=container['barcode'],\n kind=container['kind'],\n container_parent=container_parent_obj if container_parent_obj else None,\n coordinates=container['parent_coordinates'] if container_parent_obj else None,\n creation_comment=comment)\n\n if container_obj and not created:\n self.warnings['library_container'] = ('Using existing container {0}', [container_obj.name])\n\n index_obj, self.errors['index'], self.warnings['index'] = get_index(index)\n\n library_info = dict(\n library_type=library_batch_info['library_type'],\n library_date=library_batch_info['library_date'],\n platform=library_batch_info['platform'],\n index=index_obj,\n strandedness=strandedness,\n )\n\n libraries_by_derived_sample = {}\n for derived_sample_source in source_sample_obj.derived_samples.all():\n library_obj, self.errors['library'], self.warnings['library'] = create_library(library_type=library_info['library_type'],\n index=index_obj,\n platform=library_info['platform'],\n strandedness=strandedness)\n libraries_by_derived_sample[derived_sample_source.id] = library_obj\n\n sample_destination, self.errors['library_preparation'], self.warnings['library_preparation'] = \\\n prepare_library(process=process_obj,\n sample_source=source_sample_obj,\n container_destination=container_obj,\n libraries_by_derived_sample=libraries_by_derived_sample,\n volume_used=volume_used,\n execution_date=library_info['library_date'],\n coordinates_destination=container_coordinates,\n volume_destination=volume,\n comment=comment,\n workflow=workflow)\n else:\n self.errors['sample_source'] = 'Sample source is needed to prepare a library.'\n","repo_name":"c3g/freezeman","sub_path":"backend/fms_core/template_importer/row_handlers/library_preparation/library_preparation.py","file_name":"library_preparation.py","file_ext":"py","file_size_in_byte":5312,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"16"}
+{"seq_id":"42599886504","text":"from collections import defaultdict\nfrom typing import Optional, Tuple, Set, Iterable\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nfrom torch.utils.data._utils.collate import default_collate\nfrom torch.utils.data._utils.pin_memory import pin_memory\n\nfrom .config import DataConfig\nfrom .dataset import DataTable, Chart\nfrom .sequence import Sequence, State\nfrom .special_tokens import SpecialTokens\nfrom .token import AnaType, Token\n\n\nclass ChartUserActions(Dataset):\n __slots__ = \"chart\", \"seq_len\"\n\n def __init__(self, cUID: str, ana_type: AnaType, idx_to_field: dict,\n config: DataConfig, search_sampling: bool):\n # TODO: remove this try-catch. (Work item #63)\n try:\n self.chart = Chart(cUID, ana_type, idx_to_field, config, search_sampling)\n self.seq_len = self.chart.seq_len()\n except:\n self.seq_len = 0\n\n def __len__(self):\n return len(self.chart.complete_states()) * (self.seq_len - 1)\n\n def __getitem__(self, index) -> Tuple[State, Token]:\n state_idx = index // (self.seq_len - 1)\n state_len = index % (self.seq_len - 1) + 1\n state = self.chart.states[state_idx].prefix(state_len)\n action = self.chart.states[state_idx][state_len]\n return state, action\n\n\nclass QValue:\n __slots__ = 'state', 'actions', 'valid_mask', 'has_valid_action', 'values', 'n_fields'\n\n def __init__(self, state: State, action_space: Sequence, valid_actions: Iterable[bool], action_values: Iterable):\n \"\"\"\n :param state: a token sequence describing the state\n :param action_space: the whole action space (context), including invalid ones for the state\n :param valid_actions: a bool list indicating if an action in the action_space is valid\n :param action_values: 1 if the action leads to the final reward\n \"\"\"\n self.state = state\n self.actions = action_space # The field tokens should always be the first n_fields ones.\n self.valid_mask = np.array(valid_actions)\n self.has_valid_action = any(valid_actions)\n self.values = np.array(action_values)\n self.n_fields = action_space.num_fields()\n\n def __hash__(self) -> int:\n return hash(self.state)\n\n def __len__(self):\n return len(self.state)\n\n def __copy__(self):\n return QValue(self.state, self.actions, self.valid_mask, self.values)\n\n def to_dict(self, state_len: int, action_len: int, field_permutation: bool, config: DataConfig):\n # Necessary preparations for \"values\" tensor\n values = self.values.copy()\n values[np.logical_not(self.valid_mask)] = -1 # Only 0, 1 for valid actions\n if field_permutation: # randomly permute field order in a table\n permutation = np.random.permutation(self.n_fields)\n values[:self.n_fields] = values[permutation] # we only need to focus on the field tokens\n else:\n permutation = None\n\n return {\n \"state\": self.state.to_dict(state_len, permutation, config.need_field_indices, False, config),\n \"actions\": self.actions.to_dict(action_len, permutation, False, True, config),\n \"values\": torch.tensor(np.pad(values, (0, action_len - len(values)), mode='constant', constant_values=-1),\n dtype=torch.long)\n }\n\n @staticmethod\n def collate(batch, config: DataConfig, field_permutation: bool, pin: bool = False):\n state_len = max(map(lambda x: len(x.state), batch))\n action_len = max(map(lambda x: len(x.actions), batch))\n\n batch = default_collate([x.to_dict(state_len, action_len, field_permutation, config) for x in batch])\n return pin_memory(batch) if pin else batch\n\n\ndef determine_action_values(action_space: Sequence, positive_actions: Optional[Set[Token]]):\n if positive_actions:\n return [1 if action in positive_actions else 0 for action in action_space]\n else:\n return [0] * len(action_space)\n\n\nclass TableQValues(Dataset):\n def __init__(self, tUID: str, special_tokens: SpecialTokens, config: DataConfig, search_sampling: bool = False):\n self.table = DataTable(tUID, special_tokens, config)\n\n self.complete_states = set()\n # Merge the samples from the Charts with specified types in config\n self.state_actions = defaultdict(set)\n\n self.valid_c = 0\n for cUID, cType in zip(self.table.cUIDs, self.table.cTypes):\n if cType not in config.input_types:\n continue\n chart = ChartUserActions(cUID, cType, self.table.idx2field, config, search_sampling)\n if chart.seq_len == 0:\n continue\n\n for state, action in chart:\n self.state_actions[state].add(action)\n chart_complete_states = chart.chart.complete_states()\n if search_sampling:\n self.complete_states.update(chart_complete_states)\n if len(chart_complete_states) > 0:\n self.valid_c += 1\n\n self.samples = list(self.state_actions.items())\n\n def __len__(self):\n return len(self.samples)\n\n def __getitem__(self, index) -> QValue:\n state, positive_actions = self.samples[index]\n valid_actions = state.valid_actions(self.table.action_space, top_freq_func=self.table.config.top_freq_func)\n action_values = determine_action_values(self.table.action_space, positive_actions)\n\n return QValue(state, self.table.action_space, valid_actions, action_values)\n\n def get_state_actions(self):\n return self.state_actions\n\n def get_positive_prefixes(self):\n return self.complete_states | self.get_state_actions().keys()\n","repo_name":"Table2Charts/Table2Charts","sub_path":"Table2Charts/data/qvalues.py","file_name":"qvalues.py","file_ext":"py","file_size_in_byte":5746,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"16"}
+{"seq_id":"1136527697","text":"import math\ninput = open(\"3/input.txt\").read().split(\"\\n\")\nexample = open(\"3/example.txt\").read().split(\"\\n\")\nhax = open(\"3/hax.txt\").read().split(\"\\n\")\n\n#input = [x.split(\" \") for x in input]\n\n\n\ndef part1(list):\n gamma = []\n epsilon = []\n \n for i in range(len(list[0])):\n ones = 0\n zeros = 0\n for row in list:\n if int(row[i]) == 1:\n ones +=1\n else:\n zeros +=1\n most = 1 if ones > zeros else 0\n least = 0 if ones > zeros else 1\n gamma.append(most)\n epsilon.append(least)\n \n g = int(\"\".join(map(str,gamma)),2)\n e = int(\"\".join(map(str,epsilon)),2)\n # print(gamma,epsilon)\n # g = 0\n # e = 0\n # gamma.reverse()\n # epsilon.reverse()\n # for i in range(len(gamma)):\n # g += gamma[i] * (2**i)\n # e += epsilon[i]*(2**i)\n # print(int(t,2) * int(y,2))\n\n return g*e\n\n\n\ndef part2(list):\n oxygen = 0\n co2 = 0\n\n oxygen_list = [x for x in list]\n co2_list = [x for x in list]\n \n for i in range(len(list[0])): \n ox_ones = 0\n ox_zeros = 0\n co2_ones = 0\n co2_zeros = 0\n\n for row in oxygen_list:\n if int(row[i]) == 1:\n ox_ones +=1\n else:\n ox_zeros +=1\n for row in co2_list:\n if int(row[i]) == 1:\n co2_ones +=1\n else:\n co2_zeros +=1\n most = 1 if ox_ones >= ox_zeros else 0\n least = 0 if co2_ones >= co2_zeros else 1\n #filter \n if(len(oxygen_list) != 1):\n oxygen_list = [x for x in oxygen_list if int(x[i])==most]\n if(len(co2_list) != 1):\n co2_list = [x for x in co2_list if int(x[i])==least]\n if (len(co2_list) == 1 and len(oxygen_list) == 1):\n break\n\n #reverse string\n\n oxygen = int(\"\".join(oxygen_list),2)\n co2 = int(\"\".join(co2_list),2)\n\n \n return(oxygen * co2)\n\nprint(f\"mine part 1: {part1(input)}\")\nprint(f\"hax part 1: {part1(hax)}\")\nprint(f\"mine part 2: {part2(input)}\")\nprint(f\"example part 2: {part2(example)}\")","repo_name":"Olivolja/Aoc_2021","sub_path":"3/aoc_3.py","file_name":"aoc_3.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"5646974619","text":"# Find the sum of all numbers under one million that are palindromic in both\n# bases 10 and 2 (binary)\n\nimport MyModule as mm\n\nsum = 0\n\nfor baseTen in range(0,1000000):\n if mm.is_it_palindromic(baseTen):\n binaryString = bin(baseTen)[2:]\n if binaryString == binaryString[::-1]:\n sum += baseTen\n\nprint(sum)\n","repo_name":"bencouser/project_euler","sub_path":"36.py","file_name":"36.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"33799438533","text":"import datetime as dt\nimport numpy as np\n\n\ndef load_data(file_name):\n with open(file_name, 'r') as input_file:\n lines_read = input_file.readlines()\n # Read all the data from the 5th index until before the last index\n # Parse the line into index numbers and coordinates\n # Convert coordinates to float\n name = ''\n data = []\n for text in lines_read:\n if len(text) > 0 and text[0].isdigit():\n data.append(tuple(map(float, text.strip().split(' ')[1:3])))\n elif 'NAME: ' in text:\n name = text[6:-1]\n return name, data\n\n\ndef early_stop_checker(seconds=float('inf'), target_cost=0):\n start_time = dt.datetime.now()\n def _lambda(q): \n return ((dt.datetime.now() - start_time).total_seconds() < seconds) and q > target_cost\n return _lambda\n\n\ndef distance(node_a: list, node_b: list) -> float:\n return np.sqrt((node_a[0] - node_b[0]) ** 2 + (node_a[1] - node_b[1]) ** 2)\n\n\ndef tour_cost(path: list) -> float:\n cost = 0\n for previous_index, current_node in enumerate(path[1:]):\n previous_node = path[previous_index]\n cost += distance(previous_node, current_node)\n cost += distance(path[0], path[-1])\n return cost","repo_name":"moalani/CSE6140-TSP-Project","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"70548338568","text":"while True:\n try:\n N = int(input())\n\n somas = []\n while len(somas) < N:\n numeros = [int(x) for x in input().strip().split(' ')]\n somas.extend(numeros)\n\n for i in range(1, N):\n somas[i] += somas[i - 1]\n\n inicio, fim, resposta = 0, N, somas[N - 1]\n while(inicio < fim):\n meio = (inicio + fim)//2\n\n rangel = somas[meio]\n gugu = somas[N - 1] - rangel\n resposta = min(resposta, abs(rangel - gugu))\n\n if(rangel == gugu):\n break\n elif(rangel < gugu):\n meio = inicio + 1\n else:\n meio = fim\n\n print(resposta)\n except EOFError:\n break\n","repo_name":"xTecna/solucoes-da-beecrowd","sub_path":"problemas/iniciante/2715/2715.py","file_name":"2715.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"pt","doc_type":"code","stars":42,"dataset":"github-code","pt":"16"}
+{"seq_id":"1053536003","text":"import torch\nimport re\nfrom operator import itemgetter\nfrom nsvqa.nn.interpreter import util\nfrom nsvqa.nn.interpreter.batch_base_types import TokenType\n\nclass OracleBase(torch.nn.Module):\n \n def __init__(self, ontology, feature_dim=1):\n super(OracleBase, self).__init__()\n self._feature_dim = feature_dim\n self._ontology = ontology\n\n def forward(self, token_type, token_list, token_image_map, world, default_log_likelihood=-30, normalized_probability=True):\n if not isinstance(token_list, list):\n token_list = [token_list]\n t_list = [a.strip() for a in token_list]\n \n if token_type == TokenType.ATTRIBUTE:\n res = self._compute_attribute_log_likelihood(world._device, t_list, world._attribute_features, world._meta_data, world._object_num, token_image_map, \\\n world._object_image_map, default_log_likelihood=default_log_likelihood, normalized_probability=normalized_probability)\n\n if isinstance(res, torch.Tensor):\n res = res.view(len(token_list), world._object_num, self._feature_dim)\n \n elif token_type == TokenType.RELATION:\n res = self._compute_relation_log_likelihood(world._device, t_list, world._relation_features, world._meta_data, world._object_num, token_image_map, \\\n world._object_image_map, default_log_likelihood=default_log_likelihood, normalized_probability=normalized_probability)\n \n if isinstance(res, torch.Tensor):\n res = res.view(len(token_list), world._object_num, world._object_num, self._feature_dim)\n\n return res\n\n def _compute_attribute_log_likelihood(self, device, attribute_list, object_features, meta_data, object_num, attribute_image_map, object_image_map, default_log_likelihood=-30, normalized_probability=True):\n pass\n\n def _compute_relation_log_likelihood(self, device, relation_list, pair_object_features, meta_data, object_num, relation_image_map, object_image_map, default_log_likelihood=-30, normalized_probability=True):\n pass\n\n def get_embedding(self, tokens, meta_data, device):\n if meta_data is None:\n embedding = torch.from_numpy(self._ontology.get_embedding(tokens)).float().to(device)\n else:\n try:\n ind = itemgetter(*tokens)(meta_data['index'])\n embedding = meta_data['embedding'][ind, :]\n except KeyError as e:\n embedding = torch.from_numpy(self._ontology.get_embeddings(tokens)).float().to(device)\n\n return embedding\n\n######################################################################################################################################\n\nclass RandomOracle(OracleBase):\n \n def __init__(self, ontology, device):\n super(RandomOracle, self).__init__(ontology)\n self._device = device\n\n def _compute_attribute_log_likelihood(self, device, attribute_list, object_features, meta_data, object_num, attribute_image_map, object_image_map, default_log_likelihood=-30):\n res = torch.rand(len(attribute_list) * self._object_num, device=self._device)\n # print(\"\\nAttribute likelihood:\")\n # print(res.view(len(attribute_list), -1))\n return util.safe_log(res)\n\n def _compute_relation_log_likelihood(self, device, relation_list, pair_object_features, meta_data, object_num, relation_image_map, object_image_map, default_log_likelihood=-30):\n res = torch.rand(len(relation_list) * (self._object_num**2), device=self._device)\n # print(\"\\nRelation likelihood:\")\n # print(res.view(len(relation_list), self._object_num, self._object_num))\n return util.safe_log(res)\n\n######################################################################################################################################\n\nclass StaticOracle(OracleBase):\n \n def __init__(self, ontology, feature_dim=1):\n super(StaticOracle, self).__init__(ontology, feature_dim=feature_dim)\n\n def _extract_entries(self, a_list, features):\n i = [features['index'][c] if c in features['index'] else 0 for c in a_list]\n ind = torch.tensor(i, dtype=torch.int64, device=features['log_likelihood'].device)\n return features['log_likelihood'][ind]\n\n def _compute_attribute_log_likelihood(self, device, attribute_list, object_features, meta_data, object_num, attribute_image_map, object_image_map, default_log_likelihood=-30):\n return self._extract_entries(attribute_list, object_features)\n\n def _compute_relation_log_likelihood(self, device, relation_list, pair_object_features, meta_data, object_num, relation_image_map, object_image_map, default_log_likelihood=-30):\n return self._extract_entries(relation_list, pair_object_features)\n","repo_name":"microsoft/DFOL-VQA","sub_path":"src/nsvqa/nn/vision/base_oracle.py","file_name":"base_oracle.py","file_ext":"py","file_size_in_byte":4798,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"16"}
+{"seq_id":"9276448861","text":"from .database import connect\nfrom .exists import check_existsquery\nfrom .handlers import get_handler\nfrom .request import Request\nfrom .responses import (\n ErrorResponse,\n MethodNotAllowedResponse,\n NotFoundResponse,\n PermanentRedirectResponse,\n)\nfrom .routing import route\n\nimport logging\n\nlogger = logging.getLogger(\"sqlsite\")\n\n\ndef should_append_slash(request):\n return request.route.pattern.endswith(\"/\") and not request.path.endswith(\"/\")\n\n\ndef method_allowed(request):\n return request.method in {\"GET\", \"HEAD\"}\n\n\ndef get_response(request):\n if not method_allowed(request):\n return MethodNotAllowedResponse()\n matched_route = route(request.db, request.path)\n if not matched_route:\n return NotFoundResponse()\n request.route = matched_route\n if should_append_slash(request):\n return PermanentRedirectResponse(f\"/{request.path}/\")\n if not check_existsquery(request):\n return NotFoundResponse()\n handler = get_handler(matched_route.handler)\n response = handler(request)\n return response\n\n\ndef make_app(test_db=None):\n def app(environ, start_response):\n db = test_db or connect()\n request = Request(environ, db)\n try:\n response = get_response(request)\n except Exception as exception:\n logger.exception(exception)\n response = ErrorResponse()\n start_response(response.get_status_line(), response.get_headers())\n return response.get_content()\n\n return app\n","repo_name":"j4mie/sqlsite","sub_path":"sqlsite/wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","stars":177,"dataset":"github-code","pt":"16"}
+{"seq_id":"16513138068","text":"def coordinateLister(jsonlist):\n \"\"\"\n -------------------\n VERSION: 2021-11-15\n -------------------\n \n Give a list of jsons as a parameter. For example a list created with readJson()-function.\n This function gives all x- and y-coordinates of density blocks, moisture blocks and all defects.\n \n Six lists will be returned, which all contains lists of all sheets as a parameter.\n \n Example\n -------\n \n xDensity, yDensity, xMoisture, yMoisture, xDefects, yDefects = coordinateLister(jsonlist)\n \n So if your jsonlist contains all 146 peeling sheets, then for example\n list xDensity contains 146 lists. First list inside xDensity contains all density x-coordinates of the first sheet and so on. \n \n \"\"\"\n xD_ALL = []; yD_ALL = []; xM_ALL = []; yM_ALL = []; xDEF_ALL = []; yDEF_ALL = []\n\n # Looping all sheets and appending sheets coordinates lists to lists containing lists of all sheets coordinate-lists\n for sheet in jsonlist:\n # Density-blocks\n xD = []; yD = []\n for dblock in sheet['DensityBlocks']:\n for key in dblock:\n if key == 'm_pntTL' or key == 'm_pntTR' or key == 'm_pntBL' or key == 'm_pntBR':\n xD.append(dblock[key]['x'])\n yD.append(dblock[key]['y'])\n xD_ALL.append(xD)\n yD_ALL.append(yD)\n\n # Moisture blocks\n xM = []; yM = []\n for dblock in sheet['MoistureBlocks']:\n for key in dblock:\n if key == 'm_pntTL' or key == 'm_pntTR' or key == 'm_pntBL' or key == 'm_pntBR':\n xM.append(dblock[key]['x'])\n yM.append(dblock[key]['y'])\n xM_ALL.append(xM)\n yM_ALL.append(yM)\n\n # Defects\n xDEF = []; yDEF = []\n for dblock in sheet['Defects']:\n for key in dblock:\n if key == 'm_mmpntGravity':\n xDEF.append(dblock[key]['x']/sheet['ObjectData'][0]['ObjectResX'])\n yDEF.append(dblock[key]['y']/sheet['ObjectData'][0]['ObjectResY'])\n xDEF_ALL.append(xDEF)\n yDEF_ALL.append(yDEF)\n return xD_ALL, yD_ALL, xM_ALL, yM_ALL, xDEF_ALL, yDEF_ALL","repo_name":"TuomasKarjalainen/project-RAUTE","sub_path":"Modules/coordinatelister.py","file_name":"coordinatelister.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"24983332155","text":"import numpy as np\nimport threading\nimport time\nimport math\n\n'''\nnaive implementation of vector-matrix multiplication\n\nweight matrix shape: (n,n)\nvector shape: (n,1)\n'''\nglobal y\n\ndef naive_vector_matrix_mult(w, x):\n n = w.shape[0]\n # y = np.zeros((n,1))\n for i in range(n):\n for j in range(n):\n y[i]+=w[i,j]*x[j]\n # y[i] = np.dot(w[i,:], x)\n return\n\n\ndef vector_vector_thread(row, x, ind):\n y[ind] = np.dot(row, x)\n return\n \ndef single_partition(w, x, num_threads=16):\n n = w.shape[0]\n\n \n threads = []\n #8 cores, hyperthreading doubles to 16\n # we will broadcast to make 16 copies of x\n xb = np.broadcast_to(x.T, shape=(num_threads,n))\n \n vec_ind = 0\n thread_ind = 0\n \n while(vec_ind%s[^'\"]*)['\"].*\\/>\"\"\" % settings.STATIC_URL\n\n image_matches = re.findall(image_pattern, message.alternatives[0][0])\n\n added_images = {}\n\n for image_match in image_matches:\n\n if image_match not in added_images:\n img_content_cid = id_generator()\n on_disk_path = os.path.join(settings.MEDIA_ROOT, image_match.replace(settings.STATIC_URL, ''))\n img_data = open(on_disk_path, 'rb').read()\n img = MIMEImage(img_data)\n img.add_header('Content-ID', '<%s>' % img_content_cid)\n img.add_header('Content-Disposition', 'inline')\n message.attach(img)\n\n added_images[image_match] = img_content_cid\n\n def repl(matchobj):\n x = matchobj.group('img_src')\n y = 'cid:%s' % str(added_images[matchobj.group('img_src')])\n return matchobj.group(0).replace(matchobj.group('img_src'), 'cid:%s' % added_images[matchobj.group('img_src')])\n\n if added_images:\n message.alternatives = [(re.sub(image_pattern, repl, message.alternatives[0][0]), 'text/html')]\n message.body = re.sub(image_pattern, repl, message.body)\n \n ","repo_name":"su-danny/famdates","sub_path":"notification/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"34863728865","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim: ai ts=4 sts=4 et sw=4 nu\n\nimport os\nimport time\nimport json\nfrom io import BytesIO\n\nimport pytest\nimport requests\n\nfrom warcio import ArchiveIterator\nfrom jinja2 import Environment, PackageLoader\nfrom zimscraperlib.zim import Archive\n\nfrom warc2zim.main import (\n warc2zim,\n canonicalize,\n iter_warc_records,\n get_record_url,\n)\n\n\nTEST_DATA_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"data\")\n\n\n# ============================================================================\nCMDLINES = [\n [\"example-response.warc\"],\n [\"example-response.warc\", \"--progress-file\", \"progress.json\"],\n [\"example-resource.warc.gz\", \"--favicon\", \"https://example.com/some/favicon.ico\"],\n [\"example-resource.warc.gz\", \"--favicon\", \"https://www.google.com/favicon.ico\"],\n [\"example-revisit.warc.gz\"],\n [\n \"example-revisit.warc.gz\",\n \"-u\",\n \"http://example.iana.org/\",\n \"--lang\",\n \"eng\",\n ],\n [\n \"example-utf8.warc\",\n \"-u\",\n \"https://httpbin.org/anything/utf8=%E2%9C%93?query=test&a=b&1=%E2%9C%93\",\n ],\n [\"single-page-test.warc\"],\n]\n\n\n@pytest.fixture(params=CMDLINES, ids=[\" \".join(cmds) for cmds in CMDLINES])\ndef cmdline(request):\n return request.param\n\n\n# ============================================================================\nFUZZYCHECKS = [\n {\n \"filename\": \"video-yt.warc.gz\",\n \"entries\": [\n \"H/youtube.fuzzy.replayweb.page/get_video_info?video_id=aT-Up5Y4uRI\",\n \"H/youtube.fuzzy.replayweb.page/videoplayback?id=o-AE3bg3qVNY-gAWwYgL52vgpHKJe9ijdbu2eciNi5Uo_w\",\n ],\n },\n {\n \"filename\": \"video-yt-2.warc.gz\",\n \"entries\": [\n \"H/youtube.fuzzy.replayweb.page/youtubei/v1/player?videoId=aT-Up5Y4uRI\",\n \"H/youtube.fuzzy.replayweb.page/videoplayback?id=o-AGDtIqpFRmvgVVZk96wgGyFxL_SFSdpBxs0iBHatQpRD\",\n ],\n },\n {\n \"filename\": \"video-vimeo.warc.gz\",\n \"entries\": [\n \"H/vimeo.fuzzy.replayweb.page/video/347119375\",\n \"H/vimeo-cdn.fuzzy.replayweb.page/01/4423/13/347119375/1398505169.mp4\",\n ],\n },\n]\n\n\n@pytest.fixture(params=FUZZYCHECKS, ids=[fuzzy[\"filename\"] for fuzzy in FUZZYCHECKS])\ndef fuzzycheck(request):\n return request.param\n\n\n# ============================================================================\nclass TestWarc2Zim(object):\n def list_articles(self, zimfile):\n zim_fh = Archive(zimfile)\n for x in range(zim_fh.entry_count):\n yield zim_fh.get_entry_by_id(x)\n\n def get_metadata(self, zimfile, name):\n zim_fh = Archive(zimfile)\n return zim_fh.get_metadata(name)\n\n def get_article(self, zimfile, path):\n zim_fh = Archive(zimfile)\n return zim_fh.get_content(path)\n\n def get_article_raw(self, zimfile, path):\n zim_fh = Archive(zimfile)\n return zim_fh.get_item(path)\n\n def verify_warc_and_zim(self, warcfile, zimfile):\n assert os.path.isfile(warcfile)\n assert os.path.isfile(zimfile)\n\n # autoescape=False to allow injecting html entities from translated text\n env = Environment(\n loader=PackageLoader(\"warc2zim\", \"templates\"),\n extensions=[\"jinja2.ext.i18n\"],\n autoescape=False,\n )\n\n head_insert = env.get_template(\"sw_check.html\").render().encode(\"utf-8\")\n\n # track to avoid checking duplicates, which are not written to ZIM\n warc_urls = set()\n\n zim_fh = Archive(zimfile)\n for record in iter_warc_records([warcfile]):\n url = get_record_url(record)\n if not url:\n continue\n\n if url in warc_urls:\n continue\n\n if record.rec_type not in ((\"response\", \"resource\", \"revisit\")):\n continue\n\n # ignore revisit records that are to the same url\n if (\n record.rec_type == \"revisit\"\n and record.rec_headers[\"WARC-Refers-To-Target-URI\"] == url\n ):\n continue\n\n # parse headers as record, ensure headers match\n url_no_scheme = url.split(\"//\", 2)[1]\n print(url_no_scheme)\n parsed_record = next(\n ArchiveIterator(BytesIO(zim_fh.get_content(\"H/\" + url_no_scheme)))\n )\n\n assert record.rec_headers == parsed_record.rec_headers\n assert record.http_headers == parsed_record.http_headers\n\n # ensure payloads match\n try:\n payload = zim_fh.get_item(\"A/\" + url_no_scheme)\n except KeyError:\n payload = None\n\n if record.rec_type == \"revisit\" or (\n record.http_headers and record.http_headers.get(\"Content-Length\") == \"0\"\n ):\n assert not payload\n else:\n payload_content = payload.content.tobytes()\n\n # if HTML, still need to account for the head insert, otherwise should have exact match\n if payload.mimetype.startswith(\"text/html\"):\n assert head_insert in payload_content\n assert (\n payload_content.replace(head_insert, b\"\")\n == record.buffered_stream.read()\n )\n else:\n assert payload_content == record.buffered_stream.read()\n\n warc_urls.add(url)\n\n def test_canonicalize(self):\n assert canonicalize(\"http://example.com/?foo=bar\") == \"example.com/?foo=bar\"\n\n assert canonicalize(\"https://example.com/?foo=bar\") == \"example.com/?foo=bar\"\n\n assert (\n canonicalize(\"https://example.com/some/path/http://example.com/?foo=bar\")\n == \"example.com/some/path/http://example.com/?foo=bar\"\n )\n\n assert (\n canonicalize(\"example.com/some/path/http://example.com/?foo=bar\")\n == \"example.com/some/path/http://example.com/?foo=bar\"\n )\n\n def test_warc_to_zim_specify_params_and_metadata(self, tmp_path):\n zim_output = \"zim-out-filename.zim\"\n warc2zim(\n [\n \"-v\",\n os.path.join(TEST_DATA_DIR, \"example-response.warc\"),\n \"--name\",\n \"example-response\",\n \"--output\",\n str(tmp_path),\n \"--zim-file\",\n zim_output,\n \"-r\",\n \"https://cdn.jsdelivr.net/npm/@webrecorder/wabac@2.16.11/dist/\",\n \"--tags\",\n \"some\",\n \"--tags\",\n \"foo\",\n \"--desc\",\n \"test zim\",\n \"--tags\",\n \"bar\",\n \"--title\",\n \"Some Title\",\n ]\n )\n\n zim_output = tmp_path / zim_output\n\n assert os.path.isfile(zim_output)\n\n all_articles = {\n article.path: article.title for article in self.list_articles(zim_output)\n }\n\n assert all_articles == {\n # entries from WARC\n \"A/example.com/\": \"Example Domain\",\n \"H/example.com/\": \"H/example.com/\",\n # replay system files\n \"A/index.html\": \"A/index.html\",\n \"A/load.js\": \"A/load.js\",\n \"A/404.html\": \"A/404.html\",\n \"A/sw.js\": \"A/sw.js\",\n \"A/topFrame.html\": \"A/topFrame.html\",\n }\n\n zim_fh = Archive(zim_output)\n\n # ZIM metadata\n assert list(zim_fh.metadata.keys()) == [\n \"Counter\",\n \"Creator\",\n \"Date\",\n \"Description\",\n \"Language\",\n \"Name\",\n \"Publisher\",\n \"Scraper\",\n \"Tags\",\n \"Title\",\n ]\n\n assert zim_fh.has_fulltext_index\n assert zim_fh.has_title_index\n\n assert self.get_metadata(zim_output, \"Description\") == b\"test zim\"\n assert (\n self.get_metadata(zim_output, \"Tags\")\n == b\"_ftindex:yes;_category:other;_sw:yes;some;foo;bar\"\n )\n assert self.get_metadata(zim_output, \"Title\") == b\"Some Title\"\n\n def test_warc_to_zim(self, cmdline, tmp_path):\n # intput filename\n filename = cmdline[0]\n\n # set intput filename (first arg) to absolute path from test dir\n warcfile = os.path.join(TEST_DATA_DIR, filename)\n cmdline[0] = warcfile\n\n cmdline.extend([\"--output\", str(tmp_path), \"--name\", filename])\n\n warc2zim(cmdline)\n\n zimfile = filename + \"_\" + time.strftime(\"%Y-%m\") + \".zim\"\n\n if \"--progress-file\" in cmdline:\n with open(tmp_path / \"progress.json\", \"r\") as fh:\n progress = json.load(fh)\n assert (\n progress[\"written\"] > 0\n and progress[\"total\"] > 0\n and progress[\"written\"] <= progress[\"total\"]\n )\n\n self.verify_warc_and_zim(warcfile, tmp_path / zimfile)\n\n def test_same_domain_only(self, tmp_path):\n zim_output = \"same-domain.zim\"\n warc2zim(\n [\n os.path.join(TEST_DATA_DIR, \"example-revisit.warc.gz\"),\n \"--favicon\",\n \"http://example.com/favicon.ico\",\n \"--include-domains\",\n \"example.com/\",\n \"--lang\",\n \"eng\",\n \"--zim-file\",\n zim_output,\n \"--name\",\n \"same-domain\",\n \"--output\",\n str(tmp_path),\n ]\n )\n\n zim_output = tmp_path / zim_output\n\n for article in self.list_articles(zim_output):\n url = article.path\n # ignore the replay files, which have only one path segment\n if url.startswith(\"A/\") and len(url.split(\"/\")) > 2:\n assert url.startswith(\"A/example.com/\")\n\n def test_skip_self_redirect(self, tmp_path):\n zim_output = \"self-redir.zim\"\n warc2zim(\n [\n os.path.join(TEST_DATA_DIR, \"self-redirect.warc\"),\n \"--output\",\n str(tmp_path),\n \"--zim-file\",\n zim_output,\n \"--name\",\n \"self-redir\",\n ]\n )\n\n zim_output = tmp_path / zim_output\n\n for article in self.list_articles(zim_output):\n url = article.path\n if url.startswith(\"H/\"):\n # ensure there is only one H/ record, and its a 200 (not 301)\n assert url == \"H/kiwix.org/\"\n assert b\"HTTP/1.1 200 OK\" in self.get_article(\n zim_output, \"H/kiwix.org/\"\n )\n\n def test_include_domains_favicon_and_language(self, tmp_path):\n zim_output = \"spt.zim\"\n warc2zim(\n [\n os.path.join(TEST_DATA_DIR, \"single-page-test.warc\"),\n \"-i\",\n \"reseau-canope.fr\",\n \"--output\",\n str(tmp_path),\n \"--zim-file\",\n zim_output,\n \"--name\",\n \"spt\",\n ]\n )\n\n zim_output = tmp_path / zim_output\n\n for article in self.list_articles(zim_output):\n url = article.path\n # ignore the replay files, which have only one path segment\n if url.startswith(\"A/\") and len(url.split(\"/\")) > 2:\n assert \"reseau-canope.fr/\" in url\n\n # test detected language\n assert self.get_metadata(zim_output, \"Language\") == b\"fra\"\n\n # test detected favicon\n assert self.get_article(\n zim_output,\n \"A/lesfondamentaux.reseau-canope.fr/fileadmin/template/img/favicon.ico\",\n )\n assert self.get_metadata(zim_output, \"Illustration_48x48@1\")\n\n # test default tags added\n assert (\n self.get_metadata(zim_output, \"Tags\")\n == b\"_ftindex:yes;_category:other;_sw:yes\"\n )\n\n def test_all_warcs_root_dir(self, tmp_path):\n zim_output = \"test-all.zim\"\n warc2zim(\n [\n os.path.join(TEST_DATA_DIR),\n \"--output\",\n str(tmp_path),\n \"--zim-file\",\n zim_output,\n \"--name\",\n \"test-all\",\n \"--url\",\n \"http://example.com\",\n ]\n )\n zim_output = tmp_path / zim_output\n\n # check articles from different warc records in tests/data dir\n\n # ensure trailing slash added\n assert b'window.mainUrl = \"http://example.com/\"' in self.get_article(\n zim_output, \"A/index.html\"\n )\n\n # from example.warc.gz\n assert self.get_article(zim_output, \"A/example.com/\") != b\"\"\n\n # from single-page-test.warc\n assert (\n self.get_article(\n zim_output, \"A/lesfondamentaux.reseau-canope.fr/accueil.html\"\n )\n != b\"\"\n )\n\n # timestamp fuzzy match from example-with-timestamp.warc\n assert self.get_article(zim_output, \"H/example.com/path.txt?\") != b\"\"\n\n def test_fuzzy_urls(self, tmp_path, fuzzycheck):\n zim_output = fuzzycheck[\"filename\"] + \".zim\"\n warc2zim(\n [\n os.path.join(TEST_DATA_DIR, fuzzycheck[\"filename\"]),\n \"--output\",\n str(tmp_path),\n \"--zim-file\",\n zim_output,\n \"--name\",\n \"test-fuzzy\",\n ]\n )\n zim_output = tmp_path / zim_output\n\n for entry in fuzzycheck[\"entries\"]:\n res = self.get_article(zim_output, entry)\n assert b\"Location: \" in res\n\n def test_local_replay_viewer_url(self, tmp_path):\n zim_local_sw = \"zim-local-sw.zim\"\n\n res = requests.get(\n \"https://cdn.jsdelivr.net/npm/@webrecorder/wabac@2.16.11/dist/sw.js\"\n )\n\n with open(tmp_path / \"sw.js\", \"wt\") as fh:\n fh.write(res.text)\n\n warc2zim(\n [\n \"-v\",\n os.path.join(TEST_DATA_DIR, \"example-response.warc\"),\n \"-r\",\n str(tmp_path) + \"/\",\n \"--output\",\n str(tmp_path),\n \"--name\",\n \"local-sw\",\n \"--zim-file\",\n zim_local_sw,\n ]\n )\n\n assert os.path.isfile(tmp_path / zim_local_sw)\n\n def test_error_bad_replay_viewer_url(self, tmp_path):\n zim_output_not_created = \"zim-out-not-created.zim\"\n with pytest.raises(Exception) as e:\n warc2zim(\n [\n \"-v\",\n os.path.join(TEST_DATA_DIR, \"example-response.warc\"),\n \"-r\",\n \"x-invalid-x\",\n \"--output\",\n str(tmp_path),\n \"--name\",\n \"bad\",\n \"--zim-file\",\n zim_output_not_created,\n ]\n )\n\n # zim file should not have been created since replay viewer could not be loaded\n assert not os.path.isfile(tmp_path / zim_output_not_created)\n\n def test_error_bad_main_page(self, tmp_path):\n zim_output_not_created = \"zim-out-not-created.zim\"\n with pytest.raises(Exception) as e:\n warc2zim(\n [\n \"-v\",\n os.path.join(TEST_DATA_DIR, \"example-response.warc\"),\n \"-u\",\n \"https://no-such-url.example.com\",\n \"--output\",\n str(tmp_path),\n \"--name\",\n \"bad\",\n \"--zim-file\",\n zim_output_not_created,\n ]\n )\n\n def test_args_only(self):\n # error, name required\n with pytest.raises(SystemExit) as e:\n warc2zim([])\n assert e.code == 2\n\n # error, no such output directory\n with pytest.raises(Exception) as e:\n warc2zim([\"--name\", \"test\", \"--output\", \"/no-such-dir\"])\n\n # success, special error code for no output files\n assert warc2zim([\"--name\", \"test\", \"--output\", \"./\"]) == 100\n\n def test_custom_css(self, tmp_path):\n custom_css = b\"* { background-color: red; }\"\n custom_css_path = tmp_path / \"custom.css\"\n with open(custom_css_path, \"wb\") as fh:\n fh.write(custom_css)\n\n zim_output = \"test-css.zim\"\n\n warc2zim(\n [\n os.path.join(TEST_DATA_DIR, \"example-response.warc\"),\n \"--output\",\n str(tmp_path),\n \"--zim-file\",\n zim_output,\n \"--name\",\n \"test-css\",\n \"--custom-css\",\n str(custom_css_path),\n ]\n )\n zim_output = tmp_path / zim_output\n\n res = self.get_article(zim_output, \"A/example.com/\")\n assert \"https://warc2zim.kiwix.app/custom.css\".encode(\"utf-8\") in res\n\n res = self.get_article(zim_output, \"A/warc2zim.kiwix.app/custom.css\")\n assert custom_css == res\n\n def test_custom_css_remote(self, tmp_path):\n zim_output = \"test-css.zim\"\n url = (\n \"https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap-reboot.css\"\n )\n\n warc2zim(\n [\n os.path.join(TEST_DATA_DIR, \"example-response.warc\"),\n \"--output\",\n str(tmp_path),\n \"--zim-file\",\n zim_output,\n \"--name\",\n \"test-css\",\n \"--custom-css\",\n url,\n ]\n )\n zim_output = tmp_path / zim_output\n\n res = self.get_article(zim_output, \"A/example.com/\")\n assert \"https://warc2zim.kiwix.app/custom.css\".encode(\"utf-8\") in res\n\n res = self.get_article(zim_output, \"A/warc2zim.kiwix.app/custom.css\")\n assert res == requests.get(url).content\n","repo_name":"openzim/warc2zim","sub_path":"tests/test_warc_to_zim.py","file_name":"test_warc_to_zim.py","file_ext":"py","file_size_in_byte":18112,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"16"}
+{"seq_id":"12904417084","text":"\"\"\"\nTODO: Add docstring.\n\nrequires:\npip install chromadb\npip install chromadb-client\n\"\"\n\n\"\"\"\nfrom typing import Dict, Optional, List, Union\nimport uuid\n\n\n# pylint: disable=import-error\nimport chromadb as chroma\nfrom chromadb.types import Collection\n\n# pylint: disable=no-name-in-module\nfrom chromadb import PersistentClient\n\nfrom .vector_store import VectorStore, QueryResult\n\n\nclass ChromaVectorStore(VectorStore):\n \"\"\"\n Implementation of the VectorStore for the Chroma vector database.\n\n Provides methods to interact with Chroma, including creating, querying,\n and managing collections. Supports ephemeral, persistent, and HTTP Chroma clients.\n\n Ensure `chromadb` and `chromadb-client` packages are installed.\n\n Attributes:\n client: Chroma client instance.\n current_collection: Current active collection in Chroma.\n\n Args:\n api_key (Optional[str]): API key or token.\n client_type (str): Chroma client type (\"ephemeral\", \"persistent\", or \"http\").\n path (Optional[str]): Path for persistent storage.\n host (Optional[str]): Host for HTTP client.\n port (Optional[int]): Port for HTTP client.\n config (Optional[Dict[str, str]]): Additional configurations.\n \"\"\"\n\n # pylint: disable=R0913\n def __init__(\n self,\n api_key: Optional[str] = None,\n client_type: str = \"ephemeral\",\n path: Optional[str] = None,\n host: Optional[str] = None,\n port: Optional[int] = None,\n config: Optional[Dict[str, str]] = None,\n ):\n \"\"\"\n Initializes the ChromaVectorStore with optional parameters.\n\n Args:\n api_key (str, optional): API key or authentication token.\n client_type (str): Type of Chroma client (\"ephemeral\", \"persistent\", or \"http\").\n path (str, optional): Path for persistent client storage.\n host (str, optional): Host for HTTP client.\n port (int, optional): Port for HTTP client.\n config (Dict[str, str], optional): Additional configuration settings.\n \"\"\"\n super().__init__(api_key, None, config)\n\n if client_type == \"ephemeral\":\n self.client = chroma.Client()\n elif client_type == \"persistent\":\n if not path:\n raise ValueError(\"Path is required for persistent client.\")\n # pylint: disable=no-member\n self.client = chroma.PersistentClient(path=path)\n elif client_type == \"http\":\n if not host or not port:\n raise ValueError(\"Host and port are required for HTTP client.\")\n # pylint: disable=no-member\n self.client = chroma.HttpClient(host=host, port=port)\n else:\n raise ValueError(f\"Invalid client type: {client_type}\")\n\n self.current_collection = None\n\n def create_collection(\n self, name: str, metadata: Optional[Dict[str, str]] = None\n ) -> Collection:\n \"\"\"\n Creates a new collection with the given name and metadata in Chroma.\n\n Args:\n name (str): The name of the collection to create.\n metadata (Optional[Dict[str, str]]): Optional metadata to associate with the collection.\n\n Returns:\n Collection: The newly created collection.\n\n Raises:\n ValueError: If the collection already exists.\n ValueError: If the collection name is invalid.\n \"\"\"\n # Using the Chroma client to create a collection\n self.current_collection = self.client.create_collection(\n name=name, metadata=metadata\n )\n\n def use_collection(self, name):\n \"\"\"\n Sets the current collection to an existing one or creates it if it doesn't exist.\n\n Args:\n name (str): Name of the collection to use or create.\n \"\"\"\n # Set the current collection to an existing one\n self.current_collection = self.client.get_or_create_collection(name)\n\n def delete_collection(self, name: str) -> None:\n \"\"\"\n Deletes a collection with the given name from Chroma.\n\n Args:\n name (str): The name of the collection to delete.\n\n Raises:\n ValueError: If the collection does not exist.\n \"\"\"\n # Using the Chroma client to delete a collection\n self.client.delete_collection(name=name)\n\n def add_documents(\n self,\n texts: List[str],\n embeddings: Optional[List[List[float]]] = None,\n metadata_list: Optional[List[Dict[str, str]]] = None,\n ids: Optional[List[str]] = None,\n ) -> None:\n \"\"\"\n Adds documents and their associated embeddings and metadata\n to the current collection in Chroma.\n\n Args:\n texts (List[str]): List of documents to be added.\n embeddings (Optional[List[List[float]]]): List of embeddings.\n If not provided, embeddings will be generated by Chroma.\n metadata_list (Optional[List[Dict[str, str]]]): Metadata associated with each document.\n ids (Optional[List[str]]): IDs for each document.\n If not provided, unique IDs will be auto-generated.\n\n Raises:\n ValueError: If no collection is set.\n ValueError: Handled by the underlying Chroma library for various conditions.\n \"\"\"\n # Ensure a collection is set\n if not self.current_collection:\n # pylint: disable=line-too-long\n raise ValueError(\n \"No collection is set. Use 'create_collection' or 'use_collection' first.\"\n )\n\n # If ids are not provided, auto-generate unique IDs for each document\n if not ids:\n ids = [str(uuid.uuid4()) for _ in texts]\n\n # Add documents to the current collection\n self.current_collection.add(\n ids=ids, embeddings=embeddings, metadatas=metadata_list, documents=texts\n )\n\n def remove_documents(self, ids: List[str]) -> None:\n \"\"\"\n Removes documents with the specified IDs from the current collection in Chroma.\n\n Args:\n ids (List[str]): List of document IDs to be removed.\n\n Raises:\n ValueError: If no collection is set.\n \"\"\"\n # Ensure a collection is set\n if not self.current_collection:\n # pylint: disable=line-too-long\n raise ValueError(\n \"No collection is set. Use 'create_collection' or 'use_collection' first.\"\n )\n\n # Remove documents from the current collection\n self.current_collection.delete(ids=ids)\n\n def save_index(self, file_path: str) -> None:\n \"\"\"\n Saves the current Chroma index to the specified file path.\n\n Args:\n file_path (str): The path where the Chroma index will be saved.\n \"\"\"\n self.client = PersistentClient(path=file_path)\n # pylint: disable=line-too-long\n # Since Chroma automatically persists data with PersistentClient, no further action is needed.\n\n def load_index(self, file_path: str) -> None:\n \"\"\"\n Loads the Chroma index from the specified file path.\n\n Args:\n file_path (str): The path from where the Chroma index will be loaded.\n \"\"\"\n # pylint: disable=no-member\n self.client = PersistentClient(path=file_path)\n # Chroma will automatically load the data from the provided path.\n\n def query_collection(\n self,\n query_texts: Optional[List[str]] = None,\n n_results: int = 10,\n query_embeddings: Optional[List[List[float]]] = None,\n where: Optional[Dict[str, Union[str, float]]] = None,\n where_document: Optional[Dict[str, Dict[str, str]]] = None,\n include: Optional[List[str]] = None,\n ) -> QueryResult:\n \"\"\"\n Queries the current collection in Chroma and returns the nearest neighbors.\n\n Args:\n # pylint: disable=line-too-long\n query_texts (Optional[List[str]]): Document texts for querying.\n n_results (int): Number of nearest neighbors to return.\n query_embeddings (Optional[List[List[float]]]): Embeddings for querying.\n where (Optional[Dict[str, Union[str, float]]]): A filter to narrow down results based on metadata criteria. For example, {\"color\": \"red\", \"price\": 4.20} would return vectors with metadata matching these criteria.\n where_document (Optional[Dict[str, Dict[str, str]]]): A filter to narrow down results based on document content. For instance, {$contains: {\"text\": \"hello\"}} would return vectors whose documents contain the word \"hello\".\n include (Optional[List[str]]): Data to include in the results. Defaults to [\"metadatas\", \"documents\", \"distances\"].\n\n\n Returns:\n QueryResult: Contains the results.\n\n Raises:\n ValueError: If no collection is set or incorrect query parameters are provided.\n \"\"\"\n if include is None:\n include = [\"metadatas\", \"documents\", \"distances\"]\n\n if not self.current_collection:\n # pylint: disable=line-too-long\n raise ValueError(\n \"No collection set. Use 'create_collection' or 'use_collection' first.\"\n )\n\n if not query_embeddings and not query_texts:\n raise ValueError(\"Provide either 'query_embeddings' or 'query_texts'.\")\n if query_embeddings and query_texts:\n raise ValueError(\"Provide only one of 'query_embeddings' or 'query_texts'.\")\n\n return self.current_collection.query(\n query_embeddings=query_embeddings,\n query_texts=query_texts,\n n_results=n_results,\n where=where,\n where_document=where_document,\n include=include,\n )\n\n def list_collections(self) -> List[str]:\n \"\"\"\n Lists all collections in Chroma.\n\n Returns:\n List[str]: A list of collection names.\n \"\"\"\n return self.client.list_collections()\n","repo_name":"dirkjbreeuwer/ai_podcast","sub_path":"src/search_and_retrieval/chroma_vector_store.py","file_name":"chroma_vector_store.py","file_ext":"py","file_size_in_byte":10048,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"16"}
+{"seq_id":"26676490687","text":"\"\"\" Game backbone, shared instances used in other modules \"\"\"\n\n# global constants\nWIDTH = 640 # framebuffer width\nHEIGHT = 360 # framebuffer height\nMAX_LAYERS = 3 # backgroudn layers\nMAX_SPRITES = 32 # max sprites\nASSETS_PATH = \"../assets\"\n\n# global game objects, delayed creation\n\nengine = ()\t # tilengine main instance\nwindow = ()\t # tilengine window instance\nactors = ()\t # list that contains every active game entity\nui = ()\t\t # UI items\nworld = ()\t # world/level instance\nplayer = () # player instance\nsounds = ()\t # sound effects handler\n","repo_name":"megamarc/TilenginePythonPlatformer","sub_path":"src/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"16"}
+{"seq_id":"70388010568","text":"import numpy as np\nfrom astropy import units as u\nfrom falafel.utils import config\nfrom orphics import cosmology, maps as omaps \nfrom classy_sz import Class\n\ndef ell2ang(ell, angle_unit=None):\n \"\"\"Convert from harmonic mode ell to an angle with units.\n\n Parameters\n ----------\n ell : float\n Harmonic mode ell\n angle_unit : str, optional\n Desired unit for the angle, by default None\n\n Returns\n -------\n astropy Quantity with astropy Units\n Angle with units\n\n Raises\n ------\n ValueError\n You need to give an appropriate value for the angle's units\n\n \"\"\"\n\n #Possible Units\n units_dict = {}\n units_dict['deg'] = u.deg\n units_dict['rad'] = u.rad\n units_dict['arcmin'] = u.arcmin\n units_dict['arcsec'] = u.arcsec\n\n if angle_unit == None:\n raise ValueError(f\"Valid angle units are {', '.join(units_dict.keys())}\")\n\n #Calculate Angle\n theta = 2 * np.pi / ell * u.rad\n\n #Convert Unit\n return theta.to(units_dict[angle_unit], equivalencies=u.dimensionless_angles())\n\n\ndef ang2ell(angle, angle_unit=None):\n \"\"\"Convert from an angle to harmonic mode ell. This function adds the astropy units so you only need numbers and strings to use it.\n\n Parameters\n ----------\n angle : float\n Value of angle\n angle_unit : str, optional\n String of the unit for the angle, by default None\n\n Returns\n -------\n int\n Harmonic mode ell\n\n Raises\n ------\n ValueError\n You need to give an appropriate value for the angle's units\n \"\"\"\n\n #Possible Units\n units_dict = {}\n units_dict['deg'] = u.deg\n units_dict['rad'] = u.rad\n units_dict['arcmin'] = u.arcmin\n units_dict['arcsec'] = u.arcsec\n\n if angle_unit == None:\n raise ValueError(f\"Valid angle units are {', '.join(units_dict.keys())}\")\n\n #Convert to Radians\n angle = angle * units_dict[angle_unit]\n angle = angle.to(u.rad, equivalencies=u.dimensionless_angles())\n\n #Calculate Angle\n return int(2 * np.pi / angle.value)\n\n\ndef nanToZeros(array):\n return np.where(array == np.nan, 0., array)\n\n\ndef str2bool(string):\n valid_true = ['true', 't', 'yes', 'y']\n valid_false = ['false', 'f', 'no', 'n']\n choice = string.lower()\n\n if choice in valid_true:\n boolean_val = True\n elif choice in valid_false:\n boolean_val = False\n else:\n raise ValueError(f'Valid boolean values are {valid_true + valid_false}')\n\n return boolean_val\n\n\ndef sort_str_list(l):\n \"\"\"\n Sorts list of strings of integers.\n \"\"\"\n int_list = np.fromiter(l, dtype=int)\n string_list = np.sort(int_list).astype(str)\n\n return string_list\n\n\n\ndef percentDiscrepancy(exp, ref):\n return (exp - ref) / ref * 100\n\n\ndef SN(signal, noise):\n return np.sqrt(np.sum( signal**2 / noise**2 ))\n\n\ndef get_theory_dicts(nells=None,lmax=9000,grad=True):\n\n #Initialize\n if nells is None: nells = {'TT':0,'EE':0,'BB':0} # noise (dimensionless)\n ls = np.arange(lmax+1)\n ucls = {}\n tcls = {}\n unlensedcls = {}\n\n #Load Theory\n thloc = config['data_path'] + config['theory_root']\n theory = cosmology.loadTheorySpectraFromCAMB(thloc,get_dimensionless=False)\n ells,gt,ge,gb,gte = np.loadtxt(f\"{thloc}_camb_1.0.12_grads.dat\",unpack=True,usecols=[0,1,2,3,4])\n\n #Repackage Theory into Dictionaries\n ucls['TT'] = omaps.interp(ells,gt)(ls) if grad else theory.lCl('TT',ls)\n ucls['TE'] = omaps.interp(ells,gte)(ls) if grad else theory.lCl('TE',ls)\n ucls['EE'] = omaps.interp(ells,ge)(ls) if grad else theory.lCl('EE',ls)\n ucls['BB'] = omaps.interp(ells,gb)(ls) if grad else theory.lCl('BB',ls)\n unlensedcls['TT'] = theory.uCl('TT',ls)\n unlensedcls['TE'] = theory.uCl('TE',ls)\n unlensedcls['EE'] = theory.uCl('EE',ls)\n unlensedcls['BB'] = theory.uCl('BB',ls)\n ucls['kk'] = theory.gCl('kk',ls) # this doesn't exist\n tcls['TT'] = theory.lCl('TT',ls) + nells['TT']\n tcls['TE'] = theory.lCl('TE',ls)\n tcls['EE'] = theory.lCl('EE',ls) + nells['EE']\n tcls['BB'] = theory.lCl('BB',ls) + nells['BB']\n\n return ls, unlensedcls, ucls, tcls\n\n\n\n#DEPRECATED!\n#Mat's version in orphics is better documented, can take pre-calculated pixel area maps, and works for FFTs and equal area maps\n# def wn(mask1, n1, mask2=None, n2=None):\n# \"\"\"TODO: check pixel area average\"\"\"\n# pmap = orphics.maps.psizemap(mask1.shape, mask1.wcs)\n# if mask2 is None:\n# output = np.sum(mask1**n1 * pmap) /np.pi / 4.\n# else:\n# output = np.sum(mask1**n1 * mask2**n2 * pmap) /np.pi / 4.\n# return output\n\ndef getClassyCIB(spectra, nu_list, params={}, emulFlag=False, kappaFlag=False):\n \"\"\"Wrapper for classy_sz calculations of CIB auto and CIB x lensing theory spectra.\n\n Parameters\n ----------\n spectra : str\n Which CIB spectra do you want? Options: 'auto', 'cross', 'both'\n nu_list : float\n List of observing frequencies as numbers in GHz.\n params : dict, optional\n Dictionary of classy_sz parameters, by default empty\n emulFlag : bool, optional\n Use the cosmopower emulators?, by default False\n kappaFlag : bool, optional\n return kappa autospectrum?, by defualt False\n\n Returns\n -------\n ells, Cls_dict\n Array of ells and a dictionary of Cls. The keys are 'auto' and 'cross', and each of those entries is itself a dictionary indexed by observing frequency as a string.\n \"\"\"\n\n if spectra.lower() not in ['both', 'cross', 'auto']:\n raise ValueError(\"Your 'spectra' variable is incorrect\")\n\n #Parameters for Cosmology Planck 14, https://arxiv.org/pdf/1303.5076.pdf, best-fit\n p14_dict={}\n p14_dict['h'] = 0.6711 \n p14_dict['omega_b'] = 0.022068\n p14_dict['Omega_cdm'] = 0.3175 - 0.022068/p14_dict['h']/p14_dict['h']\n p14_dict['A_s'] = 2.2e-9\n p14_dict['n_s'] = .9624\n p14_dict['k_pivot'] = 0.05\n p14_dict['tau_reio'] = 0.0925\n p14_dict['N_ncdm'] = 1\n p14_dict['N_ur'] = 0.00641\n p14_dict['deg_ncdm'] = 3\n p14_dict['m_ncdm'] = 0.02\n p14_dict['T_ncdm'] = 0.71611\n\n p_hm_dict = {}\n\n p_hm_dict['mass function'] = 'T10'\n p_hm_dict['concentration parameter'] = 'D08'\n p_hm_dict['delta for cib'] = '200m'\n p_hm_dict['hm_consistency'] = 1\n p_hm_dict['damping_1h_term'] = 0\n # Precision\n p_hm_dict['pressure_profile_epsabs'] = 1.e-8\n p_hm_dict['pressure_profile_epsrel'] = 1.e-3\n # HOD parameters for CIB\n p_hm_dict['M_min_HOD'] = pow(10.,10) # was M_min_HOD_cib\n\n #Grid Parameters\n # Mass bounds\n p_hm_dict['M_min'] = 1e8 * p14_dict['h'] # was M_min_cib\n p_hm_dict['M_max'] = 1e16 * p14_dict['h'] # was M_max_cib\n # Redshift bounds\n p_hm_dict['z_min'] = 0.07\n p_hm_dict['z_max'] = 6. # fiducial for MM20 : 6\n p_hm_dict['freq_min'] = 10.\n p_hm_dict['freq_max'] = 5e4 # fiducial for MM20 : 6\n p_hm_dict['z_max_pk'] = p_hm_dict['z_max']\n\n #Precision Parameters\n # Precision for redshift integal\n p_hm_dict['redshift_epsabs'] = 1e-40#1.e-40\n p_hm_dict['redshift_epsrel'] = 1e-4#1.e-10 # fiducial value 1e-8\n # Precision for mass integal\n p_hm_dict['mass_epsabs'] = 1e-40 #1.e-40\n p_hm_dict['mass_epsrel'] = 1e-4#1e-10\n # Precision for Luminosity integral (sub-halo mass function)\n p_hm_dict['L_sat_epsabs'] = 1e-40 #1.e-40\n p_hm_dict['L_sat_epsrel'] = 1e-3#1e-10\n # Multipole array\n p_hm_dict['dlogell'] = 1\n p_hm_dict['ell_max'] = 3968.0\n p_hm_dict['ell_min'] = 2.0\n\n #CIB Parameters\n p_CIB_dict = {}\n p_CIB_dict['alpha'] = 0.36\n p_CIB_dict['T_o'] = 24.4\n p_CIB_dict['beta'] = 1.75\n p_CIB_dict['gamma'] = 1.7\n p_CIB_dict['delta'] = 3.6\n p_CIB_dict['M_eff'] = 10**12.6\n p_CIB_dict['L_o'] = 6.4e-8\n p_CIB_dict['sigma_sq'] = 0.5\n\n # nu_list = [353,545,857]\n nu_list_str = str(nu_list)[1:-1] # Note: this must be a single string, not a list of strings!\n\n #Frequency Parameters\n p_freq_dict = {}\n p_freq_dict['cib_frequency_list_num'] = len(nu_list)\n p_freq_dict['cib_frequency_list_in_GHz'] = nu_list_str\n\n #Flux Cuts\n cib_fcut_dict = {}\n\n #Planck flux cut, Table 1 in https://arxiv.org/pdf/1309.0382.pdf\n cib_fcut_dict['100'] = 400\n cib_fcut_dict['143'] = 350\n cib_fcut_dict['217'] = 225\n cib_fcut_dict['353'] = 315\n cib_fcut_dict['545'] = 350\n cib_fcut_dict['857'] = 710\n cib_fcut_dict['3000'] = 1000\n\n def _make_flux_cut_list(cib_flux, nu_list):\n \"\"\"\n Make a string of flux cut values for given frequency list to pass into class_sz\n Beware: if frequency not in the flux_cut dictionary, it assigns 0\n \"\"\"\n cib_flux_list = []\n keys = list(cib_flux.keys())\n for i,nu in enumerate(nu_list):\n if str(nu) in keys:\n cib_flux_list.append(cib_flux[str(nu)])\n else:\n cib_flux_list.append(0)\n return cib_flux_list\n\n #Format Flux Cuts\n cib_flux_list = _make_flux_cut_list(cib_fcut_dict, nu_list)\n\n #Add Flux Cuts\n p_freq_dict['cib_Snu_cutoff_list [mJy]'] = str(list(cib_flux_list))[1:-1]\n p_freq_dict['has_cib_flux_cut'] = 1\n\n # M.set({# class_sz parameters:\n # 'output':'lens_cib_1h,lens_cib_2h', \n \n # #CIB Parameters\n # 'Redshift evolution of dust temperature' : 0.36,\n # 'Dust temperature today in Kelvins' : 24.4,\n # 'Emissivity index of sed' : 1.75,\n # 'Power law index of SED at high frequency' : 1.7,\n # 'Redshift evolution of L - M normalisation' : 3.6,\n # 'Most efficient halo mass in Msun' : 10.**12.6,\n # 'Normalisation of L - M relation in [Jy MPc2/Msun]' : 6.4e-8,\n # 'Size of of halo masses sourcing CIB emission' : 0.5,\n\n # #M_min_HOD is the threshold above which nc = 1:\n # 'M_min_HOD' : 10.**10,\n\n # 'M_min' : 1e10*common_settings['h'],\n # 'M_max' : 1e16*common_settings['h'],\n # 'z_min' : 0.06,\n # 'z_max' : 15,\n\n # ### Precision\n # #redshift_epsabs : 1.0e-40\n # #redshift_epsrel : 0.0005\n # #mass_epsabs : 1.0e-40\n # #mass_epsrel : 0.0005\n # 'dell' : 64,\n # #multipoles_sz : 'ell_mock'\n # 'ell_max' : 3968.0,\n # 'ell_min' : 2.0,\n # 'ndim_masses' : 100,\n # 'ndim_redshifts' : 100,\n \n # 'cib_frequency_list_num' : Nfreq,\n # #'cib_frequency_list_in_GHz' : '217,353,545,857,3000',\n # 'cib_frequency_list_in_GHz' : '353, 545, 857'\n # })\n\n #Create Class Object\n M = Class()\n \n #Add Spectra\n outspec = []\n if spectra.lower() == 'both' or spectra == 'auto':\n outspec.append('cib_cib_1h,cib_cib_2h')\n if spectra.lower() == 'both' or spectra == 'cross':\n outspec.append('lens_cib_1h,lens_cib_2h')\n if kappaFlag:\n outspec.append('lens_lens_1h,lens_lens_2h')\n M.set({'output': ','.join(outspec)})\n\n #Add Parameters\n M.set(p14_dict)\n M.set(p_hm_dict)\n M.set(p_CIB_dict)\n M.set(p_freq_dict)\n if params:\n M.set(params)\n \n #Compute Spectra\n if emulFlag:\n M.compute_class_szfast()\n else:\n M.compute()\n \n #Extract Spectra\n Dl_spectra = {}\n if spectra.lower() == 'both' or spectra == 'auto':\n Dl_spectra['auto'] = M.cl_cib_cib()\n if spectra.lower() == 'both' or spectra == 'cross':\n Dl_spectra['cross'] = M.cl_lens_cib()\n M.struct_cleanup()\n M.empty()\n\n ells = []\n Cls_dict = {}\n #Cycle Through CIB Spectra\n for spec_key, Dl_dict in Dl_spectra.items():\n if spec_key.lower() in ['cross', 'both']:\n freq_list = sort_str_list( list(Dl_dict.keys()) )\n else:\n freq_list = Dl_dict.keys()\n Cls_dict[spec_key] = {}\n\n #Cycle through Frequencies\n for nu in freq_list:\n #Get ells\n if not len(ells):\n ells = np.array(Dl_dict[nu]['ell'])\n\n #Get Spectra\n Dl_total = np.array(Dl_dict[nu]['1h']) + np.array(Dl_dict[nu]['2h'])\n Cl_total = dl2cl(Dl_total, ells= ells)\n\n #Save Spectra\n Cls_dict[spec_key][nu] = Cl_total\n \n #Get Kappa Autospectrum\n if kappaFlag:\n Dl_phi = M.cl_lens_lens()\n Cl_phi = dl2cl(Dl_phi, ells= ells)\n Cls_dict['lens'] = Cl_phi\n\n return ells, Cls_dict\n \n \n\ndef phi2kappa(phi, type= 'spectrum', ells= None):\n\n if ells is None:\n ells = np.arange(len(phi))\n\n factor = ells * (ells + 1.) / 2.\n\n if type == 'spectrum':\n kappa = factor**2 * phi\n elif type == 'map':\n kappa = factor**2 * phi\n else:\n raise ValueError('Invalid \"type\" argument')\n\n return kappa\n\n\ndef dl2cl(Dl, ells= None):\n \n if ells is None:\n ells = np.arange(len(Dl))\n \n factor = ells * (ells+1) / (2*np.pi)\n \n return Dl / factor\n\n\ndef cl2dl(Cl, ells= None):\n \n if ells is None:\n ells = np.arange(len(Cl))\n \n factor = ells * (ells+1) / (2*np.pi)\n \n return Cl * factor\n\n\n\n\ndef bin_cen2edg(centers, dbins= None):\n \"\"\"\n Shifts from midpoints of bins to the edges of the bins (inclusive of the lower and upper endpoints).\n\n Parameters\n ----------\n centers : 1darray\n Midpoints of bins\n dbins : 1darray, optional\n Size of each bin if you have unevenly spaced bins. By default None\n\n Returns\n -------\n 1darray\n Edges of the bins (including both the lowest and highest edges). Length is 1+len(centers)\n \"\"\"\n if dbins is None:\n delta = centers[1] - centers[0]\n dbins = np.ones(centers.shape) * delta\n\n right_edges = centers - dbins/2\n edges = np.append(right_edges, right_edges[-1] + delta) # doing this instead of centers[-1] * delta/2 avoids issues with odd deltas\n\n return edges\n\n\ndef bin_edg2cen(edges):\n \"\"\"\n Shifts from the edges of bins to their midpoints. Works for unevenly sized bins.\n\n Parameters\n ----------\n edges : 1darray\n Edges of the bins, including the left edge of the first bin and right edge of the last bin.\n\n Returns\n -------\n 1darray\n Midponts of the bins. Length is len(edges) - 1.\n \"\"\"\n return (edges[1:] + edges[:-1]) / 2\n\n\ndef binning(binsize, xdata, ydata, start='midpoint'):\n \"\"\"\n Bins x and y data. Handles NaNs just fine. Only works for bins of equal length. For arbitrary or uneven spacing (e.g. log), use orphics.\n \"\"\"\n\n #Bin xdata\n if start.lower() == 'midpoint':\n midpoint = binsize//2 - 1 # midpoint if binsize = odd and to the left of midpoint if binsize = even\n xbins = xdata[midpoint : (xdata.size//binsize) * binsize : binsize]\n elif start.lower() == 'left':\n xbins = xdata[: (xdata.size//binsize) * binsize : binsize] \n else:\n raise ValueError('Need a valid')\n \n #Bin ydata\n ybins = ydata[:(ydata.size//binsize) * binsize] # drop the last bin if it's too small\n ybins = np.nanmean(ybins.reshape(-1, binsize), axis=-1)\n\n return xbins, ybins\n","repo_name":"Yogesh3/ymfuncs","sub_path":"myfuncs/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":15038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"19096963672","text":"# -*- coding: utf-8 -*-\n#\nimport helpers\n\n\ndef plot():\n from matplotlib import pyplot as plt\n import numpy as np\n\n data = np.zeros((3, 3))\n data[:2, :2] = 1.0\n\n fig = plt.figure()\n\n ax1 = plt.subplot(131)\n ax2 = plt.subplot(132)\n ax3 = plt.subplot(133)\n axes = [ax1, ax2, ax3]\n\n for ax in axes:\n im = ax.imshow(data)\n fig.colorbar(im, ax=ax, orientation=\"horizontal\")\n\n return fig\n\n\ndef test():\n phash = helpers.Phash(plot())\n assert phash.phash == \"6bc42bd46a95c03f\", phash.get_details()\n return\n","repo_name":"moritzmuehlbauer/matplotlib2tikz","sub_path":"test/test_subplots_with_colorbars.py","file_name":"test_subplots_with_colorbars.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"16"}
+{"seq_id":"5226091652","text":"from typing import Union, Literal\nfrom fbi.connection import __get_api_response\n\n\ndef wanted(person_classification: Union[Literal['Main'], Literal['Accomplice'], Literal['Victim']] = None,\n page_size: int = 20, page: int = 1, sort_order: Union[Literal['asc'], Literal['desc']] = None) -> dict:\n \"\"\"\n Get listing of wanted people\n :param person_classification: person classification\n :param page_size: number of items to return\n :param page: page of result listing\n :param sort_order: result sort order\n :return: a list of result dictionaries\n \"\"\"\n if person_classification is None:\n person_classification = \"\"\n else:\n person_classification = f\"&person_classification={person_classification}\"\n\n if sort_order is None:\n sort_order = \"\"\n else:\n sort_order = f\"&sort_order={sort_order}\"\n\n response = __get_api_response(f\"https://api.fbi.gov/@wanted?pageSize={page_size}&page={page}{person_classification}\")\n return response['items']\n\n\ndef wanted_person(person_id: str) -> dict:\n \"\"\"\n Retrieve information on wanted person\n :param person_id: id of wanted person\n :return: a dictionary of person's information\n \"\"\"\n return __get_api_response(f\"https://api.fbi.gov/@wanted-person/{person_id}\")\n\n\ndef art_crimes(page_size: int = 20, page: int = 1, sort_order: Union[Literal['asc'], Literal['desc'], None] = None,\n reference_number: Union[int, str] = None) -> dict:\n \"\"\"\n Get listing of national art theft\n :param page_size: number of items to return\n :param page: page of result listing\n :param sort_order: result sort order\n :param reference_number: art crime reference number\n :return: a list of result dictionaries\n \"\"\"\n if reference_number is None:\n reference_number = \"\"\n else:\n reference_number = f\"&referenceNumber={reference_number}\"\n\n if sort_order is None:\n sort_order = \"\"\n else:\n sort_order = f\"&sort_order={sort_order}\"\n\n response = __get_api_response(f\"https://api.fbi.gov/@artcrimes?pageSize={page_size}&page={page}\"\n f\"{sort_order}{reference_number}\")\n return response['items']\n\n\ndef art_crime(crime_id: str) -> dict:\n \"\"\"\n Retrieve information on an art crime\n :param crime_id: id of an art crime\n :return: dictionary of an art crime's information\n \"\"\"\n return __get_api_response(f\"https://api.fbi.gov/@artcrimes/{crime_id}\")\n","repo_name":"rly0nheart/fbi-api","sub_path":"fbi/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"16"}
+{"seq_id":"36425844143","text":"from decimal import Decimal\nfrom domain import Rates\nimport json\nimport urllib.request\n\nAPI_KEY = 'c15dab3a23b14a1d82ef0ab60b3b417d'\nURL = \"https://openexchangerates.org/api/latest.json?app_id={}\".format(API_KEY)\n\n\ndef build_rates_db() -> Rates:\n req = urllib.request.Request(URL)\n with urllib.request.urlopen(req) as response:\n result = json.loads(response.read().decode('utf-8'))\n\n rates = result['rates']\n base = result['base']\n timestamp = result['timestamp']\n\n rt = {k: Decimal(rates[k]) for k in rates}\n openexc_rates = Rates(base, rt, timestamp)\n #print(openexc_rates)\n return openexc_rates\n\n","repo_name":"evgenii-malov/interviews","sub_path":"CURR_XCHG_REST_14_03_18/datasources/openexc_datasource.py","file_name":"openexc_datasource.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"23479140545","text":"import tensorflow as tf\nimport numpy as np\n\nfrom layers import Mish, ScaledRandomUniform\nimport utils\n\n\n\nanchor_sizes = [\n [(12, 16), (19, 36), (40, 28)],\n [(36, 75), (76, 55), (72, 146)],\n [(142, 110), (192, 243), (459, 401)],\n]\nscales = [1.2, 1.1, 1.05]\n\n\ndef calc_loss(layer_id, gt, preds, debug=False):\n gt_boxes = gt[..., : 4]\n gt_labels = tf.cast(gt[..., 4], tf.int32)\n gt_count = tf.shape(gt_labels)[-1]\n gt_mask = tf.where(gt_labels == -1, 0.0, 1.0)\n layer_xywh, layer_obj, layer_cls = utils.decode_layer(preds, layer_id)\n cls_count = layer_cls.shape[-1]\n\n s = tf.shape(preds)\n batch_size = s[0]\n gw = s[1]\n gh = s[2]\n stride_x = 1 / gw\n stride_y = 1 / gh\n d = s[3]\n truth_mask = tf.zeros((batch_size, gw, gh, 3))\n\n box_loss = 0.0\n cls_loss = 0.0\n\n ix = tf.cast(tf.math.floor(tf.cast(gw, tf.float32) * gt_boxes[..., 0]), tf.int32)\n iy = tf.cast(tf.math.floor(tf.cast(gh, tf.float32) * gt_boxes[..., 1]), tf.int32)\n ix = tf.clip_by_value(ix, 0, gw - 1)\n iy = tf.clip_by_value(iy, 0, gh - 1)\n\n box_shape = tf.shape(gt_labels)\n zeros = tf.zeros_like(gt_labels, dtype=tf.float32)\n gt_shift = tf.stack([zeros, zeros, gt_boxes[..., 2], gt_boxes[..., 3]], axis=-1)\n gt_shift = tf.stack([gt_shift, gt_shift, gt_shift], axis=1)\n\n anchors_ws = [tf.cast(tf.fill(box_shape, anchor_sizes[layer_id][ir][0]), dtype=tf.float32) / 608.0 for ir in range(3)]\n anchors_hs = [tf.cast(tf.fill(box_shape, anchor_sizes[layer_id][ir][1]), dtype=tf.float32) / 608.0 for ir in range(3)]\n anchors = tf.stack([tf.stack([zeros, zeros, anchors_ws[ir], anchors_hs[ir]], axis=-1) for ir in range(3)], axis=1)\n\n ious = utils.calc_ious(gt_shift, anchors)\n ious_argmax = tf.cast(tf.argmax(ious, axis=1), dtype=tf.int32)\n batch_idx = tf.tile(tf.range(batch_size)[ : , tf.newaxis], [1, box_shape[-1]])\n\n indices = tf.stack([batch_idx, iy, ix, ious_argmax], axis=-1)\n pred_boxes = tf.gather_nd(layer_xywh, indices)\n box_loss = tf.math.reduce_sum(gt_mask * (1.0 - utils.calc_gious(pred_boxes, gt_boxes)))\n\n cls_one_hot = tf.one_hot(gt_labels, cls_count)\n pred_cls = tf.gather_nd(layer_cls, indices)\n cls_diffs = tf.math.reduce_sum(tf.math.square(pred_cls - cls_one_hot), axis=-1)\n cls_loss = tf.math.reduce_sum(gt_mask * cls_diffs)\n\n indices_not_null = tf.gather_nd(indices, tf.where(gt_labels != -1))\n truth_mask = tf.tensor_scatter_nd_update(truth_mask, indices_not_null, tf.ones_like(indices_not_null, dtype=tf.float32)[:,0])\n inv_truth_mask = 1.0 - truth_mask\n\n obj_loss = tf.math.reduce_sum(tf.math.square(1 - layer_obj) * truth_mask)\n gt_boxes_exp = tf.tile(tf.reshape(gt_boxes, (batch_size, 1, 1, 1, gt_count, 4)), [1, gw, gh, 3, 1, 1])\n pred_boxes_exp = tf.tile(tf.reshape(layer_xywh, (batch_size, gw, gh, 3, 1, 4)), [1, 1, 1, 1, gt_count, 1])\n iou_mask = tf.cast(tf.math.reduce_max(utils.calc_ious(gt_boxes_exp, pred_boxes_exp), axis=-1) < 0.7, tf.float32)\n obj_loss += tf.math.reduce_sum(tf.math.square(layer_obj) * inv_truth_mask * iou_mask)\n\n return (0.05 * box_loss + 1.0 * obj_loss + 0.5 * cls_loss) / tf.cast(batch_size, dtype=tf.float32)\n\n\n\n\nclass YOLOv4Model(tf.keras.Model):\n def __init__(self, classes_num=80, image_size=(608, 608)):\n\n self.classes_num = classes_num\n self.image_size = (image_size[0], image_size[1], 3)\n\n input = tf.keras.Input(shape=self.image_size)\n output = self.CSPDarknet53WithSPP()(input)\n output = self.YOLOHead()(output)\n super().__init__(input, output)\n\n self.loss_tracker = tf.keras.metrics.Mean(name=\"loss\")\n self.lr_tracker = tf.keras.metrics.Mean(name=\"lr\")\n self.mAP_tracker = tf.keras.metrics.Mean(name=\"mAP\")\n\n\n def fit(self, dataset, **kwargs):\n\n start_step = 1 + kwargs['steps_per_epoch'] * kwargs['initial_epoch']\n self.current_step = tf.Variable(start_step, trainable=False, dtype=tf.int32)\n self.total_steps = kwargs['epochs'] * kwargs['steps_per_epoch']\n super().fit(dataset, **kwargs)\n\n\n def train_step(self, data):\n\n input, gt_boxes = data\n with tf.GradientTape() as tape:\n output = self(input, training=True)\n loss0 = calc_loss(0, gt_boxes, output[0])\n loss1 = calc_loss(1, gt_boxes, output[1])\n loss2 = calc_loss(2, gt_boxes, output[2])\n total_loss = loss0 + loss1 + loss2\n gradients = tape.gradient(total_loss, self.trainable_variables)\n self.optimizer.apply_gradients(zip(gradients, self.trainable_variables))\n\n self.loss_tracker.update_state(total_loss)\n self.lr_tracker.update_state(self.optimizer.lr(self.current_step))\n self.current_step.assign_add(1)\n\n return {\"loss\" : self.loss_tracker.result(), \"lr\": self.lr_tracker.result()}\n\n def test_step(self, data):\n\n input, gt_boxes = data\n prediction = self(input, training=False)\n ap = tf.py_function(\n func=lambda *args: utils.calc_mAP(args[:-2], args[-2], args[-1]),\n inp=[*prediction, gt_boxes, self.classes_num],\n Tout=tf.float64,\n )\n self.mAP_tracker.update_state(ap)\n\n return {\"mAP\" : self.mAP_tracker.result()}\n\n\n @property\n def metrics(self):\n return [self.loss_tracker, self.mAP_tracker, self.lr_tracker]\n\n\n\n def load_weights(self, weights_file):\n if weights_file.endswith(\".h5\"):\n super().load_weights(weights_file)\n else:\n self._load_weights_yolo(weights_file)\n\n # load weights from darknet weight file\n def _load_weights_yolo(self, weights_file):\n with open(weights_file, \"rb\") as f:\n major, minor, revision = np.fromfile(f, dtype=np.int32, count=3)\n if (major * 10 + minor) >= 2:\n seen = np.fromfile(f, dtype=np.int64, count=1)\n else:\n seen = np.fromfile(f, dtype=np.int32, count=1)\n j = 0\n for i in range(110):\n conv_layer_name = \"conv2d_%d\" % i if i > 0 else \"conv2d\"\n bn_layer_name = \"batch_normalization_%d\" % j if j > 0 else \"batch_normalization\"\n\n conv_layer = self.get_layer(conv_layer_name)\n in_dim = conv_layer.input_shape[-1]\n filters = conv_layer.filters\n size = conv_layer.kernel_size[0]\n\n if i not in [93, 101, 109]:\n # darknet weights: [beta, gamma, mean, variance]\n bn_weights = np.fromfile(f, dtype=np.float32, count=4 * filters)\n # tf weights: [gamma, beta, mean, variance]\n bn_weights = bn_weights.reshape((4, filters))[[1, 0, 2, 3]]\n bn_layer = self.get_layer(bn_layer_name)\n j += 1\n else:\n conv_bias = np.fromfile(f, dtype=np.float32, count=filters)\n\n # darknet shape (out_dim, in_dim, height, width)\n conv_shape = (filters, in_dim, size, size)\n conv_weights = np.fromfile(f, dtype=np.float32, count=np.product(conv_shape))\n # tf shape (height, width, in_dim, out_dim)\n conv_weights = conv_weights.reshape(conv_shape).transpose([2, 3, 1, 0])\n\n if i not in [93, 101, 109]:\n conv_layer.set_weights([conv_weights])\n bn_layer.set_weights(bn_weights)\n else:\n conv_layer.set_weights([conv_weights, conv_bias])\n\n assert len(f.read()) == 0, \"failed to read all data\"\n\n\n\n\n def darknetConv(\n self, filters, size, strides=1, batch_norm=True, activate=True, activation=\"leaky\"\n ):\n def feed(x):\n if strides == 1:\n padding = \"same\"\n else:\n x = tf.keras.layers.ZeroPadding2D(((1, 0), (1, 0)))(x)\n padding = \"valid\"\n\n x = tf.keras.layers.Conv2D(\n filters=filters,\n kernel_size=size,\n strides=strides,\n padding=padding,\n use_bias=not batch_norm,\n kernel_initializer=ScaledRandomUniform(\n scale=tf.sqrt(2 / (size * size * self.image_size[2])), minval=-0.01, maxval=0.01\n ),\n kernel_regularizer=tf.keras.regularizers.l2(0.0005),\n )(x)\n\n if batch_norm:\n x = tf.keras.layers.BatchNormalization(moving_variance_initializer=\"zeros\", momentum = 0.9)(x)\n\n if activate:\n if activation == \"mish\":\n x = Mish()(x)\n elif activation == \"leaky\":\n x = tf.keras.layers.LeakyReLU(alpha=0.1)(x)\n\n return x\n\n return feed\n\n def darknetResidualBlock(self, filters, repeats=1, initial=False):\n def feed(x):\n filters2 = 2 * filters if initial else filters\n x = self.darknetConv(2 * filters, 3, strides=2, activation=\"mish\")(x)\n route = self.darknetConv(filters2, 1, activation=\"mish\")(x)\n x = self.darknetConv(filters2, 1, activation=\"mish\")(x)\n for i in range(repeats):\n skip = x\n x = self.darknetConv(filters, 1, activation=\"mish\")(x)\n x = self.darknetConv(filters2, 3, activation=\"mish\")(x)\n x = tf.keras.layers.Add()([skip, x])\n x = self.darknetConv(filters2, 1, activation=\"mish\")(x)\n x = tf.keras.layers.Concatenate()([x, route])\n x = self.darknetConv(2 * filters, 1, activation=\"mish\")(x)\n return x\n\n return feed\n\n def CSPDarknet53WithSPP(self):\n def feed(x):\n x = self.darknetConv(32, 3, activation=\"mish\")(x)\n x = self.darknetResidualBlock(32, initial=True)(x)\n x = self.darknetResidualBlock(64, repeats=2)(x)\n x = route_1 = self.darknetResidualBlock(128, repeats=8)(x)\n x = route_2 = self.darknetResidualBlock(256, repeats=8)(x)\n x = self.darknetResidualBlock(512, repeats=4)(x)\n x = self.darknetConv(512, 1)(x)\n x = self.darknetConv(1024, 3)(x)\n x = self.darknetConv(512, 1)(x)\n\n # SPP\n spp1 = tf.keras.layers.MaxPooling2D(pool_size=13, strides=1, padding=\"same\")(x)\n spp2 = tf.keras.layers.MaxPooling2D(pool_size=9, strides=1, padding=\"same\")(x)\n spp3 = tf.keras.layers.MaxPooling2D(pool_size=5, strides=1, padding=\"same\")(x)\n\n x = tf.keras.layers.Concatenate()([spp1, spp2, spp3, x])\n\n x = self.darknetConv(512, 1)(x)\n x = self.darknetConv(1024, 3)(x)\n x = self.darknetConv(512, 1)(x)\n return route_1, route_2, x\n\n return feed\n\n def yoloUpsampleConvBlock(self, filters):\n def feed(x, y):\n x = self.darknetConv(filters, 1)(x)\n x = tf.keras.layers.UpSampling2D()(x)\n y = self.darknetConv(filters, 1)(y)\n x = tf.keras.layers.Concatenate()([y, x])\n\n x = self.darknetConv(filters, 1)(x)\n x = self.darknetConv(2 * filters, 3)(x)\n x = self.darknetConv(filters, 1)(x)\n x = self.darknetConv(2 * filters, 3)(x)\n x = self.darknetConv(filters, 1)(x)\n\n return x\n\n return feed\n\n def yoloDownsampleConvBlock(self, filters):\n def feed(x, y):\n x = self.darknetConv(filters, 3, strides=2)(x)\n x = tf.keras.layers.Concatenate()([x, y])\n\n x = self.darknetConv(filters, 1)(x)\n x = self.darknetConv(2 * filters, 3)(x)\n x = self.darknetConv(filters, 1)(x)\n x = self.darknetConv(2 * filters, 3)(x)\n x = self.darknetConv(filters, 1)(x)\n\n return x\n\n return feed\n\n def yoloBboxConvBlock(self, filters):\n def feed(x):\n x = self.darknetConv(filters, 3)(x)\n x = self.darknetConv(3 * (self.classes_num + 5), 1, activate=False, batch_norm=False)(x)\n\n return x\n\n return feed\n\n def YOLOHead(self):\n def feed(x):\n route_1, route_2, route = x\n x = route_2 = self.yoloUpsampleConvBlock(256)(route, route_2)\n x = route_1 = self.yoloUpsampleConvBlock(128)(x, route_1)\n small_bbox = self.yoloBboxConvBlock(256)(x)\n x = self.yoloDownsampleConvBlock(256)(route_1, route_2)\n medium_bbox = self.yoloBboxConvBlock(512)(x)\n x = self.yoloDownsampleConvBlock(512)(x, route)\n large_bbox = self.yoloBboxConvBlock(1024)(x)\n\n return small_bbox, medium_bbox, large_bbox\n\n return feed\n","repo_name":"NVIDIA/DALI","sub_path":"docs/examples/use_cases/tensorflow/yolov4/src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":12700,"program_lang":"python","lang":"en","doc_type":"code","stars":4689,"dataset":"github-code","pt":"16"}
+{"seq_id":"42425623023","text":"#!/usr/bin/python3\n\nimport sys\n\n\ndef safe_function(fct, *args):\n try:\n result_of = fct(*args)\n return result_of\n except Exception as er:\n error_messages = \"Exception: {}\".format(er)\n print(error_messages, file=sys.stderr)\n return None\n","repo_name":"MMahmudd/alx-higher_level_programming","sub_path":"0x05-python-exceptions/101-safe_function.py","file_name":"101-safe_function.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"31563297925","text":"import cv2\nimport os\nimport pandas as pd\nimport numpy as np\n\ndef load_images_from_folder(folder):\n images = [] \n labels = []\n for filename in os.listdir(folder):\n img = cv2.imread(os.path.join(folder,filename))\n if img is not None:\n images.append(img)\n labels.append(ord(filename[0]) -97)\n return images, labels\n\nfolder=\"testImages\"\nimgs, labels= load_images_from_folder(folder)\ncol = pd.read_csv('/home/alecsoc/Desktop/mygit/EECS504_Project_F20/sign_mnist_test.csv').columns\ndata1 = pd.read_csv('/home/alecsoc/Desktop/mygit/EECS504_Project_F20/sign_mnist_test.csv')\ndata = np.zeros((len(imgs), 28*28+1))\nfor i in range(len(imgs)):\n gray = cv2.cvtColor(imgs[i], cv2.COLOR_BGR2GRAY)\n grayF = gray.reshape((1,28*28))\n data[i,:] = np.insert(grayF,0,labels[i])\nnewData = pd.DataFrame(data,columns = col)\ndata2 = data1.append(newData)\ndata2.to_csv('AlecData.csv',index =False)\n\n\n","repo_name":"AlecS19/EECS504_Project_F20","sub_path":"dataCreation.py","file_name":"dataCreation.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"75046008007","text":"#https://www.acmicpc.net/problem/1213\n#Implementation, Greedy\n\nfrom collections import defaultdict \n\ns = list(input())\ns.sort()\n\nd = defaultdict(int)\nfor i in s:\n d[i] += 1\n\nc = []\ncnt = 0\nfor key, val in d.items():\n if val%2 != 0:\n cnt += 1\n c.append(key)\n s.remove(key)\n\n if cnt > 1:\n print(\"I'm Sorry Hansoo\")\n break\nelse:\n l = []\n for i in range(0, len(s), 2):\n l.append(s[i])\n\n result = l+c+l[::-1]\n print(''.join(result))\n\n#Counter 사용#\nfrom collections import Counter \n\ns = list(input())\ns.sort()\n\ncounter = Counter(s)\n\nc = []\ncnt = 0\nfor i in counter:\n if counter[i]%2!=0:\n cnt += 1\n c.append(i)\n s.remove(i)\n\n if cnt > 1:\n print(\"I'm Sorry Hansoo\")\n break\nelse:\n l = []\n for i in range(0, len(s), 2):\n l.append(s[i])\n\n result = l+c+l[::-1]\n print(''.join(result))\n ","repo_name":"JeongHo16/Coding_Test","sub_path":"Problems/python/boj_팰린드롬만들기.py","file_name":"boj_팰린드롬만들기.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"44239756330","text":"from dateutil.parser import parse as parse_date\n\nfrom kp_scrapers.lib.parser import may_strip\nfrom kp_scrapers.models.normalize import DataTypes\nfrom kp_scrapers.spiders.bases.mail import MailSpider\nfrom kp_scrapers.spiders.charters import CharterSpider\nfrom kp_scrapers.spiders.charters.banchero_vlcc import normalize\n\n\nclass BancheroCostaVLCCSpider(CharterSpider, MailSpider):\n name = 'BCR_Fixtures_VLCC'\n provider = 'Banchero'\n version = '1.0.1'\n produces = [DataTypes.SpotCharter, DataTypes.Vessel]\n\n spider_settings = {\n # push items on GDrive spreadsheet\n 'KP_DRIVE_ENABLED': True,\n # notify in Slack the document is ready\n 'NOTIFY_ENABLED': True,\n }\n\n def parse_mail(self, mail):\n \"\"\"\n\n Args:\n mail (Mail):\n\n Returns:\n SpotCharter:\n\n \"\"\"\n reported_date = parse_date(mail.envelope['date']).strftime('%d %b %Y')\n start_processing = False if 'wake up' not in mail.envelope['subject'].lower() else True\n\n for tr_sel in self.select_body_html(mail).xpath('//tr'):\n row = [\n may_strip(''.join(td_sel.xpath('.//text()').extract()))\n for td_sel in tr_sel.xpath('.//td')\n ]\n\n if 'med/black sea' in row:\n start_processing = True\n continue\n\n # wake up attachment has unneccesary tables\n if len(row) < 8:\n continue\n\n if start_processing:\n raw_item = {str(idx): row[idx] for idx, r in enumerate(row)}\n\n raw_item.update(provider_name=self.provider, reported_date=reported_date)\n yield normalize.process_item(raw_item)\n","repo_name":"theHausdorffMetric/test","sub_path":"kp_scrapers/spiders/charters/banchero_vlcc/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"34273413740","text":"import os\nimport json\nfrom flask import Flask\nimport pytest\nfrom api.routes import config_routes\nfrom api.config import Config\nfrom flask_sqlalchemy import SQLAlchemy\n\n# app = Flask(__name__)\n# @pytest.fixture\n# def client():\n \nroot_url = \"/todo/api/v1.0/\"\n\napp = Flask(__name__)\napp.config.from_object(Config)\ndb = SQLAlchemy(app)\nconfig_routes(app, db)\nclient = app.test_client()\n\ndef test_base_route(): \n url = \"/\"\n response = client.get(url)\n assert b'Hello' in response.get_data()\n assert response.status_code == 200\n\ndef test_tasks_list():\n url = root_url + \"tasks\"\n response = client.get(url)\n assert response.status_code == 200\n # assert b'[]' in response.get_data()\n\n\ndef test_retrieve_task():\n url = root_url + \"tasks/1\"\n response = client.get(url)\n assert response.status_code == 200\n assert b'\"id\": 1' in response.get_data()\n\ndef test_create_task():\n url = root_url + \"tasks\"\n request_data = {\n \"description\": \"hmmm\",\n \"id\": \"4\",\n \"title\": \"WOW AMZING\"\n }\n response = client.post(url,\n data = json.dumps(request_data),\n content_type = 'application/json')\n assert response.status_code == 200\n assert \"Success\" or \"Error\" in response.get_data()\n\ndef test_update_task():\n url = root_url + \"tasks/1\"\n request_data = {\n \"description\": \"hmmm\"\n }\n response = client.put(url,\n data = json.dumps(request_data),\n content_type = 'application/json')\n\n assert response.status_code == 200\n\n# def test_delete_task():\n# url = root_url + \"tasks/1\"\n# response = client.delete(url)\n# # assert response.status_code == 204","repo_name":"usamasubhani/todo-rest","sub_path":"tests/test_routes.py","file_name":"test_routes.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"26279126674","text":"# This is the Driver module of the Amazon Textract program.\n# Author: Guangqi Li \n# Import the Utility module\nimport Amazon_Textract_Utility as Utility\n# First check whether the tracking csv exists. If not, create one.\nUtility.tracking_csv()\n# Get the progress of the extraction.\ntracking_list = Utility.track_progress()\n# Call the extraction functions.\nfor j in range(tracking_list[1],tracking_list[0]):\n # If you want to extract forms instead of tables, replace the \"Utility.Amazon_tesseract_tables(j)\" by \"Utility.Amazon_tesseract_forms(j)\"\n Utility.Amazon_tesseract_tables(j)\n","repo_name":"GLiUMN/MergentProcessing","sub_path":"Step_3/Amazon_Textract_Driver.py","file_name":"Amazon_Textract_Driver.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"32889901105","text":"def detectLoop(head):\n #code here\n start = head\n forward = head\n while(start and forward and forward.next):\n start = start.next\n forward = forward.next.next\n if start == forward:\n return True\n return False","repo_name":"AgrimNautiyal/Problem-solving","sub_path":"linked_list/loop_present/detect_loop_floyds_circling_algorithm_2_pointer.py","file_name":"detect_loop_floyds_circling_algorithm_2_pointer.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"71023930888","text":"import requests\nfrom bs4 import BeautifulSoup\nurl = \"https://stackoverflow.com/questions/tagged/python\"\nr = requests.get(url)\nques_lst = []\nsoup = BeautifulSoup(r.text, 'html.parser')\nques_summary = soup.find_all('div', class_='s-post-summary--content')\nfor summary in ques_summary:\n question = summary.find(class_='s-link').text\n ques_lst.append(question)\nprint(*ques_lst, sep = \"\\n\")\n \n\n\n","repo_name":"vamshisurya/WebScrapping","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"1017613647","text":"\n\ndef intersection(a, b):\n result = []\n for i in a:\n for j in b:\n if i == j:\n result.append(i)\n return sorted(result)\n\n\ndef reunion(a, b):\n result = []\n for i in a:\n result.append(i)\n for j in b:\n if j not in result:\n result.append(j)\n return sorted(result)\n\n\ndef difference(a, b):\n result = []\n for i in a:\n result.append(i)\n for j in b:\n if j in result:\n result.remove(j)\n return sorted(result)\n\n# def operation(a, b):\n# return (a intersectat cu b, a reunit cu b, a - b, b - a)\n\n\na = [1, 3, 5, 7]\nb = [2, 8, 12, 5, 9]\nprint(difference(b, a))\n","repo_name":"emilianraduu/an3semestru1","sub_path":"Python/Laborator 2/ex4.py","file_name":"ex4.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"19678770322","text":"from classes.helpers import LoopHelper\nimport sys\nimport argparse\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description='''Usage python PATHTO/bundle_check.py ROOTDIR ''')\n parser.add_argument('path', nargs='*', default=[1], help='root dir to check for bundles')\n args = parser.parse_args()\n\n print(\"Bundle check in dir: \" + sys.argv[1])\n LoopHelper.LoopHelper().loop_through(sys.argv[1])\n","repo_name":"yirez/BundleChecker","sub_path":"bundle_check.py","file_name":"bundle_check.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"74125382088","text":"import tkinter as tk\n\n# Create a new window and configure it\nwindow = tk.Tk()\nwindow.title(\"Miles to Km Converter\")\nwindow.minsize(width=300, height=200)\nwindow.config(padx=50, pady=50)\n\n# Entry widget for user input\nmiles_entry = tk.Entry(width=10, justify=\"center\")\nmiles_entry.grid(column=1, row=0, padx=10, pady=10)\n\n# Label for miles\nmiles_label = tk.Label(text=\"Miles\")\nmiles_label.grid(column=2, row=0, padx=10, pady=10)\n\n# Label for \"is equal to\" text\nequal_label = tk.Label(text=\"is equal to\")\nequal_label.grid(column=0, row=1, padx=10, pady=10)\n\n# Label for the converted value\nconversion_value = 0.00\nconverted_label = tk.Label(text=f\"{conversion_value}\")\nconverted_label.grid(column=1, row=1, padx=10, pady=10)\n\n# Label for km\nkm_label = tk.Label(text=\"Km\")\nkm_label.grid(column=2, row=1, padx=10, pady=10)\n\n# Function to perform the conversion\ndef calculate():\n conversion_value = round(float(miles_entry.get()) * 1.60934, 2)\n converted_label.config(text=f\"{conversion_value}\")\n\n# Button to trigger the conversion\ncalculate_button = tk.Button(text=\"Calculate\", command=calculate)\ncalculate_button.grid(column=1, row=2, padx=10, pady=10)\n\n# Start the main event loop to handle user interactions with the GUI\nwindow.mainloop()\n","repo_name":"dannychan0510/100-days-of-code","sub_path":"day-27-miles-to-km-converter/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"39607858781","text":"import cv2\nimport numpy as np\nimport time\n\n\ndef multi_template(image, temp):\n img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n temp_gray = cv2.cvtColor(temp, cv2.COLOR_BGR2GRAY)\n\n res_ = cv2.matchTemplate(img_gray, temp_gray, cv2.TM_CCOEFF_NORMED)\n\n w, h = temp_gray.shape[:2]\n\n threshold = 0.75\n loc = np.where(res_ >= threshold)\n print(\"# Check ~\")\n\n pixel_ = 50\n\n T_count = 4\n\n th1, th2, cnt = 0, 0, 0\n pt_data = []\n F_i = len(loc[0])-2\n\n for i in range(len(loc[0])-1):\n check1 = abs(loc[0][i] - loc[0][i+1])\n check2 = abs(loc[1][i] - loc[1][i+1])\n\n if check1 > pixel_ and check2 > pixel_:\n th1 = i + 1\n cnt += 1\n # print(\"# \", check1, \" < = > \", th2, \" - \", th1, \" | Current Counts : \", cnt)\n new_pt = tuple([int(np.mean(loc[1][th2:th1])), int(np.mean(loc[0][th2:th1]))])\n pt_data.append(new_pt)\n th2 = th1\n\n if cnt + 1 == T_count or i == F_i:\n new_pt = tuple([int(np.mean(loc[1][th2:])), int(np.mean(loc[0][th2:]))])\n pt_data.append(new_pt)\n # print(\"# \", check1, \" < = > \", th2, \" - End\", \" | Current Counts : \", cnt+1)\n print(\"# Done ~\")\n break\n\n for i in range(len(pt_data)):\n cv2.rectangle(image, pt_data[i], (pt_data[i][0] + w, pt_data[i][1] + h), (0, 0, 255), 2)\n print(\"# Mark Point Info : (\", pt_data[i], \")\")\n\n return image\n\n\ndef resize_img(image_, ratio=1.0):\n h, w = image_.shape[:2]\n image_ = cv2.resize(image_, (int(ratio * w), int(ratio * h)))\n return image_\n\n\nif __name__ == \"__main__\":\n # obj_image1 = cv2.imread(\"D:\\\\temp5.png\")\n obj_image2 = cv2.imread(\"D:\\\\FF_.png\")\n temp_image = cv2.imread(\"D:\\\\AOI_STI\\\\images\\\\MarkPoint\\\\MarkPointTemplate1.png\")\n\n tic = time.time()\n\n # obj_image1 = resize_img(obj_image1, 0.4)\n obj_image2 = resize_img(obj_image2, 0.4)\n temp_image = resize_img(temp_image, 0.4)\n\n # out_image1 = multi_template(obj_image1, temp_image)\n out_image2 = multi_template(obj_image2, temp_image)\n print(\"# Total Spent Times : %.3f ms\" % ((time.time() - tic)*1000))\n\n # out_image1 = resize_img(out_image1)\n out_image2 = resize_img(out_image2)\n # cv2.imshow(\"Out1\", out_image1)\n cv2.imshow(\"Out2\", out_image2)\n # cv2.imwrite(\"D:\\\\out1.png\", out_image1)\n cv2.imwrite(\"D:\\\\out2.png\", out_image2)\n cv2.waitKey()\n","repo_name":"gogo12235LYH/Image-Processing-Base","sub_path":"Muti_Template.py","file_name":"Muti_Template.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"37358773994","text":"\nfrom asyncio import FastChildWatcher\nfrom django.shortcuts import HttpResponse\nfrom django.http import JsonResponse\n\nimport json\nimport time\nimport os\n\nfrom HModules import HMySQL, HConfig, HActuator\n\nsql = HMySQL.HSQL('HHOME')\ncam = HActuator.CAM()\n\nMDIR = 'HModules'\nFACES = MDIR + '/baseFaces'\nif not os.path.isdir(FACES): os.mkdir(FACES)\nCONFS = MDIR + '/conf'\nif not os.path.isdir(CONFS): os.mkdir(CONFS)\n\nlightConf = HConfig.CONFIG(CONFS + '/light_conf', CONFS + '/light_conf_reset')\ndhtConf = {\n 'temperature': 24,\n 'humidity': 60,\n 'water_auto': True,\n 'water_state': False,\n 'heat_auto': True,\n 'heat_state': False,\n}\ndhtConf = HConfig.CONFIG(CONFS + '/dht_conf', CONFS + '/dht_conf_reset', dhtConf)\n\ndef index(request):\n return HttpResponse('这不是你该来的地方')\n\n############################## 设置系列 ##############################\n\ndef set_hconfig(change_info: dict) -> bool:\n with open('HModules/thresholds', encoding='utf8') as f: hconfig = json.loads(f.readline())\n for k, v in change_info.items():\n if k in hconfig: hconfig[k] = v\n with open('HModules/thresholds_reset', 'w', encoding='utf8') as f: f.write(json.dumps(hconfig))\n return True\n\ndef set_temperature(request):\n query_data = json.loads(request.body)\n rdata = dict()\n rdata['temperature'] = float(query_data['num'])\n set_hconfig(rdata)\n rdata['state'] = 'ok'\n return JsonResponse(rdata)\n\ndef set_humidity(request):\n query_data = json.loads(request.body)\n rdata = {'pid': query_data['houseNum']}\n rdata['humidity'] = int(query_data['num'])\n set_hconfig(rdata)\n rdata['state'] = 'ok'\n return JsonResponse(rdata)\n\ndef set_light(request):\n r\"\"\"\n POST request\n 设置灯光配置,请求数据\n 必须字段:\n houseNum -- 节点 id\n lightId -- 灯光配置 id\n 非必须字段:\n name -- 灯光名\n local -- 灯光安置地点\n light -- 灯光亮度\n color -- 灯光颜色\n state -- 灯光状态 1 - 开,0 - 关\n \"\"\"\n query_data = json.loads(request.body)\n rdata = {'pid': query_data['houseNum']}\n for newConf in query_data['setLights']:\n lightId = str(newConf['lightId'])\n conf = lightConf.get_data([lightId])\n for k in conf:\n if k in newConf:\n conf[k] = newConf[k]\n lightConf.save()\n rdata['config'] = lightConf.get_data()\n rdata['state'] = 'ok'\n return JsonResponse(rdata)\n\ndef set_water(request):\n query_data = json.loads(request.body)\n rdata = dict()\n rdata['water_auto'] = False\n rdata['water_state'] = bool(query_data['status'])\n set_hconfig(rdata)\n rdata['state'] = 'ok'\n return JsonResponse(rdata)\n\ndef set_curtain(request):\n query_data = json.loads(request.body)\n rdata = dict()\n rdata['curtain_auto'] = False\n rdata['curtain_state'] = bool(query_data['status'])\n set_hconfig(rdata)\n rdata['state'] = 'ok'\n return JsonResponse(rdata)\n\n############################## 获取系列 ##############################\n\ndef get_ports(request):\n rdata = {'ports': sql.get_ports()}\n rdata['state'] = 'ok'\n return JsonResponse(rdata)\n\ndef get_data(request):\n # print(f\"get_data = {request.GET}\")\n r\"\"\"\n GET request\n \"\"\"\n rdata = dict()\n rdata['pid'] = request.GET['houseNum'][0]\n if 'startTime' in request.GET and 'endTime' in request.GET:\n rdata['start_date'] = request.GET['startTime']\n rdata['end_date'] = request.GET['endTime']\n else:\n rdata['start_date'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time() - 24*3600))\n rdata['end_date'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n rdata['data_type'] = 'dht'\n dht_data = sql.get_data(rdata)\n # rdata['data_type'] = 'light'\n # light_data = sql.get_data(rdata)\n # return JsonResponse({'state': 'ok', 'dht_data': dht_data, 'light_data': light_data})\n return JsonResponse({'state': 'ok', 'dht_data': dht_data})\n\ndef get_light_config(request):\n r\"\"\"\n 此函数用于返回灯光的配置数据\n\n Return value / exceptions raised:\n - 返回一个字典\n \"\"\"\n rdata = {'pid': request.GET['houseNum'][0]}\n if not lightConf.data:\n lightFields = ['id', 'name', 'local', 'light', 'color', 'state']\n query_sql = f\"\"\"\n SELECT {', '.join(['`' + f + '`' for f in lightFields])}\n FROM `light_config` WHERE `pid` = {rdata['pid']}\n \"\"\"\n lights = sql.sql_select(lightFields, query_sql)\n for light in lights:\n lid = light['id']\n del light['id']\n lightConf.updata(lid, light)\n # lightConf.save()\n rdata['lights'] = lightConf.get_data()\n rdata['state'] = 'ok'\n return JsonResponse(rdata)\n\ndef get_dht_config(request):\n r\"\"\"\n GET request\n 此函数用于返回DHT传感器的配置数据\n\n Return value / exceptions raised:\n - 返回一个字典,内容是\n {\n \"temperature\": 27,\n \"humidity\": 44,\n \"curtain_auto\": true,\n \"curtain_state\": true,\n \"water_auto\": false,\n \"water_state\": false,\n }\n \"\"\"\n rdata = dhtConf.get_data()\n rdata['pid'] = request.GET['houseNum'][0]\n rdata['state'] = 'ok'\n return JsonResponse(rdata)\n\ndef get_masters(request):\n r\"\"\"\n GET request\n 返回已经登陆的人脸\n\n Return value / exceptions raised:\n - 返回一个列表 [{}, {},]\n \"\"\"\n rdata = {'state': 'ok'}\n masters = [cam.get_user_info(userHeadPic[:-4]) for userHeadPic in os.listdir(FACES)]\n rdata['masters'] = masters\n return JsonResponse(rdata)\n\n############################## 添加系列 ##############################\n\ndef add_port(request):\n r\"\"\"\n POST 请求:\n 首先获取请求中的 name 和 local 字段插入添加一个节点\n 之后查询最新的节点信息\n \"\"\"\n qdata = json.loads(request.body)\n query_data = [qdata['portName'], qdata['portLocal']]\n # query_data = ['新', '奥秘客人']\n query_sql = \"INSERT INTO `ports`(`name`, `local`) VALUES(%s, %s)\"\n sql.sql_insert(query_sql, query_data)\n\n query_sql = \"SELECT * FROM `ports` WHERE `id` = (SELECT MAX(`id`) FROM `ports`)\"\n rdata = sql.sql_select(['id', 'name', 'local'], query_sql)[0]\n rdata['state'] = 'ok'\n return JsonResponse(rdata)\n\ndef add_light(request):\n r\"\"\"\n POST 请求:\n 需要获取的字段:\n pid -- 节点 id【必须\n name -- 灯光名称备注【非必须\n local -- 灯光布置地点备注【非必须\n \"\"\"\n qdata = json.loads(request.body)\n # qdata = {'pid':1 ,'name': '卧室主灯', 'local': '卧室'}\n insert_data = dict()\n for f in ['pid', 'name', 'local']:\n if qdata.get(f, None):\n insert_data[f] = qdata[f]\n query_sql = f\"\"\"\n INSERT INTO `light_config`({', '.join(['`' + f + '`' for f in insert_data.keys()])})\n VALUES({', '.join(['%s']*len(insert_data.keys()))})\n \"\"\"\n sql.sql_insert(query_sql, list(insert_data.values()))\n\n query_sql = \"SELECT * FROM `light_config` WHERE `id` = (SELECT MAX(`id`) FROM `light_config`)\"\n rdata = sql.sql_select(['id', 'pid', 'name', 'local', 'light', 'color', 'state'], query_sql)[0]\n rdata['state'] = 'ok'\n return JsonResponse(rdata)\n\ndef add_master(request):\n r\"\"\"\n POST 注册新的房屋主人\n 需要的字段:\n facePic -- 人脸的照片的 base64 编码字符串\n name -- 需要注册的照片的 id / 名字\n \"\"\"\n qdata = json.loads(request.body)\n with open(f\"{FACES}/{qdata['name']}.jpg\", 'wb') as f:\n f.write(base64.b64decode(qdata['facePic']))\n cam.add_user(qdata['name'])\n rdata = cam.user_info(qdata['name'])\n return JsonResponse(rdata)\n\n","repo_name":"Hybrogen/HHOME","sub_path":"HHOME/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"46109803790","text":"# 1 ~ 10 사이의 어떤 수로도 나누어 떨어지는 가장 작은 수는 2520입니다.\n# 그러면 1 ~ 20 사이의 어떤 수로도 나누어 떨어지는 가장 작은 수는 얼마입니까?\n\n#방법 1 : 오래 걸림\n# value = 1\n# check = True\n# while check:\n# for i in range(1,21):\n# print()\n# if value % i == 0 :\n# continue\n# else :\n# value = value+1\n# break\n\n# print(\"kk\",value)\n# else:\n# print(value)\n# break\n\n\n# 방법2: 수학이론을 적용한 더 빠르고 좋은 방법 #김웅규 t\n\ndef gcd(a,b):\n while (b!=0):\n r=a%b\n a,b=b,r\n return a\ndef lcm(a,b):\n return a*b/gcd(a,b)\n\nn=20\nc=lcm(1,2)\nfor i in range(3,n+1):\n c=lcm(c,i)\nprint(c)\n\n\n#232792560.0","repo_name":"xzeromath/euler","sub_path":"ep5.py","file_name":"ep5.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"37011572814","text":"from django.urls import path\nfrom .views import *\n\n\nurlpatterns = [\n path('', inicio, name=\"inicio\"),\n\n path('jugadorFormulario/', jugadorFormulario, name=\"jugadorFormulario\"),\n path('equipoFormulario/', equipoFormulario, name=\"equipoFormulario\"),\n path('estadioFormulario/', estadioFormulario, name=\"estadioFormulario\"),\n\n path('busquedaJugador/', busquedaJugador, name=\"busquedaJugador\"),\n path('buscar/', buscar, name=\"buscar\"),\n\n path('leerJugadores/', leerJugadores, name=\"leerJugadores\"),\n path('eliminarJugador/', eliminarJugador, name=\"eliminarJugador\"),\n path('editarJugador/', editarJugador, name=\"editarJugador\"),\n\n path('leerEquipos/', leerEquipos, name=\"leerEquipos\"),\n path('eliminarEquipo/', eliminarEquipo, name=\"eliminarEquipo\"),\n path('editarEquipo/', editarEquipo, name=\"editarEquipo\"),\n\n path('leerEstadios/', leerEstadios, name=\"leerEstadios\"),\n path('eliminarEstadio/', eliminarEstadio, name=\"eliminarEstadio\"),\n path('editarEstadio/', editarEstadio, name=\"editarEstadio\"),\n \n\n]","repo_name":"fedebaldasso/Entrega1-Baldasso_Federico","sub_path":"AppEI/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"11188336868","text":"import math as mt\n\nfrom Scene.class_scene_Gl import *\n\n\nclass TestGlScene(SceneThird):\n debug = False\n\n ambient = (1.0, 1.0, 1.0, 1) # Первые три числа цвет в формате RGB, а последнее - яркость\n lightpos = (1.0, 1.0, 1.0) # Положение источника освещения по осям xyz\n\n rquad = 2.0\n speed = 0.1\n wireframe = False\n\n cur_x = 0.\n cur_y = 0.\n\n def gl_mouse_motion(self, x, y):\n self.cur_x = x\n self.cur_y = y\n self.print('callback gl_mouse_motion in point (%d, %d)' % (x, y))\n if not self.left_button_down:\n return\n\n pass\n\n def gl_mouse_motion_passive(self, x, y):\n self.cur_x = x\n self.cur_y = y\n\n return super().gl_mouse_motion_passive(x, y)\n\n def init(self):\n if self.wireframe:\n glPolygonMode(GL_FRONT, GL_LINE)\n glPolygonMode(GL_BACK, GL_LINE)\n elif not self.wireframe:\n glPolygonMode(GL_FRONT, GL_FILL)\n glPolygonMode(GL_BACK, GL_FILL)\n\n # glLoadIdentity()\n # glTranslatef(0.0, 0.0, -5.0)\n\n glLightModelfv(GL_LIGHT_MODEL_AMBIENT, self.ambient) # Определяем текущую модель освещения\n glEnable(GL_LIGHTING) # Включаем освещение\n glEnable(GL_LIGHT0) # Включаем один источник света\n glLightfv(GL_LIGHT0, GL_POSITION, self.lightpos) # Определяем положение источника света\n\n glutSetCursor(GLUT_CURSOR_NONE)\n\n self.gen_draw()\n\n def gl_key_pressed(self, *args):\n # todo super().gl_key_pressed(args)\n if args[0] == b\"c\":\n self.is_projection_ortho = not self.is_projection_ortho\n if args[0] == b\"\\x1b\":\n glutLeaveMainLoop()\n exit()\n if args[0] == b\"x\":\n if not self.wireframe:\n glPolygonMode(GL_FRONT, GL_LINE)\n glPolygonMode(GL_BACK, GL_LINE)\n else:\n glPolygonMode(GL_FRONT, GL_FILL)\n glPolygonMode(GL_BACK, GL_FILL)\n self.wireframe = not self.wireframe\n elif args[0] == b\"v\":\n self.rquad = 2\n\n if args[0] == b\"w\":\n self.rotate_up()\n if args[0] == b\"s\":\n self.rotate_down()\n if args[0] == b\"a\":\n self.rotate_left()\n if args[0] == b\"d\":\n self.rotate_right()\n\n def point_pos(self, cnt, r):\n # type: (int, int) -> TestGlScene\n # points = [(self.width / 2 + r * mt.cos(a), self.height / 2 + r * mt.sin(a)) for a in [2 * mt.pi * i / cnt for i in range(cnt)]]\n points = [(r * mt.cos(a), r * mt.sin(a)) for a in [2 * mt.pi * i / cnt for i in range(cnt)]]\n\n glPointSize(7.0)\n self.set_pixels(points, self.get_color(150, 0, 0))\n '''\n for pt in points:\n self.setpixel(pt[0], pt[1], self.getcolor(1.0, 0.0, 0.0))\n '''\n\n glLineWidth(0.1)\n for pt1 in points:\n for pt2 in points:\n '''\n c_x1, c_y1 = self.get_xy_scene(pt1[0], pt1[1])\n c_x2, c_y2 = self.get_xy_scene(pt2[0], pt2[1])\n self.line(c_x1, c_y1, c_x2, c_y2, self.getcolor(0.0, 1.0, 0.0))\n '''\n self.line(pt1[0], pt1[1], pt2[0], pt2[1], self.get_color(0, 150, 0))\n\n return self\n\n the_img = None\n\n def gen_draw(self):\n self.the_img = glGenLists(1)\n glNewList(self.the_img, GL_COMPILE)\n self.draw_obj()\n glEndList()\n\n def redraw(self):\n # type: () -> TestGlScene\n\n glCallList(self.the_img)\n\n glPushMatrix()\n koef = 1\n c_x, c_y = self.get_xy_scene(self.cur_x, self.cur_y)\n glTranslatef(c_x * koef / self.nSca, c_y * koef / self.nSca, 0.)\n # glutSolidCube(0.05)\n glutSolidSphere(0.01 / self.nSca, 20, 20)\n\n color = [1, 0.2, 0.5, 1.]\n glMaterialfv(GL_FRONT, GL_DIFFUSE, color)\n glDisable(GL_LIGHTING)\n glPopMatrix()\n\n glPushMatrix()\n self.line(0, 0, self.cur_x - self.width / 2, self.cur_y - self.height / 2, self.get_color(0, 0, 255))\n glPopMatrix()\n\n return super().redraw()\n\n def draw_obj(self):\n # type: () -> TestGlScene\n\n lol = 45\n\n '''\n glPushMatrix()\n glTranslatef(*self.lightpos)\n glutSolidSphere(0.05, 20, 20)\n glPopMatrix()\n \n glPushMatrix()\n glPointSize(17.0)\n glBegin(GL_POINTS)\n glColor3d(*self.ambient)\n glVertex3f(*self.lightpos)\n glEnd()\n glPopMatrix()\n '''\n glPushMatrix()\n\n self.lines()\n\n for x, y in [[-self.width / 2, -self.height / 2], [-self.width / 2, self.height / 2],\n [self.width / 2, self.height / 2], [self.width / 2, -self.height / 2]]:\n '''\n c_x, c_y = self.get_xy_scene(x + self.width / 2, y + self.height / 2)\n self.line(0, 0, c_x, c_y, self.getcolor(255, 0, 0))\n '''\n self.line(0, 0, x, y, self.get_color(255, 128, 0))\n\n self.point_pos(lol, self.height / 2)\n glEnable(GL_LIGHTING)\n glPopMatrix()\n\n return self\n\n\nt = TestGlScene(640, 480)\nt.draw()\n","repo_name":"thenzen34/Scene","sub_path":"examples/test_gl_scene3.py","file_name":"test_gl_scene3.py","file_ext":"py","file_size_in_byte":5341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"9577107479","text":"\"\"\"my_controller controller.\"\"\"\n\n# You may need to import some classes of the controller module. Ex:\n# from controller import Robot, Motor, DistanceSensor\nfrom turtle import left\nfrom controller import Robot\nfrom PyCTRNN import CTRNN\nimport numpy\n# create the Robot instance.\nrobot = Robot()\n\n# get the time step of the current world.\ntimestep = int(robot.getBasicTimeStep())\n\n\nbrain = CTRNN(4)\n\nds1 = robot.getDevice(\"ds1\")\nds2 = robot.getDevice(\"ds2\")\nds1.enable(timestep)\nds2.enable(timestep)\nleftMotor = robot.getDevice(\"leftMotor\")\nrightMotor = robot.getDevice(\"rightMotor\")\nleftMotor.setPosition(float(\"inf\"))\nrightMotor.setPosition(float(\"inf\"))\n\n# brain.weights = numpy.zeros((brain.size,brain.size))\n# brain.bias = numpy.zeros(brain.size)\n\n# brain.weights[2,0] = 4\n# brain.weights[3,1] = 4\n# brain.weights[2,1] = -4\n# brain.weights[3,0] = -4\n\nprint(brain.weights)\n\nmutateTimer=0\n\nwhile robot.step(timestep) != -1:\n\n if(mutateTimer > 100000):\n brain.mutate(0.5)\n mutateTimer = 0\n print(brain.weights)\n else:\n mutateTimer += timestep\n sensorInput = numpy.array([ds1.getValue(),ds2.getValue(),0,0])\n\n brainOutput = brain.step(sensorInput)\n \n \n leftMotor.setVelocity(5*brainOutput[2])\n rightMotor.setVelocity(5*brainOutput[3])\n #print(brainOutput)\n \n\n# Enter here exit cleanup code.\n","repo_name":"BhargavaGowda/WebotsCTRNNVisual","sub_path":"trial/controllers/my_controller/my_controller.py","file_name":"my_controller.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"71430310407","text":"import socket\nimport time\n\ndns_ip = \"127.0.0.1\"\ndns_port = 53\n# Dictionary to store IP address mappings\ndns_cache = {\"www.doryevhttp.com\": \"127.0.0.1\"}\n\n\ndef check_internet():\n try:\n socket.getaddrinfo(\"www.google.com\", None)\n return True\n except socket.gaierror:\n return False\n\n\ndef dns_reply():\n domain, client_ip = sock.recvfrom(1024)\n domain = domain.decode('utf-8')\n if domain in dns_cache:\n ip_address = dns_cache[domain]\n print(f\"{domain} : {dns_cache[domain]}\")\n if check_internet():\n sock.sendto(ip_address.encode('utf-8'), client_ip)\n print(\"IP SENT\")\n print(f\"Domain: {domain} , IP : {ip_address}\")\n\n else:\n if check_internet():\n try:\n ip_address = socket.gethostbyname(domain)\n dns_cache[domain] = ip_address\n sock.sendto(ip_address.encode('utf-8'), client_ip)\n print(\"IP SENT\")\n print(f\"Domain: {domain} , IP : {ip_address}\")\n\n except socket.gaierror:\n print(\"Could not resolve domain / no internet connection\")\n ip_address = \"Couldn't Resolve\"\n sock.sendto(ip_address.encode('utf-8'), client_ip)\n\n\nif __name__ == '__main__':\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n sock.bind((dns_ip, 53))\n print(\"DNS SERVER IS ON...\")\n # Start sniffing DNS queries on port 53 on the specified interface\n while True:\n dns_reply()\n time.sleep(1)\n","repo_name":"yevgenyivanov/Networking_Proj","sub_path":"dns.py","file_name":"dns.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"1212044163","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jan 23 11:13:14 2020\r\n\r\n@author: 766810\r\n\"\"\"\r\nelements = \"H He Li Be B C N O F Ne Na Mg Al Si P S Cl Ar K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe Cs Ba La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn Fr Ra Ac Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr Rf Db Sg Bh Hs Mt Ds Rg Cn Uut Fl Uup Lv Uus Uuo\".split()\r\n\r\nimport PyPDF2\r\ni=elements.index\r\ndef m(w,p=(\"\",[])):\r\n if not w:return p\r\n x,y,z=w[0],w[:2],w[:3]\r\n if x!=y and y in elements:\r\n a=m(w[2:],(p[0]+y,p[1]+[i(y)]))\r\n if a:return a\r\n if x in elements:\r\n b=m(w[1:],(p[0]+x,p[1]+[i(x)]))\r\n if b:return b\r\n if z in elements:\r\n c=m(w[3:],(p[0]+z,p[1]+[i(z)]))\r\n if c:return c\r\n\r\nf=open('/Users/766810/python/largedictionary.pdf','rb')\r\n# creating a pdf reader object \r\npdfReader = PyPDF2.PdfFileReader(f) \r\nfor l in f:\r\n x=m(l[:-1])\r\n if x:print(x[0],x[1])\r\nf.close()","repo_name":"mcvenkat/Python-Programs","sub_path":"Longest Word from Periodic Table 2.py","file_name":"Longest Word from Periodic Table 2.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"7986260397","text":"import sys\nimport json\nfrom awsglue.transforms import *\nfrom awsglue.utils import getResolvedOptions\nfrom pyspark.context import SparkContext\nfrom awsglue.context import GlueContext\n\ndef get_s3_object_source_path():\n args = getResolvedOptions(sys.argv, ['JOB_NAME', 's3_trigger_event'])\n s3_event = json.loads(args['s3_trigger_event'])\n bucket = s3_event['s3']['bucket']['name']\n key = s3_event['s3']['object']['key']\n s3_file_location = f's3://{bucket}/{key}'\n\n return s3_file_location\n\ndef get_s3_object_destination_path():\n output_filename = \"custom_output_file.json\"\n return get_s3_object_source_path() + \"/\" + output_filename\n\ndef main():\n sc = SparkContext()\n glueContext = GlueContext(sc)\n\n dynamicFrame = glueContext.create_dynamic_frame.from_options(\n format_options={\"rowTag\": \"Categorias\"},\n connection_type=\"s3\",\n format=\"xml\",\n connection_options={\"paths\": [get_s3_object_source_path()]},\n transformation_ctx=\"dynamicFrame\",\n )\n\n dynamicFrame = dynamicFrame.repartition(1)\n\n glueContext.write_dynamic_frame.from_options(\n frame=dynamicFrame,\n connection_type=\"s3\",\n connection_options={\"path\": get_s3_object_destination_path(), \"partitionKeys\": []},\n format=\"json\"\n )\n\nmain()\n","repo_name":"bryannbarbosa/aws-glue-s3-python","sub_path":"glue.py","file_name":"glue.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"33166032394","text":"import json\nfrom machine_settings import _MachineConfig\nimport os.path as os_path\n\n\nENCODING = 'utf8'\n\n\ndef get_config():\n config = Config()\n return config\n\n\nclass _ConfigBase:\n def __init__(self, parent):\n self._parent = parent\n machine_config = _MachineConfig()\n self._initialize(machine_config)\n\n def _initialize(self, machine_config):\n pass\n\n def __str__(self):\n dict = {}\n self._toJson(dict, self)\n return json.dumps(dict, indent=4)\n \n @classmethod\n def _toJson(cls, parent, obj):\n for attribute_name in dir(obj): \n if not attribute_name.startswith('_'):\n attribute = getattr(obj, attribute_name)\n if isinstance(attribute, _ConfigBase):\n child = {}\n parent[attribute_name] = child\n cls._toJson(child, attribute)\n else:\n parent[attribute_name] = attribute \n \n\nclass _CheckpointConfig(_ConfigBase):\n def _initialize(self, _):\n \n self.enabled = True\n self.weights_only = True\n self.dir = 'checkpoints'\n self.filename = 'best_model.hdf5'\n\n\nclass _CrossValidationConfig(_ConfigBase):\n def _initialize(self, machine_config):\n self.train_set_ids_path = os_path.join(machine_config.data_dir, 'preprocessed/cross-validation/group_1_train_set_1809-2018.txt')\n self.dev_set_ids_path = os_path.join(machine_config.data_dir, 'preprocessed/cross-validation/group_1_target_dev_set_2018-2018.txt')\n self.test_set_ids_path = os_path.join(machine_config.data_dir, 'preprocessed/cross-validation/group_1_reporting_test_set_2018-2018.txt')\n self.encoding = ENCODING\n self.train_limit = machine_config.train_limit\n self.dev_limit = machine_config.dev_limit\n self.test_limit = machine_config.test_limit\n\n\nclass _CsvLoggerConfig(_ConfigBase):\n def _initialize(self, _):\n\n self.dir = 'logs'\n self.filename = 'logs.csv'\n self.best_epoch_filename = 'best_epoch_logs.txt'\n self.encoding = ENCODING\n\n\nclass _DatabaseConfig(_ConfigBase):\n def _initialize(self, machine_config):\n\n self.config = { 'user': '****',\n 'database': '****',\n 'password': '****', \n 'host': machine_config.database_host,\n 'charset': 'utf8mb4', \n 'collation': 'utf8mb4_unicode_ci', \n 'use_unicode': True }\n\n\nclass _EarlyStoppingConfig(_ConfigBase):\n def _initialize(self, _):\n\n self.min_delta = 0.001\n self.patience = 2\n\n\nclass _ModelConfig(_ConfigBase):\n def _initialize(self, _):\n\n self.checkpoint = _CheckpointConfig(self)\n\n self.word_embedding_size = 300\n self.word_embedding_dropout_rate = 0.25\n \n self.conv_act = 'relu'\n self.num_conv_filter_sizes = 3\n self.min_conv_filter_size = 2\n self.conv_filter_size_step = 3\n self.total_conv_filters = 350\n self.num_pool_regions = 5\n\n self.num_journals = 30347\n self.journal_embedding_size = 50\n\n self.num_hidden_layers = 1\n self.hidden_layer_size = 3365\n self.hidden_layer_act = 'relu'\n self.inputs_dropout_rate = 0.0\n self.dropout_rate = 0.5\n\n self.output_layer_act = 'sigmoid'\n self.output_layer_size = self._pp_config.num_labels \n \n self.init_threshold = 0.5\n self.init_learning_rate = 0.001\n\n @property\n def hidden_layer_sizes(self):\n return [self.hidden_layer_size]*self.num_hidden_layers\n\n @property\n def conv_filter_sizes(self):\n sizes = [self.min_conv_filter_size + self.conv_filter_size_step*idx for idx in range(self.num_conv_filter_sizes)]\n return sizes\n\n @property\n def conv_num_filters(self):\n num_filters = round(self.total_conv_filters / len(self.conv_filter_sizes))\n return num_filters\n\n @property\n def _pp_config(self):\n return self._parent.inputs.preprocessing\n\n @property\n def vocab_size(self):\n return self._pp_config.vocab_size\n\n @property\n def title_max_words(self):\n return self._pp_config.title_max_words\n\n @property\n def abstract_max_words(self):\n return self._pp_config.abstract_max_words\n\n @property\n def num_year_completed_time_periods(self):\n return self._pp_config.num_year_completed_time_periods\n\n @property\n def num_pub_year_time_periods(self):\n return self._pp_config.num_pub_year_time_periods\n\n\nclass _PreprocessingConfig(_ConfigBase):\n def _initialize(self, machine_config):\n\n self.word_index_lookup_path = os_path.join(machine_config.data_dir, 'preprocessed/vocab/cross_val_group_1_word_index_lookup.pkl') # indices start from 2\n self.unknown_index = 1\n self.padding_index = 0\n self.title_max_words = 64\n self.abstract_max_words = 448\n self.num_labels = 1 \n self.vocab_size = 400000\n self.min_year_completed= 1965 \n self.max_year_completed = 2018 \n self.num_year_completed_time_periods = 1 + self.max_year_completed - self.min_year_completed\n self.min_pub_year = 1809 \n self.max_pub_year = 2018 \n self.num_pub_year_time_periods = 1 + self.max_pub_year - self.min_pub_year\n\n \nclass _ProcessingConfig(_ConfigBase):\n def _initialize(self, machine_config):\n \n self.run_on_cpu = machine_config.run_on_cpu \n self.use_multiprocessing = machine_config.use_multiprocessing \n self.workers = machine_config.workers \n self.max_queue_size = machine_config.max_queue_size\n\n\nclass _ReduceLearningRateConfig(_ConfigBase):\n def _initialize(self, _):\n\n self.factor = 0.33\n self.patience = 1\n self.min_delta = 0.001\n\n\nclass _RestoreConfig(_ConfigBase):\n def _initialize(self, machine_config):\n super()._initialize(machine_config)\n \n self.sub_dir = '****'\n self.model_json_filename = 'model.json'\n self.encoding = ENCODING\n self.model_checkpoint_dir = 'checkpoints'\n self.model_checkpoint_filename = 'best_model.hdf5'\n self.weights_only_checkpoint = True\n self.threshold = 0.5\n self.learning_rate = 0.001\n \n\nclass _ResumeConfig(_RestoreConfig):\n def _initialize(self, machine_config):\n super()._initialize(machine_config)\n\n self.enabled = False\n self.resume_checkpoint_filename = 'best_model_resume.hdf5'\n self.resume_logger_filename = 'logs_resume.csv'\n\n\nclass _SaveConfig(_ConfigBase):\n def _initialize(self, _):\n\n self.settings_filename = 'settings.json'\n self.model_json_filename = 'model.json'\n self.encoding = ENCODING\n self.model_img_filename = 'model.png'\n\n\nclass _TensorboardConfig(_ConfigBase):\n def _initialize(self, _):\n\n self.enabled = False\n self.dir = 'logs'\n self.write_graph = True\n\n\nclass _EvaluateConfig(_RestoreConfig, _ProcessingConfig):\n def _initialize(self, machine_config):\n super()._initialize(machine_config)\n\n self.results_filename = 'eval-result.txt'\n self.encoding = ENCODING\n self.batch_size = 128\n self.limit = 1000000000\n\n\nclass _PredictConfig(_RestoreConfig, _ProcessingConfig):\n def _initialize(self, machine_config):\n super()._initialize(machine_config)\n\n self.pmids_filepath = '../datasets/pipeline_validation_set.json'\n self.results_dir = 'predictions_val'\n self.results_filename = 'predictions.csv'\n self.dereferenced_filename = 'dereferenced_predictions.csv'\n self.metrics_filename_template = 'metrics{}.csv'\n self.journal_groups_filepath = os_path.join(machine_config.data_dir, 'preprocessed/selective-indexing/selectively_indexed_journal_groups.csv') \n self.encoding = ENCODING\n self.delimiter = ','\n self.batch_size = 128\n self.limit = 1000000000\n \n \nclass _InputsConfig(_ConfigBase):\n def _initialize(self, _):\n\n self.preprocessing = _PreprocessingConfig(self)\n\n\nclass _OptimizeFscoreThresholdConfig(_ProcessingConfig):\n def _initialize(self, machine_config):\n super()._initialize(machine_config)\n \n self.enabled = True\n self.batch_size = 128\n self.limit = 1000000000\n self.metric_name = 'fscore'\n self.alpha = 0.005\n self.k = 3\n\n\nclass _TrainingConfig(_ProcessingConfig):\n def _initialize(self, machine_config):\n super()._initialize(machine_config)\n\n self.batch_size = 128\n self.initial_epoch = 0\n self.max_epochs = 500\n self.train_limit = 1000000000\n self.dev_limit = 1000000000\n self.monitor_metric = 'val_fscore'\n self.monitor_mode = 'max'\n self.save_config = _SaveConfig(self)\n self.optimize_fscore_threshold = _OptimizeFscoreThresholdConfig(self)\n self.reduce_learning_rate = _ReduceLearningRateConfig(self)\n self.early_stopping = _EarlyStoppingConfig(self)\n self.tensorboard = _TensorboardConfig(self)\n self.csv_logger = _CsvLoggerConfig(self)\n self.resume = _ResumeConfig(self)\n\n\nclass Config(_ConfigBase):\n def __init__(self):\n super().__init__(self)\n\n def _initialize(self, machine_config):\n\n self.root_dir = machine_config.runs_dir\n self.data_dir = machine_config.data_dir\n self.inputs = _InputsConfig(self)\n self.model = _ModelConfig(self)\n self.cross_val = _CrossValidationConfig(self)\n self.train = _TrainingConfig(self)\n self.eval = _EvaluateConfig(self)\n self.pred = _PredictConfig(self)\n self.database = _DatabaseConfig(self)","repo_name":"indexing-initiative/selective_indexing","sub_path":"cnn/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":9929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"512262085","text":"\"\"\"\nUse these functions to seed(insert) fake data to database\nRunning this script is similar to executing the same code\nas in the script in the shell console.\n\"\"\"\nfrom datetime import date\nfrom faker import Faker\nimport random\n\nfrom typing import Optional\nfrom seed_data_to_data_base.django_connection import create_con\nfrom django.db.models import Q\n\nfrom app.models import Employees, Positions\n\n# create connection from this script to Django project\ncreate_con()\n\n# Let`s localise Faker lib\nfake = Faker('ru_RU')\n\n# You can use this if everything is broken\n# Employees.fix_tree()\n\n# This method delete all data from model\n# Employees.objects.all().delete()\n\n\ndef get_first_name() -> str:\n \"\"\"\n :return: String with random first name.\n \"\"\"\n first_name_ = fake.first_name()\n return first_name_\n\n\ndef get_last_name() -> str:\n \"\"\"\n :return: String with random last name.\n \"\"\"\n last_name_ = fake.last_name()\n return last_name_\n\n\ndef get_random_day() -> date:\n \"\"\"\n :return: random day.\n \"\"\"\n random_day_ = fake.date_this_year()\n return random_day_\n\n\ndef get_random_salary() -> float:\n \"\"\"\n :return: Returns a random float number up to 2 decimal places == random salary\n \"\"\"\n random_salary_ = round(random.uniform(80000, 600000), 2)\n\n return random_salary_\n\n\ndef get_position(name: str) -> Positions:\n \"\"\"\n Function return an instance of a class Positions\n :param name: Name of position\n :return: Function return an instance of a class Positions\n \"\"\"\n position_ = Positions.objects.get(position_name=name)\n return position_\n\n\ndef get_employee(employee_id: Optional[int] = None, position_id: Optional[int] = None) -> Employees:\n \"\"\"\n Function return an instance of a class Employees\n :param employee_id: id of employee\n :param position_id: position_id of employee\n :return: Function return an instance of a class Employees\n \"\"\"\n if employee_id:\n employee_ = Employees.objects.get(id=employee_id)\n return employee_\n\n employee_ = Employees.objects.get(position_id=position_id)\n return employee_\n\n\ndef created_seo() -> None:\n \"\"\"\n This function creates SEO company == The initial vertex of the graph\n :return: None\n \"\"\"\n # The position for which the employee is being created\n position = get_position('Генеральный директор')\n # Created random field\n day = get_random_day()\n salary = get_random_salary()\n first_name = get_first_name()\n last_name = get_last_name()\n\n seo = Employees.add_root(first_name=first_name,\n last_name=last_name,\n position=position,\n date_employment=day,\n salary=salary)\n seo.refresh_from_db()\n print('User SEO creation completed successfully')\n\n\ndef created_subordinate(chief_id: int, position_name: str) -> None:\n \"\"\"\n This function create subordinate of the specified chief (chief_position)\n :param position_name: Name of the position for which the employee is being created\n :param chief_id: Еhe id of the chief of the employee(subordinate) being created\n :return: None\n \"\"\"\n # Get object chief\n chief = Employees.objects.get(id=chief_id)\n # Get position for which the employee is being created\n position = get_position(position_name)\n # Created random field\n day = get_random_day()\n salary = get_random_salary()\n first_name = get_first_name()\n last_name = get_last_name()\n # Let`s create employee\n created_employee = chief.add_child(first_name=first_name,\n last_name=last_name,\n position=position,\n date_employment=day,\n salary=salary)\n\n created_employee.refresh_from_db()\n print(f'Subordinate of the chief_id =={chief_id} creation completed successfully, {created_employee.id}')","repo_name":"cheremyha/org_str","sub_path":"seed_data_to_data_base/functions_to_seed_data.py","file_name":"functions_to_seed_data.py","file_ext":"py","file_size_in_byte":4003,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"8523114366","text":"import csv\nimport io\nimport tempfile\nimport unittest\nfrom src.advisor.reports.csv_issue_type_count_by_file_report import CsvIssueTypeCountByFileReport\nfrom src.advisor.reports.issues.issue_type_config import IssueTypeConfig\nfrom src.advisor.scanners.config_guess_scanner import ConfigGuessScanner\nfrom src.advisor.scanners.source_scanner import SourceScanner\n\n\nclass TestCsvIssueTypeCountByFileReport(unittest.TestCase):\n def test_output(self):\n config_guess_scanner = ConfigGuessScanner()\n source_scanner = SourceScanner()\n\n issue_type_config = IssueTypeConfig()\n report = CsvIssueTypeCountByFileReport('/root', issue_type_config=issue_type_config)\n report.add_source_file('test_negative.c')\n io_object = io.StringIO('__asm__(\"mov r0, r1\")')\n source_scanner.scan_file_object(\n 'test_negative.c', io_object, report)\n report.add_source_file('test_neutral.c')\n io_object = io.StringIO('#pragma simd foo')\n source_scanner.scan_file_object(\n 'test_neutral.c', io_object, report)\n report.add_source_file('config.guess')\n io_object = io.StringIO('aarch64:Linux')\n config_guess_scanner.scan_file_object(\n 'config.guess', io_object, report)\n report.add_source_file('test_nothing.c')\n io_object = io.StringIO('foobar')\n source_scanner.scan_file_object(\n 'test_nothing.c', io_object, report)\n self.assertEqual(len(report.issues), 2)\n self.assertEqual(len(report.remarks), 1)\n\n with tempfile.NamedTemporaryFile(mode='w', delete=False) as ofp:\n report.write(ofp)\n fname = ofp.name\n ofp.close()\n\n with open(fname) as ifp:\n csv_reader = csv.DictReader(ifp)\n seen_negative = False\n seen_neutral = False\n seen_config_guess = False\n seen_nothing = False\n for row in csv_reader:\n if 'test_negative.c' in row['filename']:\n seen_negative = True\n for (field, actual) in row.items():\n if field == 'filename':\n continue\n expected = '1' if field == 'InlineAsm' else '0'\n self.assertEqual(expected, actual)\n elif 'test_neutral.c' in row['filename']:\n seen_neutral = True\n for (field, actual) in row.items():\n if field == 'filename':\n continue\n expected = '1' if field == 'PragmaSimd' else '0'\n self.assertEqual(expected, actual)\n elif 'config.guess' in row['filename']:\n seen_config_guess = True\n for (field, actual) in row.items():\n if field == 'filename':\n continue\n self.assertEqual('0', actual)\n elif 'test_nothing.c' in row['filename']:\n seen_nothing = True\n for (field, actual) in row.items():\n if field == 'filename':\n continue\n self.assertEqual('0', actual)\n else:\n print(row)\n self.fail('Unexpected row in CSV output')\n self.assertTrue(seen_negative)\n self.assertTrue(seen_neutral)\n self.assertTrue(seen_config_guess)\n self.assertTrue(seen_nothing)\n\n","repo_name":"aws/porting-advisor-for-graviton","sub_path":"unittest/test_csv_issue_type_count_by_file_report.py","file_name":"test_csv_issue_type_count_by_file_report.py","file_ext":"py","file_size_in_byte":3727,"program_lang":"python","lang":"en","doc_type":"code","stars":122,"dataset":"github-code","pt":"16"}
+{"seq_id":"12618445780","text":"\"\"\"\nThe prime factors of 13195 are 5, 7, 13 and 29.\n\nWhat is the largest prime factor of the number 600851475143 ?\n\"\"\"\nfrom math import sqrt\n\n\ndef compute_factors(num):\n # limit = int(sqrt(num))\n limit = num // 2\n factors = []\n for d in range(2, limit):\n if num % d == 0:\n factors.append(d)\n print(len(factors))\n \n return factors\n\n\ndef solve_1(num):\n # Get the list of factors\n factors = compute_factors(num)\n # print(factors)\n\n # Get the last prime from list\n i = len(factors) - 1\n while i >= 0:\n prime = True\n for j in range(i):\n if factors[i] % factors[j] == 0:\n # print(factors[i], factors[j])\n prime = False\n break\n if prime:\n return factors[i]\n i = i - 1\n\n\ndef prime_factors(n):\n factors = []\n \n # Print the number of two's that divide n\n flag = False\n while n % 2 == 0:\n flag = True\n n = n / 2\n if flag:\n factors.append(2)\n\n for i in range(3, int(sqrt(n))+1, 2):\n flag = False\n # while i divides n , print i ad divide n\n while n % i == 0:\n flag = True\n n = n / i\n if flag:\n factors.append(i)\n\n if n > 2:\n factors.append(int(n))\n\n return factors\n\n\ndef solve_2(num):\n factors = prime_factors(num)\n print(factors)\n\n factors.sort()\n\n return factors[-1]\n\n\ndef main():\n num = int(input())\n print(solve_2(num))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"romitheguru/ProjectEuler","sub_path":"3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"28328056534","text":"import pygame\r\npygame.init()\r\n\r\nscreen = pygame.display.set_mode((500,500))\r\npygame.display.set_caption('Designs')\r\n\r\nx,y = 100,100\r\nwidth, height = 10,10\r\nspeed = 10\r\n\r\nwhile True:\r\n pygame.time.delay(10)\r\n for events in pygame.event.get():\r\n if events.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n \r\n key = pygame.key.get_pressed()\r\n\r\n if key[pygame.K_UP] and y>0:\r\n y -= speed\r\n if key[pygame.K_DOWN] and y<500-height:\r\n y += speed\r\n if key[pygame.K_LEFT] and x>0:\r\n x -= speed\r\n if key[pygame.K_RIGHT] and x<500 -width:\r\n x += speed\r\n \r\n pygame.draw.rect(screen, 'white', (x,y, width, height))\r\n pygame.display.update()\r\n \r\n","repo_name":"pickry/programmingknowledge","sub_path":"design.py","file_name":"design.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"16"}
+{"seq_id":"32667268729","text":"\nf = open('a.php','w')\nfrom urllib.request import urlopen\nimport urllib3.request\nfrom dataclasses import replace\nimport requests\nfrom bs4 import BeautifulSoup\nimport sys\nkeyword =sys.argv[1]\nurlA = 'https://www.amazon.in/s?k='+keyword+''\nurlF = 'https://www.flipkart.com/search?q='+keyword+''\nurlR = 'https://www.reliancedigital.in/search?q='+keyword+''\nurlH = 'https://www.happimobiles.com/mobiles/all?serach=&q='+keyword+''\nurlL = 'https://www.lotmobiles.com/catalogsearch/result/?q='+keyword+''\nurlP = 'https://www.paiinternational.in/SearchResults.aspx?search='+keyword+''\nurlB = 'https://www.bajajelectronics.com/product/search?q='+keyword+''\n\nprices = {}\ndef scrape(url):\n if url == urlF:\n try:\n res = requests.get(url).content\n soup = BeautifulSoup(res, 'html.parser')\n itemF = soup.find_all('div', class_='_4rR01T')\n costF = soup.find_all('div', class_='_30jeq3 _1_WHN1')\n #print(itemF[0].text + \" \" + costF[0].text)\n costF = costF[0].text[1:]\n prices[\"Flipkart\"] = costF\n fp = \"\\nData is Retrieved Successfully!!\\n\"\n fp1 = fp.replace('\\n',' ')\n print(fp1)\n fp2 = ''\n print (fp2)\n fp=\"\\n========================================================\\n\"\n fp1=fp.replace('\\n',' ')\n print(fp1)\n\n except Exception as e:\n fp3=\"\\ndata from Flipkart is not found\\n\"\n fp4=fp3.replace('\\n',' ')\n print(fp4)\n fp=\"\\n========================================================\\n\"\n fp1=fp.replace('\\n',' ')\n print(fp1)\n\n elif url == urlA:\n try:\n res = requests.get(url).content\n soup = BeautifulSoup(res, 'html.parser')\n itemA = soup.find_all('span', class_='a-size-medium a-color-base a-text-normal')\n costA = soup.find_all('span', class_='a-offscreen')\n #print(itemA[0].text + \" \" + costA[0].text)\n costA = costA[0].text[1:]\n prices[\"Amazon\"] = costA\n fp=\"\\nData is Retrieved Successfully!!\\n\"\n fp4=fp.replace('\\n',' ')\n print(fp4)\n fp2 = ''\n print (fp2)\n\n \n fp=\"\\n========================================================\\n\"\n fp4=fp.replace('\\n',' ')\n print(fp4)\n\n except Exception as e:\n fp=\"\\ndata from amazon is not found\\n\"\n fp4=fp.replace('\\n',' ')\n print(fp4)\n fp=\"\\n========================================================\\n\"\n fp1=fp.replace('\\n',' ')\n print(fp1)\n\n elif url == urlR:\n try:\n res = requests.get(url).content\n soup = BeautifulSoup(res, 'html.parser')\n itemR = soup.find_all('p', class_='sp__name')\n costR = soup.find_all('span', class_='sc-bxivhb cHwYJ')\n #print(itemR[0].text + \" \" + costR[0].text)\n costR = costR[0].text[1:]\n prices[\"Reliance\"] = costR\n fp=\"\\nData is Retrieved Successfully!!\\n\"\n fp4=fp.replace('\\n',' ')\n print(fp4)\n fp2 = ''\n print (fp2)\n fp=\"\\n========================================================\\n\"\n fp4=fp.replace('\\n',' ')\n print(fp4)\n except Exception as e:\n fp=\"\\ndata from reliance is not found\\n\"\n fp4=fp.replace('\\n',' ')\n print(fp4)\n fp=\"\\n========================================================\\n\"\n fp1=fp.replace('\\n',' ')\n print(fp1)\n\n elif url == urlH:\n try:\n res = requests.get(url).content\n soup = BeautifulSoup(res, 'html.parser')\n itemH = soup.find_all('a', class_='name')\n costH = soup.find_all('div', class_='p-c')\n #print(itemH[0].text + \" \" + costH[0].text)\n costH = costH[0].text[1:]\n prices[\"Happi Mobiles\"] = costH\n fp=\"\\nData is Retrieved Successfully!!\\n\"\n fp4=fp.replace('\\n',' ')\n print(fp4)\n fp2 = ''\n print (fp2)\n \n fp=\"\\n========================================================\\n\"\n fp4=fp.replace('\\n',' ')\n print(fp4)\n except Exception as e:\n fp=\"\\ndata from Happi mobiles is not found\\n\"\n fp4=fp.replace('\\n',' ')\n print(fp4)\n fp=\"\\n========================================================\\n\"\n fp1=fp.replace('\\n',' ')\n print(fp1)\n\n elif url == urlL:\n try:\n res = requests.get(url).content\n soup = BeautifulSoup(res, 'html.parser')\n itemL = soup.find_all('a', class_='product-item-link')\n costL = soup.find_all('span', class_='price')\n #print(itemL[0].text+ \" \" + costL[0].text)\n costL = costL[0].text[1:]\n prices[\"Lot Mobiles\"] = costL\n fp=\"\\nData is Retrieved Successfully!!\\n\"\n fp4=fp.replace('\\n',' ')\n print(fp4)\n fp2 = ''\n print (fp2)\n fp=\"\\n========================================================\\n\"\n fp4=fp.replace('\\n',' ')\n print(fp4)\n except Exception as e:\n fp=\"\\ndata from Lot mobiles is not found\\n\"\n fp4=fp.replace('\\n',' ')\n print(fp4)\n fp=\"\\n========================================================\\n\"\n fp1=fp.replace('\\n',' ')\n print(fp1)\n\n\n elif url == urlB:\n try:\n res = requests.get(url).content\n soup = BeautifulSoup(res, 'html.parser')\n itemB = soup.find_all('h3',class_='prodHeaderDesc mb10')\n costB = soup.find_all('h3', class_='prodPrice d-inline')\n #print(itemB[0].text+ \" \" + costB[0].text)\n costB = costB[0].text[1:]\n prices[\"Bajaj\"] = costB\n fp=\"\\nData is Retrieved Successfully!!\\n\"\n fp4=fp.replace('\\n',' ')\n print(fp4)\n fp2 = ''\n print (fp2)\n fp=\"\\n========================================================\\n\"\n fp4=fp.replace('\\n',' ')\n print(fp4)\n except Exception as e:\n fp=\"\\ndata from Bajaj is not found\\n\"\n fp4=fp.replace('\\n',' ')\n print(fp4)\n fp=\"\\n========================================================\\n\"\n fp1=fp.replace('\\n',' ')\n print(fp1)\n\ndef priceComparision():\n a=f'Showing results for : {keyword} in different sites'\n b=\"\\n\"+a+\"\\n\"\n fp4=b.replace('\\n',' ')\n print(fp4)\n \n for item in prices.items():\n a=item[0],\":\",item[1]\n fp=\"\\n\"+item[0]+\":\"+item[1]+\"\\n\"\n fp4=fp.replace('\\n',' ')\n print(fp4)\n \nif __name__ == '__main__':\n print('connecting to Flipkart.com\\n')\n flip=scrape(urlF)\n print('connecting to Amazon.in\\n')\n ama=scrape(urlA)\n print('connecting to Reliance\\n')\n rel=scrape(urlR)\n print('connecting to happi mobiles\\n')\n hap=scrape(urlH)\n print('connecting to Lot Mobiles\\n')\n lot=scrape(urlL)\n print('connecting to Bajaj Electronics\\n')\n baj=scrape(urlB)\n b=priceComparision()\nmessage = f\"\"\"\n\n
Flipkart : {prices[\"Flipkart\"]}
Link\n\"\"\"\nf.write(message)\nf.close()\n\n\n","repo_name":"ManvithDevadiga/Price-Comparison-website-using-Python-Beautifulsoup","sub_path":"qwe.py","file_name":"qwe.py","file_ext":"py","file_size_in_byte":7964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"43601034663","text":"#from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer\nimport http.server\nimport socketserver\nimport simplejson\nimport json\nimport random\nimport myFSM\nimport diaLogic\nimport mqttDriver\nimport os\n\n\n# mqttIp = 'ACA PONGO LA IP'\n\n# # Callback para mensajes de mqtt, todavia no se bien como armar este callback jaja xd\n# topic = ''\n# msg = ''\n\n\n# def messageCallback(client, userdata, message):\n# userdata.topic = message.topic\n# userdata.msg = message.payload\n# return userdata\n\n# Callbacks para la FSM\n\n\n# def idle2EspObj():\n\n\n# def idle2EspAcc():\n\n\n# def espAcc2EspAcc():\n\n\n# def espAcc2EspObj():\n\n\n# def espObj2EspObj():\n\n\n# def espObj2EspAcc():\n\n\n# # Una vez definidos los callbacks y el IP creo el cliente\n# mqttClient = mqttDriver.mqttClient(mqttIp, messageCallback)\n\n# # Una vez definidos los callbacks genero la FSM\n# myLogic = jsonParser.myDiaLogic(\n# checkCallback=checkCallback, setCallback=setCallback)\n# FSM = myFSM.myFSM()\n\n# # Creo estados\n# FSM.addState('Idle')\n# FSM.addState('EsperoAccion')\n# FSM.addState('EsperoObjeto')\n\n# # Creo eventos para Idle\n# FSM.addPath('Idle', myFSM.myOptions('Pregunta', callBack1, 'EsperoAccion'))\n# FSM.addPath('Idle', myFSM.myOptions('Accion', callBack2, 'EsperoObjeto'))\n\n# # Creo eventos para EsperoAccion\n\n# FSM.addPath('EsperoAccion', myFSM.myOptions(\n# 'Accion', callBack2, 'EsperoObjeto'))\n# FSM.addPath('EsperoAccion', myFSM.myOptions(\n# 'Pregunta', callBack1, 'EsperoAccion'))\n\n# # Creo eventos para EsperoObjeto\n\n# FSM.addPath('EsperoObjeto', myFSM.myOptions(\n# 'Accion', callBack2, 'EsperoObjeto'))\n# FSM.addPath('EsperoObjeto', myFSM.myOptions(\n# 'Pregunta', callBack1, 'EsperoAccion'))\n\n\n# # Testeo commit desde PC\n# FSM.printFSM()\n\n\ndef jsonPPrint(filename):\n f = open(filename, 'r')\n data = json.loads(f.read())\n print(json.dumps(data, indent=4, sort_keys=True))\n\n\nclass S(http.server.BaseHTTPRequestHandler):\n '''Servidor HTTP'''\n\n def get_File(self, mime):\n self.send_response(200)\n self.send_header('Content-type', mime)\n self.end_headers()\n f = open(os.path.dirname(\n os.path.abspath(__file__)) + self.path, 'rb')\n self.wfile.write(f.read())\n f.close()\n\n def do_GET(self):\n '''Callback para GETs'''\n print(self.path)\n try:\n if(self.path.endswith('/')):\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n f = open(\"myPag.htm\", \"r\", encoding=\"utf8\")\n self.wfile.write(f.read().encode())\n f.close()\n\n elif(self.path.endswith('.png')):\n self.get_File('image/png')\n\n elif(self.path.endswith('.htm')):\n self.get_File('text/html')\n\n elif(self.path.endswith('.jpg')):\n self.get_File('image/jpg')\n\n elif(self.path.endswith('.js')):\n self.get_File('text/javascript')\n\n elif(self.path.endswith('.css')):\n self.get_File('text/css')\n\n elif(self.path.endswith('.woff')):\n self.get_File('application/x-font-woff')\n\n elif(self.path.endswith('.ico')):\n self.get_File('image/ico')\n\n elif(self.path.endswith('.pdf')):\n self.get_File('application/pdf')\n else:\n self.send_error(\n 403, \"Forbidden File, Format Not Supported {}\".format(self.path))\n\n except FileNotFoundError:\n self.send_error(404, \"File Not Found {}\".format(self.path))\n\n def do_HEAD(self):\n self._set_headers()\n\n def do_POST(self):\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n self.data_string = self.rfile.read(int(self.headers['Content-Length']))\n # self.send_response(200)\n data = simplejson.loads(self.data_string)\n with open(\"myFulfillment.json\", \"w\") as outfile:\n simplejson.dump(data, outfile)\n # jsonPPrint(\"myFulfillment.json\")\n f = open(\"response.json\")\n self.wfile.write(f.read().encode())\n return\n\n\ndef run(server_class=http.server.HTTPServer, handler_class=S, server='localhost', port=80):\n server_address = (server, port)\n httpd = server_class(server_address, handler_class)\n print('Server starting at ' + str(server_address[0]) + ':' + str(port))\n httpd.serve_forever()\n\n\nif __name__ == \"__main__\":\n from sys import argv\n\nif len(argv) == 3:\n run(server=argv[1], port=int(argv[2]))\n print(argv[1])\nelse:\n run()\n","repo_name":"sfalcona/myIOT","sub_path":"myServer.py","file_name":"myServer.py","file_ext":"py","file_size_in_byte":4658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"19213330481","text":"import cv2\r\nimport numpy as np\r\nfrom skimage.morphology import convex_hull_image\r\nimport glob\r\nfrom natsort import natsorted\r\nimport csv\r\nimport os\r\n\r\ndef dens(folder):\r\n\r\n # 画像ファイルの読み込み\r\n imgs = folder + \"/*png\"\r\n imgs_list = glob.glob(imgs)\r\n imgs_list = natsorted(imgs_list)\r\n\r\n # データを出力するcsv作成\r\n filename = \"result.csv\"\r\n with open(filename, \"w\", newline=\"\") as f:\r\n header = ['img_name', 'evaluation value']\r\n writer = csv.writer(f)\r\n writer.writerow(header) \r\n\r\n # 画像ごとに処理を実施\r\n for image in imgs_list:\r\n img = cv2.imread(image, cv2.IMREAD_GRAYSCALE)\r\n\r\n # 凸包計算\r\n img_hull = convex_hull_image(img)\r\n img_t = np.where(img_hull == False, 0, 255).astype(np.uint8)\r\n\r\n # 凸包の重心計算\r\n mu = cv2.moments(img_t, False)\r\n x,y= int(mu[\"m10\"]/mu[\"m00\"]) , int(mu[\"m01\"]/mu[\"m00\"])\r\n\r\n # 画像内での重心からのばらつき計算\r\n eva = 0\r\n h, w = img.shape[: 2]\r\n for i in range(h):\r\n for j in range(w):\r\n eva =eva + (img[i][j])/255 * ((i-y)**2 + (j-x)**2)\r\n \r\n eva = int(eva)\r\n i = os.path.basename(image)\r\n writer.writerow([i, eva])\r\n\r\nif __name__ == \"__main__\":\r\n dens(\"source\")","repo_name":"yamamura-san/test3","sub_path":"density.py","file_name":"density.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"491659562","text":"import json\nimport os\nimport re\nfrom typing import Optional\n\nfrom django.http import HttpResponse, HttpResponseServerError\n\nimport tools.ffmpeg\nfrom core.interface import Service\nfrom core.model import Result, ErrorResult, Info, Extra\nfrom tools import http_utils, store\nfrom core import config\nfrom core.type import Video\nfrom tools.store import make_path\n\nheaders = {\n \"accept\": \"*/*\",\n \"content-type\": \"json\",\n \"user-agent\": config.user_agent\n}\n\nweb_headers = {\n \"accept\": \"*/*\",\n \"sec-ch-ua\": \"\\\"Not?A_Brand\\\";v=\\\"8\\\", \\\"Chromium\\\";v=\\\"108\\\", \\\"Google Chrome\\\";v=\\\"108\\\"\",\n \"sec-ch-ua-mobile\": \"?0\",\n \"sec-ch-ua-platform\": \"\\\"macOS\\\"\",\n \"sec-fetch-dest\": \"document\",\n \"sec-fetch-mode\": \"navigate\",\n \"sec-fetch-site\": \"none\",\n \"sec-fetch-user\": \"?1\",\n \"upgrade-insecure-requests\": \"1\",\n \"cookie\": config.bilibili_cookie,\n \"user-agent\": config.web_user_agent,\n}\n\nuser_headers = {\n \"Accept\": \"json\",\n \"Sec-Ch-Ua\": \"\\\"Not?A_Brand\\\";v=\\\"8\\\", \\\"Chromium\\\";v=\\\"108\\\", \\\"Google Chrome\\\";v=\\\"108\\\"\",\n \"Sec-Ch-Ua-mobile\": \"?0\",\n \"Sec-Ch-Ua-Platform\": \"\\\"macOS\\\"\",\n \"Sec-Fetch-Dest\": \"empty\",\n \"Sec-Fetch-Mode\": \"cors\",\n \"Sec-Fetch-Site\": \"same-site\",\n \"Origin\": \"https://www.bilibili.com\",\n \"Cookie\": config.bilibili_cookie,\n \"User-Agent\": config.web_user_agent\n}\n\ndownload_headers = {\n \"accept\": \"*/*\",\n \"accept-encoding\": \"identity;q=1, *;q=0\",\n \"range\": \"bytes=0-\",\n \"sec-fetch-dest\": \"video\",\n \"sec-fetch-mode\": \"no-cors\",\n \"sec-fetch-site\": \"cross-sit\",\n \"referer\": \"https://www.bilibili.com\",\n \"user-agent\": config.user_agent\n}\n\n\nvtype = Video.BILIBILI\n\n\nclass BiliBiliService(Service):\n\n @classmethod\n def get_url(cls, text: str) -> Optional[str]:\n print(text)\n if \"bilibili\" in text:\n urls = re.findall(r'(?<=www\\.bilibili\\.com\\/video\\/).+', text, re.I | re.M)\n if urls:\n return \"https://www.bilibili.com/video/\" + urls[0]\n return None\n\n urls = re.findall(r'(?<=b23\\.tv\\/)\\w+', text, re.I | re.M)\n print(urls)\n if len(urls) == 0:\n return None\n url = \"https://b23.tv/\" + urls[0]\n res = http_utils.get(url, header=headers, redirect=False)\n url = res.headers['location']\n print(url)\n return url\n\n # @classmethod\n # def get_prefix_pattern(cls) -> str:\n # # https://b23.tv/lizymu4\n # return 'www\\.bilibili\\.com\\/video\\/'\n\n @classmethod\n def make_url(cls, index) -> str:\n return index\n\n @classmethod\n def index(cls, url) -> Optional[str]:\n if \"b23.tv\" in url:\n return re.findall(r'(?<=b23\\.tv\\/)\\w+', url, re.I | re.M)[0]\n\n try:\n bvid = re.findall(r'(?<=video\\/)\\w+', url)[0]\n except IndexError:\n return None\n\n p = re.findall(r\"(?<=p=)(\\d)\", url)\n if len(p) == 0:\n return bvid\n else:\n return bvid + '-' + p[0]\n\n @classmethod\n def get_bvid(cls, url) -> Optional[str]:\n try:\n return re.findall(r'(?<=video\\/)\\w+', url)[0]\n except IndexError:\n return None\n\n @classmethod\n def get_info(cls, url: str) -> Result:\n burl = cls.get_url(url)\n if burl is None:\n print('error')\n return ErrorResult.URL_NOT_INCORRECT\n\n video_data = BiliBiliService.get_data(burl)\n\n bvid = video_data['bvid']\n\n res = http_utils.get('https://api.bilibili.com/x/player/pagelist',\n param={'bvid': bvid, 'jsonp': 'jsonp'}, header=headers)\n if http_utils.is_error(res):\n return Result.error(res)\n\n data = json.loads(res.content)\n\n p = re.findall(r\"(?<=p=)(\\d)\", burl)\n if len(p) == 0:\n index = 0\n else:\n index = int(p[0]) - 1\n\n try:\n cid = data['data'][index]['cid']\n except (KeyError, IndexError):\n return ErrorResult.VIDEO_ADDRESS_NOT_FOUNT\n\n res = http_utils.get(url, header=user_headers)\n result = re.findall(r'(?<=', response.content.decode(\"utf-8\"), re.M)\n json = json_parser.loads(data[0])\n\n items = json[\"entry_data\"][\"ProfilePage\"][0][\"graphql\"][\"user\"][\"edge_owner_to_timeline_media\"][\"edges\"]\n time_limit = datetime.now() - timedelta(hours=12)\n\n media = []\n\n for i, item in enumerate(items):\n node = item[\"node\"]\n if (datetime.fromtimestamp(int(node[\"taken_at_timestamp\"])) > time_limit\n and node[\"is_video\"] != True):\n media.append({\n \"text\": \"\",\n \"photo\": node[\"display_url\"],\n \"url\": \"http://instagram.com/p/%s\" % node[\"shortcode\"]\n });\n\n if (len(media) != 0):\n return media;\n else:\n return None\n\nGROUP_ID = 37862023\nvk = VK()\n\ncelebrities = {\n \"Селена Гомес\": \"selenagomez\",\n \"Зак Эфрон\": \"zacefron\",\n \"Блейк Лавли\": \"blakelively\",\n \"Нина Добрев\": \"nina\",\n \"Крис Пратт\": \"prattprattpratt\",\n \"Эмма Робертс\": \"emmaroberts\",\n \"Лили Колинз\": \"lilyjcollins\",\n \"Бейонсе\": \"beyonce\",\n \"Криштиану Роналду\": \"cristiano\",\n \"Джей Ло\": \"jlo\",\n \"Victoria's Secret\": \"victoriassecret\",\n \"Джастин Тимберлейк\": \"justintimberlake\",\n \"Дэвид Бекхэм\": \"davidbeckham\",\n \"Рианна\": \"badgalriri\",\n \"Марго Робби\": \"margotrobbie\",\n \"Уилл Смит\": \"willsmith\",\n \"Настя Ивлеева\": \"_agentgirl_\",\n \"Меган Фокс\": \"the_native_tiger\",\n \"Дрейк\": \"champagnepapi\",\n \"Дженнифер Лоуренс\": \"jenniferlawrencepx\",\n \"Кайли Дженнер\": \"kyliejenner\",\n \"Джиджи Хадид\": \"gigihadid\",\n \"Белла Хадид\": \"bellahadid\",\n \"Эмили Ратаковски\": \"emrata\",\n \"Роми Стрейд\": \"romeestrijd\",\n \"Кендалл Дженнер\": \"kendalljenner\",\n \"Жозефин Скривер\": \"josephineskriver\",\n \"Сара Сампайо\": \"sarasampaio\",\n \"Ирина Шейк\": \"irinashayk\",\n \"Грейс Элизабет\": \"lovegrace_e\",\n \"Адриана Лима\": \"adrianalima\",\n \"Эльза Хоск\": \"hoskelsa\",\n \"Кара Делевинь\": \"caradelevingne\",\n \"Вика Одинцова\": \"viki_odintcova\",\n \"Алексис Рэн\": \"alexisren\",\n \"Ким Кардашян\": \"kimkardashian\",\n \"Тейлор Хилл\": \"taylor_hill\",\n \"Роузи Хантингтон-Уайтли\": \"rosiehw\",\n \"Джессика Ли Бьюкенен\": \"jessleebuchanan\",\n \"Жасмин Тукс\": \"jastookes\",\n \"Алессандра Амбросио\": \"alessandraambrosio\",\n \"Стелла Максвелл\": \"stellamaxwell\",\n \"Кайя ��ербер\": \"kaiagerber\",\n \"Барбара Палвин\": \"realbarbarapalvin\",\n \"Марта Хант\": \"marthahunt\",\n \"Синди Мелло\": \"cindymello\"\n}\n\n'''\nmessage = \"Лучшие публикации из инстаграмм-аккаунтов селебрити за последние 24 часа 🔥\\n\\n\"\nphotos = []\n'''\n\nfor name, username in celebrities.items():\n\n media = getMediaFromInstagram(username)\n print(media)\n\n if (media != None):\n \n photos = []\n\n for item in media:\n response = requests.get(item[\"photo\"])\n open(\"photo.jpg\", \"wb\").write(response.content)\n photos.append(vk.uploadPhoto(GROUP_ID, \"photo.jpg\", name))\n \n vk.post(-GROUP_ID, \"💣 %s\\n📷 Instagram: %s\" % (name, username), photos)\n\n'''\nif (len(photos) >= 3):\n message += \"#Селебрити@faces\"\n vk.post(-GROUP_ID, message, photos)\n'''\n","repo_name":"alexmustdie/faces","sub_path":"getMediaFromInstagram.py","file_name":"getMediaFromInstagram.py","file_ext":"py","file_size_in_byte":3783,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"29444406542","text":"#!/usr/bin/env python3\nimport requests, json\ns = requests.Session()\ns.headers['Wanikani-Revision'] = '20170710'\ns.headers['Authorization'] = 'Bearer a2344c7b-6d09-4aca-bd14-1945105c35b4'\n\ndef fetch_paginated(url):\n data = []\n while url:\n print(url)\n stuff = s.get(url).json()\n data += stuff['data']\n url = stuff['pages']['next_url']\n return data\n\ndef dump(stuff, path):\n with open(path, 'w') as fp:\n json.dump(stuff, fp, indent=' ')\ndef do_study_materials():\n data = fetch_paginated('https://api.wanikani.com/v2/study_materials')\n dump(data, 'study_materials.json')\ndef do_subjects():\n data = fetch_paginated('https://api.wanikani.com/v2/subjects')\n by_kind = {}\n for item in data:\n by_kind.setdefault(item['object'], []).append(item)\n\n #open('tmp.json', 'w').write(json.dumps(by_kind))\n\n assert set(by_kind.keys()) == {'radical', 'kanji', 'vocabulary', 'kana_vocabulary'}\n for kind, items in by_kind.items():\n dump(items, f'{kind}.json')\ndo_study_materials()\n","repo_name":"comex/wk","sub_path":"fetch.py","file_name":"fetch.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"40252608743","text":"#!/usr/bin/python\n\nfrom double import double\nfrom io import StringIO\nimport pytest\n\nnumber_inputs = StringIO(u'1234\\n')\n\ndef test_double(monkeypatch):\n monkeypatch.setattr('sys.stdin', number_inputs)\n assert double() == 2468\n\nstr_inputs = StringIO(u'abcd\\n')\ndef test_double_str(monkeypatch):\n with pytest.raises(NameError) as e:\n monkeypatch.setattr('sys.stdin', str_inputs)\n result = double()\n assert str(e.value) == \"name 'abcd' is not defined\"\n","repo_name":"srkiNZ84/pytest_intro","sub_path":"test_double.py","file_name":"test_double.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"41994800601","text":"import os\nimport numpy as np\nimport pandas as pd\nimport argparse\nfrom train_utils import prepare_datamodule\nfrom data.chexpert_data_module import CheXpert\nfrom data.vindrcxr_data_module import Vindr_CXR\nfrom solvers.resnet_solver import resnet_solver\nfrom solvers.attrinet_solver import task_switch_solver\nimport torchvision.transforms as tfs\nfrom torch.utils.data import DataLoader\nfrom experiment_utils import update_key_value_pairs\nfrom train_utils import to_numpy\nimport matplotlib.pyplot as plt\nimport torch\nfrom train_utils import to_numpy\nfrom tqdm import tqdm\nfrom PIL import Image\n\n\ndef ncc(a,v, zero_norm=True):\n a = a.flatten()\n v = v.flatten()\n if zero_norm:\n a = (a - np.mean(a)) / (np.std(a) * len(a))\n v = (v - np.mean(v)) / np.std(v)\n else:\n a = (a) / (np.std(a) * len(a))\n v = (v) / np.std(v)\n\n return np.correlate(a, v)\n\ndef save_img(img, prefix, path):\n path = os.path.join(path, prefix)\n if \"input\" in prefix:\n plt.imsave(path, img, cmap='gray')\n if \"mask\" in prefix:\n vmax = np.abs(img).flatten().max()\n plt.imsave(path, img, cmap='bwr', vmax=vmax, vmin=-vmax)\n\n\n\n\n\n\n\n\nclass spurious_detection():\n\n def __init__(self, solver, spu_dataloader, norm_dataloader, confounder, threshold, sample_indices_dict, out_dir, attr_method, config):\n self.ratio = 0.1\n self.solver = solver\n self.spu_dataloader = spu_dataloader\n self.norm_dataloader = norm_dataloader\n self.confounder = confounder\n self.threshold = threshold\n self.flip_idx = sample_indices_dict[\"flip_idx\"]\n self.neg_idx = sample_indices_dict[\"all_neg_idx\"]\n self.all_pos_idx = sample_indices_dict[\"all_pos_idx\"]\n self.attr_method = attr_method\n self.device = torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")\n os.makedirs(out_dir, exist_ok=True)\n self.out_dir = out_dir\n os.makedirs(self.out_dir, exist_ok=True)\n self.label_idx = solver.TRAIN_DISEASES.index(config.contaminated_class)\n self.all_results_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), config.all_results_file)\n self.model_name = config.model + \"_\" + config.dataset # \"resnet_chexpert_Pneumothorax_stripe_degree0.0\"\n\n def get_ncc(self, positive_only, num_samples):\n\n sample_idces = self.flip_idx\n samples_out_dir = os.path.join(self.out_dir, \"flip_idx\")\n os.makedirs(samples_out_dir, exist_ok=True)\n\n ncc_values = []\n count = 0\n\n for i in tqdm(range(len(sample_idces))):\n idx = sample_idces[i]\n spu_data = self.spu_dataloader.dataset[int(idx)]\n spu_img = spu_data['img']\n lbl = spu_data['label'].squeeze()\n norm_data = self.norm_dataloader.dataset[int(idx)]\n norm_img = norm_data['img']\n spu_img = torch.from_numpy(spu_img[None])\n norm_img = torch.from_numpy(norm_img[None])\n\n if self.attr_method == \"attrinet\":\n spu_y_pred = self.solver.get_probs(spu_img.to(self.device), self.label_idx)\n spu_p = to_numpy(spu_y_pred)\n spu_attr = self.solver.get_attributes(spu_img, self.label_idx)\n spu_attr = -to_numpy(spu_attr).squeeze()\n norm_y_pred = self.solver.get_probs(norm_img.to(self.device),self.label_idx)\n norm_p = to_numpy(norm_y_pred)\n norm_attr = self.solver.get_attributes(norm_img, self.label_idx)\n norm_attr = -to_numpy(norm_attr).squeeze()\n\n else:\n spu_y_pred_logits = self.solver.model(spu_img.to(self.device))\n spu_y_pred = torch.sigmoid(spu_y_pred_logits).squeeze()\n spu_p = to_numpy(spu_y_pred)\n spu_attr = self.solver.get_attributes(spu_img, self.label_idx, positive_only=positive_only)\n spu_attr = to_numpy(spu_attr).squeeze()\n norm_y_pred_logits = self.solver.model(norm_img.to(self.device))\n norm_y_pred = torch.sigmoid(norm_y_pred_logits).squeeze()\n norm_p = to_numpy(norm_y_pred)\n norm_attr = self.solver.get_attributes(norm_img, self.label_idx, positive_only=positive_only)\n norm_attr = to_numpy(norm_attr).squeeze()\n\n ncc_measurement = ncc(spu_attr, norm_attr)\n count += 1\n ncc_values.append(ncc_measurement)\n\n if count < 20:\n # save some samples for qualitative evaluation\n save_img(to_numpy(spu_img).squeeze(), prefix=str(idx) + '_spu_GT_' + str(lbl.squeeze()) + '_T_' + str(self.threshold.squeeze()) + '_input.png',\n path=samples_out_dir)\n save_img(to_numpy(norm_img).squeeze(), prefix=str(idx) + '_norm_GT_' + str(lbl.squeeze()) + '_T_' + str(self.threshold.squeeze()) + '_input.png',\n path=samples_out_dir)\n save_img(spu_attr.squeeze(), prefix=str(idx) + '_spu_pred: ' + str(spu_p) + '_mask.png', path=samples_out_dir)\n save_img(norm_attr.squeeze(), prefix=str(idx) + '_norm_pred: ' + str(norm_p) + '_mask.png', path=samples_out_dir)\n\n if count >= num_samples:\n break\n ncc_values = np.asarray(ncc_values)\n mean_ncc = np.mean(ncc_values)\n if self.attr_method == \"attrinet\":\n update_key_value_pairs(self.all_results_file, self.model_name, \"explanation_ncc\", float(mean_ncc))\n else:\n update_key_value_pairs(self.all_results_file, self.model_name, self.attr_method +\"_explanation_ncc\", float(mean_ncc))\n print(\"mean_ncc\", mean_ncc)\n\n def get_sensitivity(self, num_samples, positive_only=True):\n sample_idces = self.flip_idx\n count = 0\n sensitivity_values = []\n\n for i in tqdm(range(len(sample_idces))):\n idx = sample_idces[i]\n spu_data = self.spu_dataloader.dataset[int(idx)]\n spu_img = spu_data['img']\n lbl = spu_data['label'].squeeze()\n spu_img = torch.from_numpy(spu_img[None])\n\n if self.attr_method == \"attrinet\":\n spu_y_pred = self.solver.get_probs(spu_img.to(self.device), self.label_idx)\n spu_attr = self.solver.get_attributes(spu_img, self.label_idx)\n spu_attr = -to_numpy(spu_attr).squeeze()\n\n else:\n spu_y_pred_logits = self.solver.model(spu_img.to(self.device))\n spu_y_pred = torch.sigmoid(spu_y_pred_logits).squeeze()\n spu_attr = self.solver.get_attributes(spu_img, self.label_idx, positive_only=positive_only)\n spu_attr = to_numpy(spu_attr).squeeze()\n\n if i < 20:\n hitts = self.sstt(spu_attr, confounder=self.confounder, attr_method=self.attr_method, ratio=self.ratio, plot_itsect=True, out_dir=self.out_dir, prefix=str(idx))\n else:\n hitts = self.sstt(spu_attr, confounder=self.confounder, attr_method=self.attr_method, ratio=self.ratio, plot_itsect=False, out_dir=None, prefix=None)\n sensitivity_values.append(hitts)\n count += 1\n if count >= num_samples:\n break\n\n sensitivity_values = np.asarray(sensitivity_values)\n mean_sensitivity = np.mean(sensitivity_values)\n if self.attr_method == \"attrinet\":\n update_key_value_pairs(self.all_results_file, self.model_name, \"confounder_sensitivity\", float(mean_sensitivity))\n else:\n update_key_value_pairs(self.all_results_file, self.model_name, self.attr_method + \"_confounder_sensitivity\", float(mean_sensitivity))\n\n print(\"mean_sensitivity\", mean_sensitivity)\n def sstt(self, spu_attr, confounder, attr_method, ratio, plot_itsect, out_dir, prefix):\n #'lime', 'GCam', 'GB', 'shap', 'gifsplanation','attrinet'\n # get confounder pixel positions\n confounder_pos = np.where(confounder == 1)\n confounder_pos_x = confounder_pos[0]\n confounder_pos_y = confounder_pos[1]\n num_founder_pixels = len(confounder_pos_y)\n confounder_pixels = list(zip(confounder_pos_x, confounder_pos_y))\n confounder_set = set(confounder_pixels)\n\n #select top 10% pixel with highest value\n all_attr_pixel = 320*320\n num_pixels = int(ratio * all_attr_pixel)\n\n if attr_method == 'attrinet' or attr_method == 'gifsplanation':\n pixel_importance = np.absolute(to_numpy(spu_attr.squeeze()))\n else:\n pixel_importance = spu_attr\n\n idcs = np.argsort(pixel_importance.flatten()) # from smallest to biggest\n idcs = idcs[::-1] # if we want the order biggest to smallest, we reverse the indices array\n idcs = idcs[:num_pixels]\n # Compute the corresponding masks for deleting pixels in the given order\n positions = np.array(np.unravel_index(idcs, pixel_importance.shape)).T # first colum, h index, second column, w index\n attri_pos_x = positions[:, 0]\n attri_pos_y = positions[:, 1]\n top_attri_pixels = list(zip(attri_pos_x, attri_pos_y))\n top_attri_set = set(top_attri_pixels)\n inter_set = confounder_set.intersection(top_attri_set)\n hitts = len(inter_set)/num_founder_pixels\n if hitts!=0 and plot_itsect == True:\n pixels = [list(item) for item in inter_set]\n pixels = np.asarray(pixels)\n background = np.zeros((320, 320))\n background[pixels[:, 0], pixels[:, 1]] = 255\n img = Image.fromarray(background)\n img = img.convert(\"L\")\n out_path = os.path.join(out_dir, prefix + \"_\" + str(hitts) + \"_hitts.png\")\n img.save(out_path)\n return hitts\n\n\n\n\n\n\n\ndef str2bool(v):\n return v.lower() in ('true')\n\ndef argument_parser():\n \"\"\"\n Create a parser with run_experiments arguments.\n Returns:\n argparse.ArgumentParser:\n \"\"\"\n parser = argparse.ArgumentParser(description=\"spurious model/sample analyser.\")\n\n parser.add_argument('--model', type=str, default='resnet', choices=['resnet', 'attrinet'])\n parser.add_argument('--dataset', type=str, default='chexpert', choices=['chexpert', 'vindrcxr'])\n parser.add_argument('--contaminated_class', type=str, default=\"Cardiomegaly\",\n choices=[\"Cardiomegaly\", \"Aortic enlargement\"])\n parser.add_argument('--attr_method', type=str, default='GCam',\n help=\"choose the explaination methods, can be 'lime', 'GCam', 'GB', 'shap', 'gifsplanation', 'attrinet'\")\n parser.add_argument('--positive_only', type=str2bool, default=False,\n help=\"if Ture, only select positive attributions, if False, keep all attribution\")\n parser.add_argument('--mode', type=str, default='test', choices=['train', 'test'])\n\n parser.add_argument('--contaim_scale', type=int, default=2, choices=[0, 1, 2, 3, 4])\n parser.add_argument('--contaim_type', type=str, default=\"tag\", choices=[\"tag\", \"hyperintensities\", \"obstruction\"])\n\n parser.add_argument('--num_samples', type=int, default=100, choices=[100],\n help=\"number of flipped sample to evaluate on, 100 for short evaluate, 2500 for larger evaluation\")\n\n parser.add_argument(\"--img_size\", default=320,\n type=int, help=\"image size for the data loader.\")\n parser.add_argument(\"--batch_size\", default=1,\n type=int, help=\"Batch size for the data loader.\")\n parser.add_argument('--manual_seed', type=int, default=42, help='set seed')\n parser.add_argument('--use_gpu', type=str2bool, default=True, help='whether to run on the GPU')\n parser.add_argument('--all_results_file', type=str, default=\"all_results.json\", help='dictionary to save all results')\n\n return parser\n\n\ndef get_arguments():\n parser = argument_parser()\n exp_configs = parser.parse_args()\n if exp_configs.attr_method == \"attrinet\":\n # configurations of generator\n exp_configs.image_size = 320\n exp_configs.generator_type = 'stargan'\n exp_configs.deep_supervise = False\n\n # configurations of latent code generator\n exp_configs.n_fc = 8\n exp_configs.n_ones = 20\n exp_configs.num_out_channels = 1\n # configurations of classifiers\n exp_configs.lgs_downsample_ratio = 32\n\n return exp_configs\n\n\ndef prep_solver(exp_configs):\n from models_dict import resnet_model_path_dict, attrinet_model_path_dict\n from data.dataset_params import dataset_dict_chexpert_Cardiomegaly, dataset_dict_vindrcxr_Aortic_enlargement\n exp_configs.dataset += '_' + exp_configs.contaminated_class + '_' + exp_configs.contaim_type + '_' + 'degree' + str(\n exp_configs.contaim_scale) # \"chexpert_Cardiomegaly_tag_degree2\"\n\n if \"chexpert\" in exp_configs.dataset:\n if \"Cardiomegaly\" in exp_configs.dataset:\n dataset_dict = dataset_dict_chexpert_Cardiomegaly[exp_configs.dataset]\n if \"vindrcxr\" in exp_configs.dataset:\n dataset_dict = dataset_dict_vindrcxr_Aortic_enlargement[exp_configs.dataset]\n datamodule = prepare_datamodule(exp_configs, dataset_dict)\n exp_configs.train_diseases = dataset_dict[\"train_diseases\"]\n\n if exp_configs.attr_method == \"attrinet\":\n exp_configs.model_path = attrinet_model_path_dict[exp_configs.dataset]\n data_loader = {}\n data_loader['train_pos'] = None\n data_loader['train_neg'] = None\n data_loader['vis_pos'] = None\n data_loader['vis_neg'] = None\n data_loader['valid'] = None\n data_loader[\"test\"] = None\n solver = task_switch_solver(exp_configs, data_loader=data_loader)\n\n else:\n exp_configs.model_path = resnet_model_path_dict[exp_configs.dataset]\n data_loader = {}\n data_loader[\"train\"] = None\n data_loader[\"valid\"] = None\n data_loader[\"test\"] = None\n solver = resnet_solver(exp_configs, data_loader=data_loader)\n solver.set_explainer(which_explainer=exp_configs.attr_method)\n\n exp_configs.result_dir = os.path.join(exp_configs.model_path, \"miccai23\", \"selected_flip_prediction_samples\", \"new_eval_1615\", exp_configs.attr_method)\n os.makedirs(exp_configs.result_dir, exist_ok=True)\n\n print(\"exp_configs.result_dir: \",exp_configs.result_dir)\n print(\"exp_configs.model_path: \",exp_configs.model_path)\n\n return solver\n\n\n\ndef prep_dataloaders(exp_configs):\n\n from data.contaminate_data_settings import TGT_DATA_ROOT\n confounder_dict = {\n \"tag\": os.path.join(os.path.dirname(os.path.abspath(__file__)), \"confounder_masks\", \"tag.txt\"),\n \"hyperintensities\": os.path.join(os.path.dirname(os.path.abspath(__file__)), \"confounder_masks\", \"hyperintensities.txt\"),\n \"obstruction\": os.path.join(os.path.dirname(os.path.abspath(__file__)), \"confounder_masks\", \"obstruction.txt\")\n }\n\n os.path.join(os.path.dirname(os.path.abspath(__file__)), \"confounder_masks\", \"tag.txt\")\n\n\n normal_chexpert_Cardiomegaly_root_folders = {\n \"tag\": os.path.join(TGT_DATA_ROOT, \"chexpert\", \"Cardiomegaly\", \"tag\", \"degree0\"),\n \"hyperintensities\": os.path.join(TGT_DATA_ROOT, \"chexpert\", \"Cardiomegaly\", \"hyperintensities\", \"degree0\"),\n \"obstruction\": os.path.join(TGT_DATA_ROOT, \"chexpert\", \"Cardiomegaly\", \"obstruction\", \"degree0\")\n }\n\n normal_vindr_Aortic_enlargement_root_folders = {\n \"tag\": os.path.join(TGT_DATA_ROOT, \"vindr\", \"Aortic enlargement\", \"tag\", \"degree0\"),\n \"hyperintensities\": os.path.join(TGT_DATA_ROOT, \"vindr\", \"Aortic enlargement\", \"hyperintensities\", \"degree0\"),\n \"obstruction\": os.path.join(TGT_DATA_ROOT, \"vindr\", \"Aortic enlargement\", \"obstruction\", \"degree0\")\n\n }\n spu_chexpert_Cardiomegaly_root_folders = {\n \"tag\": os.path.join(TGT_DATA_ROOT, \"chexpert\", \"Cardiomegaly\", \"tag\", \"degree4\"),\n \"hyperintensities\": os.path.join(TGT_DATA_ROOT, \"chexpert\", \"Cardiomegaly\", \"hyperintensities\", \"degree4\"),\n \"obstruction\": os.path.join(TGT_DATA_ROOT, \"chexpert\", \"Cardiomegaly\", \"obstruction\", \"degree4\")\n }\n\n spu_vindr_Aortic_enlargement_root_folders = {\n \"tag\": os.path.join(TGT_DATA_ROOT, \"vindr\", \"Aortic enlargement\", \"tag\", \"degree4\"),\n \"hyperintensities\": os.path.join(TGT_DATA_ROOT, \"vindr\", \"Aortic enlargement\", \"hyperintensities\", \"degree4\"),\n \"obstruction\": os.path.join(TGT_DATA_ROOT, \"vindr\", \"Aortic enlargement\", \"obstruction\", \"degree4\")\n }\n\n transforms = tfs.Compose([tfs.Resize((exp_configs.img_size, exp_configs.img_size)), tfs.ToTensor()])\n if \"chexpert\" in exp_configs.dataset:\n normal_data_root = normal_chexpert_Cardiomegaly_root_folders[exp_configs.contaim_type]\n spu_data_root = spu_chexpert_Cardiomegaly_root_folders[exp_configs.contaim_type]\n\n if \"vindrcxr\" in exp_configs.dataset:\n normal_data_root = normal_vindr_Aortic_enlargement_root_folders[exp_configs.contaim_type]\n spu_data_root = spu_vindr_Aortic_enlargement_root_folders[exp_configs.contaim_type]\n\n spu_img_dir = os.path.join(spu_data_root, \"test\")\n normal_img_dir = os.path.join(normal_data_root, \"test\")\n spu_csv_path = os.path.join(spu_data_root, \"test_df.csv\")\n normal_csv_path = os.path.join(normal_data_root, \"test_df.csv\")\n spu_df = pd.read_csv(spu_csv_path)\n normal_df = pd.read_csv(normal_csv_path)\n if \"chexpert\" in exp_configs.dataset:\n spu_testset = CheXpert(spu_img_dir, spu_df, exp_configs.train_diseases, transforms=transforms)\n normal_testset = CheXpert(normal_img_dir, normal_df, exp_configs.train_diseases, transforms=transforms)\n if \"vindrcxr\" in exp_configs.dataset:\n spu_testset = Vindr_CXR(image_dir=spu_img_dir, df=spu_df, train_diseases=exp_configs.train_diseases,\n transforms=transforms)\n normal_testset = Vindr_CXR(image_dir=normal_img_dir, df=normal_df,\n train_diseases=exp_configs.train_diseases,\n transforms=transforms)\n\n spu_test_loader = DataLoader(spu_testset, batch_size=exp_configs.batch_size, shuffle=False)\n normal_test_loader = DataLoader(normal_testset, batch_size=exp_configs.batch_size, shuffle=False)\n confounder = np.loadtxt(confounder_dict[exp_configs.contaim_type])\n return normal_test_loader, spu_test_loader, confounder\n\n\n\n\n\n\ndef main(config):\n\n solver = prep_solver(config)\n normal_test_loader, spu_test_loader, confounder = prep_dataloaders(config)\n threshlod_path = os.path.join(config.model_path, \"miccai23\", \"valid\", \"auc_result_dir\", \"best_threshold.txt\")\n threshold = np.loadtxt(threshlod_path)\n eval_root_dir = os.path.join(config.model_path, \"miccai23\", \"selected_flip_prediction_samples\")\n flip_idx = np.loadtxt(os.path.join(eval_root_dir, \"flip_idx.txt\")).tolist()\n all_neg_idx = np.loadtxt(os.path.join(eval_root_dir, \"neg_idx.txt\")).tolist()\n all_pos_idx = np.loadtxt(os.path.join(eval_root_dir, \"all_pos_idx.txt\")).tolist()\n\n idx_dict = {\n \"flip_idx\": flip_idx,\n \"all_neg_idx\": all_neg_idx,\n \"all_pos_idx\":all_pos_idx\n }\n\n detector = spurious_detection(solver, spu_test_loader, normal_test_loader, confounder, threshold=threshold,\n sample_indices_dict=idx_dict, out_dir=config.result_dir,\n attr_method=config.attr_method, config=config)\n\n detector.get_ncc(positive_only=False, num_samples=config.num_samples)\n detector.get_sensitivity(num_samples=config.num_samples, positive_only=True)\n\n\nif __name__ == \"__main__\":\n params = get_arguments()\n main(params)\n\n","repo_name":"ss-sun/right-for-the-wrong-reason","sub_path":"spurious_detection_eval.py","file_name":"spurious_detection_eval.py","file_ext":"py","file_size_in_byte":19696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"36820520947","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef conv_shift(arr, dx):\n \"\"\"\n Shift an array arr by dx \n like a worse version of np.roll!\n \"\"\"\n dx = len(arr)//2 + int(dx) # need to set the impulse position to index from the middle of the array!\n arr = np.array(arr)\n shift = np.zeros(arr.shape)\n shift[dx] = 1\n longarr = np.concatenate((arr, arr))\n return np.convolve(longarr, shift, 'same')[len(arr):]\n\n\nif __name__ == \"__main__\":\n\n x = np.linspace(-5, 5, 201)\n g = np.exp(- x**2/2)/(np.sqrt(2*np.pi))\n\n\n plt.figure()\n plt.title('Convolution shift example')\n plt.plot(g, label='Input array')\n plt.plot(conv_shift(g, len(g)//2), label='Shifted array')\n plt.xlabel('x')\n plt.ylabel('y')\n plt.legend()\n plt.show()","repo_name":"teolemay/PHYS_512","sub_path":"ProblemSet6/Q1_convolution_shift.py","file_name":"Q1_convolution_shift.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"2711326326","text":"# -*- coding: future_fstrings -*-\n\n\"\"\"Interface for the control api d-bus service.\"\"\"\n\nfrom typing import Callable, Any\nimport sys, os\nfrom time import perf_counter\nfrom difflib import get_close_matches\n\nfrom PyQt5.QtCore import pyqtSlot, QObject\nfrom PyQt5.QtDBus import QDBusConnection, QDBusInterface, QDBusReply, QDBusPendingCallWatcher, QDBusPendingReply\n\nfrom debugger import *; dbg\nfrom animate import delay\nimport logging; log = logging.getLogger('Chronos.api')\n\n#Mock out the old API; use production for this one so we can switch over piecemeal.\nUSE_MOCK = False #os.environ.get('USE_CHRONOS_API_MOCK') in ('always', 'web')\nAPI_INTERCALL_DELAY = 0\nAPI_SLOW_WARN_MS = 100\nAPI_TIMEOUT_MS = 5000\n\n\n# Set up d-bus interface. Connect to mock system buses. Check everything's working.\nif not QDBusConnection.systemBus().isConnected():\n\tprint(\"Error: Can not connect to D-Bus. Is D-Bus itself running?\", file=sys.stderr)\n\traise Exception(\"D-Bus Setup Error\")\n\ncameraControlAPI = QDBusInterface(\n\tf\"ca.krontech.chronos.{'control_mock' if USE_MOCK else 'control'}\", #Service\n\tf\"/ca/krontech/chronos/{'control_mock' if USE_MOCK else 'control'}\", #Path\n\tf\"\", #Interface\n\tQDBusConnection.systemBus() )\ncameraVideoAPI = QDBusInterface(\n\tf\"ca.krontech.chronos.{'video_mock' if USE_MOCK else 'video'}\", #Service\n\tf\"/ca/krontech/chronos/{'video_mock' if USE_MOCK else 'video'}\", #Path\n\tf\"\", #Interface\n\tQDBusConnection.systemBus() )\n\ncameraControlAPI.setTimeout(API_TIMEOUT_MS) #Default is -1, which means 25000ms. 25 seconds is too long to go without some sort of feedback, and the only real long-running operation we have - saving - can take upwards of 5 minutes. Instead of setting the timeout to half an hour, we use events which are emitted as the task progresses. One frame (at 15fps) should be plenty of time for the API to respond, and also quick enough that we'll notice any slowness.\ncameraVideoAPI.setTimeout(API_TIMEOUT_MS)\n\nif not cameraControlAPI.isValid():\n\tprint(\"Error: Can not connect to control D-Bus API at %s. (%s: %s)\" % (\n\t\tcameraControlAPI.service(), \n\t\tcameraControlAPI.lastError().name(), \n\t\tcameraControlAPI.lastError().message(),\n\t), file=sys.stderr)\n\traise Exception(\"D-Bus Setup Error\")\n\nif not cameraVideoAPI.isValid():\n\tprint(\"Error: Can not connect to video D-Bus API at %s. (%s: %s)\" % (\n\t\tcameraVideoAPI.service(), \n\t\tcameraVideoAPI.lastError().name(), \n\t\tcameraVideoAPI.lastError().message(),\n\t), file=sys.stderr)\n\traise Exception(\"D-Bus Setup Error\")\n\n\n\nclass DBusException(Exception):\n\t\"\"\"Raised when something goes wrong with dbus. Message comes from dbus' msg.error().message().\"\"\"\n\tpass\n\nclass APIException(Exception):\n\t\"\"\"Raised when something goes wrong with dbus. Message comes from dbus' msg.error().message().\"\"\"\n\tpass\n\nclass ControlReply():\n\tdef __init__(self, value=None, errorName=None, message=None):\n\t\tself.value = value\n\t\tself.message = message\n\t\tself.errorName = errorName\n\t\n\tdef unwrap(self):\n\t\tif self.errorName:\n\t\t\traise APIException(self.errorName + ': ' + self.message)\n\t\telse:\n\t\t\treturn self.value\n\n\nclass video():\n\t\"\"\"Call the D-Bus video API, asynchronously.\n\t\t\n\t\tMethods:\n\t\t\t- call(function[, arg1[ ,arg2[, ...]]])\n\t\t\t\tCall the remote function.\n\t\t\t- get([value[, ...]])\n\t\t\t\tGet the named values from the API.\n\t\t\t- set({key: value[, ...]}])\n\t\t\t\tSet the named values in the API.\n\t\t\n\t\tAll methods return an A* promise-like, in that you use\n\t\t`.then(cb(value))` and `.catch(cb(error))` to get the results\n\t\tof calling the function.\n\t\"\"\"\n\t\n\t_videoEnqueuedCalls = []\n\t_videoCallInProgress = False\n\t_activeCall = None\n\t\n\t@staticmethod\n\tdef _enqueueCallback(pendingCall, coalesce: bool=True): #pendingCall is video.call\n\t\t\"\"\"Enqueue callback. Squash and elide calls to set for efficiency.\"\"\"\n\t\t\n\t\t#Step 1: Will this call actually do anything? Elide it if not.\n\t\tanticipitoryUpdates = False #Emit update signals before sending the update to the API. Results in faster UI updates but poorer framerate.\n\t\tif coalesce and pendingCall._args[0] == 'set':\n\t\t\t#Elide this call if it would not change known state.\n\t\t\thasNewInformation = False\n\t\t\tnewItems = pendingCall._args[1].items()\n\t\t\tfor key, value in newItems:\n\t\t\t\tif _camState[key] != value:\n\t\t\t\t\thasNewInformation = True\n\t\t\t\t\tif not anticipitoryUpdates:\n\t\t\t\t\t\tbreak\n\t\t\t\t\t#Update known cam state in advance of state transition.\n\t\t\t\t\tlog.info(f'Anticipating {key} → {value}.')\n\t\t\t\t\t_camState[key] = value\n\t\t\t\t\tfor callback in apiValues._callbacks[key]:\n\t\t\t\t\t\tcallback(value)\n\t\t\tif not hasNewInformation:\n\t\t\t\treturn\n\t\t\n\t\tif coalesce and pendingCall._args[0] == 'playback':\n\t\t\t#Always merge playback states.\n\t\t\t#Take the playback state already enqueued, {}, and overlay the current playback state. (so, {a:1, b:1} + {b:2} = {a:1, b:2})\n\t\t\tassert type(pendingCall._args[1]) is dict, f\"playback() takes a {{key:value}} dict, got {pendingCall._args[1]} of type {type(pendingCall._args[1])}.\"\n\t\t\texistingParams = [call._args[1] for call in video._videoEnqueuedCalls if call._args[0] == 'playback']\n\t\t\tif not existingParams:\n\t\t\t\tvideo._videoEnqueuedCalls += [pendingCall]\n\t\t\telse:\n\t\t\t\t#Update the parameters of the next playback call instead of enqueueing a new call.\n\t\t\t\tfor k, v in pendingCall._args[1].items():\n\t\t\t\t\texistingParams[-1][k] = v\n\t\t\t\t\n\t\t\treturn\n\t\t\n\t\t#Step 2: Is there already a set call pending? (Note that non-set calls act as set barriers; two sets won't get coalesced if a non-set call is between them.)\n\t\tif coalesce and [pendingCall] == video._videoEnqueuedCalls[:1]:\n\t\t\tvideo._videoEnqueuedCalls[-1] = pendingCall\n\t\telse:\n\t\t\tvideo._videoEnqueuedCalls += [pendingCall]\n\t\n\t@staticmethod\n\tdef _startNextCallback():\n\t\t\"\"\"Check for pending callbacks.\n\t\t\t\n\t\t\tIf none are found, simply stop.\n\t\t\t\n\t\t\tNote: Needs to be manually pumped.\n\t\t\"\"\"\n\t\t\n\t\tif video._videoEnqueuedCalls:\n\t\t\tvideo._videoCallInProgress = True\n\t\t\tvideo._videoEnqueuedCalls.pop(0)._startAsyncCall()\n\t\telse:\n\t\t\tvideo._videoCallInProgress = False\n\t\n\t\n\tclass call(QObject):\n\t\t\"\"\"Call the camera video DBus API. First arg is the function name. Returns a promise.\n\t\t\n\t\t\tSee http://doc.qt.io/qt-5/qdbusabstractinterface.html#call for details about calling.\n\t\t\tSee https://github.com/krontech/chronos-cli/tree/master/src/api for implementation details about the API being called.\n\t\t\tSee README.md at https://github.com/krontech/chronos-cli/tree/master/src/daemon for API documentation.\n\t\t\"\"\"\n\t\t\n\t\tdef __init__(self, *args, immediate=True):\n\t\t\tassert args, \"Missing call name.\"\n\t\t\t\n\t\t\tsuper().__init__()\n\t\t\t\n\t\t\tself._args = args\n\t\t\tself._thens = []\n\t\t\tself._catches = []\n\t\t\tself._done = False\n\t\t\tself._watcherHolder = None\n\t\t\tself.performance = {\n\t\t\t\t'enqueued': perf_counter(),\n\t\t\t\t'started': 0.,\n\t\t\t\t'finished': 0.,\n\t\t\t\t'handled': 0.,\n\t\t\t}\n\t\t\t\n\t\t\tlog.debug(f'enquing {self}')\n\t\t\tvideo._enqueueCallback(self)\n\t\t\t#log.print(f'current video queue: {video._videoEnqueuedCalls}')\n\t\t\tif not video._videoCallInProgress:\n\t\t\t\t#Don't start multiple callbacks at once, the most recent one will block.\n\t\t\t\tvideo._startNextCallback()\n\t\t\n\t\tdef __eq__(self, other):\n\t\t\t# If a video call sets the same keys as another\n\t\t\t# video call, then it is equal to itself and can\n\t\t\t# be deduplicated as all sets of the same values\n\t\t\t# have the same side effects. (ie, Slider no go\n\t\t\t# fast if me no drop redundant call.)\n\t\t\t# –DDR 2019-05-14\n\t\t\treturn (\n\t\t\t\t'set' == self._args[0] == other._args[0]\n\t\t\t\tand self._args[1].keys() == other._args[1].keys()\n\t\t\t)\n\t\t\n\t\tdef __repr__(self):\n\t\t\treturn f'''video.call({', '.join([repr(x) for x in self._args])})'''\n\t\t\t\n\t\t\n\t\tdef _startAsyncCall(self):\n\t\t\tlog.debug(f'starting async call: {self._args[0]}({self._args[1:]})')\n\t\t\tself.performance['started'] = perf_counter()\n\t\t\tself._watcherHolder = QDBusPendingCallWatcher(\n\t\t\t\tcameraVideoAPI.asyncCallWithArgumentList(self._args[0], self._args[1:])\n\t\t\t)\n\t\t\tself._watcherHolder.finished.connect(self._asyncCallFinished)\n\t\t\tvideo._activeCall = self\n\t\t\t\n\t\t\n\t\tdef _asyncCallFinished(self, watcher):\n\t\t\tlog.debug(f'finished async call: {self}')\n\t\t\tself.performance['finished'] = perf_counter()\n\t\t\tself._done = True\n\t\t\t\n\t\t\treply = QDBusPendingReply(watcher)\n\t\t\ttry:\n\t\t\t\tif reply.isError():\n\t\t\t\t\tif self._catches:\n\t\t\t\t\t\tfor catch in self._catches:\n\t\t\t\t\t\t\tcatch(reply.error())\n\t\t\t\t\telse:\n\t\t\t\t\t\t#This won't do much, but (I'm assuming) most calls simply won't ever fail.\n\t\t\t\t\t\tif reply.error().name() == 'org.freedesktop.DBus.Error.NoReply':\n\t\t\t\t\t\t\traise DBusException(f\"{self} timed out ({API_TIMEOUT_MS}ms)\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\traise DBusException(\"%s: %s\" % (reply.error().name(), reply.error().message()))\n\t\t\t\telse:\n\t\t\t\t\tvalue = reply.value()\n\t\t\t\t\tfor then in self._thens:\n\t\t\t\t\t\tvalue = then(value)\n\t\t\texcept Exception as e:\n\t\t\t\traise e\n\t\t\tfinally:\n\t\t\t\t#Wait a little while before starting on the next callback.\n\t\t\t\t#This makes the UI run much smoother, and usually the lag\n\t\t\t\t#is covered by the UI updating another few times anyway.\n\t\t\t\t#Note that because each call still lags a little, this\n\t\t\t\t#causes a few dropped frames every time the API is called.\n\t\t\t\t#video._startNextCallback()\n\t\t\t\tdelay(self, API_INTERCALL_DELAY, video._startNextCallback)\n\t\t\t\t\n\t\t\t\tself.performance['handled'] = perf_counter()\n\t\t\t\tif self.performance['finished'] - self.performance['started'] > API_SLOW_WARN_MS / 1000:\n\t\t\t\t\tlog.warn(\n\t\t\t\t\t\tf'''slow call: {self} took {\n\t\t\t\t\t\t\t(self.performance['finished'] - self.performance['started'])*1000\n\t\t\t\t\t\t:0.0f}ms/{API_SLOW_WARN_MS}ms. (Total call time was {\n\t\t\t\t\t\t\t(self.performance['handled'] - self.performance['enqueued'])*1000\n\t\t\t\t\t\t:0.0f}ms.)'''\n\t\t\t\t\t)\n\t\t\n\t\tdef then(self, callback):\n\t\t\tassert callable(callback), \"video().then() only accepts a single, callable function.\"\n\t\t\tassert not self._done, \"Can't register new then() callback, call has already been resolved.\"\n\t\t\tself._thens += [callback]\n\t\t\treturn self\n\t\t\n\t\tdef catch(self, callback):\n\t\t\tassert callable(callback), \"video().then() only accepts a single, callable function.\"\n\t\t\tassert not self._done, \"Can't register new then() callback, call has already been resolved.\"\n\t\t\tself._catches += [callback]\n\t\t\treturn self\n\t\n\tdef callSync(*args, warnWhenCallIsSlow=True, **kwargs):\n\t\t\"\"\"Call the camera video DBus API. First arg is the function name.\n\t\t\t\n\t\t\tThis is the synchronous version of the call() method. It\n\t\t\tis much slower to call synchronously than asynchronously!\n\t\t\n\t\t\tSee http://doc.qt.io/qt-5/qdbusabstractinterface.html#call for details about calling.\n\t\t\tSee https://github.com/krontech/chronos-cli/tree/master/src/api for implementation details about the API being called.\n\t\t\tSee README.md at https://github.com/krontech/chronos-cli/tree/master/src/daemon for API documentation.\n\t\t\"\"\"\n\t\t\n\t\t#Unwrap D-Bus errors from message.\n\t\tlog.debug(f'control.callSync{tuple(args)}')\n\t\t\n\t\tstart = perf_counter()\n\t\tmsg = QDBusReply(cameraVideoAPI.call(*args, **kwargs))\n\t\tend = perf_counter()\n\t\tif warnWhenCallIsSlow and (end - start > API_SLOW_WARN_MS / 1000):\n\t\t\tlog.warn(f'slow call: control.callSync{tuple(args)} took {(end-start)*1000:.0f}ms/{API_SLOW_WARN_MS}ms.')\n\t\t\n\t\tif msg.isValid():\n\t\t\treturn msg.value()\n\t\telse:\n\t\t\tif msg.error().name() == 'org.freedesktop.DBus.Error.NoReply':\n\t\t\t\traise DBusException(f\"control.callSync{tuple(args)} timed out ({API_TIMEOUT_MS}ms)\")\n\t\t\telse:\n\t\t\t\traise DBusException(\"%s: %s\" % (msg.error().name(), msg.error().message()))\n\t\n\t\n\tdef restart(*_):\n\t\t\"\"\"Helper method to reboot the video pipeline.\n\t\t\t\n\t\t\tSometimes calls do not apply until you restart the daemon, although they should.\n\t\t\tLiterally every use of this function is a bug.\n\t\t\"\"\"\n\t\t\n\t\tos.system('killall -HUP cam-pipeline')\n\n\nclass control():\n\t\"\"\"Call the D-Bus control API, asychronously.\n\t\t\n\t\tMethods:\n\t\t\t- call(function[, arg1[ ,arg2[, ...]]])\n\t\t\t\tCall the remote function.\n\t\t\t- get([value[, ...]])\n\t\t\t\tGet the named values from the API.\n\t\t\t- set({key: value[, ...]}])\n\t\t\t\tSet the named values in the API.\n\t\t\n\t\tAll methods return an A* promise-like, in that you use\n\t\t`.then(cb(value))` and `.catch(cb(error))` to get the results\n\t\tof calling the function.\n\t\"\"\"\n\t\n\t_controlEnqueuedCalls = []\n\t_controlCallInProgress = False\n\t_activeCall = None\n\t\n\t@staticmethod\n\tdef _enqueueCallback(pendingCall, coalesce: bool=True): #pendingCall is control.call\n\t\t\"\"\"Enqueue callback. Squash and elide calls to set for efficiency.\"\"\"\n\t\t\n\t\t#Step 1: Will this call actually do anything? Elide it if not.\n\t\tanticipitoryUpdates = False #Emit update signals before sending the update to the API. Results in faster UI updates but poorer framerate.\n\t\tif coalesce and pendingCall._args[0] == 'set':\n\t\t\t#Elide this call if it would not change known state.\n\t\t\thasNewInformation = False\n\t\t\tnewItems = pendingCall._args[1].items()\n\t\t\tfor key, value in newItems:\n\t\t\t\tif _camState[key] != value:\n\t\t\t\t\thasNewInformation = True\n\t\t\t\t\tif not anticipitoryUpdates:\n\t\t\t\t\t\tbreak\n\t\t\t\t\t#Update known cam state in advance of state transition.\n\t\t\t\t\tlog.info(f'Anticipating {key} → {value}.')\n\t\t\t\t\t_camState[key] = value\n\t\t\t\t\tfor callback in apiValues._callbacks[key]:\n\t\t\t\t\t\tcallback(value)\n\t\t\tif not hasNewInformation:\n\t\t\t\treturn\n\t\t\n\t\t#Step 2: Is there already a set call pending? (Note that non-set calls act as set barriers; two sets won't get coalesced if a non-set call is between them.)\n\t\tif coalesce and [pendingCall] == control._controlEnqueuedCalls[:1]:\n\t\t\tcontrol._controlEnqueuedCalls[-1] = pendingCall\n\t\telse:\n\t\t\tcontrol._controlEnqueuedCalls += [pendingCall]\n\t\n\t@staticmethod\n\tdef _startNextCallback():\n\t\t\"\"\"Check for pending callbacks.\n\t\t\t\n\t\t\tIf none are found, simply stop.\n\t\t\t\n\t\t\tNote: Needs to be manually pumped.\n\t\t\"\"\"\n\t\t\n\t\tif control._controlEnqueuedCalls:\n\t\t\tcontrol._controlCallInProgress = True\n\t\t\tcontrol._controlEnqueuedCalls.pop(0)._startAsyncCall()\n\t\telse:\n\t\t\tcontrol._controlCallInProgress = False\n\t\n\t\n\tclass call(QObject):\n\t\t\"\"\"Call the camera control DBus API. First arg is the function name. Returns a promise.\n\t\t\n\t\t\tSee http://doc.qt.io/qt-5/qdbusabstractinterface.html#call for details about calling.\n\t\t\tSee https://github.com/krontech/chronos-cli/tree/master/src/api for implementation details about the API being called.\n\t\t\tSee README.md at https://github.com/krontech/chronos-cli/tree/master/src/daemon for API documentation.\n\t\t\"\"\"\n\t\t\n\t\tdef __init__(self, *args, immediate=True):\n\t\t\tassert args, \"Missing call name.\"\n\t\t\t\n\t\t\tsuper().__init__()\n\t\t\t\n\t\t\tself._args = args\n\t\t\tself._thens = []\n\t\t\tself._catches = []\n\t\t\tself._done = False\n\t\t\tself._watcherHolder = None\n\t\t\tself.performance = {\n\t\t\t\t'enqueued': perf_counter(),\n\t\t\t\t'started': 0.,\n\t\t\t\t'finished': 0.,\n\t\t\t\t'handled': 0.,\n\t\t\t}\n\t\t\t\n\t\t\tlog.debug(f'enquing {self}')\n\t\t\tcontrol._enqueueCallback(self)\n\t\t\t#log.print(f'current control queue: {control._controlEnqueuedCalls}')\n\t\t\tif not control._controlCallInProgress:\n\t\t\t\t#Don't start multiple callbacks at once, the most recent one will block.\n\t\t\t\tcontrol._startNextCallback()\n\t\t\n\t\tdef __eq__(self, other):\n\t\t\t# If a control call sets the same keys as another\n\t\t\t# control call, then it is equal to itself and can\n\t\t\t# be deduplicated as all sets of the same values\n\t\t\t# have the same side effects. (ie, Slider no go\n\t\t\t# fast if me no drop redundant call.)\n\t\t\t# –DDR 2019-05-14\n\t\t\treturn (\n\t\t\t\t'set' == self._args[0] == other._args[0]\n\t\t\t\tand self._args[1].keys() == other._args[1].keys()\n\t\t\t)\n\t\t\n\t\tdef __repr__(self):\n\t\t\treturn f'''control.call({', '.join([repr(x) for x in self._args])})'''\n\t\t\t\n\t\t\n\t\tdef _startAsyncCall(self):\n\t\t\tlog.debug(f'starting async call: {self._args[0]}({self._args[1:]})')\n\t\t\tself.performance['started'] = perf_counter()\n\t\t\tself._watcherHolder = QDBusPendingCallWatcher(\n\t\t\t\tcameraControlAPI.asyncCallWithArgumentList(self._args[0], self._args[1:])\n\t\t\t)\n\t\t\tself._watcherHolder.finished.connect(self._asyncCallFinished)\n\t\t\tcontrol._activeCall = self\n\t\t\t\n\t\t\n\t\tdef _asyncCallFinished(self, watcher):\n\t\t\tlog.debug(f'finished async call: {self}')\n\t\t\tself.performance['finished'] = perf_counter()\n\t\t\tself._done = True\n\t\t\t\n\t\t\treply = QDBusPendingReply(watcher)\n\t\t\ttry:\n\t\t\t\tif reply.isError():\n\t\t\t\t\tif self._catches:\n\t\t\t\t\t\terror = reply.error()\n\t\t\t\t\t\tfor catch in self._catches:\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\terror = catch(error)\n\t\t\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\t\t\terror = e\n\t\t\t\t\telse:\n\t\t\t\t\t\t#This won't do much, but (I'm assuming) most calls simply won't ever fail.\n\t\t\t\t\t\tif reply.error().name() == 'org.freedesktop.DBus.Error.NoReply':\n\t\t\t\t\t\t\traise DBusException(f\"{self} timed out ({API_TIMEOUT_MS}ms)\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\traise DBusException(\"%s: %s\" % (reply.error().name(), reply.error().message()))\n\t\t\t\telse:\n\t\t\t\t\tvalue = reply.value()\n\t\t\t\t\tfor then in self._thens:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tvalue = then(value)\n\t\t\t\t\t\texcept Exception as error:\n\t\t\t\t\t\t\tif self._catches:\n\t\t\t\t\t\t\t\tfor catch in self._catches:\n\t\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\t\terror = catch(error)\n\t\t\t\t\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\t\t\t\t\terror = e\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\traise e\n\t\t\texcept Exception as e:\n\t\t\t\traise e\n\t\t\tfinally:\n\t\t\t\t#Wait a little while before starting on the next callback.\n\t\t\t\t#This makes the UI run much smoother, and usually the lag\n\t\t\t\t#is covered by the UI updating another few times anyway.\n\t\t\t\t#Note that because each call still lags a little, this\n\t\t\t\t#causes a few dropped frames every time the API is called.\n\t\t\t\tdelay(self, API_INTERCALL_DELAY, control._startNextCallback)\n\t\t\t\t\n\t\t\t\tself.performance['handled'] = perf_counter()\n\t\t\t\tif self.performance['finished'] - self.performance['started'] > API_SLOW_WARN_MS / 1000:\n\t\t\t\t\tlog.warn(\n\t\t\t\t\t\tf'''slow call: {self} took {\n\t\t\t\t\t\t\t(self.performance['finished'] - self.performance['started'])*1000\n\t\t\t\t\t\t:0.0f}ms/{API_SLOW_WARN_MS}ms. (Total call time was {\n\t\t\t\t\t\t\t(self.performance['handled'] - self.performance['enqueued'])*1000\n\t\t\t\t\t\t:0.0f}ms.)'''\n\t\t\t\t\t)\n\t\t\n\t\tdef then(self, callback):\n\t\t\tassert callable(callback), \"control().then() only accepts a single, callable function.\"\n\t\t\tassert not self._done, \"Can't register new then() callback, call has already been resolved.\"\n\t\t\tself._thens += [callback]\n\t\t\treturn self\n\t\t\n\t\tdef catch(self, callback):\n\t\t\tassert callable(callback), \"control().then() only accepts a single, callable function.\"\n\t\t\tassert not self._done, \"Can't register new then() callback, call has already been resolved.\"\n\t\t\tself._catches += [callback]\n\t\t\treturn self\n\t\n\tdef callSync(*args, warnWhenCallIsSlow=True, **kwargs):\n\t\t\"\"\"Call the camera control DBus API. First arg is the function name.\n\t\t\t\n\t\t\tThis is the synchronous version of the call() method. It\n\t\t\tis much slower to call synchronously than asynchronously!\n\t\t\n\t\t\tSee http://doc.qt.io/qt-5/qdbusabstractinterface.html#call for details about calling.\n\t\t\tSee https://github.com/krontech/chronos-cli/tree/master/src/api for implementation details about the API being called.\n\t\t\tSee README.md at https://github.com/krontech/chronos-cli/tree/master/src/daemon for API documentation.\n\t\t\"\"\"\n\t\t\n\t\t#Unwrap D-Bus errors from message.\n\t\tlog.debug(f'control.callSync{tuple(args)}')\n\t\t\n\t\tstart = perf_counter()\n\t\tmsg = QDBusReply(cameraControlAPI.call(*args, **kwargs))\n\t\tend = perf_counter()\n\t\tif warnWhenCallIsSlow and (end - start > API_SLOW_WARN_MS / 1000):\n\t\t\tlog.warn(f'slow call: control.callSync{tuple(args)} took {(end-start)*1000:.0f}ms/{API_SLOW_WARN_MS}ms.')\n\t\t\t\n\t\tif msg.isValid():\n\t\t\treturn msg.value()\n\t\telse:\n\t\t\tif msg.error().name() == 'org.freedesktop.DBus.Error.NoReply':\n\t\t\t\traise DBusException(f\"control.callSync{tuple(args)} timed out ({API_TIMEOUT_MS}ms)\")\n\t\t\telse:\n\t\t\t\traise DBusException(\"%s: %s\" % (msg.error().name(), msg.error().message()))\n\n\t\n\n\ndef getSync(keyOrKeys):\n\t\"\"\"Call the camera control DBus get method.\n\t\n\t\tConvenience method for `control('get', [value])[0]`.\n\t\t\n\t\tAccepts key or [key, …], where keys are strings.\n\t\t\n\t\tReturns value or {key:value, …}, respectively.\n\t\t\n\t\tSee control's `availableKeys` for a list of valid inputs.\n\t\"\"\"\n\t\n\tvalueList = control.callSync('get',\n\t\t[keyOrKeys] if isinstance(keyOrKeys, str) else keyOrKeys )\n\treturn valueList[keyOrKeys] if isinstance(keyOrKeys, str) else valueList\n\ndef get(keyOrKeys):\n\t\"\"\"Call the camera control DBus get method.\n\t\n\t\tConvenience method for `control('get', [value])[0]`.\n\t\t\n\t\tAccepts key or [key, …], where keys are strings.\n\t\t\n\t\tReturns value or {key:value, …}, respectively.\n\t\t\n\t\tSee control's `availableKeys` for a list of valid inputs.\n\t\"\"\"\n\t\n\treturn control.call(\n\t\t'get', [keyOrKeys] if isinstance(keyOrKeys, str) else keyOrKeys\n\t).then(lambda valueList:\n\t\tvalueList[keyOrKeys] if isinstance(keyOrKeys, str) else valueList\n\t)\n\ndef setSync(*args):\n\t\"\"\"Call the camera control DBus set method.\n\t\t\n\t\tAccepts {str: value, ...} or a key and a value.\n\t\tReturns either a map of set values or the set\n\t\t\tvalue, if the second form was used.\n\t\"\"\"\n\t\n\tif len(args) == 1:\n\t\treturn control.callSync('set', *args)\n\telif len(args) == 2:\n\t\treturn control.callSync('set', {args[0]:args[1]})[args[0]]\n\telse:\n\t\traise valueError('bad args')\n\n\n\ndef set(*args):\n\t\"\"\"Call the camera control DBus set method.\n\t\t\n\t\tAccepts {str: value, ...} or a key and a value.\n\t\tReturns either a map of set values or the set\n\t\t\tvalue, if the second form was used.\n\t\"\"\"\n\t\n\tlog.debug(f'simple set call: {args}')\n\tif len(args) == 1:\n\t\treturn control.call('set', *args)\n\telif len(args) == 2:\n\t\treturn control.call(\n\t\t\t'set', {args[0]:args[1]}\n\t\t).then(lambda valueDict: \n\t\t\tvalueDict[args[0]]\n\t\t)\n\telse:\n\t\traise valueError('bad args')\n\n\n\n\n\n# State cache for observe(), so it doesn't have to query the status of a variable on each subscription.\n# Since this often crashes during development, the following line can be run to try getting each variable independently.\n# for key in [k for k in control.callSync('availableKeys') if k not in {'dateTime', 'externalStorage'}]: print('getting', key); control.callSync('get', [key])\n__badKeys = {} #set of blacklisted keys - useful for when one is unretrievable during development.\n_camState = control.callSync('get', [\n\tkey\n\tfor key in control.callSync('availableKeys')\n\tif key not in __badKeys\n], warnWhenCallIsSlow=False)\nif(not _camState):\n\traise Exception(\"Cache failed to populate. This indicates the get call is not working.\")\n_camState['error'] = '' #Last error is reported inline sometimes.\nif 'videoSegments' not in _camState:\n\tlog.warn('videoSegments not found in availableKeys (pychronos/issues/31)')\n\t_camState['videoSegments'] = []\nif 'videoZoom' not in _camState:\n\tlog.warn('videoZoom not found in availableKeys (pychronos/issues/52)')\n\t_camState['videoZoom'] = 1\n_camStateAge = {k:0 for k,v in _camState.items()}\n\nclass APIValues(QObject):\n\t\"\"\"Wrapper class for subscribing to API values in the chronos API.\"\"\"\n\t\n\tdef __init__(self):\n\t\tsuper(APIValues, self).__init__()\n\t\t\n\t\t#The .connect call freezes if we don't do this, or if we do this twice.\n\t\tQDBusConnection.systemBus().registerObject(\n\t\t\tf\"/ca/krontech/chronos/{'control_mock_hack' if USE_MOCK else 'control_hack'}\", \n\t\t\tself,\n\t\t)\n\t\t\n\t\tself._callbacks = {value: [] for value in _camState}\n\t\tself._callbacks['all'] = [] #meta, watch everything\n\t\t\n\t\tQDBusConnection.systemBus().connect(\n\t\t\tf\"ca.krontech.chronos.{'control_mock' if USE_MOCK else 'control'}\", \n\t\t\tf\"/ca/krontech/chronos/{'control_mock' if USE_MOCK else 'control'}\",\n\t\t\tf\"\",\n\t\t\t'notify', \n\t\t\tself.__newKeyValue,\n\t\t)\n\t\n\tdef observe(self, key, callback):\n\t\t\"\"\"Add a function to get called when a value is updated.\"\"\"\n\t\tassert callable(callback), f\"Callback is not callable. (Expected function, got {callback}.)\"\n\t\tassert key in self._callbacks, f\"Unknown value, '{key}', to observe.\\n\\nAvailable keys are: \\n{chr(10).join(self._callbacks.keys())}\\n\\nDid you mean to observe '{(get_close_matches(key, self._callbacks.keys(), n=1) or ['???'])[0]}' instead of '{key}'?\\n\"\n\t\tself._callbacks[key].append(callback)\n\t\n\tdef unobserve(self, key, callback):\n\t\t\"\"\"Stop a function from getting called when a value is updated.\"\"\"\n\t\tassert callable(callback), f\"Callback is not callable. (Expected function, got {callback}.)\"\n\t\tself._callbacks[key].remove(callback)\n\t\n\tdef __newValueIsEnqueued(self, key):\n\t\treturn True in [\n\t\t\tkey in call._args[1]\n\t\t\tfor call in control._controlEnqueuedCalls\n\t\t\tif call._args[0] == 'set'\n\t\t]\n\t\n\t@pyqtSlot('QDBusMessage')\n\tdef __newKeyValue(self, msg):\n\t\t\"\"\"Update _camState and invoke any registered observers.\"\"\"\n\t\tnewItems = msg.arguments()[0].items()\n\t\tlog.info(f'Received new information. {msg.arguments()[0] if len(str(msg.arguments()[0])) <= 45 else chr(10)+prettyFormat(msg.arguments()[0])}')\n\t\tfor key, value in newItems:\n\t\t\tif _camState[key] != value and not self.__newValueIsEnqueued(key):\n\t\t\t\t_camState[key] = value\n\t\t\t\t_camStateAge[key] += 1\n\t\t\t\tfor callback in self._callbacks[key]:\n\t\t\t\t\tcallback(value)\n\t\t\t\tfor callback in self._callbacks['all']:\n\t\t\t\t\tcallback(key, value)\n\t\t\telse:\n\t\t\t\tlog.info(f'Ignoring {key} → {value}, stale.')\n\t\n\tdef get(self, key):\n\t\treturn _camState[key]\n\napiValues = APIValues()\ndel APIValues\n\n\ndef observe(name: str, callback: Callable[[Any], None]) -> None:\n\t\"\"\"Observe changes in a state value.\n\t\n\t\tArgs:\n\t\t\tname: ID of the state variable. \"exposure\", \"focusPeakingColor\", etc.\n\t\t\tcallback: Function called when the state updates and upon subscription.\n\t\t\t\tCalled with one parameter, the new value. Called when registered\n\t\t\t\tand when the value updates.\n\t\t\n\t\tNote: Some frequently updated values (~> 10/sec) are only available via\n\t\t\tpolling due to flooding concerns. They can not be observed, as they're\n\t\t\tassumed to *always* be changed. See the API docs for more details.\n\t\t\n\t\t\n\t\tRationale:\n\t\tIt is convenient and less error-prone if we only have one callback that\n\t\thandles the initialization and update of values. The API provides separate\n\t\tinitialization and update methods, so we'll store the initialization and\n\t\tuse it to perform the initial call to the observe() callback.\n\t\t\n\t\tIn addition, this means we only have to query the initial state once,\n\t\tretrieving a blob of all the data available, rather than retrieving each\n\t\tkey one syscall at a time as we instantiate each Qt control.\n\t\"\"\"\n\t\n\tassert callable(callback), f\"Callback is not callable. (Expected function, got {callback}.)\"\n\tapiValues.observe(name, callback)\n\tcallback(apiValues.get(name))\n\n\ndef observe_future_only(name: str, callback: Callable[[Any], None]) -> None:\n\t\"\"\"Like `observe`, but without the initial callback when observing.\n\t\n\t\tUseful when `observe`ing a derived value, which observe can't deal with yet.\n\t\"\"\"\n\t\n\tassert callable(callback), f\"Callback is not callable. (Expected function, got {callback}.)\"\n\tapiValues.observe(name, callback)\n\n\nunobserve = apiValues.unobserve\n\n\n\nclass Signal(QObject):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\t\n\t\tself._signalObservers = {\n\t\t\t'sof': [], #Use lists here to preserve order of callbacks.\n\t\t\t'eof': [],\n\t\t\t'segment': [],\n\t\t}\n\t\t\n\t\t\n\t\t#The .connect call freezes if we don't do this, or if we do this twice.\n\t\tQDBusConnection.systemBus().registerObject(\n\t\t\tf\"/ca/krontech/chronos/{'video_mock_hack' if USE_MOCK else 'video_hack'}\", \n\t\t\tself,\n\t\t)\n\t\t\n\t\tfor signal_ in self._signalObservers:\n\t\t\tQDBusConnection.systemBus().connect(\n\t\t\t\tf\"ca.krontech.chronos.{'video_mock' if USE_MOCK else 'video'}\", \n\t\t\t\tf\"/ca/krontech/chronos/{'video_mock' if USE_MOCK else 'video'}\",\n\t\t\t\tf\"\",\n\t\t\t\tsignal_, \n\t\t\t\tgetattr(self, f'_{type(self).__name__}__{signal_}')\n\t\t\t)\n\t\n\t\n\t#Sort of a reverse trampoline, needed because callbacks must be decorated.\n\t@pyqtSlot('QDBusMessage')\n\tdef __sof(self, msg):\n\t\tlog.debug(f'''video signal: sof ({len(self._signalObservers['sof'])} handlers)''')\n\t\tself.__invokeCallbacks('sof', *msg.arguments())\n\t@pyqtSlot('QDBusMessage')\n\tdef __eof(self, msg):\n\t\tlog.debug(f'''video signal: eof ({len(self._signalObservers['eof'])} handlers)''')\n\t\tself.__invokeCallbacks('eof', *msg.arguments())\n\t@pyqtSlot('QDBusMessage')\n\tdef __segment(self, msg):\n\t\tlog.debug(f'''video signal: segment ({len(self._signalObservers['segment'])} handlers)''')\n\t\tself.__invokeCallbacks('segment', *msg.arguments())\n\t\n\tdef __invokeCallbacks(self, signal, data):\n\t\tfor callback in self._signalObservers[signal]:\n\t\t\tcallback(data)\n\t\n\t\n\tdef observe(self, signal: str, handler: Callable[[Any], None]) -> None:\n\t\t\"\"\"Add a function to get called when a D-BUS signal is emitted.\"\"\"\n\t\tassert callable(handler), f\"Handler is not callable. (Expected function, got {handler}.)\"\n\t\tself._signalObservers[signal].append(handler)\n\t\n\tdef unobserve(self, signal: str, handler: Callable[[Any], None]) -> None:\n\t\t\"\"\"Stop a function from getting called when a D-BUS signal is emitted.\"\"\"\n\t\tassert callable(handler), f\"Handler is not callable. (Expected function, got {handler}.)\"\n\t\tself._signalObservers[signal].remove(handler)\nsignal = Signal()\ndel Signal\t\n\n\n\n#Perform self-test if launched as a standalone.\nif __name__ == '__main__':\n\tfrom PyQt5.QtCore import QCoreApplication\n\timport signal as sysSignal\n\t\n\tapp = QCoreApplication(sys.argv)\n\t\n\t#Quit on ctrl-c.\n\tsysSignal.sysSignal(sysSignal.SIGINT, sysSignal.SIG_DFL)\n\t\n\tprint(\"Self-test: Retrieve exposure period.\")\n\tprint(f\"Exposure is {get('exposurePeriod')}ns.\")\n\tprint(\"Control API self-test passed. Goodbye!\")\n\t\n\tsys.exit(0)","repo_name":"krontech/chronos-web-interface","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":28921,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"70341120330","text":"def fn(a,i,n,key):\n if i==n:\n return -1\n if a[i]==key:\n return i\n return fn(a,i+1,n,key)\nlist1=list(map(int,input().split()))\nn=len(list1)\nkey=int(input())\nc=fn(list1,0,n,key)\nif c==-1:\n print(\"No is not present\")\nelse:\n print(c)\n","repo_name":"tinkalkumar007/Competitive_Coding","sub_path":"linearSearch_rcrsn.py","file_name":"linearSearch_rcrsn.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"21952014190","text":"from re import template\nfrom django.shortcuts import render, get_object_or_404\nfrom django.views import View\nfrom .models import Job, field_choices, field_choices_dict\nfrom django.urls import reverse, reverse_lazy\nfrom django.http import Http404, HttpResponseRedirect\nfrom .forms import JobCreationForm\n# Create your views here.\n\nclass index(View):\n def get(self, request):\n return render(request, \"jobs/index.html\", {'field_choices' : field_choices})\n \nclass listJobs(View):\n \n def get(self, request, *args, **kwargs):\n \n if kwargs['field'] not in field_choices_dict.keys():\n raise Http404('
\r\n Hi page\r\n \r\n Comment!\r\n \r\n \r\n \"\"\"\r\n return html\r\n\r\n\r\n@app.route('/hello')\r\ndef say_hello():\r\n \"\"\"Return simple 'hello' greeting in flask basics demo\"\"\"\r\n html = \"\"\"\r\n \r\n \r\n
Hello
\r\n \r\n \r\n \"\"\"\r\n return html\r\n\r\n\r\n@app.route('/querystringtest')\r\ndef query_string_test():\r\n \"\"\"Parses query string into more legible format in query string demo\"\"\"\r\n response = ''\r\n for item in request.args:\r\n response+= f\"
{item}:{request.args[item]}
\"\r\n \r\n return response\r\n \r\n\r\n@app.route('/postrequestpage',methods=[\"POST\"])\r\ndef post_request_page():\r\n \"\"\"Makes a post request in POST request demo\"\"\"\r\n\r\n return 'this was a POST request'\r\n\r\n\r\n@app.route('/addcomment')\r\ndef add_comment_form():\r\n \"\"\"Serves a comment form to be POSTed in form submission demo\"\"\"\r\n\r\n html = \"\"\"\r\n \r\n \r\n \r\n \r\n \r\n \"\"\"\r\n return html\r\n\r\n\r\n@app.route('/addcomment',methods=[\"POST\"])\r\ndef post_comment():\r\n \"\"\"Posts comment to page in form submission demo\"\"\"\r\n\r\n comment = request.form[\"comment\"]\r\n return f\"You commented: \\n {comment}\"\r\n\r\n\r\n@app.route('/comments/')\r\ndef show_comment(id):\r\n \"\"\"Shows comment number in path variable demo\"\"\"\r\n #int in route path is optional, specifies that path variable is int\r\n\r\n html = f\"\"\"\r\n \r\n \r\n
You've reached comment number {id}
\r\n \r\n \r\n \"\"\"\r\n return html\r\n\r\n\r\n#let's pretend there's a function here to showcase the incredible difficulty of using multiple path variables in one route path\r\n\r\n\r\n@app.route('/templates/hello')\r\ndef jinja_hello():\r\n \"\"\"Demo of Jinja to render static template of hello.html\"\"\"\r\n\r\n return render_template('hello.html')\r\n\r\n\r\n@app.route('/lucky')\r\ndef lucky_page():\r\n \"\"\"Demo of dynamic HTML template using Jinja by making a page that displays a random lucky number\"\"\"\r\n\r\n lucky_num = randint(1,20)\r\n #inside lucky.html, the variable is named lucky_var and we can use it inside {{ }}\r\n return render_template('lucky.html',lucky_num = lucky_num)\r\n\r\n\r\n@app.route('/base')\r\ndef base_temp():\r\n \"\"\"Demo of template inheritance, base template\"\"\"\r\n\r\n return render_template('base.html')\r\n\r\n\r\n@app.route('/child')\r\ndef child_temp():\r\n \"\"\"Demo of template inheritance, child template\"\"\"\r\n\r\n return render_template('child.html')\r\n\r\n\r\n@app.route('/funform')\r\ndef funform_view():\r\n \"\"\"Returns simple name submission form\"\"\"\r\n\r\n return render_template('funform.html')\r\n\r\n\r\nname = 'ravi'\r\n@app.route('/funform', methods=[\"POST\"])\r\ndef funform_post():\r\n \"\"\"Saves name to global variable\"\"\"\r\n name = request.form.get(\"name\",default=\"kiran\")\r\n return redirect('/funformdone')\r\n\r\n\r\n@app.route('/funformdone')\r\ndef funformdone_view():\r\n return name","repo_name":"RaviP1494/PythonFlaskUnit","sub_path":"first-flask-server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"39540382635","text":"import requests\nimport re\n\nfrom collections import defaultdict\nfrom datetime import datetime\nfrom bs4 import BeautifulSoup\nfrom cloudbot import hook\n\nsearch_pages = defaultdict(list)\n\nuser_url = \"http://reddit.com/user/{}/\"\nsubreddit_url = \"http://reddit.com/r/{}/\"\n# This agent should be unique for your cloudbot instance\nagent = {\"User-Agent\":\"gonzobot a cloudbot (IRCbot) implementation for snoonet.org by /u/bloodygonzo\"}\n\n\ndef two_lines(bigstring, chan):\n \"\"\"Receives a string with new lines. Groups the string into a list of strings with up to 2 new lines per string element. Returns first string element then stores the remaining list in search_pages.\"\"\"\n global search_pages\n temp = bigstring.split('\\n')\n for i in range(0, len(temp), 2):\n search_pages[chan].append('\\n'.join(temp[i:i+2]))\n search_pages[chan+\"index\"] = 0\n return search_pages[chan][0]\n\n\ndef smart_truncate(content, length=355, suffix='...\\n'):\n if len(content) <= length:\n return content\n else:\n return content[:length].rsplit(' \\u2022 ', 1)[0]+ suffix + content[:length].rsplit(' \\u2022 ', 1)[1] + smart_truncate(content[length:])\n\ndef statuscheck(status, item):\n \"\"\"since we are doing this a lot might as well return something more meaningful\"\"\"\n out = \"\"\n if status == 404:\n out = \"It appears {} does not exist.\".format(item)\n elif status == 403:\n out = \"Sorry {} is set to private and I cannot access it.\".format(item)\n elif status == 429:\n out = \"Reddit appears to be rate-limiting me. Please try again in a few minutes.\"\n elif status == 503:\n out = \"Reddit is having problems, it would be best to check back later.\"\n else:\n out = \"Reddit returned an error, response: {}\".format(status)\n return out\n\n@hook.command(\"moremod\", autohelp=False)\ndef moremod(text, chan):\n \"\"\"if a sub or mod list has lots of results the results are pagintated. If the most recent search is paginated the pages are stored for retreival. If no argument is given the next page will be returned else a page number can be specified.\"\"\"\n if not search_pages[chan]:\n return \"There are modlist pages to show.\"\n if text:\n index = \"\"\n try:\n index = int(text)\n except:\n return \"Please specify an integer value.\"\n if abs(int(index)) > len(search_pages[chan]) or index == 0:\n return \"please specify a valid page number between 1 and {}.\".format(len(search_pages[chan]))\n else:\n return \"{}(page {}/{})\".format(search_pages[chan][index-1], index, len(search_pages[chan]))\n else:\n search_pages[chan+\"index\"] += 1\n if search_pages[chan+\"index\"] < len(search_pages[chan]):\n return \"{}(page {}/{})\".format(search_pages[chan][search_pages[chan+\"index\"]], search_pages[chan+\"index\"] + 1, len(search_pages[chan]))\n else:\n return \"All pages have been shown.\"\n\n\n@hook.command(\"subs\", \"moderates\", singlethreaded=True)\ndef moderates(text, chan):\n \"\"\"This plugin prints the list of subreddits a user moderates listed in a reddit users profile. Private subreddits will not be listed.\"\"\"\n #This command was written using concepts from FurCode http://github.com/FurCode.\n global search_pages\n search_pages[chan] = []\n search_pages[chan+\"index\"] = 0\n user = text\n r = requests.get(user_url.format(user), headers=agent)\n if r.status_code != 200:\n return statuscheck(r.status_code, user)\n soup = BeautifulSoup(r.text)\n try:\n modlist = soup.find('ul', id=\"side-mod-list\").text\n except:\n return \"{} does not moderate any public subreddits.\".format(user)\n modlist = modlist.split('/r/')\n del modlist[0]\n out = \"\\x02{}\\x02 moderates these public subreddits: \".format(user)\n for sub in modlist:\n out += \"{} \\u2022 \".format(sub)\n out = out[:-2]\n out = smart_truncate(out)\n if len(out.split('\\n')) > 2:\n out = two_lines(out, chan)\n return \"{}(page {}/{}) .moremod\".format(out, search_pages[chan+\"index\"] + 1 , len(search_pages[chan]))\n return out\n\n\n@hook.command(\"karma\", \"ruser\", singlethreaded=True)\ndef karma(text):\n \"\"\"karma will return the information about the specified reddit username\"\"\"\n user = text\n url = user_url + \"about.json\"\n r = requests.get(url.format(user), headers=agent)\n if r.status_code != 200:\n return statuscheck(r.status_code, user)\n data = r.json()\n out = \"\\x02{}\\x02 \".format(user)\n out += \"\\x02{:,}\\x02 link karma and \".format(data['data']['link_karma'])\n out += \"\\x02{:,}\\x02 comment karma, \".format(data['data']['comment_karma'])\n if data['data']['is_gold']:\n out += \"has reddit gold, \"\n if data['data']['is_mod']:\n out += \"is a moderator, \"\n if data['data']['has_verified_email']:\n out += \"email has been verified, \"\n account_age = datetime.now() - datetime.fromtimestamp(data['data']['created'])\n if account_age.days > 365:\n age = int(account_age.days / 365)\n out += \"and has been a redditor for {} years.\".format(age)\n else:\n out += \"and has been a redditor for {} days.\".format(account_age.days)\n return out\n\ndef time_format(numdays):\n age = ()\n if numdays >= 365:\n age = (int(numdays / 365), \"y\")\n if age[0] > 1:\n age = (age[0], \"y\")\n else:\n age = (numdays, \"d\")\n return age\n\n@hook.command(\"submods\", \"mods\", \"rmods\", singlethreaded=True)\ndef submods(text, chan):\n \"\"\"submods prints the moderators of the specified subreddit. Do not include /r/ when specifying a subreddit.\"\"\"\n global search_pages\n search_pages[chan] = []\n search_pages[chan+\"index\"] = 0\n sub = text\n url = subreddit_url + \"about/moderators.json\"\n r = requests.get(url.format(sub), headers=agent)\n if r.status_code != 200:\n return statuscheck(r.status_code, 'r/'+sub)\n data = r.json()\n out = \"r/\\x02{}\\x02 mods: \".format(sub)\n for mod in data['data']['children']:\n username = mod['name']\n # Showing the modtime makes the message too long for larger subs\n # if you want to show this information add modtime.days to out below\n modtime = datetime.now() - datetime.fromtimestamp(mod['date'])\n modtime = time_format(modtime.days)\n out += \"{} ({}{}) \\u2022 \".format(username, modtime[0], modtime[1])\n out = smart_truncate(out)\n out = out[:-3]\n if len(out.split('\\n')) > 2:\n out = two_lines(out, chan)\n return \"{}(page {}/{}) .moremod\".format(out, search_pages[chan+\"index\"] + 1 , len(search_pages[chan]))\n return out\n\n@hook.command(\"subinfo\",\"subreddit\", \"sub\", \"rinfo\", singlethreaded=True)\ndef subinfo(text):\n \"\"\"subinfo fetches information about the specified subreddit. Do not include /r/ when specifying a subreddit.\"\"\"\n sub = text\n url = subreddit_url + \"about.json\"\n r = requests.get(url.format(sub), headers=agent)\n if r.status_code != 200:\n return statuscheck(r.status_code, 'r/'+sub)\n data = r.json()\n if data['kind'] == \"Listing\":\n return \"It appears r/{} does not exist.\".format(sub)\n name = data['data']['display_name']\n title = data['data']['title']\n nsfw = data['data']['over18']\n subscribers = data['data']['subscribers']\n active = data['data']['accounts_active']\n sub_age = datetime.now() - datetime.fromtimestamp(data['data']['created'])\n age = ()\n if sub_age.days >= 365:\n age = (int(sub_age.days / 365), \"y\")\n else:\n age = (sub_age.days, \"d\")\n out = \"r/\\x03{}\\x02 - {} - a community for {}{}, there are {:,} subscribers and {:,} people online now.\".format(name, title, age[0], age[1], subscribers, active)\n if nsfw:\n out += \" \\x0304NSFW\\x0304\"\n return out\n","repo_name":"CrushAndRun/Cloudbot-Tarball","sub_path":"plugins/reddit_info.py","file_name":"reddit_info.py","file_ext":"py","file_size_in_byte":7813,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"20647469102","text":"#User function Template for python3\n\nclass Solution:\n def getPairsCount(self, arr, n, k):\n # code here\n d={}\n ans=0\n for i in range(len(arr)):\n if k-arr[i] in d:\n ans+=d[k-arr[i]]\n if arr[i] in d:\n d[arr[i]]+=1\n else:\n d[arr[i]]=1\n return ans\n\n\n#{ \n # Driver Code Starts\n#Initial Template for Python 3\n\nif __name__ == '__main__':\n tc = int(input())\n while tc > 0:\n n, k = list(map(int, input().strip().split()))\n arr = list(map(int, input().strip().split()))\n ob = Solution()\n ans = ob.getPairsCount(arr, n, k)\n print(ans)\n tc -= 1\n\n# } Driver Code Ends","repo_name":"sumanthboorla/DSA-solving","sub_path":"Count pairs with given sum - GFG/count-pairs-with-given-sum.py","file_name":"count-pairs-with-given-sum.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"70414610888","text":"## Rasa \nfrom typing import Any, Text, Dict, List\nfrom rasa_sdk import Action, Tracker\nfrom rasa_sdk.executor import CollectingDispatcher\nfrom rasa_sdk.events import (\n UserUtteranceReverted,\n FollowupAction,\n AllSlotsReset,\n Restarted,\n SlotSet,\n EventType,\n LoopInterrupted,\n ActionExecutionRejected\n)\nimport threading\nimport asyncio\n## Telethon Client\nfrom actions.telegram_members.telethonhandler import TelethonHandler\nfrom actions.users.userhandler import UserHandler\nfrom actions.users.user import User\nfrom actions.groups.grouphandler import GroupHandler\nfrom actions.common.common import get_credentials, setup_logging\nimport logging\nlogger = setup_logging()\n\nclass ActionGetChannelMembers(Action):\n\n def name(self) -> Text:\n return \"action_get_channel_members\"\n\n async def run(self, dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\n try:\n is_user = False\n team_mates = None\n if not tracker.get_slot('my_group'): \n user_handler = UserHandler() \n telethon_handler = TelethonHandler()\n team_mates, is_user = await telethon_handler.get_users(tracker.sender_id) \n print(\"\\033[94mTEAM_MATES:\\033[0m \\n%s\" %team_mates)\n if '_id' in team_mates:\n team_mates['_id'] = str(team_mates['_id'])\n return[SlotSet('is_user', is_user), SlotSet('my_group',team_mates), FollowupAction(\"action_start\")]\n else:\n print(\"\\033[94mdont call get members again\\033[0m\")\n except Exception as e:\n logger.exception(e)\n return[SlotSet('is_user', is_user), SlotSet('my_group',team_mates), FollowupAction(\"action_start\")]\n","repo_name":"tubspaulkeller/PCA-Ben","sub_path":"actions/telegram_members/get_channel_members.py","file_name":"get_channel_members.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"25400994908","text":"import logging\nimport os\n\nfrom intents import detect_intent_texts\nfrom dotenv import load_dotenv\nfrom log_handler import TelegramBotHandler\nfrom telegram.ext import (Updater, CommandHandler, MessageHandler,\n Filters, CallbackContext)\n\n\nlogger = logging.getLogger('intents')\n\n\ndef error_handler(update, context):\n logger.exception(context.error)\n\n\ndef start(update, context):\n update.message.reply_text('Здравствуйте')\n\n\ndef reply(update, context):\n user_text = update.message.text\n answer, is_fallback = detect_intent_texts(\n context.bot_data['project_id'],\n context.bot_data['token'],\n user_text,\n language_code='ru',\n )\n update.message.reply_text(answer)\n\n\ndef main():\n load_dotenv()\n\n tg_token = os.getenv('TG_BOT_TOKEN')\n logbot_token = os.getenv('TG_LOG_BOT_TOKEN')\n chat_id = os.getenv('TG_CHAT_ID')\n\n logger.setLevel(logging.WARNING)\n logger.addHandler(TelegramBotHandler(logbot_token, chat_id))\n\n updater = Updater(tg_token)\n dispatcher = updater.dispatcher\n context = CallbackContext(dispatcher)\n\n context.bot_data['project_id'] = os.getenv('GOOGLE_CLOUD_PROJECT_ID')\n context.bot_data['token'] = os.getenv('TG_BOT_TOKEN')\n\n dispatcher.add_error_handler(error_handler)\n dispatcher.add_handler(CommandHandler('start', start))\n dispatcher.add_handler(MessageHandler(Filters.text, reply))\n\n updater.start_polling()\n updater.idle()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"multipassport/flowbot","sub_path":"tgbot.py","file_name":"tgbot.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"9144940243","text":"import warnings\nfrom dependency_management.requirements.PackageRequirement import (\n PackageRequirement)\n\n\nclass AnyOneOfRequirements(PackageRequirement):\n \"\"\"\n This class is a subclass of ``PackageRequirement``. It determines which\n requirements can be used to resolve the dependency.\n \"\"\"\n\n def __init__(self, requirements: list):\n \"\"\"\n Constructs a new ``AnyOneOfRequirements``.\n\n Requirements are ordered by priority.\n\n >>> from dependency_management.requirements.ExecutableRequirement \\\\\n ... import ExecutableRequirement\n >>> aor = AnyOneOfRequirements([ExecutableRequirement(\"python\"),\n ... ExecutableRequirement(\"python3\")])\n >>> str(aor)\n 'ExecutableRequirement(python) ExecutableRequirement(python3)'\n \"\"\"\n self.requirements = requirements\n self._packages_str = \" \".join(sorted(\n [\"%s(%s)\" %\n (requirement.__class__.__name__,\n str(requirement))\n for requirement in self.requirements]))\n PackageRequirement.__init__(self, \"any-one-of\", self._packages_str)\n\n def is_installed(self):\n \"\"\"\n Check if any one of the requirements are satisfied.\n\n :return: True if any of the requirements are satisfied, false otherwise\n \"\"\"\n for requirement in self.requirements:\n try:\n if requirement.is_installed():\n return True\n except Exception as e:\n message = 'Exception of type {0} occurred : {1!r}\\n'\n warnings.warn(message.format(type(e).__name__, e.args))\n return False\n","repo_name":"yzgyyang/dependency_management","sub_path":"dependency_management/requirements/AnyOneOfRequirements.py","file_name":"AnyOneOfRequirements.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"16"}
+{"seq_id":"19277742525","text":"# Name: Eimantas Pusinskas\r\n# Student ID: 120312336\r\n\r\nfrom queues import *\r\nfrom process import *\r\nfrom block import *\r\nfrom random import randint\r\n\r\nclass BuddySystemBST(object):\r\n \t\r\n class node(object):\r\n def __init__ (self, size):\r\n self._block = Block(size)\r\n self._parent = None\r\n self._leftchild = None\r\n self._rightchild = None\r\n\r\n def __str__ (self):\r\n return f\"{self._block.size} KB\"\r\n\r\n def get_block(self):\r\n return self._block\r\n\r\n def set_block(self, block):\r\n self._block = block\r\n \r\n block = property(get_block, set_block)\r\n\r\n\r\n def __init__(self, size):\r\n self._root = self.node(size)\r\n self._block_nodes = self._root\r\n \r\n def get_root(self):\r\n return self._root \r\n\r\n # checks if a node is a leaf node\r\n def is_leaf(self, node):\r\n if node._leftchild == None and node._rightchild == None:\r\n return True\r\n else:\r\n return False\r\n\r\n # returns a list of all leaf nodes in the tree\r\n def get_leaf_nodes(self):\r\n root = self.get_root()\r\n blocks = []\r\n blocks = self._get_leaf_nodes(root, blocks)\r\n return blocks\r\n \r\n def _get_leaf_nodes(self, node, blocks):\r\n if self.is_leaf(node):\r\n blocks.append(node)\r\n else:\r\n if node._leftchild != None:\r\n self._get_leaf_nodes(node._leftchild, blocks)\r\n\r\n if node._rightchild != None:\r\n self._get_leaf_nodes(node._rightchild, blocks)\r\n return blocks \r\n\r\n # splits a node by instantiating to node objects and setting them\r\n # as the original nodes children\r\n def split_node(self, node):\r\n parent_block_size = node.block.size\r\n\r\n left_child = self.node(parent_block_size//2)\r\n right_child = self.node(parent_block_size//2)\r\n\r\n node._leftchild = left_child\r\n node._rightchild = right_child\r\n\r\n left_child._parent = node\r\n right_child._parent = node\r\n\r\n return node\r\n\r\n def print_leaf_nodes(self):\r\n nodes = self.get_leaf_nodes()\r\n output = \"< \"\r\n for node in nodes:\r\n output += f\"({node}:\"\r\n if node.block._allocated == True:\r\n output += \"1) \"\r\n else:\r\n output += \"0) \"\r\n output += \">\"\r\n print(output)\r\n\r\n # returns a list of every node in the tree\r\n def get_all_nodes(self):\r\n nodes = []\r\n root = self.get_root()\r\n nodes = self._get_all_nodes(root, nodes)\r\n return nodes\r\n\r\n def _get_all_nodes(self, node, nodes):\r\n nodes.append(node)\r\n\r\n if node._leftchild != None:\r\n self._get_all_nodes(node._leftchild, nodes)\r\n\r\n if node._rightchild != None:\r\n self._get_all_nodes(node._rightchild, nodes)\r\n return nodes\r\n\r\n def print_all_nodes(self):\r\n nodes = self.get_all_nodes()\r\n output = \"\"\r\n for node in nodes:\r\n output += f\"({node.block.size}, \"\r\n if node.block._allocated == True:\r\n output += \"1) \"\r\n else:\r\n output += \"0) \"\r\n print(output)\r\n\r\n # removes two children nodes of a parent node\r\n def merge_children_nodes(self, node):\r\n node._leftchild.block = None\r\n node._leftchild._parent = None\r\n node._leftchild = None\r\n\r\n node._rightchild.block = None\r\n node._rightchild._parent = None\r\n node._rightchild = None\r\n\r\n # sets a node to being deallocated. in other words the node is now free for memory allocation\r\n def deallocate_node(self, node):\r\n node.block._allocated = False\r\n node.block._process = None \r\n node.block._accessed = 0\r\n \r\n \r\n\r\nclass memory(object):\r\n\r\n def __init__(self):\r\n # in KB, 1 = 1KB, 1024 = 1024KB = 1MB\r\n self._user_space_mem_size = 4096\r\n self._page_size = 4\r\n self._allocation_queue = QueueV0() #this is the queue where processes in need of memory allocation are enqueue\r\n self._buddy_tree = BuddySystemBST(self._user_space_mem_size)\r\n self._bitmap = {0:0}\r\n self._replacement_queue = QueueV0() # this is the queue used for the second chance algorithm\r\n\r\n def request_memory_allocation(self, process):\r\n self._allocation_queue.enqueue(process)\r\n\r\n # processes requesting memory are dequeued on a FIFO basis and allocated memory\r\n def allocate_memory(self):\r\n if self._allocation_queue.length() != 0:\r\n proc = self._allocation_queue.dequeue()\r\n node_found = self._allocate_memory(proc)\r\n self._replacement_queue.enqueue(node_found)\r\n print(f\"process {proc.pid}: requested {proc.memory}KB - allocated {node_found.block.size}KB\")\r\n return node_found\r\n\r\n def _allocate_memory(self, proc):\r\n if self.is_memory_full():\r\n self.replace()\r\n\r\n # the amount of memory that the process is requesting\r\n mem_required = proc.memory\r\n \r\n if mem_required < self._page_size:\r\n mem_required = self._page_size\r\n \r\n # the memory requested by the process is rounded to the nearest power of 2\r\n mem_required -= 1\r\n k = 1 \r\n while k < mem_required:\r\n k *= 2\r\n target_size = k\r\n\r\n # finds a free block that suits the process and allocates the block to that process\r\n block_nodes = self._buddy_tree.get_leaf_nodes()\r\n found = False\r\n node_found = None\r\n for node in block_nodes:\r\n if node.block.size == target_size and node.block._allocated == False:\r\n found = True\r\n node.block.process = proc\r\n node.block._allocated = True\r\n node.block._accessed = 0\r\n self.update_bitmap()\r\n node_found = node\r\n break\r\n \r\n if found == False:\r\n # finds if any free blocks can be split recursively to be allocated to the process\r\n block_node_to_split = None\r\n max_free_node_size = 0\r\n for node in block_nodes:\r\n if node.block.size > max_free_node_size and node.block._allocated == False and node.block.size >= target_size:\r\n max_free_node_size = node.block.size\r\n block_node_to_split = node\r\n break\r\n \r\n # if a node suitable for a split is found, it is split until its size matches the target_size \r\n # and then allocates the left-most split leaf node to the process requesting memory\r\n # otherwise blocks are deallocated recursively unitl the process requesting memory \r\n # can have memory allocated to it \r\n if block_node_to_split != None:\r\n free_block_node = self.split_until_allocated(target_size, block_node_to_split)\r\n free_block_node.block.process = proc\r\n free_block_node.block._allocated = True\r\n free_block_node.block._accessed = 0\r\n self.update_bitmap()\r\n node_found = free_block_node\r\n else:\r\n self.replace()\r\n node_found = self._allocate_memory(proc)\r\n\r\n return node_found\r\n\r\n # split tree nodes recursively until the leaf nodes of that subtree\r\n # match the target size\r\n def split_until_allocated(self, target_size, block_node_to_split):\r\n free_block_node = None\r\n parent_node = self._buddy_tree.split_node(block_node_to_split)\r\n if parent_node._leftchild.block.size == target_size:\r\n free_block_node = parent_node._leftchild\r\n else:\r\n free_block_node = self.split_until_allocated(target_size, parent_node._leftchild)\r\n return free_block_node\r\n\r\n # does a simple check to see if the memory is completely full\r\n def is_memory_full(self):\r\n full = True\r\n for block in self._bitmap:\r\n if self._bitmap[block] == 0:\r\n full = False\r\n break\r\n return full\r\n\r\n # deallocated blocks from memory using the second chance algorithm\r\n def replace(self):\r\n if self._replacement_queue.length() != 0:\r\n node = self._replacement_queue.dequeue() \r\n if node.block._accessed == 1:\r\n node.block._accessed = 0\r\n self._replacement_queue.enqueue(node)\r\n print(f\"process {node.block.process.pid} has been given a second chance\")\r\n else:\r\n print(f\"process {node.block.process.pid} has been deallocated\")\r\n self.remove_block(node)\r\n \r\n self.update_bitmap()\r\n \r\n def update_bitmap(self):\r\n block_nodes = self._buddy_tree.get_leaf_nodes()\r\n self._bitmap = {}\r\n for node in block_nodes:\r\n if node.block._allocated == True:\r\n self._bitmap[block_nodes.index(node)] = 1\r\n else:\r\n self._bitmap[block_nodes.index(node)] = 0\r\n return self._bitmap\r\n\r\n # merges a block and its buddy if both are not allocated\r\n # othewise the block is simply deallocated and the tree stays as it is\r\n def remove_block(self, node):\r\n if self._buddy_tree.is_leaf(node) == True:\r\n if self._buddy_tree.is_leaf(node._parent._rightchild) == True and node._parent._rightchild.block._allocated == False:\r\n node._parent.block._allocated = False\r\n self._buddy_tree.merge_children_nodes(node._parent) \r\n else:\r\n self._buddy_tree.deallocate_node(node)\r\n self.update_bitmap()\r\n\r\n def calculate_fragmentation(self):\r\n nodes = self._buddy_tree.get_leaf_nodes()\r\n internal_memory_consumed = 0\r\n external_memory_consumed = 0\r\n for node in nodes:\r\n if node.block.process != None:\r\n internal_memory_consumed += node.block.process.memory\r\n external_memory_consumed += node.block.size\r\n\r\n # fragmentation result is the percentage of unused memory\r\n internal_fragmentation = ((external_memory_consumed - internal_memory_consumed) / external_memory_consumed ) * 100\r\n external_fragmentation = ((self._user_space_mem_size - external_memory_consumed) / self._user_space_mem_size) * 100\r\n print(f\"-----------------\\nFragmentation: \\nInternal: {internal_fragmentation}% \\nExternal: {external_fragmentation }%\\n-----------------\")\r\n\r\n \r\n\r\n\r\nif __name__ == \"__main__\":\r\n def basic_test():\r\n mem = memory()\r\n proc1 = Process(1, 50)\r\n mem.request_memory_allocation(proc1)\r\n proc1_node = mem.allocate_memory()\r\n\r\n proc2 = Process(2, 254)\r\n mem.request_memory_allocation(proc2)\r\n mem.allocate_memory()\r\n\r\n proc4 = Process(4, 120)\r\n mem.request_memory_allocation(proc4)\r\n mem.allocate_memory()\r\n \r\n proc5 = Process(5, 1000)\r\n mem.request_memory_allocation(proc5)\r\n mem.allocate_memory()\r\n\r\n proc6 = Process(6, 500)\r\n mem.request_memory_allocation(proc6)\r\n mem.allocate_memory()\r\n\r\n proc7 = Process(7, 2010)\r\n mem.request_memory_allocation(proc7)\r\n mem.allocate_memory()\r\n\r\n\r\n print(mem._bitmap)\r\n mem._buddy_tree.print_leaf_nodes()\r\n\r\n print(\"----------------------\")\r\n\r\n #mem.remove_block(proc1_node)\r\n #print(mem._bitmap)\r\n #mem._buddy_tree.print_leaf_nodes()\r\n\r\n proc8 = Process(8, 60)\r\n mem.request_memory_allocation(proc8)\r\n mem.allocate_memory()\r\n mem._buddy_tree.print_leaf_nodes()\r\n mem.calculate_fragmentation()\r\n\r\n \r\n proc9 = Process(9, 100)\r\n mem.request_memory_allocation(proc9)\r\n mem.allocate_memory()\r\n mem._buddy_tree.print_leaf_nodes()\r\n\r\n proc10 = Process(10, 1500)\r\n mem.request_memory_allocation(proc10)\r\n mem.allocate_memory()\r\n mem._buddy_tree.print_leaf_nodes()\r\n\r\n #proc11 = Process(11, 1)\r\n #mem.request_memory_allocation(proc11)\r\n #mem.allocate_memory()\r\n #mem._buddy_tree.print_leaf_nodes()\r\n\r\n mem.calculate_fragmentation()\r\n\r\n def random_test():\r\n mem = memory()\r\n \r\n for i in range(250):\r\n proc = Process(i, randint(mem._page_size, 32))\r\n mem.request_memory_allocation(proc)\r\n node = mem.allocate_memory()\r\n\r\n node.block._accessed = randint(0,1)\r\n\r\n mem.calculate_fragmentation()\r\n mem._buddy_tree.print_leaf_nodes()\r\n \r\n\r\n #basic_test()\r\n random_test()","repo_name":"EimantasPusinskas/operating_systems_2","sub_path":"assignment2/main_memory.py","file_name":"main_memory.py","file_ext":"py","file_size_in_byte":12828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"6492236997","text":"# Faça um Programa que leia um número inteiro menor que 1000\n# e imprima a quantidade de centenas, dezenas e unidades do mesmo.\n\n# Observando os termos no plural a colocação do \"e\", da vírgula entre\n# outros. Exemplo:\n# 326 = 3 centenas, 2 dezenas e 6 unidades\n# 12 = 1 dezena e 2 unidades Testar com: 326, 300, 100, 320, 310,305, 301,\n# 101, 311, 111, 25, 20, 10, 21, 11, 1, 7 e 16\n\nnumero_completo = int(input(\"Insira um número inteiro positivo: \"))\n\nunidade = numero_completo % 10\nnumero = (numero_completo - unidade) / 10\ndezena = numero % 10\nnumero = (numero - dezena) / 10\ncentena = numero % 10\nmilhar = (numero - centena) / 10\n\nunidade = int(unidade)\ndezena = int(dezena)\ncentena = int(centena)\nmilhar = int(milhar)\n\nif numero_completo >= 1000:\n if unidade == 1:\n un = \"unidade\"\n else:\n un = \"unidades\"\n\n if dezena == 1:\n dz = \"dezena\"\n else:\n dz = \"dezenas\"\n\n if centena == 1:\n cent = \"centena\"\n else:\n cent = \"centenas\"\n\n if milhar == 1:\n mil = \"milhar\"\n else:\n mil = \"milhares\"\n\n print(f\"{numero_completo} - {milhar} {mil}, {centena} {cent}, \"\n f\"{dezena} {dz} e {unidade} {un}.\")\n\nelif numero_completo >= 100:\n if unidade == 1:\n un = \"unidade\"\n else:\n un = \"unidades\"\n\n if dezena == 1:\n dz = \"dezena\"\n else:\n dz = \"dezenas\"\n\n if centena == 1:\n cent = \"centena\"\n else:\n cent = \"centenas\"\n\n print(f\"{numero_completo} - {centena} {cent}, {dezena} {dz} \"\n f\"e {unidade} {un}.\")\n\nelif numero_completo >= 10:\n if unidade == 1:\n un = \"unidade\"\n else:\n un = \"unidades\"\n\n if dezena == 1:\n dz = \"dezena\"\n else:\n dz = \"dezenas\"\n\n print(f\"{numero_completo} - {dezena} {dz} e {unidade} {un}.\")\n\nelse:\n if unidade == 1:\n un = \"unidade\"\n else:\n un = \"unidades\"\n\n print(f\"{numero_completo} - {unidade} {un}.\")\n\n# print(f\"{numero_completo} - {milhar} {mil}, {centena} {cent}, {dezena} {dz} \"\n# f\"e {unidade} { un}.\")\n","repo_name":"AndreGorny/exercicios_python","sub_path":"estrutura_decisao/19.py","file_name":"19.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"29403973147","text":"import re\r\nimport tweepy\r\nfrom tweepy import OAuthHandler\r\nfrom textblob import TextBlob\r\nfrom wordcloud import WordCloud\r\nimport pandas as pd \r\nimport numpy as np \r\nimport matplotlib.pyplot as plt \r\nplt.style.use('fivethirtyeight')\r\n\r\n#twitter Api credentials\r\nconsumerKey = \"xxxxx-xxxxxxx--xxxxxxx--xxxx\"\r\nconsumerSecret = 'xxxxx--xxxxxxxxxxx---------xxxxxxxx'\r\naccessToken = 'xxxxxxxxxxxx---xxx--xxxxxxxxx--------xxxxxxxx'\r\naccessTokenSecret = 'xxxxxxxxxxxxxxxx---xxxxxxxxxxxxx'\r\n\r\n#Create the authentication object\r\nauthenticate = tweepy.OAuthHandler(consumerKey, consumerSecret)\r\n\r\n#set the authentication ojject\r\nauthenticate.set_access_token(accessToken, accessTokenSecret) \r\n\r\n#Create the API object while passing in the auth information\r\napi = tweepy.API(authenticate, wait_on_rate_limit=True)\r\n\r\n#Extract 100 tweets from the twitter user\r\nposts = api.user_timeline(screen_name = \"BillGates\", count =100, lang = 'en', tweet_mode=\"extended\")\r\n \r\n#create a dataframe with a coulmn called Tweets\r\ndf = pd.DataFrame( [tweet.full_text for tweet in posts] , columns=['Tweets'])\r\n\r\n#Show the first 5 rows of data\r\ndf.head()\r\n\r\n#Clean the text\r\n\r\n#Create a function to clean text\r\ndef cleantxt(text):\r\n text = re.sub(r'@[A-Za-z0-9]+','',text) #Removed @mentions\r\n text = re.sub(r'#', '', text) #Removing the '#' symbol\r\n text = re.sub(r'RT[\\s]+', '', text) #Removing RT\r\n text = re.sub(r'https?:\\/\\/\\S+', '', text)\r\n return text\r\n\r\n#Cleaning the text\r\ndf['Tweets']=df['Tweets'].apply(cleantxt)\r\n\r\n#show the cleaned text\r\ndf\r\n\r\n#Create a function to get the subjectivity\r\ndef getSubjectivity(text):\r\n return TextBlob(text).sentiment.subjectivity\r\n\r\n#create a function to get the polarity\r\ndef getPolarity(text):\r\n return TextBlob(text).sentiment.subjectivity\r\n\r\n#Create two new columns\r\ndf['Subjectivity'] = df['Tweets'].apply(getSubjectivity)\r\ndf['Polarity'] = df['Tweets'].apply(getPolarity)\r\n\r\n#Show the new dataframe with the new columns\r\ndf\r\n\r\n#Plot the word cloud\r\nallWords = ' '.join( [twts for twts in df['Tweets']] )\r\ncloud = WordCloud(width = 500, height = 300, random_state = 21, max_font_size = 119).generate(allWords)\r\n\r\nplt.imshow(cloud, interpolation = \"bilinear\")\r\nplt.axis('off')\r\nplt.show()\r\n\r\n#create a function to compute the negatve, neutral and positive\r\ndef getAnalysis(score):\r\n if score < 0:\r\n return 'Negative'\r\n elif score == 0:\r\n return 'Neutral'\r\n else:\r\n return 'Positive'\r\n\r\ndf['Analysis'] = df['Polarity'].apply(getAnalysis)\r\n\r\n#show the dataframe\r\ndf\r\n\r\n#Print all of the positive tweets\r\nj=1\r\nsortedDF = df.sort_values(by=['Polarity'])\r\nfor i in range(0,sortedDF.shape[0]):\r\n if(sortedDF['Analysis'][i] == 'Positive'):\r\n print(str(j) + ') '+sortedDF['Tweets'][i])\r\n print()\r\n j = j+1\r\n\r\n#print the negative tweets\r\nj=1\r\nsortedDF = df.sort_values(by=['Polarity'], ascending = 'False')\r\nfor i in range(0, sortedDF.shape[0]):\r\n if( sortedDF['Analysis'][i] == 'Negative'):\r\n print(str(j) +') '+ sortedDF['Tweets'][i])\r\n print()\r\n j = j+1\r\n\r\n#plot the polarity and subjectivity\r\nplt.figure(figsize=(8,6))\r\nfor i in range(0,df.shape[0]):\r\n plt.scatter(df['Polarity'][i], df['Subjectivity'][i], color='Blue')\r\n\r\nplt.title('Sentiment Analysis')\r\nplt.xlabel('Polarity')\r\nplt.ylabel('Subjectivity')\r\nplt.show()\r\n\r\n#Get the percentage of positive tweets\r\nptweets = df[df.Analysis == 'Positive']\r\nptweets = ptweets['Tweets']\r\n\r\nround( (ptweets.shape[0] / df.shape[0]) *100 , 1)\r\n\r\n#Get the percentage of negative tweets\r\nntweets = df[df.Analysis == 'Negative']\r\nntweets = ntweets['Tweets']\r\nround( (ntweets.shape[0] / df.shape[0]*100),1)\r\n\r\n#show the value counts\r\ndf['Analysis'].value_counts()\r\n#plot and visualize the counts\r\nplt.title('Sentiment Analysis')\r\nplt.xlabel('Sentiment')\r\nplt.ylabel('Counts')\r\ndf['Analysis'].value_counts().plot(kind='bar')\r\nplt.show()","repo_name":"sohailali26/Sentimental-Analysis-using-Python","sub_path":"SENTIMENT ANYLISIS.py","file_name":"SENTIMENT ANYLISIS.py","file_ext":"py","file_size_in_byte":3896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"31859251912","text":"# Импортируем необходимые библиотеки и адаптеры\nimport psycopg2\nimport sys\n\nfrom PyQt5.QtWidgets import (QApplication, QWidget,\n QTabWidget, QAbstractScrollArea,\n QVBoxLayout, QHBoxLayout,\n QTableWidget, QGroupBox,\n QTableWidgetItem, QPushButton, QMessageBox)\n\n# Создаем класс MainWindow с конструктором\nclass MainWindow(QWidget): # Класс QTabWidget создает структуру, которую можно заполнять вкладками.\n def __init__(self):\n super(MainWindow, self).__init__()\n\n self._connect_to_db()\n\n self.setWindowTitle(\"Shedule\")\n self.setGeometry(270, 100, 915, 700)\n\n self.vbox = QVBoxLayout(self)\n\n self.tabs = QTabWidget(self)\n self.vbox.addWidget(self.tabs)\n\n self.update_button = QPushButton(\"Update\")\n self.update_button.clicked.connect(lambda _: self._update())\n self.updatebtn_lay = QHBoxLayout()\n self.vbox.addLayout(self.updatebtn_lay)\n self.updatebtn_lay.addWidget(self.update_button)\n\n self._create_shedule_tab()\n self._create_teachers_tab()\n self._create_subjects_tab()\n\n# Создаем метод для подключения к базе данных\n def _connect_to_db(self):\n self.conn = psycopg2.connect(database=\"postgres\",\n user=\"postgres\",\n password=\"qwerty123\",\n host=\"localhost\",\n port=\"5432\")\n\n self.cursor = self.conn.cursor()\n\n# Создаем метод для отображения вкладки с расписанием\n def _create_shedule_tab(self):\n self.shedule_tab = QWidget() # Класс QWidget() создает виджет, который будет являться вкладкой\n self.tabs.addTab(self.shedule_tab, \"Расписание\")\n days = ['Понедельник', 'Вторник', 'Среда',\n 'Четверг', 'Пятница', 'Суббота']\n\n day_tab = QTabWidget(self)\n\n for i in days:\n day_tab.addTab(self._create_day_table(i.upper()), i)\n day_tab_layout = QVBoxLayout()\n day_tab_layout.addWidget(day_tab)\n self.shedule_tab.setLayout(day_tab_layout)\n\n def _create_day_table(self, day):\n table = QTableWidget()\n table.setColumnCount(8) # Метод setColumnCount() задает таблице количество колонок.\n table.setHorizontalHeaderLabels([\"timetable_id\", \"day\", \"subject\", \"room_numb\", \"start_time\", \"week\", \"\", \"\"])\n self._update_day_table(table, day)\n return table\n\n def _update_day_table(self, table, day):\n self.cursor.execute(f\"SELECT * FROM timetable join subject on\"\n f\" timetable.subject = subject.subject_id WHERE day='{day}' \"\n f\"ORDER BY timetable_id\")\n records = list(self.cursor.fetchall())\n table.setRowCount(len(records) + 1) # Метод setRowCount() задает таблице количество строк.\n\n for i, r in enumerate(records):\n r = list(r)\n editButton = QPushButton(\"Edit\")\n delButton = QPushButton(\"Delete\")\n table.setItem(i, 0,\n QTableWidgetItem(str(r[0]))) # Метод setItem() записывает в ячейку с определенным адресом строковые данные.\n table.setItem(i, 1,\n QTableWidgetItem(str(r[1])))\n table.setItem(i, 2,\n QTableWidgetItem(str(r[7])))\n table.setItem(i, 3,\n QTableWidgetItem(str(r[3])))\n table.setItem(i, 4,\n QTableWidgetItem(str(r[4])))\n table.setItem(i, 5,\n QTableWidgetItem(str(r[5])))\n table.setCellWidget(i, 6, editButton) # Метод setCellWidget() помещает в ячейку с определенным адресом виджет.\n table.setCellWidget(i, 7, delButton)\n\n editButton.clicked.connect(\n lambda _, rowNum=i, table=table: self._change_from_timetable(rowNum, table))\n delButton.clicked.connect(lambda _, rowNum=i, table=table: self._delete_from_timetable(rowNum, table))\n\n addButton = QPushButton(\"Add\")\n addButton.clicked.connect(lambda _, rowNum=len(records), table=table: self._add_row_timetable(rowNum, table))\n table.setCellWidget(len(records), 6, addButton)\n table.resizeRowsToContents() # Метод resizeRowsToContents() автоматически адаптирует размеры ячеек таблицы под размер данных внутри этой ячейки.\n\n def _change_from_timetable(self, rowNum, table):\n row = list()\n for i in range(table.columnCount() - 2):\n try:\n row.append(table.item(rowNum, i).text())\n except:\n row.append(None)\n try:\n self.cursor.execute(\"select subject_id from subject where name=%s\", (row[2],))\n subject = self.cursor.fetchone()\n row[2] = subject[0]\n row.append(row[0])\n row = row[1:]\n self.cursor.execute(\"update timetable set day=%s, subject=%s, room_numb=%s, start_time=%s, \"\n \"week=%s where timetable_id=%s\", tuple(row))\n self.conn.commit()\n except Exception as e:\n QMessageBox.about(self, \"Error\", str(e))\n self._connect_to_db()\n\n def _delete_from_timetable(self, rowNum, table):\n try:\n id = table.item(rowNum, 0).text()\n day = table.item(rowNum, 1).text()\n self.cursor.execute(\"delete from timetable where timetable_id=%s\", (id,))\n self.conn.commit()\n table.setRowCount(0)\n self._update_day_table(table, day)\n except Exception as e:\n QMessageBox.about(self, \"Error\", str(e))\n self._connect_to_db()\n\n def _add_row_timetable(self, rowNum, table):\n row = list()\n for i in range(1, table.columnCount() - 2):\n try:\n row.append(table.item(rowNum, i).text())\n except:\n row.append(None)\n try:\n self.cursor.execute(\"select subject_id from subject where name=%s\", (row[1],))\n subject = self.cursor.fetchone()\n row[1] = subject[0]\n self.cursor.execute(\n \"insert into timetable (day, subject, room_numb, start_time, week) values(%s, %s, %s, %s, %s)\",\n (tuple(row)))\n self.conn.commit()\n table.setRowCount(0)\n self._update_day_table(table, row[0])\n except Exception as e:\n print(e)\n QMessageBox.about(self, \"Error\", str(e))\n self._connect_to_db()\n\n def _create_teachers_tab(self):\n self.teachers = QWidget()\n self.tabs.addTab(self.teachers, \"Преподаватели\")\n table = QTableWidget(self)\n table.setColumnCount(5)\n table.setHorizontalHeaderLabels([\"teacher_id\", \"Имя\", \"Предмет\", \"\", \"\"])\n\n teachers_tab_layout = QVBoxLayout()\n teachers_tab_layout.addWidget(table)\n\n self._update_teachers_tab(table)\n self.teachers.setLayout(teachers_tab_layout)\n\n def _update_teachers_tab(self, table):\n self.cursor.execute(f\"SELECT * FROM teacher join subject on teacher.subject=subject.subject_id\"\n f\" ORDER BY teacher_id\")\n records = list(self.cursor.fetchall())\n table.setRowCount(len(records) + 1)\n\n for i, r in enumerate(records):\n r = list(r)\n editButton = QPushButton(\"Edit\")\n delButton = QPushButton(\"Delete\")\n table.setItem(i, 0,\n QTableWidgetItem(str(r[0])))\n table.setItem(i, 1,\n QTableWidgetItem(str(r[1])))\n table.setItem(i, 2,\n QTableWidgetItem(str(r[4])))\n table.setCellWidget(i, 3, editButton)\n table.setCellWidget(i, 4, delButton)\n\n editButton.clicked.connect(\n lambda _, rowNum=i, tabl=table: self._change_from_teacher(rowNum, tabl))\n delButton.clicked.connect(\n lambda _, rowNum=i, tabl=table:\n self._delete_from_teacher(rowNum, table))\n addButton = QPushButton(\"Add\")\n addButton.clicked.connect(\n lambda _, rowNum=len(records), table=table: self._add_row_teacher(rowNum, table))\n table.setCellWidget(len(records), 3, addButton)\n table.resizeRowsToContents()\n\n def _change_from_teacher(self, rowNum, table):\n row = list()\n\n for i in range(table.columnCount() - 2):\n try:\n row.append(table.item(rowNum, i).text())\n except:\n row.append(None)\n try:\n self.cursor.execute(\"select subject_id from subject where name=%s\", (row[2],))\n subject = self.cursor.fetchone()\n row[2] = subject[0]\n row.append(row[0])\n row = row[1:]\n self.cursor.execute(\"update teacher set full_name=%s, subject=%s where teacher_id=%s\", tuple(row))\n self.conn.commit()\n except Exception as e:\n QMessageBox.about(self, \"Error\", str(e))\n self._connect_to_db()\n\n def _delete_from_teacher(self, rowNum, table):\n try:\n id = table.item(rowNum, 0).text()\n self.cursor.execute(\"delete from teacher where teacher_id=%s\", (id,))\n self.conn.commit()\n table.setRowCount(0)\n self._update_teachers_tab(table)\n except Exception as e:\n QMessageBox.about(self, \"Error\", str(e))\n self._connect_to_db()\n\n def _add_row_teacher(self, rowNum, table):\n row = list()\n for i in range(1, table.columnCount() - 2):\n try:\n row.append(table.item(rowNum, i).text())\n except:\n row.append(None)\n self.cursor.execute(\"select subject_id from subject where name=%s\", (row[1],))\n subject = self.cursor.fetchone()\n row[1] = subject[0]\n try:\n self.cursor.execute(\n \"insert into teacher (full_name, subject) values(%s, %s)\",\n (tuple(row)))\n self.conn.commit()\n table.setRowCount(0)\n self._update_teachers_tab(table)\n except Exception as e:\n print(e)\n QMessageBox.about(self, \"Error\", str(e))\n self._connect_to_db()\n\n def _create_subjects_tab(self):\n self.subjects = QWidget()\n self.tabs.addTab(self.subjects, \"Предметы\")\n table = QTableWidget(self)\n table.setColumnCount(4)\n table.setHorizontalHeaderLabels([\"subject_id\", \"Предмет\", \"\", \"\"])\n\n subjects_tab_layout = QVBoxLayout()\n subjects_tab_layout.addWidget(table)\n\n self._update_subjects_tab(table)\n self.subjects.setLayout(subjects_tab_layout)\n\n def _update_subjects_tab(self, table):\n self.cursor.execute(f\"SELECT * FROM subject ORDER BY subject_id\")\n records = list(self.cursor.fetchall())\n table.setRowCount(len(records) + 1)\n for i, r in enumerate(records):\n r = list(r)\n editButton = QPushButton(\"Edit\")\n delButton = QPushButton(\"Delete\")\n table.setItem(i, 0,\n QTableWidgetItem(str(r[0])))\n table.setItem(i, 1,\n QTableWidgetItem(str(r[1])))\n table.setCellWidget(i, 2, editButton)\n table.setCellWidget(i, 3, delButton)\n\n editButton.clicked.connect(\n lambda _, rowNum=i, table=table: self._change_from_subjects(rowNum, table))\n delButton.clicked.connect(\n lambda _, rowNum=i, table=table:\n self._delete_from_subjects(rowNum, table))\n\n addButton = QPushButton(\"Add\")\n addButton.clicked.connect(\n lambda _, rowNum=len(records), table=table: self._add_row_subject(rowNum, table))\n table.setCellWidget(len(records), 2, addButton)\n table.resizeRowsToContents()\n\n def _change_from_subjects(self, rowNum, table):\n row = list()\n\n for i in range(table.columnCount() - 2):\n try:\n row.append(table.item(rowNum, i).text())\n except:\n row.append(None)\n try:\n row.append(row[0])\n row = row[1:]\n self.cursor.execute(\"update subject set name=%s where subject_id=%s\", tuple(row))\n self.conn.commit()\n except Exception as e:\n QMessageBox.about(self, \"Error\", str(e))\n self._connect_to_db()\n\n def _delete_from_subjects(self, rowNum, table):\n try:\n id = table.item(rowNum, 0).text()\n self.cursor.execute(\"delete from teacher where subject=%s\", (id,))\n self.cursor.execute(\"delete from timetable where subject=%s\", (id,))\n self.cursor.execute(\"delete from subject where subject_id=%s\", (id,))\n self.conn.commit()\n table.setRowCount(0)\n self._update_subjects_tab(table)\n except Exception as e:\n QMessageBox.about(self, \"Error\", str(e))\n self._connect_to_db()\n\n def _add_row_subject(self, rowNum, table):\n subject = table.item(rowNum, 1).text()\n try:\n self.cursor.execute(\n \"insert into subject (name) values(%s)\",\n (subject,))\n self.conn.commit()\n table.setRowCount(0)\n self._update_subjects_tab(table)\n except Exception as e:\n print(e)\n QMessageBox.about(self, \"Error\", str(e))\n self._connect_to_db()\n\n# Создаем метод обновляющий все таблицы на вкладке\n def _update(self):\n self.tabs.removeTab(0)\n self.tabs.removeTab(0)\n self.tabs.removeTab(0)\n self._create_shedule_tab()\n self._create_teachers_tab()\n self._create_subjects_tab()\n\n\napp = QApplication(sys.argv)\nwin = MainWindow()\nwin.show()\nsys.exit(app.exec_())\n","repo_name":"Michael-merlot/All-labaratories-","sub_path":"8_lab_rabota.py","file_name":"8_lab_rabota.py","file_ext":"py","file_size_in_byte":14661,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"16"}
+{"seq_id":"8771261481","text":"# Importing the necessary libraries\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport numpy as np\r\nimport os\r\n\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.metrics import r2_score\r\n\r\n# Obtain the dfset and store it in a variable\r\ndf = pd.read_csv(\"C:/Users/reibo/OneDrive/Dokumenti/dokumenti za faks/year 3/machine learning/Car prices/car data.csv\")\r\n\r\n# Creating dummies for the above variables\r\nFuel_type = pd.get_dummies(df['Fuel_Type'], drop_first = True)\r\nSeller_Type = pd.get_dummies(df['Seller_Type'], drop_first = True)\r\nTransmission = pd.get_dummies(df['Transmission'], drop_first = True)\r\n\r\n# Drop the dummy variables from the data frame and combine them into a single one\r\ndf = df.drop(['Fuel_Type', 'Seller_Type', 'Transmission', 'Car_Name'], axis=1)\r\ndf = pd.concat([df,Fuel_type, Seller_Type, Transmission], axis=1)\r\n\r\n# Define the target variable\r\nY = df['Selling_Price']\r\nX = df.drop(['Selling_Price'], axis=1)\r\n#X = StandardScaler().fit_transform(df)\r\n\r\n# Split the data into train and test\r\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=.2, random_state=1)\r\n\r\n# Create the model (using Linear Regression)\r\nmodel = LinearRegression()\r\nmodel.fit(X_train, y_train)\r\n\r\n# Test the model\r\n#print(model.score(X_test, y_test))\r\n\r\n# Compare the prediction with the actual values and show the error\r\npred = model.predict(X_test)\r\npred_overview = pd.DataFrame()\r\npred_overview[\"truth\"] = y_test\r\npred_overview[\"pred\"] = pred\r\npred_overview[\"error\"] = pred_overview[\"truth\"] - pred_overview[\"pred\"]\r\npred_overview[\"error\"] = abs(pred_overview[\"error\"].astype(int))\r\npred_overview = pred_overview.reset_index(drop= True)\r\n#print(pred_overview)\r\n\r\nscore = r2_score(y_test, pred)\r\n#print(score)\r\n\r\nplot = sns.regplot(y=y_test.values.flatten(), x=pred.flatten(), line_kws={\"color\": \"g\"})\r\nplot.set_xlabel(\"predicted price\")\r\nplot.set_ylabel(\"actual price\")\r\nplt.show()\r\n\r\n","repo_name":"Evonn69/SmileDetection","sub_path":"Car prices/car price prediction.py","file_name":"car price prediction.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"41280175289","text":"#!/usr/bin/env python\\n\n# -*- coding: utf-8 -*-\n\nimport datetime\nimport sublime\nimport sublime_plugin\nfrom . import utils\nfrom .utils import Redlime\n\n\nclass RedlimeTimeEntryCreateCommand(sublime_plugin.TextCommand):\n\n timeentry_data = {}\n\n def run(self, edit):\n self.redmine = Redlime.connect()\n # issue_id = self.view.settings().get('issue_id', None)\n self.screen = self.view.settings().get('screen')\n issue_id = self.get_issue_id()\n if issue_id is None:\n projects_filter = utils.get_setting('projects_filter', [])\n if projects_filter:\n projects = [self.redmine.project.get(pid) for pid in projects_filter]\n else:\n projects = self.redmine.project.all()\n\n prj_names = []\n self.prj_ids = []\n for prj in projects:\n prj_names.append(prj.name)\n self.prj_ids.append(prj.id)\n self.view.window().show_quick_panel(prj_names, self.on_project_done)\n else:\n self.on_issue_done(issue_id)\n\n def get_issue_id(self):\n issue_id = None\n if self.screen == 'redlime_issue':\n issue_id = self.view.settings().get('issue_id', None)\n elif self.screen == 'redlime_query':\n try:\n line = self.view.substr(self.view.line(self.view.sel()[0].end()))\n issue_id = line.split(utils.TABLE_SEP)[1].strip()\n int(issue_id) # check is number\n except Exception:\n pass\n return issue_id\n\n def on_project_done(self, index):\n if index < 0:\n return\n\n self.timeentry_data['project_id'] = self.prj_ids[index]\n self.view.window().show_input_panel(\"Issue id:\", '', self.on_issue_done, None, None)\n\n def on_issue_done(self, text):\n if text:\n self.timeentry_data['issue_id'] = int(text)\n\n activities = self.redmine.enumeration.filter(resource='time_entry_activities')\n if activities:\n self.acts = []\n self.acts_ids = []\n for enum in activities:\n self.acts.append(enum.name)\n self.acts_ids.append(enum.id)\n\n sublime.set_timeout(lambda: self.view.window().show_quick_panel(self.acts, self.on_activity_done), 1)\n else:\n self.on_activity_done(-1)\n\n def on_activity_done(self, index):\n if index >= 0:\n # not required and needs redmine >= 3.4.0\n self.timeentry_data['activity_id'] = self.acts_ids[index]\n self.timeentry_data['activity_name'] = self.acts[index]\n\n self.view.window().show_input_panel(\"Date:\", datetime.datetime.now().strftime('%Y-%m-%d'), self.on_date_done, None, None)\n\n def on_date_done(self, text):\n if not text:\n return\n self.timeentry_data['spent_on'] = text\n\n self.view.window().show_input_panel(\"Hours:\", '1.0', self.on_hours_done, None, None)\n\n def on_hours_done(self, text):\n if not text:\n return\n self.timeentry_data['hours'] = float(text)\n\n self.view.window().show_input_panel(\"Comment:\", '', self.on_comment_done, None, None)\n\n def on_comment_done(self, text):\n if not text:\n return\n\n time_entry = self.redmine.time_entry.new()\n if self.timeentry_data.get('issue_id', None):\n time_entry.issue_id = self.timeentry_data['issue_id']\n elif self.timeentry_data.get('project_id', None):\n time_entry.project_id = self.timeentry_data['project_id']\n else:\n raise Exception('Issue or project required to create time entry.')\n if self.timeentry_data.get('activity_id', None):\n time_entry.activity_id = self.timeentry_data.get('activity_id', None)\n time_entry.comments = text\n time_entry.spent_on = self.timeentry_data['spent_on']\n time_entry.hours = self.timeentry_data['hours']\n time_entry.save()\n if time_entry.id:\n sublime.message_dialog('Time entry %s (\"%s: %s\") created successfully.' % (time_entry.id, self.timeentry_data['activity_name'], time_entry.comments))\n if self.timeentry_data['issue_id']:\n self.view.run_command('redlime_issue', {'issue_id': self.timeentry_data['issue_id']})\n else:\n sublime.message_dialog('Error! Time entry creation failed..')\n","repo_name":"tosher/Redlime","sub_path":"base/rl_time_entry_create.py","file_name":"rl_time_entry_create.py","file_ext":"py","file_size_in_byte":4416,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"16"}
+{"seq_id":"5601282097","text":"import os, sys, inspect\ncurrent_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparent_dir = os.path.dirname(current_dir)\nsys.path.insert(0, parent_dir)\n\nfrom datetime import date, datetime\nimport pandas as pd\nimport numpy as np\n\nfrom cl_random_forest import *\n\ndf, X_, Y_, X_train_, X_test_, y_train_, y_test_, X_train_part_, X_valid_, y_train_part_, y_valid_ = DO_PREPROCESSING()\nY_ = Y_[col_y_true].tolist()\ny_train_ = y_train_[col_y_true].tolist()\ny_train_part_ = y_train_part_[col_y_true].tolist()\ny_valid_ = y_valid_[col_y_true].tolist()\ny_test_origin = y_test_.copy()\ny_test_ = y_test_[col_y_true].tolist()\n\nM = c_Random_Forest()\nM.get_best_model(14, idx=0, random_state=71)\nM.fit_predict_model(M.best_model, X_train_, y_train_, X_test_, y_test_) \n","repo_name":"af20/mds_ml_predict_stock_market_direction","sub_path":"MAIN.py","file_name":"MAIN.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"27328253386","text":"import os\nimport glob\nimport logging\nfrom os.path import basename, splitext\n\n# Zynthian specific modules\nfrom zyngui.zynthian_gui_selector import zynthian_gui_selector\n\n#------------------------------------------------------------------------------\n# Zynthian Option Selection GUI Class\n#------------------------------------------------------------------------------\n\nclass zynthian_gui_option(zynthian_gui_selector):\n\n\tdef __init__(self):\n\t\tself.title = \"\"\n\t\tself.options = {}\n\t\tself.options_cb = None\n\t\tself.cb_select = None\n\t\tself.click_type = False\n\t\tself.close_on_select = True\n\t\tsuper().__init__(\"Option\", True)\n\n\n\tdef config(self, title, options, cb_select, close_on_select=True, click_type=False):\n\t\tself.title = title\n\t\tif callable(options):\n\t\t\tself.options_cb = options\n\t\t\tself.options = None\n\t\telse:\n\t\t\tself.options_cb = None\n\t\t\tself.options = options\n\t\tself.cb_select = cb_select\n\t\tself.close_on_select = close_on_select\n\t\tself.click_type = click_type\n\t\tself.index = 0\n\n\n\tdef config_file_list(self, title, dpaths, fpat, cb_select, close_on_select=True, click_type=False):\n\t\tself.title = title\n\t\tself.options = {}\n\t\tself.options_cb = None\n\t\tself.cb_select = cb_select\n\t\tself.close_on_select = close_on_select\n\t\tself.click_type = click_type\n\t\tself.index = 0\n\n\t\tif isinstance(dpaths, str):\n\t\t\tdpaths = [dpaths]\n\t\tif isinstance(dpaths, (list, tuple)):\n\t\t\tfor dpath in dpaths:\n\t\t\t\ttry:\n\t\t\t\t\tfor fpath in sorted(glob.iglob(\"{}/{}\".format(dpath, fpat))):\n\t\t\t\t\t\tfname = basename(fpath)\n\t\t\t\t\t\tif fpat != \"*\":\n\t\t\t\t\t\t\tfbase, fext = splitext(fname)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tfbase = fname\n\n\t\t\t\t\t\tif os.path.isfile(fpath):\n\t\t\t\t\t\t\tself.options[fbase] = fpath\n\t\t\t\texcept Exception as err:\n\t\t\t\t\tlogging.warning(\"Can't get file list for {}/{}: {}\".format(dpath, fpat, err))\n\n\n\tdef fill_list(self):\n\t\ti = 0\n\t\tself.list_data = []\n\t\tif self.options_cb:\n\t\t\tself.options = self.options_cb()\n\t\tfor k, v in self.options.items():\n\t\t\tself.list_data.append((v, i, k))\n\t\t\ti += 1\n\t\tsuper().fill_list()\n\n\n\tdef select_action(self, i, t='S'):\n\t\tif self.close_on_select:\n\t\t\tself.zyngui.close_screen()\n\t\tif self.cb_select and i < len(self.list_data):\n\t\t\tif self.click_type:\n\t\t\t\tself.cb_select(self.list_data[i][2], self.list_data[i][0], t)\n\t\t\telse:\n\t\t\t\tself.cb_select(self.list_data[i][2], self.list_data[i][0])\n\t\t\tif not self.close_on_select:\n\t\t\t\tself.fill_list()\n\n\n\tdef set_select_path(self):\n\t\tself.select_path.set(self.title)\n\n#------------------------------------------------------------------------------\n","repo_name":"zynthian/zynthian-ui","sub_path":"zyngui/zynthian_gui_option.py","file_name":"zynthian_gui_option.py","file_ext":"py","file_size_in_byte":2482,"program_lang":"python","lang":"en","doc_type":"code","stars":143,"dataset":"github-code","pt":"16"}
+{"seq_id":"5215519954","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\n@author: wushaohong\n@time: 2020/2/14 16:46\n\"\"\"\n\"\"\"给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:\n\nstruct Node {\n int val;\n Node *left;\n Node *right;\n Node *next;\n}\n填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。\n\n初始状态下,所有 next 指针都被设置为 NULL。\n\n示例:\n\n输入:{\"$id\":\"1\",\"left\":{\"$id\":\"2\",\"left\":{\"$id\":\"3\",\"left\":null,\"next\":null,\"right\":null,\"val\":4},\"next\":null,\"right\":{\"$id\":\"4\",\"left\":null,\"next\":null,\"right\":null,\"val\":5},\"val\":2},\"next\":null,\"right\":{\"$id\":\"5\",\"left\":{\"$id\":\"6\",\"left\":null,\"next\":null,\"right\":null,\"val\":6},\"next\":null,\"right\":{\"$id\":\"7\",\"left\":null,\"next\":null,\"right\":null,\"val\":7},\"val\":3},\"val\":1}\n\n输出:{\"$id\":\"1\",\"left\":{\"$id\":\"2\",\"left\":{\"$id\":\"3\",\"left\":null,\"next\":{\"$id\":\"4\",\"left\":null,\"next\":{\"$id\":\"5\",\"left\":null,\"next\":{\"$id\":\"6\",\"left\":null,\"next\":null,\"right\":null,\"val\":7},\"right\":null,\"val\":6},\"right\":null,\"val\":5},\"right\":null,\"val\":4},\"next\":{\"$id\":\"7\",\"left\":{\"$ref\":\"5\"},\"next\":null,\"right\":{\"$ref\":\"6\"},\"val\":3},\"right\":{\"$ref\":\"4\"},\"val\":2},\"next\":null,\"right\":{\"$ref\":\"7\"},\"val\":1}\n\n解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。\n提示:\n\n你只能使用常量级额外空间。\n使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\"\"\"\n\n\n# Definition for a Node.\nclass Node:\n def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):\n self.val = val\n self.left = left\n self.right = right\n self.next = next\nclass Solution:\n def connect(self, root: 'Node') -> 'Node':\n def helper(root):\n if root and root.left:\n root.left.next = root.right\n p = root.left\n q = root.right\n while p.right:\n p = p.right\n q = q.left\n p.next = q\n helper(root.left)\n helper(root.right)\n r = root\n helper(r)\n return root\n","repo_name":"hshrimp/letecode_for_me","sub_path":"letecode/1-120/97-120/116.py","file_name":"116.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"72201775689","text":"import pickle\n\nimport numpy as np\nimport torch\nimport torch.nn.parallel\nimport torch.optim\nimport torch.utils.data\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\n\nfrom core.selector import Selector\nfrom data_loaders.data_loader_all_loaded import DataLoaderAllLoaded\nfrom models.loss import get_criterion\nfrom utils.run_utils import get_model\n\n\ndef get_model_and_dataset(\n start_date,\n end_date,\n model_kwargs,\n data_kwargs,\n checkpoint_fpath,\n input_shape=(540, 420),\n is_validation=True,\n is_test=True,\n):\n loss_kwargs = {'type': 0, 'aggregation_mode': 0, 'kernel_size': None, 'residual_loss': 0, 'w': None}\n model = get_model(start_date, end_date, model_kwargs, loss_kwargs, data_kwargs, '', '', input_shape=input_shape)\n checkpoint = torch.load(checkpoint_fpath)\n _ = model.load_state_dict(checkpoint['state_dict'])\n model = torch.nn.DataParallel(model).cuda()\n\n dataset = DataLoaderAllLoaded(\n start_date,\n end_date,\n data_kwargs['input_len'],\n data_kwargs['target_len'],\n target_offset=data_kwargs['target_offset'],\n data_type=data_kwargs['data_type'],\n hourly_data=data_kwargs['hourly_data'],\n residual=data_kwargs['residual'],\n img_size=input_shape,\n sampling_rate=data_kwargs['sampling_rate'],\n random_std=data_kwargs['random_std'],\n is_validation=is_validation,\n is_test=is_test,\n workers=0,\n )\n return (model, dataset)\n\n\ndef get_worstK_prediction(k,\n start_date,\n end_date,\n model_kwargs,\n data_kwargs,\n loss_kwargs,\n checkpoint_fpath,\n batch_size,\n lean=False,\n input_shape=(540, 420),\n num_workers=4):\n\n selector = Selector(k, 'max')\n model, dataset = get_model_and_dataset(\n start_date,\n end_date,\n model_kwargs,\n data_kwargs,\n checkpoint_fpath,\n input_shape=(540, 420),\n )\n loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False)\n start_index = 0\n criterion = get_criterion(loss_kwargs)\n model.eval()\n recent_target = 0\n with torch.no_grad():\n for batch in tqdm(loader):\n if data_kwargs['residual']:\n inp, target, mask, recent_target = batch\n recent_target = np.swapaxes(recent_target.numpy(), 0, 1)\n else:\n inp, target, mask = batch\n\n N = target.shape[0]\n inp = inp.cuda()\n target = target.cuda()\n mask = mask.cuda()\n\n prediction = model(inp) + recent_target\n assert target.shape[0] == prediction.shape[1]\n loss_list = []\n for b in range(target.shape[0]):\n loss_list.append(criterion(prediction[:, b:b + 1], target[b:b + 1], mask[b:b + 1]).item())\n\n prediction = prediction.permute(1, 0, 2, 3)\n prediction = prediction.cpu().numpy()\n target = target.cpu().numpy()\n ts = [dataset.target_ts(k) for k in range(start_index, start_index + N)]\n if lean:\n selector.add_batch(loss_list, ts)\n else:\n selector.add_batch(loss_list, prediction, target, ts)\n start_index += N\n\n return selector.all()\n\n\ndef load_worstK_predictions(fpath):\n with open(fpath, 'rb') as f:\n data = pickle.load(f)\n\n loss_list = []\n target_list = []\n prediction_list = []\n ts_list = []\n lean = len(data[0]) == 2\n target, prediction = None, None\n while len(data) > 0:\n row = Selector.pop(data)\n assert len(row) == 4 or len(row) == 2\n if lean:\n loss, ts = row\n else:\n loss, prediction, target, ts = row\n loss_list.append(loss)\n target_list.append(target)\n prediction_list.append(prediction)\n ts_list.append(ts)\n\n if lean:\n return {'loss': loss_list, 'prediction': None, 'target': None, 'ts': ts_list}\n\n return {'loss': loss_list, 'prediction': prediction_list, 'target': target_list, 'ts': ts_list}\n\n\ndef get_prediction(start_date,\n end_date,\n model_kwargs,\n data_kwargs,\n loss_kwargs,\n checkpoint_fpath,\n batch_size,\n is_validation=True,\n is_test=False,\n input_shape=(540, 420),\n num_workers=4):\n model, dataset = get_model_and_dataset(\n start_date,\n end_date,\n model_kwargs,\n data_kwargs,\n checkpoint_fpath,\n input_shape=(540, 420),\n is_validation=is_validation,\n is_test=is_test,\n )\n criterion = get_criterion(loss_kwargs)\n loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False)\n\n all_prediction = []\n loss_list = []\n model.eval()\n recent_target = 0\n with torch.no_grad():\n for batch in tqdm(loader):\n if data_kwargs['residual']:\n inp, target, mask, recent_target = batch\n recent_target = np.swapaxes(recent_target.numpy(), 0, 1)\n else:\n inp, target, mask = batch\n\n N = target.shape[0]\n inp = inp.cuda()\n target = target.cuda()\n mask = mask.cuda()\n\n prediction = model(inp) + recent_target\n assert target.shape[0] == prediction.shape[1]\n loss_list.append(N * criterion(prediction, target, mask).item())\n\n prediction = prediction.cpu().numpy()\n all_prediction.append(np.swapaxes(prediction, 0, 1))\n\n print('[Loss]', round(np.sum(loss_list) / len(dataset), 3))\n return np.concatenate(all_prediction, axis=0)\n","repo_name":"ashesh-0/AccClearQPN","sub_path":"utils/prediction_utils.py","file_name":"prediction_utils.py","file_ext":"py","file_size_in_byte":6021,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"16"}
+{"seq_id":"7195039846","text":"\ndef heapify(i):\n\twhile parent>=0:\n\t\tparent=(i-1)//2\n\t\ttemp=a[i]\n\t\ta[i]=a[maxi]\n\t\ta[maxi]=temp\ndef insert(ele):\n\ta.append(ele)\n\theapify(len(a)-1)\n\nn=int(input('length of array'))\na=list(map(int,input().split()))\nfor i in range(n//2,-1,-1):\n\theapify(i)\nprint(a)","repo_name":"utkarshgupta220399/Algorithms-using-python","sub_path":"heapinsert.py","file_name":"heapinsert.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"4805381031","text":"#import flask libraries and os libraries \nfrom flask import Flask, render_template, request, jsonify, make_response, Response, redirect, url_for\nimport os\nimport json\nfrom json import JSONEncoder\n\n#define the template directory (html pages) to be the website directory.\ntemplate_dir = os.path.abspath('./website/')\n\n#define Flask Application\napp = Flask(__name__, template_folder=template_dir)\n\n\n#create routes for the certain pages. When a user travels to the URL contained withing the quotes, it will call the function.\n#index route that brings user to home page.\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n#route that brings user to the How CPU's work page\n@app.route('/howcpuswork')\ndef howcpuswork():\n return render_template('howcpuswork.html')\n\n#route that brings user to the How 8-bit CPU's work page\n@app.route('/how8bitwork')\ndef how8bitwork():\n return render_template('how8bitwork.html')\n\n#route that brings user to the Programming Page\n@app.route('/cpuprogram')\ndef cpuprogram():\n return render_template('cpuprogram.html', result=\"\")\n\n#route that brings user to page that only displays the stream.\n@app.route('/stream')\ndef stream():\n return render_template('stream.html')\n\n#route that brings user to page that has FAQs.\n@app.route('/faq')\ndef faq():\n return render_template('faq.html')\n\n#define class for one instruction\nclass instruction():\n def __init__(self, address, instruct, value):\n self.address = address\n self.instruct = instruct\n self.value = value\n\n def get_instruct(self):\n return \"%s %s %s\" % (self.address, self.instruct, self.value)\n def serialize(self):\n return {\n 'address': self.address,\n 'instruction': self.instruct,\n 'value': self.value\n }\n\n\n\n#define class that is created to contain one set of instructions\nclass program():\n def __init__(self, id, program):\n self.id = id\n self.program = program\n\n def serialize(self):\n return {\n 'id': self.id,\n 'program': self.program.serialize()\n }\n#programEncoder class for JSON encoding\nclass programEncoder(JSONEncoder):\n def default(self, o):\n return o.__dict__\n \n\n\nprograms = [] #array that holds all programs yet to be executed\nids = [] #array to hold list of all ID's. The index of an ID is it's position in queue.\ncurrentId = 1 #value to keep track of next ID to be assigned.\n\n#function that if a value is nothing, changes it to 0000.\ndef processInputVal(inp):\n if (inp == \"\"):\n return \"0000\"\n else:\n return inp\n\n#function that if a instruction is nothing, it is changed to NOP. \ndef processInputInstruct(inst):\n if (inst == \"\"):\n return \"NOP\"\n elif (inst == \"JC\"):\n return \"JC \"\n else:\n return inst\n\n#API URL for creating a new program. It is a POST method. It takes a request, and processes all the information to create a\n#instance of a program and then returns the id and it's position.\n@app.route('/api/new-program', methods=['POST'])\ndef i():\n global currentId\n global ids\n if request.method == 'POST':\n global test\n current_form = request.form\n instructions = []\n for ind in range(0, 16):\n step = format(ind, \"b\")\n \n inst = instruction(step, processInputInstruct(current_form[f'{step}in']), processInputVal(current_form[f'{step}val']))\n instructions.append(inst)\n print(step)\n\n newProgram = program(currentId,instructions)\n programs.append(newProgram)\n ids.append(currentId)\n currentId += 1\n #print(ids.index(newProgram.id))\n #programs.pop(0)\n #ids.pop(0)\n return jsonify(id=newProgram.id, position=ids.index(newProgram.id))\n\n#API URL for returning the current program. It is a GET method. \n@app.route('/api/current-program')\ndef current_program():\n if (len(programs) >= 1):\n return json.dumps(programs[0], cls=programEncoder)\n else:\n return json.dumps(\"No programs\")\n \n \n#API URL for removing the current program. It is a GET method\n@app.route('/api/remove-program')\ndef remove_program():\n programs.pop(0)\n ids.pop(0)\n return \"Success\"\n \n#API URL for getting the position in queue of an ID. It is a GET method that takes a ID value in.\n@app.route('/api/position')\ndef position():\n args = request.args\n request_id = int(args[\"id\"])\n if request_id in ids:\n return jsonify(str(ids.index(request_id)))\n else:\n return jsonify(\"Id isn't present\")\n \n#This will call Flask to run the application to run on the VAPOR link. If the file name is main, it will run the application\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=(os.environ.get('VAPOR_LOCAL_PORT')))\n","repo_name":"CJChristenson/drew-drew-this-isp","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5089,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"5215565684","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\n@author: wushaohong\n@time: 2020-06-03 10:24\n\"\"\"\n\"\"\"128. 最长连续序列\n给定一个未排序的整数数组,找出最长连续序列的长度。\n\n要求算法的时间复杂度为 O(n)。\n\n示例:\n\n输入: [100, 4, 200, 1, 3, 2]\n输出: 4\n解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。\"\"\"\n\n\nclass Solution:\n def longestConsecutive(self, nums) -> int:\n res = 0\n nums = set(nums)\n for n in nums:\n if n - 1 not in nums:\n cur = n\n cur_l = 1\n while cur + 1 in nums:\n cur += 1\n cur_l += 1\n res = max(res, cur_l)\n return res\n\n def longestConsecutive2(self, nums) -> int:\n d = {}\n res = 0\n for n in nums:\n if n not in d:\n left = d.get(n - 1, 0)\n right = d.get(n + 1, 0)\n print(d, n, left, right)\n cur = left + 1 + right\n res = max(res, cur)\n d[n] = cur\n d[n - left] = cur\n d[n + right] = cur\n return res\n\n\nif __name__ == '__main__':\n sol = Solution()\n print(sol.longestConsecutive([100, 4, 200, 1, 3, 2]))\n print(sol.longestConsecutive2([100, 4, 200, 1, 3, 2]))\n","repo_name":"hshrimp/letecode_for_me","sub_path":"letecode/121-240/121-144/128.py","file_name":"128.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"74719166089","text":"#!/usr/bin/env python3\n\n\nwith open(\"strategy_guide\") as inf:\n\tinput = inf.read().splitlines()\n\n\n# X means *lose*, 0 pts\n# Y means \"Tie\", 3 pts\n# Z means \"Win\", 6 pts\n\n# if we throw a:\n#\tRock:\t1 pt\n#\tPaper:\t2 pts\n#\tScissors: 3 pts\n\ndef brute(line):\n\tif line == \"A X\":\n\t\t# Lose to Rock ==> Throw Scissors\n\t\treturn (0 + 3)\n\tif line == \"A Y\":\n\t\t# Tie with Rock ==> Throw Rock\n\t\treturn (3 + 1)\n\tif line == \"A Z\":\n\t\t# Win vs rock, throw Paper\n\t\treturn (6 + 2)\n\tif line == \"B X\":\n\t\treturn (0 + 1)\n\tif line == \"B Y\":\n\t\treturn (3 + 2)\n\tif line == \"B Z\":\n\t\treturn (6 + 3)\n\tif line == \"C X\":\n\t\treturn (0 + 2)\n\tif line == \"C Y\":\n\t\treturn (3 + 3)\n\tif line == \"C Z\":\n\t\treturn (6 + 1)\n\n\ndef should_throw(line):\n\tif line == \"A Z\" or line == \"B Y\" or line == \"C X\":\n\t\treturn \"P\"\n\tif line == \"A Y\" or line == \"B X\" or line == \"C Z\":\n\t\treturn \"R\"\n\tif line == \"A X\" or line == \"B Z\" or line == \"C Y\":\n\t\treturn \"S\"\n\ndef show_outcome(line):\n\tif \"X\" in line:\n\t\treturn \"Lose\"\n\tif \"Y\" in line:\n\t\treturn \"Tie\"\n\treturn \"Win\"\n\ndef get_winscore(line):\n\tif \"X\" in line:\n\t\treturn 0\n\tif \"Y\" in line:\n\t\treturn 3\n\tif \"Z\" in line:\n\t\treturn 6\n\ndef get_throwscore(line):\n\tif \"R\" in line:\n\t\treturn 1\n\tif \"P\" in line:\n\t\treturn 2\n\tif \"S\" in line:\n\t\treturn 3\n\ntotal = 0\nbrute_total = 0\nfor line in input:\n\tbrute_total += brute(line)\n\tthrow = should_throw(line)\n\tround = get_winscore(line) + get_throwscore(throw)\n\tprint(f\"{line}: {show_outcome(line)}, throw {should_throw(line)}, {brute(line)}? {round} ({get_winscore(line)} + {get_throwscore(throw)})\")\n\ttotal += round\nprint(f\"brute: {brute_total}, elegant: {total}\")\n","repo_name":"natethebobo/adventOfCode2022","sub_path":"day2/2Dec.py","file_name":"2Dec.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"22327556933","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n\nimport os\nimport sys\n\nfrom setuptools import find_packages\nfrom setuptools import setup\nfrom setuptools.command.install import install\n\nVERSION = '0.0.1'\n\n\nclass VerifyVersionCommand(install):\n \"\"\"Custom command to verify that the git tag matches our version\"\"\"\n description = 'verify that the git tag matches our version'\n\n def run(self):\n tag = os.getenv('CIRCLE_TAG')\n tag = tag.lstrip('v')\n\n if tag != VERSION:\n info = f\"Git tag: {tag} does not match the version of this app: {VERSION}\"\n sys.exit(info)\n\n\nsetup(\n name='vttes',\n version=VERSION,\n license='BSD',\n description='Python Tools for Roll20 / VTTES / Better20 integrations',\n long_description='Python tools.',\n author='William Gibb',\n author_email='williamgibb@gmail.com',\n url='https://github.com/forgedconcordance/vttestools',\n packages=find_packages(include=('vttes',)),\n include_package_data=True,\n zip_safe=False,\n classifiers=[\n # complete classifier list: http://pypi.python.org/pypi?%3Aaction=list_classifiers\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: Unix',\n 'Operating System :: POSIX',\n 'Operating System :: Microsoft :: Windows',\n 'Programming Language :: Other',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n 'Programming Language :: Python :: Implementation :: CPython',\n ],\n keywords=[\n # eg: 'keyword1', 'keyword2', 'keyword3',\n ],\n install_requires=[\n 'cmd2==1.4.0',\n 'tabulate==0.8.7',\n 'synapse>=2.33.0,<3.0.0',\n ],\n extras_require={\n # eg:\n # 'rst': ['docutils>=0.11'],\n # ':python_version==\"2.6\"': ['argparse'],\n },\n entry_points={\n 'console_scripts': [\n 'vttestools= vttes.tools.cli:_main',\n ]\n },\n cmdclass={\n 'verify': VerifyVersionCommand,\n },\n)\n","repo_name":"forgedconcordance/vttestools","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"26141503390","text":"class Solution:\n def minimumFinishTime(self, tires: List[List[int]], changeTime: int, numLaps: int) -> int:\n tires.sort(key=lambda x:x[1])\n candidateTires = []\n for tire in tires:\n if not candidateTires:\n candidateTires.append(tire)\n elif tire[0] < candidateTires[-1][0]:\n candidateTires.append(tire)\n\n n = len(candidateTires)\n\n def totalTime(tire, lap):\n f, r = candidateTires[tire][0], candidateTires[tire][1]\n # f * r^(lap-1)\n # f * r^0 + f*r^1 + f*r^2 + ... + f*r^(lap-1)\n return f * (r**lap-1)//(r-1)\n\n minTime = [inf] * (numLaps + 1)\n for lap in range(1, numLaps+1):\n for i in range(n):\n minTime[lap] = min(minTime[lap], totalTime(i, lap))\n\n dp = [inf] * 1001\n dp[0] = 0\n for i in range(1, numLaps+1):\n for j in range(1, i+1):\n if j < i:\n dp[i] = min(dp[i], dp[i-j] + changeTime + minTime[j])\n elif j == i:\n dp[i] = min(dp[i], dp[i-j] + minTime[j])\n\n return dp[numLaps]","repo_name":"Vergil0327/leetcode-history","sub_path":"2-D Dynamic Programming/2188. Minimum Time to Finish the Race/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"70953013129","text":"# Создайте программу для игры с конфетами человек против человека.\n\n# Условие задачи: На столе лежит 2021 конфета. Играют два игрока делая ход друг после друга.\n# Первый ход определяется жеребьёвкой. За один ход можно забрать не более чем 28 конфет.\n# Все конфеты оппонента достаются сделавшему последний ход.\n# Сколько конфет нужно взять первому игроку, чтобы забрать все конфеты у своего конкурента?\n# a) Добавьте игру против бота\n# b) Подумайте как наделить бота \"\"интеллектом\"\"\n\nimport random\ndef input_check(sum):\n while True:\n if sum <= 28:\n max = sum\n else:\n max = 28\n print(f'сколько конфет берём? (максимум {max})')\n try:\n pos = int(input())\n if pos > 0 and pos <= 28:\n return pos\n else:\n print('попробуй ещё раз')\n except:\n print('Мы в конфетки играем. Пиши цифру или уходи')\n\nplayer_1 = input('введите имя первого игрока: ')\nplayer_2 = input('введите имя второго игрока: ')\nplayers = [(0, player_1), (1, player_2)]\nnumber = int(input('на сколько конфет играем?'))\nfirst = random.randint(0, 1)\nwhile number > 0:\n print(f'ходит {players[first%2][1]}')\n number -= input_check(number)\n if number == 0:\n print(f'{players[first%2][1]} побеждает и забирает себе все конфеты! \\n {players[first%2-1][1]} остётся ни с чем')\n break\n first = first % 2 + 1\n print(number)\n","repo_name":"j10r2/Python_meeting","sub_path":"seminar5/homework5/hw5_1.py","file_name":"hw5_1.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"5196967122","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nt, q = np.genfromtxt('CircuitoRC.txt').T\n\ndef equation(R, C):\n global t\n V0 = 10\n return V0*C*(1-np.exp(-t/(R*C)))\n\ndef error(small_q):\n global q\n return np.sum((q - small_q)**2)\n\ndef chain(steps = 1000, dr = 0.1, dc = 0.1):\n R = np.zeros(steps)\n C = np.zeros(steps)\n R[0] = np.random.random()*dr\n C[0] = np.random.random()*dc\n\n last_error = error(equation(R[0], C[0]))\n for i in range(steps-1):\n r = abs((2*np.random.random()-1)*dr + R[i])\n c = abs((2*np.random.random()-1)*dc + C[i])\n\n alpha = np.exp(error(equation(R[i], C[i])) - error(equation(r, c)))\n alpha = min(1, alpha)\n if alpha > np.random.random():\n R[i+1] = r\n C[i+1] = c\n else:\n R[i+1] = R[i]\n C[i+1] = C[i]\n return R, C\n\nR, C = chain()\nQ = equation(R[500:].mean(), C[500:].mean())\n\nfig, (ax1, ax2) = plt.subplots(1, 2)\nax1.plot(t, q, label = \"Real\")\nax1.plot(t, Q, label = \"Best\")\nax1.set_xlabel('$t$')\nax1.set_ylabel('$q(t)$')\nax1.legend()\n\nax2.plot(R, label = \"$R$\")\nax2.plot(C, label = \"$C$\")\nax2.set_ylabel('Value')\nax2.set_xlabel('Iteration')\nax2.legend()\nplt.savefig(\"CircuitoRC.png\")\n","repo_name":"ComputoCienciasUniandes/MetodosComputacionales","sub_path":"talleres/2017-01/hw_5/Solucion/CircuitoRC.py","file_name":"CircuitoRC.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"73521323529","text":"\"\"\"This is a poorly coded statistics page that gives user info.\"\"\"\n\nimport zlib\nimport random\nimport string\nimport hashlib\nimport sqlite3\nimport datetime\n\nfrom pathlib import Path\nfrom jinja2 import Template\nfrom flask import session, request, current_app\n\nfrom riddle.names import random_name, _names, _adjectives\nfrom riddle.utils import create_user, get_user\nfrom riddle.urls import without_answer, add_route\n\n\nsuper_user = (\"monty-python\", \"flying circus\")\n\n\nsuccess_message = f'''\nIf you are reading this message, it means you made it: I am {super_user[0]},\none of the funding members of the WASP10 association and I found the hole in\nthe system that I just exploited to get this message. Sorry if we were not\nvery explicit in telling how to come here, but trust is fundamental in this\nphase. I would like to let you know that you are not alone, and the number of\npeople fighting the EAI must continue to grow.\nAt the venue, among the PyConX staff, there are some WASP10 undercover agents\nthat have been sent there to scout talents and invite them to participate in\nthe competition. Those agents are still unaware of the fact that an EAI\novertook our communications.\nYour job is now to find them and inform them of what is happening.\nYou must gain their trust and let them know the truth. They might help you in \ngetting the necessary information to break into the system and destroy the AI,\nbut you will not able to do it alone.\nIf you find something interesting, use /wasp9/clues to send it to me.\n\nRemember my name when you meet the agents, it might be useful.\nGood luck.\n'''\n# But... WASP10 is now public, why having undercover agents? Why do they need\n# to trust the player?? This is fishy...\n\n# Let's use the same join date to keep it simple and fishy\njoin_date = \"2009-10-30\"\n\nhosts = (\n # Actually interesting hosts\n (1, '127.0.0.1:8888', 'telnet'), # Password breaking challenge\n (2, '5.44.12.71', 'http'), # id=2 will be used by fetch\n # Some random hosts\n # (3, '5.44.12.70', 'ftp'),\n # (4, '1.32.1.32', 'irc'), # This could actually be real :)\n # (5, '10.42.0.112', 'pop3'),\n # Some not-so-random hosts, just for fun\n (6, '20.19.5.2', 'pcx'),\n (7, '20.19.5.3', 'pcx'),\n (8, '20.19.5.4', 'pcx'),\n (9, '20.19.5.5', 'pcx'),\n)\n\nusers = (\n # Let's give PyConX organizers some credit :)\n # Those are some of the many members who made PyConX possible\n # The passwords are there just for fun, let's hope they enjoy them!\n ('patrick91', \"thank you for the birthday gift, Marilyn\"),\n ('davidmugnai', \"measure once, cut once, fix once\"),\n ('hype_fi', \"impossible is just a matter of time\"),\n ('simbasso', \"we should not test in production\"),\n ('cm', \"the glass is half full and half wrong\"),\n ('yakkys', \"d-j-a-n-g-o, the d is silent\"),\n ('mena', \"go go gadget everything\"),\n ('leriomaggio', \"from oxford import british_accent\"),\n ('__pamaron__', \"for the holy Mary\"),\n ('viperale', \"human body is 90% water, mine is 90% spritz\"),\n ('rasky', \"optimising life\"),\n ('fiorella', \"I am tooooo cute\"),\n # Back to the game\n super_user, # Easily breakable\n)\n\n\ndef password_hash(data):\n \"\"\"Return an integer value representing the hash of data.\"\"\"\n return int.from_bytes(hashlib.blake2b(data, digest_size=2).digest(), 'big')\n\n\ndef break_password_hash(target):\n \"\"\"Search for a random string with given hash.\"\"\"\n import time\n for b_order in ['big', 'little']:\n start = time.time()\n count = 0\n while True:\n if time.time() >= start + 60:\n print(\"In 60 seconds we did\", count, \"iterations\")\n count = 0\n start = time.time()\n count += 1\n x = ''.join(random.sample(string.ascii_letters, 10))\n if password_hash(x.encode()) == target:\n print(\"Found\", x, \"with byte order\", b_order)\n break\n\n\ndef get_database(user):\n \"\"\"Return the database of a given user, making it up if not existing.\"\"\"\n root = Path('./data')\n root.mkdir(parents=True, exist_ok=True)\n\n db_file = root / f'db_{user[\"id\"]}.sqlite3'\n if db_file.exists():\n print(\"Loading existing db\")\n db = sqlite3.connect(db_file)\n return db\n\n print(\"Creating database for user\", user)\n db = sqlite3.connect(db_file)\n with db:\n # Seed random number generation uniquely for each player for coherent xp\n rng = random.Random()\n rng.seed(user['id'])\n\n # Generate some random players with unique name\n num_fake_players = rng.randrange(50, 70)\n fake_player_names = {random_name('-', rng)\n for _ in range(num_fake_players)}\n # Add one user which is particular... Why would WASP9 use a special\n # python-related name? This is fishy...\n fake_player_names.add(super_user[0])\n\n # Build a (deterministically) shuffled list of uers\n # user_data = {name: ['2009-10-30'] for name in fake_player_names}\n usernames = sorted(fake_player_names)\n rng.shuffle(usernames)\n\n db.executescript('''\n CREATE TABLE user (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT NOT NULL UNIQUE,\n timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP\n );\n\n CREATE TABLE event (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT NOT NULL,\n origin INTEGER NOT NULL,\n value INTEGER NOT NULL,\n timestamp TIMESTAMP NOT NULL\n );\n\n CREATE TABLE counter (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n event_id TEXT NOT NULL,\n count INTEGER NOT NULL\n );\n\n CREATE TABLE hosts (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n host TEXT NOT NULL,\n protocol TEXT NOT NULL\n );\n\n CREATE TABLE actl (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n user TEXT NOT NULL UNIQUE,\n blake2b_16 TEXT NOT NULL\n );\n ''')\n\n for usr in usernames:\n db.execute('''INSERT INTO user (name, timestamp) VALUES (?,?)''',\n [usr, join_date])\n\n for ev in ['access', 'access', 'score', 'score']:\n db.execute('''INSERT INTO event (name, origin, value, timestamp)\n VALUES (?,?,?,?)''',\n ['access', 'wasp9/stage0', 1, '2009-02-02'])\n\n for n in [(1, 1), (2, 75), (3, 112)]:\n db.execute('''INSERT INTO counter (event_id, count)\n VALUES (?,?)''',\n n)\n\n for h in hosts:\n db.execute('''INSERT INTO hosts (id, host, protocol)\n VALUES (?,?,?)''', h)\n\n for user, pwd in users:\n db.execute('''INSERT INTO actl (user, blake2b_16) VALUES (?,?)''', \n [user, password_hash(pwd.encode())])\n\n return db\n","repo_name":"akiross/PyConXRiddle","sub_path":"riddle/game/wasp10/old/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7087,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"16"}
+{"seq_id":"34304545110","text":"\"\"\"Find the sum of multiples of three or five from 1 to n inclusive.\"\"\"\n\n\ndef find_sum(n):\n nums_sum = 0\n for i in range(3, n+1):\n if i % 3 == 0 or i % 5 == 0:\n nums_sum += i\n return nums_sum\n\n\ndef main():\n n = int(input())\n print(find_sum(n))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"0x70DA/IEEE-ZSB-Technical-Rookies-22","sub_path":"Task-1/problem_7.py","file_name":"problem_7.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"16"}
+{"seq_id":"18591305641","text":"from math import isnan, isinf\nimport re\n\njs_version = \"0.4\" # the d.o jasper version string that this is synced to.\n\nclass __OutputObject:\n\tdef __init__(self, v, s, p):\n\t\tself._dict = {'value': v, 'schema': s, 'path': p}\n\t\tself.sanitized = None\n\t\tself.errors = []\n\t\tself.warnings = []\n\tdef err(self, msg):\n\t\tself.errors.append(self._dict.copy().update({'message': msg}))\n\tdef warn(self, msg):\n\t\tself.errors.append(self._dict.copy().update({'message': msg}))\n\tdef merge_errors(self, other):\n\t\tself.errors.extend(other.errors)\n\t\tself.warnings.extend(other.warnings)\n\tdef proxy(self, other):\n\t\tself.sanitized = other.sanitized\n\t\tself.errors = other.errors\n\t\tself.warnings = other.warnings\n\nclass __Context:\n\tdef __init__(self, obj, opts):\n\t\tself.obj = obj\n\t\tself.opts = opts\n\n# \n_regex_parse = re.compile(r'^/(.*)/(i?m?|mi)$')\n_regex_flags = {\n\t'i': re.I, 'm': re.M, 'im': re.I | re.M, 'mi': re.I | re.M\n}\ntypeof = lambda s: type(s).__name__\n_inf = float(\"Infinity\")\n\ndef dictify(array):\n\tout = {}\n\tfor i in range(len(array)):\n\t\tout[str(i)] = array[i]\n\treturn out\n\n# The basic validation functions for the primitives are defined here.\n# They all take a basic set of parameters: \n# v: the value in the input object\n# o: an output object\n# m: the metadata object from the schema\n# r: a recurse function, to validate any children\n# c: the context of the function -- called opts and the overall object.\n\n# We create a primitives registry with an accompanying decorator.\nprimitives = {}\ndef primitive(fn):\n\tprimitives[fn.__name__[1:]] = fn\n\treturn fn\n\n@primitive\ndef _freeform(v, o, m, r, c):\n\to.sanitized = v;\n\n@primitive\ndef _regex(v, o, m, r, c):\n\tif typeof(v) == 'SRE_Pattern':\n\t\to.sanitized = v;\n\telif typeof(v) == 'str':\n\t\ttry: \n\t\t\tmatch = _regex_parse.search(v)\n\t\t\tflags = _regex_flags.get(match.group(2), 0)\n\t\t\to.sanitized = re.compile(match.group(1), flags)\n\t\texcept re.error:\n\t\t\to.err('invalid regular expression')\n\t\t\treturn\n\telse:\n\t\to.err('unable to coerce')\n\t\treturn\n\tif c.opts.get('regex_as_string', False):\n\t\tflags = ''\n\t\tif o.sanitized.flags & re.I:\n\t\t\tflags += 'i'\n\t\tif o.sanitized.flags & re.M:\n\t\t\tflags += 'm'\n\t\to.sanitized = '/' + o.sanitized.pattern + '/' + flags\n\n# for consistency with jasper 0.4, we only cast \"true\", not \"True\"\n@primitive\ndef _boolean(v, o, m, r, c): \n\tif typeof(v) == 'bool':\n\t\to.sanitized = v\n\telse: \n\t\tv = str(v)\n\t\tif v in ['true', 'false']:\n\t\t\to.sanitized = (v == 'true')\n\t\t\to.warn('type coercion')\n\t\telse: \n\t\t\to.err('unable to coerce')\n\n@primitive\ndef _number(v, o, m, r, c): \n\tif typeof(v) not in ['int', 'float']:\n\t\to.warn('type coercion')\n\ttry: \n\t\tv = float(v)\n\t\tif isnan(v) or isinf(v):\n\t\t\tv = None\n\texcept ValueError:\n\t\tv = None\n\t\t\n\tif v == None:\n\t\to.err('unable to coerce')\n\telse: \n\t\tif m.get('integer', False) and int(v) == v:\n\t\t\to.err('not an integer')\n\t\tif m.get('max', _inf) < v:\n\t\t\to.err('maximum violated')\n\t\tif m.get('min', -_inf) > v:\n\t\t\to.err('minimum violated')\n\t\t\n\t\to.sanitized = v;\n\n@primitive\ndef _string(v, o, m, r, c):\n\tt = typeof(v)\n\tif t == 'str':\n\t\tpass\n\telif t in ['int', 'float', 'boolean']:\n\t\to.warn('type coercion')\n\t\tv = str(v).lower()\n\telse:\n\t\to.err('unable to coerce')\n\t\treturn\n\t\n\tif m.get('max_length', _inf) < len(v):\n\t\to.err('max length violated')\n\tif m.get('min_length', -_inf) > len(v):\n\t\to.err('min length violated')\n\tif m.get('root_index', False) and v not in c.obj:\n\t\to.err('not a valid key into the root index')\n\tregex = m.get('regex', None)\n\tif regex and not regex.search(v):\n\t\to.err('regex violated')\n\tif m.get('confidential', False) and c.opts.get('hide_confidential', False):\n\t\tv = \"(confidential)\"\n\t\n\to.sanitized = v\n\n@primitive\ndef _index(v, o, m, r, c):\n\tsanitized = {}\n\tsubschema = m.get('elements', 'object')\n\tregex = m.get('valid_keys', None)\n\tt = typeof(v)\n\tif t == 'dict':\n\t\tpass\n\telif t == 'list':\n\t\tif len(v) > 0:\n\t\t\to.warn('type coercion')\n\t\tv = dictify(v)\n\telse:\n\t\to.err('unable to coerce')\n\t\treturn\n\t\n\tfor key in v:\n\t\toutput = r(v[key], subschema, key)\n\t\tsanitized[key] = output.sanitized\n\t\tif regex and not regex.search(key):\n\t\t\to.err('invalid key: ' + key)\n\t\to.merge_errors(output)\n\to.sanitized = sanitized\n\n@primitive\ndef _list(v, o, m, r, c):\n\tsanitized = []\n\tsubschema = m.get('elements', 'object')\n\tif typeof(v) == 'list':\n\t\tfor i in range(len(v)):\n\t\t\toutput = r(v[i], subschema, i)\n\t\t\tsanitized.append(output.sanitized)\n\t\t\to.merge_errors(output)\n\t\to.sanitized = sanitized\n\telse:\n\t\to.err('unable to coerce')\n\n@primitive\ndef _multi(v, o, m, r, c):\n\tsubschemas = m.get('allowed', [])\n\tattempts = []\n\t# we create a default error. The only way out will be o.proxy().\n\to.err('no options matched')\n\t\n\tfor i in range(len(subschemas)):\n\t\toutput = r(v, subschemas[i], '(multi: ' + str(i) + ')')\n\t\tattempts.append(output)\n\t\to.merge_errors(output)\n\t\n\tattempts.sort(key=lambda a: (len(a.errors), len(a.warnings)))\n\t\n\tif len(attempts) > 0:\n\t\tif len(attempts[0].errors) == 0:\n\t\t\to.proxy(attempts[0])\n\n@primitive\ndef _enum(v, o, m, r, c):\n\tvalue = m.get('value_field', 'value')\n\tmeta = m.get('meta_field', 'meta')\n\topts = m.get('options', {})\n\tsubtype = 'object' if m.get('strict', True) else 'args'\n\tt = typeof(v)\n\tif t == 'dict':\n\t\tpass\n\telif t == 'list':\n\t\tv = dictify(v)\n\telse:\n\t\to.err('unable to coerce')\n\t\treturn\n\t\n\tif value not in v:\n\t\to.err('unable to coerce')\n\telif v[value] not in opts:\n\t\to.err('value not allowed by enum: ' + v[value])\n\telse:\n\t\tsubschema = {'type': subtype, 'meta': {'fields': opts[v[value]]}}\n\t\toutput = r(v.get(meta, {}), subschema, meta)\n\t\to.merge_errors(output)\n\t\to.sanitized = {value: v[value], meta: output.sanitized} \n\t\t# note: this key ^ is not necessarily \"value\".\n\n@primitive\ndef _args(v, o, m, r, c):\n\tfields = m.get('fields', {})\n\to.sanitized = {}\n\tt = typeof(v)\n\tif t == 'list':\n\t\tv = dictify(v)\n\telif t != 'dict':\n\t\to.err('unable to coerce')\n\t\treturn\n\t\n\tfor k in v:\n\t\tif k not in fields:\n\t\t\to.warn('extra key not in schema: ' + k)\n\t\telse: \n\t\t\toutput = r(v[k], fields[k], k)\n\t\t\to.merge_errors(output)\n\t\t\to.sanitized[k] = output.sanitized\n\n@primitive\ndef _object(v, o, m, r, c):\n\tfields = m.get('fields', {})\n\t#first, validate as an `args` type\n\t_args(v, o, m, r, c)\n\t#then, check that all keys are accounted for:\n\tif typeof(o.sanitized) == 'dict':\n\t\tfor k in fields:\n\t\t\tif k not in o.sanitized:\n\t\t\t\to.err('missing field: ' + k)\n\ndef validation(obj, model, root_schema, opts=None):\n\tif typeof(opts) != 'dict':\n\t\topts = {}\n\tcontext = __Context(obj, opts)\n\t\n\tdef subvalidate(value, schema, path):\n\t\t# convert schema to {type, meta} form:\n\t\tif typeof(schema) == 'str':\n\t\t\tschema = model.get(schema, {'type': schema, 'meta': {}})\n\t\ttry:\n\t\t\tvalue = value.jasper();\n\t\texcept AttributeError:\n\t\t\tpass\n\t\tout = __OutputObject(value, schema, path)\n\t\tdef recurse(v, s, name):\n\t\t\tsubpath = path[:]\n\t\t\tsubpath.append(name)\n\t\t\treturn subvalidate(v, s, subpath)\n\t\t\n\t\tt = schema['type']\n\t\tif t in primitives:\n\t\t\tprimitives[t](value, out, schema['meta'], recurse, context)\n\t\telse: \n\t\t\tout.err(\"schema type not recognized: \" + t)\n\t\t\n\t\treturn out\n\t\n\tobj = subvalidate(obj, model[root_schema], [])\n\t\n\tif len(obj.errors) > 0:\n\t\treturn {'status': 'errors', 'meta': {'list': obj.errors}};\n\telse:\n\t\treturn {\n\t\t\t'status': 'ok', \n\t\t\t'meta': {'sanitized': obj.sanitized, 'warnings': obj.warnings}\n\t\t}\n\n__not_type = re.compile(\"^((?!type).+|type.+)$\")\n__primitives = re.compile(\"^(\" + \"|\".join(primitives.keys()) + \")$\")\n\nmetamodel = {\n\t\"model\": {\"type\": \"index\", \"meta\": {\n\t\t\"elements\": \"schema\",\n\t\t\"valid_keys\": __not_type\n\t}},\n\t\"primitive string\": {\"type\": \"string\", \"meta\": {\n\t\t\"regex\": __primitives\n\t}}, \n\t\"composite schema\": {\"type\": \"multi\", \"meta\": {\n\t\t\"allowed\": [\n\t\t\t\"schema\", \n\t\t\t\"primitive string\",\n\t\t\t{\"type\": \"string\", \"meta\": {\"root_index\": True}}\n\t\t]\n\t}},\n\t\"natural number\": {\"type\": \"number\", \"meta\": {\"integer\": True, \"min\": 0}},\n\t\"object fields\": {\"type\": \"index\", \"meta\": {\"elements\": \"composite schema\"}},\n\t\"schema\": {\"type\": \"enum\", \"meta\": {\n\t\t\"value_field\": \"type\",\n\t\t\"meta_field\": \"meta\",\n\t\t\"strict\": False,\n\t\t\"options\": {\n\t\t\t\"freeform\": {},\n\t\t\t\"boolean\": {},\n\t\t\t\"regex\": {},\n\t\t\t\"number\": {\n\t\t\t\t\"integer\": \"boolean\",\n\t\t\t\t\"max\": \"number\",\n\t\t\t\t\"min\": \"number\"\n\t\t\t},\n\t\t\t\"string\": {\n\t\t\t\t\"max_length\": \"natural number\",\n\t\t\t\t\"min_length\": \"natural number\",\n\t\t\t\t\"regex\": \"regex\",\n\t\t\t\t\"root_index\": \"boolean\",\n\t\t\t\t\"confidential\": \"boolean\"\n\t\t\t},\n\t\t\t\"enum\": {\n\t\t\t\t\"value_field\": \"string\",\n\t\t\t\t\"meta_field\": \"string\",\n\t\t\t\t\"strict\": \"boolean\",\n\t\t\t\t\"options\": {\"type\": \"index\", \"meta\": {\"elements\": \"object fields\"}}\n\t\t\t},\n\t\t\t\"index\": {\n\t\t\t\t\"elements\": \"composite schema\",\n\t\t\t\t\"valid_keys\": \"regex\"\n\t\t\t},\n\t\t\t\"list\": {\n\t\t\t\t\"elements\": \"composite schema\"\n\t\t\t},\n\t\t\t\"args\": {\n\t\t\t\t\"fields\": \"object fields\"\n\t\t\t},\n\t\t\t\"object\": {\n\t\t\t\t\"fields\": \"object fields\"\n\t\t\t},\n\t\t\t\"multi\": {\n\t\t\t\t\"allowed\": {\"type\": \"list\", \"meta\": {\"elements\": \"composite schema\"}}\n\t\t\t}\n\t\t}\n\t}}\n}\n\nclass Model:\n\tdef __init__(self, model_spec, base_opts=None):\n\t\tself.base_opts = base_opts if typeof(base_opts) == 'dict' else {}\n\t\tmodel = validation(model_spec, metamodel, \"model\")\n\t\tif model['status'] == \"errors\" or len(model['meta']['warnings']) > 0:\n\t\t\traise ValueError(\"Invalid jasper model. Please revalidate it.\")\n\t\t\n\t\tself.model = model['meta']['sanitized']\n\t\n\tdef validate(self, obj, model_name, opts={}):\n\t\tmodel_name = str(model_name)\n\t\tsubopts = self.base_opts.copy().update(opts)\n\t\tif model_name not in self.model:\n\t\t\traise ValueError(\"Unrecognized model name: \" + model_name)\n\t\telse:\n\t\t\treturn validation(obj, self.model, model_name, subopts)","repo_name":"crdrost/d.o","sub_path":"extras/jasper.py","file_name":"jasper.py","file_ext":"py","file_size_in_byte":9450,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"16"}
+{"seq_id":"69804984967","text":"from Token import Token\nfrom Error import Error\nfrom prettytable import PrettyTable\nimport webbrowser\nimport time\n\nclass Scanner:\n def __init__(self):\n self.buffer = ''\n self.fila = 1\n self.columna = 1\n self.estado = 0\n self.listaTokens = []\n self.listaErrores = []\n self.i = 0\n self.flag_comillas = False\n \n def agregar_Token(self,caracter,fila,columna,token):\n self.listaTokens.append(Token(caracter,fila,columna,token))\n self.buffer = ''\n \n def agregar_Error(self,caracter,fila,columna):\n if ord(caracter)>= 48 and ord(caracter)<= 57:\n self.listaErrores.append(Error('Caracter \\'' + caracter + '\\' error de tipo Numero',fila,columna))\n else:\n self.listaErrores.append(Error('Caracter \\'' + caracter + '\\' error de tipo Simbolo',fila,columna))\n def s0(self,caracter):\n '''Estado 0'''\n if (caracter.isalpha() and not self.flag_comillas):\n self.estado = 1\n self.buffer += caracter\n self.columna += 1\n elif caracter == '~':\n self.estado = 2\n self.buffer += caracter\n self.columna += 1\n elif caracter == '[':\n self.estado = 3\n self.buffer += caracter\n self.columna += 1\n elif caracter == ']':\n self.estado = 4\n self.buffer += caracter\n self.columna += 1\n elif caracter == '\\\"':\n self.estado = 5\n self.buffer += caracter\n self.columna += 1\n elif caracter == '\\'':\n self.estado = 6\n self.buffer += caracter\n self.columna += 1\n elif (caracter.isalpha() or (ord(caracter)>= 48 and ord(caracter)<= 57)) and self.flag_comillas:\n self.estado = 7\n self.buffer += caracter\n self.columna += 1\n elif caracter == '<':\n self.estado = 8\n self.buffer += caracter\n self.columna += 1\n elif caracter == '>':\n self.estado = 9\n self.buffer += caracter\n self.columna += 1\n elif caracter == ':':\n self.estado = 10\n self.buffer += caracter\n self.columna += 1\n elif caracter == ',':\n self.estado = 11\n self.buffer += caracter\n self.columna += 1\n elif caracter == '\\n':\n self.fila += 1\n self.columna = 1\n elif caracter in ['\\t',' ']:\n self.columna += 1\n elif caracter == '$':\n pass\n else:\n self.agregar_Error(caracter,self.fila,self.columna)\n \n def s1(self,caracter):\n '''Estado 1'''\n if caracter.isalpha():\n self.estado = 1\n self.buffer += caracter\n self.columna += 1\n else:\n if (self.buffer.lower() == 'formulario' or self.buffer.lower() == 'tipo' \n or self.buffer.lower() == 'valor' or self.buffer.lower() == 'fondo' or self.buffer.lower() == 'valores' \n or self.buffer.lower() == 'evento'): \n self.agregar_Token(self.buffer,self.fila,self.columna,'reservada_' + self.buffer)\n self.estado = 0\n self.i -= 1\n elif self.buffer in ['entrada', 'info']:\n self.agregar_Token(self.buffer,self.fila,self.columna,'evento_' + self.buffer)\n self.estado = 0\n self.i -= 1\n\n\n def s2(self):\n '''Estado 2'''\n self.agregar_Token(self.buffer,self.fila,self.columna,'Virgulilla')\n self.estado = 0\n self.i -= 1\n \n def s3(self):\n '''Estado 3'''\n self.agregar_Token(self.buffer,self.fila,self.columna,'Signo Abre corchete')\n self.estado = 0\n self.i -= 1\n \n def s4(self):\n '''Estado 4'''\n self.agregar_Token(self.buffer,self.fila,self.columna,'Signo Cierra corchete')\n self.estado = 0\n self.i -= 1\n \n def s5(self):\n '''Estado 5'''\n self.agregar_Token(self.buffer,self.fila,self.columna,'Signo de Comillas')\n self.estado = 0\n self.i -= 1\n if self.flag_comillas:\n self.flag_comillas = False\n else:\n self.flag_comillas = True\n \n def s6(self):\n '''Estado 6'''\n self.agregar_Token(self.buffer,self.fila,self.columna,'Signo Comillas Simple')\n self.estado = 0\n self.i -= 1\n if self.flag_comillas:\n self.flag_comillas = False\n else:\n self.flag_comillas = True\n \n def s7(self,caracter):\n '''Estado 7 - cadenas'''\n if caracter.isalpha():\n self.estado = 7\n self.buffer += caracter\n self.columna += 1\n elif caracter in ['+','!','*','@',' ','-',':',';','#','%','^','&','?',',','.','|']:\n self.estado = 7\n self.buffer += caracter\n self.columna += 1\n elif caracter.isdigit():\n self.estado = 7\n self.buffer += caracter\n self.columna += 1\n else:\n self.agregar_Token(self.buffer,self.fila,self.columna,'Cadena X')\n self.estado = 0\n self.i -= 1\n\n def s8(self):\n '''Estado 8'''\n self.agregar_Token(self.buffer,self.fila,self.columna,'Signo Menor Q')\n self.estado = 0\n self.i -= 1\n \n def s9(self):\n '''Estado 9'''\n self.agregar_Token(self.buffer,self.fila,self.columna,'Signo Mayor Q')\n self.estado = 0\n self.i -= 1\n \n def s10(self):\n '''Estado 10'''\n self.agregar_Token(self.buffer,self.fila,self.columna,'Signo de dos puntos')\n self.estado = 0\n self.i -= 1\n \n def s11(self):\n '''Estado 11'''\n self.agregar_Token(self.buffer,self.fila,self.columna,'Signo coma')\n self.estado = 0\n self.i -= 1\n\n def s12(self):\n '''Estado 12'''\n self.agregar_Token(self.buffer,self.fila,self.columna,'Signo coma')\n self.estado = 0\n self.i -= 1\n \n # self.agregar_Token\n def analizar(self,cadena):\n '''Realiza los cambios de estados'''\n cadena += '$'\n self.i = 0\n while self.i < len(cadena):\n if self.estado == 0:\n self.s0(cadena[self.i])\n elif self.estado == 1:\n self.s1(cadena[self.i])\n elif self.estado == 2:\n self.s2()\n elif self.estado == 3:\n self.s3()\n elif self.estado == 4:\n self.s4()\n elif self.estado == 5:\n self.s5()\n elif self.estado == 6:\n self.s6()\n elif self.estado == 7:\n self.s7(cadena[self.i])\n elif self.estado == 8:\n self.s8()\n elif self.estado == 9:\n self.s9()\n elif self.estado == 10:\n self.s10()\n elif self.estado == 11:\n self.s11()\n self.i += 1\n \n def imprimirTokens(self):\n x = PrettyTable()\n x.field_names = [\"Lexema\",\"fila\",\"Columna\",\"Tipo\"]\n for token in self.listaTokens:\n x.add_row([token.lexema,token.fila,token.columna,token.tipo])\n print(x)\n \n def imprimirErrores(self):\n x = PrettyTable()\n x.field_names = [\"Descripción\",\"fila\",\"Columna\"]\n for error in self.listaErrores:\n x.add_row([error.descripcion,error.fila,error.columna])\n print(x)\n \n def crearTTokens(self):\n texto = ''\n f = open('./ReporteTokens.html','w')\n texto += '''\n \n \n \n Reporte Tokens\n \n \n \n \n \n \n \n \n \n
\n \n
Tabla de Tokens
\n \n
A continuacion se presentan tabla de tokens encontrados en el lenguaje:
\n
\n \n
\n
LEXEMA
\n
FILA
\n
COLUMNA
\n
TIPO
\n
\n \n '''\n for token in self.listaTokens:\n texto +='''\n