diff --git "a/2196.jsonl" "b/2196.jsonl" new file mode 100644--- /dev/null +++ "b/2196.jsonl" @@ -0,0 +1,655 @@ +{"seq_id":"631079688","text":"#!/usr/bin/env python\n#\n# Created by: Shawn Chen \n#\n# LICENSE\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the Free\n# Software Foundation; either version 2 of the License, or(at your option)\n# any later version.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\n# more details at http://www.gnu.org/copyleft/gpl.html\n#\n# Brief\n# Solves LeetCode Problem 16: 3Sum Closest\n\n\nclass Solution(object):\n def threeSumClosest(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n nums.sort()\n finalsum = 0\n diff = 999999999\n for i in xrange(len(nums) - 2):\n if i > 0 and nums[i] == nums[i-1]:\n continue\n left, right = i + 1, len(nums) - 1\n while left < right:\n tmpsum = nums[left] + nums[right] + nums[i]\n tmpdiff = abs(tmpsum - target)\n if tmpdiff == 0:\n return target\n if tmpdiff < diff:\n diff = tmpdiff\n finalsum = tmpsum\n if tmpsum < target:\n left += 1\n else:\n right -= 1\n return finalsum\n","sub_path":"Problem16/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"247497519","text":"# -*- coding: utf-8 -*-\nfrom __future__ import (absolute_import, division, print_function, unicode_literals)\n\nfrom gensim.corpora.dictionary import Dictionary\nfrom pymongo import MongoClient\nfrom simple_arxiv_engine.utils.util_tasks import DictionaryFetcher\n\nimport logging\nimport luigi\nimport os\nimport spacy\n\n\n__author__ = 'Karl Ritchie '\n__copyrights__ = 'Copyright 2017 Karl Ritchie'\n\n\nlogger_name = 'simple.arxiv.engine'\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(logger_name)\n\nDATA = os.environ['SAE_DATA_FOLDER']\nUID = 'id'\nDB = 'simple_arxiv_engine'\nCOLL = 'raw'\n\n\nclass TextPreprocessor(luigi.Task):\n \"\"\"\n\n \"\"\"\n\n mongo_endpoint = luigi.Parameter(default='127.0.0.1')\n mongo_port = luigi.IntParameter(default=27017)\n\n def requires(self):\n return DictionaryFetcher(path='{0}/models/embeddings.model'.format(DATA))\n\n def output(self):\n return\n\n def run(self):\n \"\"\" Process each summary saved in the MongoDB to train word embeddings\n\n \"\"\"\n mongo = MongoClient(self.mongo_endpoint, self.mongo_port)\n items = mongo[DB][COLL].find({'summary': {'$exists': True}}, no_cursor_timeout=True)\n\n nlp = spacy.load('en')\n\n for item in items:\n if not item.get('tokens', None):\n\n # Preprocess tokens\n tokens = nlp.tokenizer(item['summary'])\n\n item['tokens'] = tokens\n mongo[DB][COLL].replace_one({UID: item[UID]}, item)\n\n return\n\nif __name__ == '__main__':\n luigi.run(main_task_cls=TextPreprocessor, local_scheduler=True,\n cmdline_args=[])\n","sub_path":"simple_arxiv_engine/data_processing/text_preprocessor.py","file_name":"text_preprocessor.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"179822207","text":"import requests\n\nheaders = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) '\n 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36'}\n\ntor_exit = []\nreq = requests.get('https://check.torproject.org/exit-addresses', headers=headers)\nreq.encoding = 'utf-8'\nr_lines = req.content.split('\\n')\nfor line in r_lines:\n if line.startswith('ExitAddress'):\n tor_exit.append(line.split(' ')[1])\n\nwith open('c:\\\\temp\\\\torexit.txt', 'w') as file:\n for i in tor_exit:\n file.write(i + '\\n')\n","sub_path":"torExitNodes.py","file_name":"torExitNodes.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"180333337","text":"from imblearn.over_sampling import ADASYN\n\n\ndef oversample_ADASYN(X, y, ratio=0.15):\n \"\"\" Oversample minority class using the ADASYN algorithm\n\n Arguments:\n X (2d array-like): feature set\n y (1d array-lile): target values\n ratio (float): desired ratio between minority and majority (optional)\n\n Return:\n X_os (2d array-like): oversampled feature set\n y_os (1d array-lile): oversampled target values\n\n Example:\n X_train_os, y_train_os = models.oversample_ADASYN(X_train, y_train, 0.3)\n \"\"\"\n\n # construct the ADASYN object\n os = ADASYN(sampling_strategy=ratio,\n n_neighbors=5,\n random_state=42)\n\n # oversample X and y data\n X_os, y_os = os.fit_sample(X, y)\n print('Oversampled minority-ratio of: {:3.1f}%'.format(100 * sum(y_os) / y_os.count()))\n\n return X_os, y_os\n","sub_path":"s2ds/src/models/oversample_data.py","file_name":"oversample_data.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"87257492","text":"from mcpi.minecraft import Minecraft\nfrom mcpi import block\nfrom time import sleep\nimport curses\nfrom datetime import datetime\n\ndef init(): \n\t# change 192.168.1.13 to 127.0.0.1 or your ip\n\tmc = Minecraft.create(\"127.0.0.1\", 4711)\n\tx, y, z = mc.player.getPos() \n\treturn mc\n\t\ndef block(mx,x,y,z,m):\n\t#mc.player.setPos(0, 0, 0)\n\tx, y, z = mc.player.getPos()\n\tmc.postToChat(\"block\") \n\tmc.setBlock(x+1, y, z+1,m)\n\t\n\t\nmc = init()\n# get the curses screen window\nscreen = curses.initscr()\n# turn off input echoing\ncurses.noecho()\n# respond to keys immediately (don't wait for enter)\ncurses.cbreak()\n# map arrow keys to special values\nscreen.keypad(True)\n \ntry:\n\twhile True:\n\t\tx1, y1, z1 = mc.player.getPos()\n\t\tchar = screen.getch()\n\t\tif char == ord('q'):\n\t\t\tbreak\n\t\telif char == curses.KEY_RIGHT:\n\t\t\tblock(mc,x1,y1,z1,8)\n # print doesn't work with curses, use addstr instead\n\t\t\tx = x + 1\n\t\t\tscreen.addstr(0, 0, 'right')\n\t\telif char == curses.KEY_LEFT:\n\t\t\tscreen.addstr(0, 0, 'left ') \n\t\telif char == curses.KEY_UP:\n\t\t\tscreen.addstr(0, 0, 'up ') \n\t\telif char == curses.KEY_DOWN:\n\t\t\tscreen.addstr(0, 0, 'down ')\nfinally:\n # shut down cleanly\n curses.nocbreak(); screen.keypad(0); curses.echo()\n curses.endwin()\n","sub_path":"cwc/inkeymc.py","file_name":"inkeymc.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"400015899","text":"from pybricks import ev3brick as brick\nfrom pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,\n InfraredSensor, UltrasonicSensor, GyroSensor)\nfrom pybricks.parameters import (Port, Stop, Direction, Button, Color,\n SoundFile, ImageFile, Align)\nfrom pybricks.tools import print, wait, StopWatch\nfrom pybricks.robotics import DriveBase\nimport time\n\ndef getReflection(name): #light sensor\n reflection = name.reflection()\n return(reflection)\n\ndef getDistance(name): #ir\n distance = name.distance()\n return(distance)\n\n#Notes:\n#in order to use, must create instance of InfraredSensor and input name as first parameter\n#returns numbers: the ascend in the order in the variables\n#channel must be a number 1-4\ndef readRemote(name, channel):\n redHigh = 128 #1\n blueHigh = 512 #2\n redLow = 2 #3\n blueLow = 8 #4\n redAndblueHigh = redHigh + blueHigh #5\n redAndBlueLow = redLow + blueLow #6\n redCrossBlue = redHigh + blueLow #7\n blueCrossRed = blueHigh + redLow #8\n allRed = redHigh + redLow #9\n allBlue = blueHigh + blueLow #10\n beacon = 256 #11\n buttonsPressed = name.buttons(channel)\n numPressed = len(buttonsPressed)\n if numPressed == 1:\n val = buttonsPressed[0]\n if val == redHigh:\n return(1)\n if val == redLow:\n return(3)\n if val == blueHigh:\n return(2)\n if val == blueLow:\n return(4)\n if val == beacon:\n return(11)\n elif numPressed == 2:\n val = buttonsPressed[0] + buttonsPressed[1]\n if val == redAndblueHigh:\n return(5)\n if val == redAndBlueLow:\n return(6)\n if val == redCrossBlue:\n return(7)\n if val == blueCrossRed:\n return(8)\n if val == allRed:\n return(9)\n if val == allBlue:\n return(10)\n else:\n return(\"None\")\n time.sleep(500)","sub_path":"EV3_programs/bobb3e/sensorTools.py","file_name":"sensorTools.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"256644965","text":"from ast import literal_eval as leval\nimport re\n\nimport numpy as np\n\n\ndef process_usgs_hazfaults(usgs_df):\n \"\"\"\n Processes the USGS HazFaults 2014 dataset for merging with master_df\n \"\"\"\n\n usgs_df = usgs_df[usgs_df['primary_st'] != 'California']\n\n preprocess_rakes(usgs_df)\n\n usgs_df['average_rake'] = usgs_df.apply(process_rake, axis=1)\n usgs_df['dip_dir'] = usgs_df.apply(process_dip_dir, axis=1)\n\n usgs_df['average_dip'] = usgs_df.apply(process_dip, axis=1)\n usgs_df['slip_type'] = usgs_df.apply(process_slip_type, axis=1)\n usgs_df['net_slip_rate'] = usgs_df.apply(process_slip_rate, axis=1)\n\n return usgs_df\n\n\ndef process_dip(row):\n return '({},,)'.format(int(row['dip']))\n\n\ndef process_dip_dir(row):\n if row['dip_dir'] not in (None, '', 'V'):\n return row['dip_dir']\n else:\n return None\n\n\ndef preprocess_rakes(df):\n df.loc[df['geo_slip_r'] == 0., 'geo_rake'] = None\n df.loc[df['bird_slip_'] == 0., 'bird_rake'] = None\n df.loc[df['zeng_slip_'] == 0., 'zeng_rake'] = None\n\n\ndef process_slip_rate(row):\n rate_list = row[['geo_slip_r', 'bird_slip_', 'zeng_slip_']].tolist()\n rate_list = sorted(rate_list)\n\n return '({},{},{})'.format(rate_list[1], rate_list[0], rate_list[2])\n\n\ndef process_rake(row):\n rake_list = row[['geo_rake', 'bird_rake', 'zeng_rake']].tolist()\n rake_list = sorted((r for r in rake_list if not np.isnan(r)))\n\n if len(rake_list) == 2:\n rake_list = [round(np.mean(rake_list)), rake_list[1], rake_list[0]]\n elif len(rake_list) == 1:\n rake_list = ['', rake_list[0], '']\n\n rake_tup = '({},{},{})'.format(rake_list[1], rake_list[0], rake_list[2])\n\n return rake_tup\n\n\ndef process_slip_type(row):\n rake_to_kin = {\n 180.: 'Dextral',\n -90.: 'Normal',\n 0.: 'Sinistral',\n 90.: 'Reverse'\n }\n\n try:\n slip_type = rake_to_kin[row['geo_rake']]\n except KeyError:\n if row['disp_slip_'] == 'normal':\n slip_type = 'Normal'\n elif row['disp_slip_'] == 'thrust':\n slip_type = 'Reverse'\n\n return slip_type\n","sub_path":"scripts/utils/usgs_hazfaults.py","file_name":"usgs_hazfaults.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"101091973","text":"# -*- codeing = utf-8 -*-\n# @Time : 2020/7/5 21:47\n# @Author : loadding...\n# @File : query_ticket.py\n# @Software : PyCharm\n\nfrom lxml import etree\nimport re\nimport requests\nimport prettytable as pt\nfrom selenium import webdriver\nimport json\nfrom time import sleep\n\n# 根据车站名字获取code\ndef get_station_code(station_name):\n url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9151'\n response = requests.get(url)\n try:\n station_code = re.findall(r'' + station_name + '\\|([A-Z]+)', response.text)[0]\n except:\n print('输入车站不存在')\n exit()\n return station_code\n\n\ndef get_station_list(station_info):\n # 构造获取停靠车站信息的url\n url = 'https://kyfw.12306.cn/otn/czxx/queryByTrainNo?train_no=' + station_info[0] + '&from_station_telecode=' + \\\n station_info[1] + '&to_station_telecode=' + station_info[2] + '&depart_date=' + station_info[3][:4] + '-' + \\\n station_info[3][4:6] + '-' + station_info[3][6:8]\n response = requests.get(url)\n html = json.loads(response.text)\n station_list = []\n for i in html['data']['data']:\n station_list.append(i['station_name'])\n return station_list\n\n\n# 标准查询\ndef get_standard_query(src_station_name, dst_station_name, date):\n src_station_code = get_station_code(src_station_name)\n dst_station_code = get_station_code(dst_station_name)\n url = 'https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc&fs=' + src_station_name + ',' + src_station_code + '&ts=' + dst_station_name + ',' + dst_station_code + '&date=' + date + '&flag=N,N,Y'\n # 创建一个浏览器对象\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument('--headless')\n driver = webdriver.Chrome(options=chrome_options)\n driver.get(url)\n\n # 获取网页源码,动态js执行后的结果与审查元素一样\n page_text = driver.page_source\n tree = etree.HTML(page_text)\n\n # 车次数量,因为一个车次信息包括2个tr(另一个是价格信息)\n number = int(len(tree.xpath('//*[@id=\"queryLeftTable\"]/tr')) / 2)\n for i in range(number):\n # 通过js点击事件生成票价代码,要经过一定时间渲染不然是拿不到更新后的源码的\n driver.find_element_by_xpath('//*[@id=\"queryLeftTable\"]/tr[' + str(2 * i + 1) + ']/td[12]').click()\n sleep(10)#等待10秒\n # 获取网页源码,此时源码包括票价信息\n page_text = driver.page_source\n tree = etree.HTML(page_text)\n tb = pt.PrettyTable()\n tb.field_names = ['车次', '出发站/到达站', '出发时间/到达时间', '历时', '硬卧/二等卧', '软座', '硬座', '无座']\n for i in range(number):\n tbody = []\n tbody.append(tree.xpath('//*[@id=\"queryLeftTable\"]/tr[' + str(2 * i + 1) + ']/td[1]/div/div[1]/div/a')[0].text)\n tbody.append(tree.xpath('//*[@id=\"queryLeftTable\"]/tr[' + str(2 * i + 1) + ']/td[1]/div/div[2]/strong[1]')[\n 0].text + '/' +\n tree.xpath('//*[@id=\"queryLeftTable\"]/tr[' + str(2 * i + 1) + ']/td[1]/div/div[2]/strong[2]')[\n 0].text)\n tbody.append(tree.xpath('//*[@id=\"queryLeftTable\"]/tr[' + str(2 * i + 1) + ']/td[1]/div/div[3]/strong[1]')[\n 0].text + '/' +\n tree.xpath('//*[@id=\"queryLeftTable\"]/tr[' + str(2 * i + 1) + ']/td[1]/div/div[3]/strong[2]')[\n 0].text)\n tbody.append(\n tree.xpath('//*[@id=\"queryLeftTable\"]/tr[' + str(2 * i + 1) + ']/td[1]/div/div[4]/strong')[0].text + '/' +\n tree.xpath('//*[@id=\"queryLeftTable\"]/tr[' + str(2 * i + 1) + ']/td[1]/div/div[4]/span')[0].text)\n #余票数量及票价\n\n price1=tree.xpath('//*[@id=\"queryLeftTable\"]/tr[' + str(2 * i + 2) + ']/td[8]')[0].text\n price2 = tree.xpath('//*[@id=\"queryLeftTable\"]/tr[' + str(2 * i + 2) + ']/td[9]')[0].text\n price3 = tree.xpath('//*[@id=\"queryLeftTable\"]/tr[' + str(2 * i + 2) + ']/td[10]')[0].text\n price4 = tree.xpath('//*[@id=\"queryLeftTable\"]/tr[' + str(2 * i + 2) + ']/td[11]')[0].text\n #处理票价为None的的情况,票价后面有换行需要先去掉\n price1='' if (price1==None) else '/'+price1.strip()\n price2='' if (price2==None) else '/'+price2.strip()\n price3='' if (price3==None) else '/'+price3.strip()\n price4='' if (price4==None) else '/'+price4.strip()\n tbody.append(tree.xpath('//*[@id=\"queryLeftTable\"]/tr[' + str(2 * i + 1) + ']/td[8]')[0].text+price1)\n tbody.append(tree.xpath('//*[@id=\"queryLeftTable\"]/tr[' + str(2 * i + 1) + ']/td[9]')[0].text+price2)\n tbody.append(tree.xpath('//*[@id=\"queryLeftTable\"]/tr[' + str(2 * i + 1) + ']/td[10]')[0].text+price3)\n tbody.append(tree.xpath('//*[@id=\"queryLeftTable\"]/tr[' + str(2 * i + 1) + ']/td[11]')[0].text+price4)\n # tbody.append(tree.xpath('//*[@id=\"queryLeftTable\"]/tr[' + str(2 * i + 1) + ']/td[13]')[0].text)\n tb.add_row(tbody)\n print('------------------------------------------------- Tickets Info ------------------------------------------')\n print(tb)\n\n\n# 根据出发站、到达站、出发日期、车次返回一个包含余票信息的列表\ndef get_single_query(src_station_name, dst_station_name, date, train_num):\n src_station_code = get_station_code(src_station_name)\n dst_station_code = get_station_code(dst_station_name)\n url = 'https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc&fs=' + src_station_name + ',' + src_station_code + '&ts=' + dst_station_name + ',' + dst_station_code + '&date=' + date + '&flag=N,N,Y'\n # 使用无界面模式,不打开浏览器\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument('--headless')\n driver = webdriver.Chrome(options=chrome_options)\n driver.get(url)\n page_text = driver.page_source\n s = \"ticket_.{5,6}\" + train_num + \".{2}\"\n pattern = re.compile(s)\n # 根据tr的id属性来获取指定车次余票信息\n ticket_id = pattern.findall(page_text)[0]\n price_id=ticket_id.replace('ticket','price')\n driver.find_element_by_xpath('//*[@id=\"' + ticket_id + '\"]/td[12]').click()\n sleep(10) # 等待10秒\n #得到包含票价的源码\n page_text = driver.page_source\n tree = etree.HTML(page_text)\n tbody = []\n tbody.append(tree.xpath('//*[@id=\"' + ticket_id + '\"]/td[1]/div/div[1]/div/a')[0].text)\n tbody.append(tree.xpath('//*[@id=\"' + ticket_id + '\"]/td[1]/div/div[2]/strong[1]')[\n 0].text + '/' +\n tree.xpath('//*[@id=\"' + ticket_id + '\"]/td[1]/div/div[2]/strong[2]')[\n 0].text)\n tbody.append(tree.xpath('//*[@id=\"' + ticket_id + '\"]/td[1]/div/div[3]/strong[1]')[\n 0].text + '/' +\n tree.xpath('//*[@id=\"' + ticket_id + '\"]/td[1]/div/div[3]/strong[2]')[\n 0].text)\n tbody.append(\n tree.xpath('//*[@id=\"' + ticket_id + '\"]/td[1]/div/div[4]/strong')[0].text + '/' +\n tree.xpath('//*[@id=\"' + ticket_id + '\"]/td[1]/div/div[4]/span')[0].text)\n\n price1 = tree.xpath('//*[@id=\"' + price_id + '\"]/td[8]')[0].text\n price2 = tree.xpath('//*[@id=\"' + price_id + '\"]/td[9]')[0].text\n price3 = tree.xpath('//*[@id=\"' + price_id + '\"]/td[10]')[0].text\n price4 = tree.xpath('//*[@id=\"' + price_id + '\"]/td[11]')[0].text\n # 处理票价为None的的情况,票价后面有换行需要先去掉\n price1 = '' if (price1 == None) else '/' + price1.strip()\n price2 = '' if (price2 == None) else '/' + price2.strip()\n price3 = '' if (price3 == None) else '/' + price3.strip()\n price4 = '' if (price4 == None) else '/' + price4.strip()\n tbody.append(tree.xpath('//*[@id=\"' + ticket_id + '\"]/td[8]')[0].text+price1)\n tbody.append(tree.xpath('//*[@id=\"' + ticket_id + '\"]/td[9]')[0].text+price2)\n tbody.append(tree.xpath('//*[@id=\"' + ticket_id + '\"]/td[10]')[0].text+price3)\n tbody.append(tree.xpath('//*[@id=\"' + ticket_id + '\"]/td[11]')[0].text+price4)\n # tbody.append(tree.xpath('//*[@id=\"' + ticket_id + '\"]/td[13]')[0].text)\n return tbody\n\n\n# 根据车次查询\ndef get_train_query(src_station_name, dst_station_name, date, train_num):\n src_station_code = get_station_code(src_station_name)\n dst_station_code = get_station_code(dst_station_name)\n url = 'https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc&fs=' + src_station_name + ',' + src_station_code + '&ts=' + dst_station_name + ',' + dst_station_code + '&date=' + date + '&flag=N,N,Y'\n # 创建一个浏览器对象\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument('--headless')\n driver = webdriver.Chrome(options=chrome_options)\n driver.get(url)\n page_text = driver.page_source\n\n tb = pt.PrettyTable()\n tb.field_names = ['车次', '出发站/到达站', '出发时间/到达时间', '历时', '硬卧/二等卧', '软座', '硬座', '无座']\n tb.align['车次']='1'\n tb.padding_width=1#填充宽度\n # 正则获取停靠站信息\n s = \"myStopStation.open\\('[0-9]?','(.{5,6}\" + train_num + \".{2})','([A-Z]*)','([A-Z]*)','([0-9]{8})'\"\n pattern = re.compile(s)\n station_info = pattern.findall(page_text)[0]\n station_list = get_station_list(station_info)\n # 指定乘车区间前后扩大三站范围,范围太大也没有买票的必要了\n # 出发站和到达站的索引\n src_index = station_list.index(src_station_name)\n dst_index = station_list.index(dst_station_name)\n src_list = [] # 考虑的出发站之前的站\n dst_list = []\n # 对出发站的位置进行判断\n if src_index > 2:\n src_list.append(station_list[src_index])\n src_list.append(station_list[src_index - 1])\n src_list.append(station_list[src_index - 2])\n src_list.append(station_list[src_index - 3])\n else:\n for j in range(src_index + 1):\n src_list.append(station_list[j])\n if dst_index < len(station_list) - 2:\n dst_list.append(station_list[dst_index])\n dst_list.append(station_list[dst_index + 1])\n dst_list.append(station_list[dst_index + 2])\n dst_list.append(station_list[dst_index + 3])\n else:\n for j in range(len(station_list) - src_index):\n src_list.append(station_list[j])\n\n for src in src_list:\n for dst in dst_list:\n result = get_single_query(src, dst, date, train_num)\n tb.add_row(result)\n print(\n '----------------------------------------------------Tickets Info -------------------------------------------')\n print(tb)\n\n\ndef main():\n src_station_name = input('出发站:')\n dst_station_name = input('到达站:')\n date = input('乘车日期(yyyy-mm-dd):')\n type = input('1、标准查询 2、车次查询\\n请选择:')\n if type == '1':\n get_standard_query(src_station_name, dst_station_name, date)\n elif type == '2':\n train_num = input('输入车次:')\n get_train_query(src_station_name, dst_station_name, date, train_num)\n else:\n print('你太笨了,这都能输错!!!')\n exit()\n \n os.system('pause')\n\nif __name__ == '__main__':\n main()\n","sub_path":"add_price_query_ticket.py","file_name":"add_price_query_ticket.py","file_ext":"py","file_size_in_byte":11266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"609714070","text":"# -*- coding: utf-8 -*-\r\nimport discord\r\nimport json\r\nimport colorama\r\nimport traceback\r\nimport time\r\n\r\nfrom discord.ext import commands\r\nfrom discord.ext.commands import errors\r\nfrom colorama import Fore, Back, Style\r\n\r\ncolorama.init()\r\n\r\ndef is_owner(ctx):\r\n return ctx.author.id in config['owners']\r\n\r\ndef user_is_owner(id: int):\r\n return id in config[\"owners\"]\r\n\r\nasync def msg_delete(ctx):\r\n try:\r\n await ctx.message.delete()\r\n except:\r\n print(Fore.YELLOW + \"Can't delete your message\")\r\n\r\nprint(Fore.LIGHTRED_EX + \"\\n\")\r\nprint(\" _____ _ \\n\"\r\n \" / ____| | \\n\"\r\n \"| (___ | | __ _ _ _ ___ _ __ \\n\"\r\n \" \\___ \\| |/ _` | | | |/ _ \\ '__|\\n\"\r\n \" ____) | | (_| | |_| | __/ | \\n\"\r\n \"|_____/|_|\\__,_|\\__, |\\___|_| \\n\"\r\n \" __/ | \\n\"\r\n \" |___/ \\n\"\r\n \"\\n\"\r\n \"Created by ICE\\n\"\r\n \"Use for educational Purpose only!\\n\")\r\n\r\ntry:\r\n with open(f\"config.json\", encoding='utf8') as data:\r\n config = json.load(data)\r\n token = config[\"token\"]\r\n prefix = config[\"prefix\"]\r\n owners = config[\"owners\"]\r\n print(Fore.CYAN + f'Loaded config.json\\nPrefix is \"{prefix}\"')\r\nexcept FileNotFoundError:\r\n print(Fore.LIGHTBLUE_EX)\r\n token = input(\"Enter token: \")\r\n prefix = input(\"Enter prefix: \")\r\n owners = input(\"Enter bot's owner ID (If several use ','): \")\r\n owners = owners.replace(\" \", \"\")\r\n if \",\" in owners:\r\n owners = owners.split(\",\")\r\n owners = list(map(int, owners))\r\n config = {\r\n \"token\": token,\r\n \"prefix\": prefix,\r\n \"owners\": owners\r\n }\r\n with open(\"config.json\", \"w\") as data:\r\n json.dump(config, data, indent=2)\r\n print(Fore.CYAN + \"Created config.json\")\r\n\r\n\r\nbot = commands.Bot(command_prefix=prefix, intents=discord.Intents.all())\r\n\r\n\r\n@bot.event\r\nasync def on_ready():\r\n print(Fore.GREEN + f\"Ready\\nLogged in as {bot.user} | {bot.user.id}\")\r\n\r\n\r\n@bot.event\r\nasync def on_command_error(ctx, err):\r\n if isinstance(err, errors.BadArgument):\r\n return\r\n print(type(err).__name__, ''.join(traceback.format_tb(err.__traceback__)), err)\r\n\r\n\r\n@bot.group(aliases=[\"all\", \"a\"])\r\nasync def allusersandroles(ctx):\r\n pass\r\n\r\n\r\n@allusersandroles.group(aliases=[\"users\", \"u\"])\r\nasync def allusers(ctx):\r\n pass\r\n\r\n\r\n@allusers.command(aliases=[\"ban\", \"bn\"])\r\nasync def allban(ctx):\r\n await msg_delete(ctx)\r\n for m in ctx.guild.members:\r\n try:\r\n if m.id not in config[\"owners\"]:\r\n await m.ban()\r\n print(Fore.GREEN + f\"Banned {m.name}\")\r\n print(Fore.YELLOW + f\"{m.name} is owner\")\r\n except Exception as e:\r\n print(Fore.YELLOW + f\"Can't ban {m.name} ({e})\")\r\n\r\n\r\n@allusers.command(aliases=[\"kick\", \"kk\"])\r\nasync def allkick(ctx):\r\n await msg_delete(ctx)\r\n for m in ctx.guild.members:\r\n try:\r\n if m.id not in config[\"owners\"]:\r\n await m.kick()\r\n print(Fore.GREEN + f\"Kicked {m.name}\")\r\n print(Fore.YELLOW + f\"{m.name} is owner\")\r\n except Exception as e:\r\n print(Fore.YELLOW + f\"Can't kick {m.name} ({e})\")\r\n\r\n\r\n@allusers.command(aliases=[\"addrole\", \"ar\"])\r\nasync def alladdrole(ctx, roleId: int=None):\r\n await msg_delete(ctx)\r\n if roleId:\r\n for m in ctx.guild.members:\r\n try:\r\n await m.add_roles(ctx.guild.get_role(roleId))\r\n print(Fore.GREEN + f\"Added role to {m.name}\")\r\n except Exception as e:\r\n print(Fore.YELLOW + f\"Can't add role to {m.name} ({e})\")\r\n\r\n\r\n@allusers.command(aliases=[\"remrole\", \"rr\"])\r\nasync def allremrole(ctx, roleId: int=None):\r\n await msg_delete(ctx)\r\n if roleId:\r\n for m in ctx.guild.members:\r\n try:\r\n await m.remove_roles(ctx.guild.get_role(roleId))\r\n print(Fore.GREEN + f\"Removed role from {m.name}\")\r\n except Exception as e:\r\n print(Fore.YELLOW + f\"Can't remove role from {m.name} ({e})\")\r\n\r\n\r\n@allusers.command(aliases=[\"nickname\", \"nn\"])\r\nasync def allnickname(ctx, *, name: str=None):\r\n await msg_delete(ctx)\r\n if not name:\r\n name = bot.user.name\r\n for m in ctx.guild.members:\r\n try:\r\n await m.edit(nick=name)\r\n print(Fore.GREEN + f\"Changed {m.name}'s nickname\")\r\n except Exception as e:\r\n print(Fore.YELLOW + f\"Can't change {m.name}'s nickname ({e})\")\r\n\r\n\r\n@allusers.command(aliases=[\"pm\"])\r\nasync def allpm(ctx, *, message: str=None):\r\n await msg_delete(ctx)\r\n if message:\r\n for m in ctx.guild.members:\r\n try:\r\n await m.send(message)\r\n print(Fore.GREEN + f\"Sent message to {m.name}\")\r\n except Exception as e:\r\n print(Fore.YELLOW + f\"Can't send message to {m.name} ({e})\")\r\n\r\n\r\n@allusers.command(aliases=[\"mute\", \"mt\"])\r\nasync def allmute(ctx, mute: bool = None):\r\n await msg_delete(ctx)\r\n if mute is not None:\r\n for m in ctx.guild.members:\r\n try:\r\n if m.voice:\r\n await m.edit(mute=mute)\r\n print(Fore.GREEN + f\"{m.name}'s mute set to {mute}\")\r\n else:\r\n print(Fore.YELLOW + f\"{m.name} not in voice channel\")\r\n except Exception as e:\r\n print(Fore.YELLOW + f\"Can't set {m.name}'s mute to {mute} ({e})\")\r\n\r\n\r\n@allusers.command(aliases=[\"deafen\", \"dn\"])\r\nasync def alldeafen(ctx, deafen: bool = None):\r\n await msg_delete(ctx)\r\n if deafen is not None:\r\n for m in ctx.guild.members:\r\n try:\r\n if m.voice:\r\n await m.edit(deafen=deafen)\r\n print(Fore.GREEN + f\"{m.name}'s deafen set to {deafen}\")\r\n else:\r\n print(Fore.YELLOW + f\"{m.name} not in voice channel\")\r\n except Exception as e:\r\n print(Fore.YELLOW + f\"Can't set {m.name}'s deafen to {deafen} ({e})\")\r\n\r\n\r\n@allusers.command(aliases=[\"move\", \"mv\"])\r\nasync def allmove(ctx, channel: int = None):\r\n await msg_delete(ctx)\r\n for m in ctx.guild.members:\r\n try:\r\n if m.voice:\r\n await m.edit(voice_channel=ctx.guild.get_channel(channel))\r\n print(Fore.GREEN + f\"Moved {m.name}\")\r\n else:\r\n print(Fore.YELLOW + f\"{m.name} not in voice channel\")\r\n except Exception as e:\r\n print(Fore.YELLOW + f\"Can't move {m.name} ({e})\")\r\n\r\n\r\n@allusersandroles.group(aliases=[\"channels\", \"ch\"])\r\nasync def allchannels(ctx):\r\n pass\r\n\r\n\r\n@allchannels.command(aliases=[\"delete\", \"del\"])\r\nasync def allchannelsdel(ctx):\r\n await msg_delete(ctx)\r\n for ch in ctx.guild.channels:\r\n try:\r\n await ch.delete()\r\n print(Fore.GREEN + f\"Deleted channel {ch.name}\")\r\n except Exception as e:\r\n print(Fore.YELLOW + f\"Can't delete channel {ch.name} ({e})\")\r\n\r\n\r\n@bot.group(aliases=[\"user\", \"u\"])\r\nasync def oneuser(ctx):\r\n pass\r\n\r\n\r\n@oneuser.command(aliases=[\"pm\"])\r\nasync def userpm(ctx, member: discord.Member=None, *, message: str=None):\r\n await msg_delete(ctx)\r\n if member and message:\r\n try:\r\n await member.send(message)\r\n print(Fore.GREEN + f\"Sent message to {member.name}\")\r\n except Exception as e:\r\n print(Fore.YELLOW + f\"Can't send message to {member.name} ({e})\")\r\n\r\n\r\n@bot.group(aliases=[\"role\", \"r\"])\r\nasync def onerole(ctx):\r\n pass\r\n\r\n\r\n@onerole.command(aliases=[\"create\", \"cr\"])\r\nasync def rolecreate(ctx, admin: bool, *, name: str = None):\r\n\r\n # TODO: Change role position\r\n\r\n await msg_delete(ctx)\r\n perms = discord.Permissions(administrator=admin)\r\n if name:\r\n try:\r\n await ctx.guild.create_role(name=name, permissions=perms)\r\n print(Fore.GREEN + f\"Created role {name}\")\r\n except Exception as e:\r\n print(Fore.GREEN + f\"Can't create role {name} ({e})\")\r\n\r\n\r\n@onerole.command(aliases=[\"delete\", \"del\"])\r\nasync def roledel(ctx, id: int = None):\r\n await msg_delete(ctx)\r\n r = ctx.guild.get_role(id)\r\n if id:\r\n try:\r\n await r.delete()\r\n print(Fore.GREEN + f\"Deleted {r.name}\")\r\n except Exception as e:\r\n print(Fore.YELLOW + f\"Can't delete {r.name} ({e})\")\r\n\r\n\r\n@onerole.command(aliases=[\"admin\", \"adm\"])\r\nasync def roleadmin(ctx, id: int = None, admin: bool = None):\r\n await msg_delete(ctx)\r\n perms = discord.Permissions(administrator=admin)\r\n r = ctx.guild.get_role(id)\r\n if id and admin is not None:\r\n try:\r\n await r.edit(permissions=perms)\r\n print(Fore.GREEN + f\"{r.name} admin is now {admin}\")\r\n except Exception as e:\r\n print(Fore.YELLOW + f\"Can't set {r.name} admin to {admin} ({e})\")\r\n\r\n\r\n@onerole.command(aliases=[\"position\", \"pos\"])\r\nasync def rolepos(ctx, id: int = None, pos: int = None):\r\n await msg_delete(ctx)\r\n r = ctx.guild.get_role(id)\r\n if id and pos:\r\n try:\r\n await r.edit(position=pos)\r\n print(Fore.GREEN + f\"Set {r.name} position to {pos}\")\r\n except Exception as e:\r\n print(Fore.YELLOW + f\"Can't set {r.name} position to {pos} ({e})\")\r\n\r\n\r\n@bot.group(aliases=[\"hard\", \"h\"])\r\nasync def hardcommands(ctx):\r\n pass\r\n\r\n\r\n@hardcommands.command(aliases=[\"nuke\", \"nk\"])\r\nasync def hardnuke(ctx, ban: bool = True, *, text: str = \"Резня\"):\r\n await msg_delete(ctx)\r\n\r\n icon = await ctx.message.attachments[0].read() if ctx.message.attachments else None\r\n await ctx.guild.edit(name=text, icon=icon, banner=icon)\r\n\r\n for ch in ctx.guild.channels:\r\n try:\r\n await ch.delete()\r\n print(Fore.GREEN + f\"Deleted channel {ch.name}\")\r\n except Exception as e:\r\n print(Fore.YELLOW + f\"Can't delete channel {ch.name} ({e})\")\r\n\r\n if ban:\r\n for m in ctx.guild.members:\r\n try:\r\n if m.id not in config[\"owners\"]:\r\n await m.ban()\r\n print(Fore.GREEN + f\"Banned {m.name}\")\r\n print(Fore.YELLOW + f\"{m.name} is owner\")\r\n except Exception as e:\r\n print(Fore.YELLOW + f\"Can't ban {m.name} ({e})\")\r\n\r\n perms = discord.Permissions(administrator=True)\r\n try:\r\n role = await ctx.guild.create_role(name=text, permissions=perms)\r\n await ctx.message.author.add_roles(role)\r\n print(Fore.GREEN + f\"Added admin role\")\r\n except Exception as e:\r\n print(Fore.GREEN + f\"Can't add admin role ({e})\")\r\n\r\n overwrites = {ctx.guild.default_role: discord.PermissionOverwrite(send_messages=True),\r\n ctx.author: discord.PermissionOverwrite(send_messages=True)}\r\n await ctx.guild.create_text_channel(name=text, overwrites=overwrites)\r\n\r\n\r\nwhile True:\r\n try:\r\n bot.run(token)\r\n except discord.errors.LoginFailure:\r\n print(Fore.RED + \"Can't login, are you sure you entered token correctly?\")\r\n input(Fore.CYAN + \"Press ENTER to exit\")\r\n raise SystemExit\r\n except Exception as e:\r\n print(Fore.RED + traceback.format_exc())\r\n print(\"\\nRetrying in 10 seconds\")\r\n time.sleep(10)\r\n","sub_path":"slayer.py","file_name":"slayer.py","file_ext":"py","file_size_in_byte":11326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"299361319","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom ckonlpy.tag import Twitter\nfrom soynlp.noun import LRNounExtractor_v2\nimport re\n\ndef get_article(url):\n r = requests.get(url, headers={'User-Agent': 'Chrome/86.0.4240.111'})\n html = r.text\n soup = BeautifulSoup(html, 'lxml')\n news_title = soup.find(attrs={'id': 'articleTitle'}).text\n news_sub_title = soup.find(attrs={'id': 'articleBodyContents'}).b.text\n news_content = soup.find(attrs={'id': 'articleBodyContents'}).text.strip().split('▶')[0].split(\"기자]\")[1].strip()\n\n return news_title, news_sub_title, news_content\n\n\ndef get_sentences(text):\n sentences = re.split(r'[\\.\\?\\!]\\s+', text)\n return sentences\n\n\nnews_title, news_sub_title, news_content = get_article(\n 'http://news.naver.com/main/read.nhn?mode=LSD&mid=sec&sid1=101&oid=277&aid=0004164498')\n\nf = open('bitcoin_news.txt', mode='w', encoding='utf-8')\nf.write('%s\\n' % news_title)\nf.write('%s\\n' % news_sub_title)\nf.write('%s' % news_content)\nf.close()\n\nf_read = open('bitcoin_news.txt', mode='r', encoding='utf-8')\ntitle, sub_title, content = f_read.read().split(\"\\n\")\n\n# 기호 제거\nfiltered_content = content.replace('.', ' ').replace(',', ' ').replace(\"'\", \"\").replace('·', ' ').replace(\n '=', ' ').replace('\"', '').replace('(', ' ').replace(')', ' ').replace('?', ' ')\n\ntwitter = Twitter()\n\n# Dictionary 추가\nsents = get_sentences(content)\nnoun_extractor = LRNounExtractor_v2(verbose=True)\nnouns = noun_extractor.train_extract(sents)\n\nfor noun in nouns:\n twitter.add_dictionary(noun, 'Noun')\n\n# 명사 추출\nNoun_words = twitter.nouns(filtered_content)\n\n# 불용어 제거\nstopwords = ['기자', '김철현'] # 기자와 관련된 내용으로 기사 내용과 무관하므로 제거\n\nunique_Noun_words = set(Noun_words)\n\nfor word in unique_Noun_words:\n if word in stopwords:\n while word in Noun_words: Noun_words.remove(word)\n\nprint(Noun_words)\n","sub_path":"pythonProject/assign07_김현진.py","file_name":"assign07_김현진.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"103296814","text":"import numpy as np\nimport cv2\n\nimage = ['xdog.jpg',\"Pamela.png\"]\nimg_orig = cv2.imread('../data/' + image[0], 0)\n\ndef dog(k):\n\tsigma = 1.22\n\tksigma = 1.6*sigma\n\ttau = 1\n\tepsilon = 0\n\tblurs = np.array(cv2.GaussianBlur(img_orig,(k,k),sigmaX=sigma,sigmaY=sigma),dtype=float)\n\tblursk = np.array(cv2.GaussianBlur(img_orig,(k,k),sigmaX=ksigma,sigmaY=ksigma),dtype=float)\n\timg = blurs-(blursk)\n\tidx1 = img[:,:] > epsilon\n\tidx2 = img[:,:] <= epsilon\n\timg[idx1] = 255\n\timg[idx2] = 0\n\timg = np.array(img,dtype=np.uint8)\n\treturn img\n\ndef getQuanitzedImage(edges):\n\timport popularity\n\timg = cv2.imread('../data/' + image[0], 1)\n\tquantizedImage = popularity.alg(img)\n\tidx = edges[:,:] == 255\n\tquantizedImage[idx] = [255,255,255]\n\treturn quantizedImage\n\ndef xdog(k):\n\tsigma = 1.22\n\tksigma = 1.6*sigma\n\ttau = 1.1\n\tphi = 1\n\tepsilon = 0\n\tblurs = np.array(cv2.GaussianBlur(img_orig,(k,k),sigmaX=sigma,sigmaY=sigma),dtype=float)\n\tblursk = np.array(cv2.GaussianBlur(img_orig,(k,k),sigmaX=ksigma,sigmaY=ksigma),dtype=float)\n\timg = blurs-(tau*blursk)\n\tdef f(x):\n\t return 0 if x epsilon\n\tidx2 = img[:,:] <= epsilon\n\timg[idx1] = 255\n\timg[idx2] = 0\n\timg = np.array(img,dtype=np.uint8)\n\treturn img\n\n\nif __name__==\"__main__\":\n\tedges = dog(7)\n\tquantizedImage = getQuanitzedImage(edges)\n\tcv2.imshow('frame',quantizedImage)\n\twhile(True):\n\t\tif cv2.waitKey(1) & 0xFF == ord('q'):\n\t\t\tbreak\n\tcv2.destroyAllWindows()","sub_path":"1/submission/code/DoG.py","file_name":"DoG.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"296746861","text":"# coding: utf-8\n\nline1 = input().rstrip().split(\" \")\nline2 = input().rstrip().split(\" \")\n\np1 = int(line1[0])\np2 = int(line1[1])\np3 = int(line2[0])\np4 = int(line2[1])\n\nline3 = input().rstrip().split(\" \")\ne1 = int(line3[0])\ne2 = int(line3[1])\ne3 = int(line3[2])\ne4 = int(line3[3])\ne = [0 , e1, e2, e3, e4]\n\nsemiWin1 = 0\nif e[p1] < e[p2]:\n semiWin1 = p1\nelse:\n semiWin1 = p2\n\nsemiWin2 = 0\nif e[p3] < e[p4]:\n semiWin2 = p3\nelse:\n semiWin2 = p4\n\nline4 = input().rstrip().split(\" \")\nf1 = int(line4[0])\nf2 = int(line4[1])\n\nfirst = 0\nsecond = 0\nif semiWin1 < semiWin2 and f1 < f2:\n first = semiWin1\n second = semiWin2\n\nif semiWin1 < semiWin2 and f2 < f1:\n first = semiWin2\n second = semiWin1\n\nif semiWin1 > semiWin2 and f1 < f2:\n first = semiWin2\n second = semiWin1\n\nif semiWin1 > semiWin2 and f2 < f1:\n first = semiWin1\n second = semiWin2\n\nprint(first)\nprint(second)\n","sub_path":"src/paiza/c/C036.py","file_name":"C036.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"382379157","text":"\"\"\" migration\n\nRevision ID: 790c7e72ce7e\nRevises: f5a149fe577e\nCreate Date: 2018-10-14 02:07:46.581758\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '790c7e72ce7e'\ndown_revision = 'f5a149fe577e'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('pitches',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('title', sa.String(length=200), nullable=True),\n sa.Column('body', sa.String(length=300), nullable=True),\n sa.Column('posted', sa.DateTime(), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.add_column('comments', sa.Column('comment', sa.String(length=240), nullable=True))\n op.create_foreign_key(None, 'comments', 'pitches', ['pitch_id'], ['id'])\n op.drop_column('comments', 'pitch_comment')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('comments', sa.Column('pitch_comment', sa.VARCHAR(), autoincrement=False, nullable=True))\n op.drop_constraint(None, 'comments', type_='foreignkey')\n op.drop_column('comments', 'comment')\n op.drop_table('pitches')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/790c7e72ce7e_migration.py","file_name":"790c7e72ce7e_migration.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"198658807","text":"from CRABClient.UserUtilities import config\nconfig = config()\n \nconfig.JobType.pluginName = 'Analysis'\nconfig.JobType.psetName = 'analysis-data.py'\nconfig.JobType.pyCfgParams = ['','mu']\n#config.JobType.inputFiles = ['../../data/Fall15_25nsV2_DATA.db']\nconfig.JobType.maxJobRuntimeMin = 180\n\nconfig.Data.inputDataset = '/SingleMuon/Run2015D-16Dec2015-v1/MINIAOD'\nconfig.Data.unitsPerJob = 150\nconfig.Data.splitting = 'LumiBased'\nconfig.Data.lumiMask = \"https://cms-service-dqm.web.cern.ch/cms-service-dqm/CAF/certification/Collisions15/13TeV/Reprocessing/Cert_13TeV_16Dec2015ReReco_Collisions15_25ns_JSON_Silver_v2.txt\"\nconfig.Data.outLFNDirBase = '/store/user/jruizvar/data/2015/EDBRtrees'\nconfig.Data.publication = False\nconfig.Data.allowNonValidInputDataset = True\n\nconfig.Site.storageSite = 'T2_BR_SPRACE'\nconfig.Site.whitelist = ['T2_US_Wisconsin','T2_FR_IPHC','T2_IT_Legnaro']\n","sub_path":"EDBRTreeMaker/promptReco/Run2015CD/crabConfig.py","file_name":"crabConfig.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"478522540","text":"from collections import namedtuple\nfrom fplmystats.utils import utils\nfrom urllib.error import HTTPError\nimport urllib.request\nimport sqlite3\nimport json\nimport math\n\nstatic_url = 'https://fantasy.premierleague.com/drf/bootstrap-static'\nmanager_info_url = 'https://fantasy.premierleague.com/drf/entry/'\n\nwith open('/home/admin/fplmystats/fplmystats/utils/current_season.txt') as file:\n# with open('C:\\\\Users\\\\seanh\\\\PycharmProjects\\\\fplmystats\\\\fplmystats\\\\utils\\\\current_season.txt') as file:\n for x in file:\n current_season = x\n\ndata_file = '/home/admin/fplmystats/FPLdb.sqlite'\n# data_file = 'FPLdb.sqlite'\n\nMINUTES_LESS_THAN_SIXTY_VALUE = 1\nMINUTES_SIXTY_PLUS_VALUE = 2\nGOAL_GK_DEF_VALUE = 6\nGOAL_MID_VALUE = 5\nGOAL_FWD_VALUE = 4\nASSIST_VALUE = 3\nCLEAN_SHEET_GK_DEF_VALUE = 4\nCLEAN_SHEET_MID_VALUE = 1\nSAVES_DIVIDER = 3\nGOALS_CONCEDED_DIVIDER = -2\nPENALTIES_SAVED_VALUE = 5\nYELLOW_CARDS_VALUE = -1\nRED_CARDS_VALUE = -3\nPENALTIES_MISSED_VALUE = -2\nOWN_GOALS_VALUE = -2\n\n\ndef get_name_and_team(manager_id):\n \"\"\"\n Return the name and team name of the manager\n \"\"\"\n names = namedtuple('names', ('manager_name', 'team_name'))\n data_url = manager_info_url + str(manager_id)\n with urllib.request.urlopen('{}'.format(data_url)) as url:\n data = json.loads(url.read().decode())\n\n names.manager_name = data['entry']['player_first_name'] + ' ' + data['entry']['player_last_name']\n names.team_name = data['entry']['name']\n return names\n\n\ndef get_stats(manager_id):\n \"\"\"\n Return the data for every table in the manager view\n \"\"\"\n table_data = namedtuple('table_data', ('headers', 'general_number', 'general_number_totals', 'general_points',\n 'general_points_totals', 'positions', 'positions_totals', 'team_selection',\n 'team_selection_totals', 'max_teams', 'squad_stats_players',\n 'squad_stats_teams'))\n\n with urllib.request.urlopen('{}'.format(static_url)) as static_json:\n static_data = json.loads(static_json.read().decode())\n current_week = 0\n for event in static_data['events']:\n if event['is_current']:\n current_week = event['id']\n\n conn = sqlite3.connect(data_file)\n c = conn.cursor()\n player_table = '{}playerIDs'.format(str(current_season))\n week = 1 # always starts at 1\n\n table_data.general_number = [] # contains the number of goals, assists etc. for each week\n table_data.general_points = [] # contains the number of points obtained via goals, assists etc. for each week\n table_data.positions = [] # contains the number of points obtained via DEFs, MIDs etc. for each week\n table_data.team_selection = [] # contains the captain, MVP, bench information etc.\n table_data.max_teams = [] # contains the best team lineup for each week\n\n formation_dict = {'5-4-1': 0, # used for counting occurrences of each formation\n '5-3-2': 0,\n '5-2-3': 0,\n '4-5-1': 0,\n '4-4-2': 0,\n '4-3-3': 0,\n '3-5-2': 0,\n '3-4-3': 0}\n\n player_apps_xi_dict = {} # records the number of times a player has appeared in the starting XI\n player_apps_xv_dict = {} # records the number of times a player has appeared in the squad\n player_captain_dict = {} # records the number of times a player has been captained\n player_points_dict = {} # records the number of points obtained via each player\n teams_dict = {} # records the number of times a player from each team has appeared in the XI\n price_dict = {} # holds prices of each player\n\n # populate teams dictionary with all 20 teams\n c.execute('SELECT name from \"{}teamIDs\"'.format(str(current_season)))\n teams = c.fetchall()\n for team in teams:\n teams_dict[team[0]] = 0\n\n active_weeks = 0\n total_points = 0\n highest_points = 0\n highest_rank = 0\n\n while week <= current_week:\n week_string = str(week)\n weekly_table = '{}week{}'.format(current_season, week_string)\n picks_url = 'https://fantasy.premierleague.com/drf/entry/{}/event/{}/picks'.format(manager_id, week_string)\n\n pitch_ids = [] # holds ids of players who are on pitch\n bench_ids = [] # holds ids of players who are on bench\n points_list = [] # holds a list of each players points and position\n second_points_list = [] # holds players who didn't play\n points_on_pitch = 0\n bench_points = 0\n captain_id = 0\n captain_name = ''\n captain_points = 0\n captain_played = False\n vice_captain_id = 0\n vice_captain_name = ''\n vice_captain_points = 0\n vice_captain_played = False\n mvp_name = 0\n mvp_points = 0\n\n # add empty lists to each section to be filled with the week's data\n table_data.general_number.append([0] * 15)\n table_data.general_points.append([0] * 15)\n table_data.positions.append([0] * 13)\n table_data.team_selection.append([0] * 14)\n formation = [0, 0, 0]\n\n # add links for each week\n link_address = 'https://fantasy.premierleague.com/a/team/{}/event/{}'.format(manager_id, week)\n table_data.general_number[week - 1][0] = link_address\n table_data.general_points[week - 1][0] = link_address\n table_data.positions[week - 1][0] = link_address\n table_data.team_selection[week - 1][0] = link_address\n\n # set first element of each section to the current working week\n table_data.general_number[week - 1][1] = week\n table_data.general_points[week - 1][1] = week\n table_data.positions[week - 1][1] = week\n table_data.team_selection[week - 1][1] = week\n\n try:\n with urllib.request.urlopen('{}'.format(picks_url)) as url:\n data = json.loads(url.read().decode())\n\n active_weeks += 1\n captain_multiplier = 2\n bench_boost = False\n chip = data['active_chip']\n if chip == '3xc':\n table_data.team_selection[week - 1][2] = 'Triple Captain'\n captain_multiplier = 3\n elif chip == 'bboost':\n table_data.team_selection[week - 1][2] = 'Bench Boost'\n bench_boost = True\n elif chip == 'freehit':\n table_data.team_selection[week - 1][2] = 'Free Hit'\n elif chip == 'wildcard':\n table_data.team_selection[week - 1][2] = 'Wildcard'\n else:\n table_data.team_selection[week - 1][2] = '-'\n table_data.team_selection[week - 1][3] = data['entry_history']['event_transfers_cost']\n\n week_points = data['entry_history']['points']\n if week_points > highest_points:\n highest_points = week_points\n week_rank = data['entry_history']['rank']\n if week_rank is not None:\n if active_weeks == 1:\n highest_rank = week_rank\n else:\n if week_rank < highest_rank:\n highest_rank = week_rank\n total_points += week_points\n\n total_value = data['entry_history']['value'] / 10.0\n\n for pick in data['picks']:\n if bench_boost:\n pitch_ids.append([pick['element'], pick['multiplier']])\n if pick['is_captain']:\n captain_id = pick['element']\n if pick['is_vice_captain']:\n vice_captain_id = pick['element']\n else:\n if pick['position'] <= 11:\n pitch_ids.append([pick['element'], pick['multiplier']])\n else:\n bench_ids.append(pick['element'])\n if pick['is_captain']:\n captain_id = pick['element']\n if pick['is_vice_captain']:\n vice_captain_id = pick['element']\n\n for player_id in pitch_ids:\n player_id_string = str(player_id[0])\n\n c.execute('SELECT webname, firstname, secondname, position, teamID FROM \"{}\" WHERE id = {}'\n .format(player_table, player_id_string))\n result = c.fetchone()\n\n # set name equal to first name + second name or webname if webname different to second name\n if result[0] == result[2]:\n player_name = result[1] + ' ' + result[2]\n else:\n player_name = result[0]\n position = result[3]\n team_id = result[4]\n\n if player_name not in player_points_dict:\n player_points_dict[player_name] = 0\n player_apps_xv_dict[player_name] = 0\n if player_name not in player_apps_xi_dict:\n player_apps_xi_dict[player_name] = 0\n\n player_apps_xi_dict[player_name] += 1\n player_apps_xv_dict[player_name] += 1\n\n c.execute('SELECT name from \"{}teamIDs\" WHERE id = {}'.format(current_season, team_id))\n team_name = c.fetchone()[0]\n teams_dict[team_name] += 1\n\n c.execute('SELECT * FROM \"{}\" WHERE id = {}'.format(weekly_table, player_id_string))\n player_datum = c.fetchone()\n if player_datum is not None:\n price = player_datum[14] / 1.0\n if player_name not in price_dict:\n price_dict[player_name] = [price, 1]\n else:\n price_dict[player_name][0] += price\n price_dict[player_name][1] += 1\n\n if player_datum[2] > 0: # if minutes > 0\n points_list.append([player_datum[1], position, player_name]) # points, position, player_name\n else:\n second_points_list.append([player_datum[1], position, player_name])\n points_on_pitch += player_datum[1]\n\n if player_datum[0] == captain_id:\n captain_name = player_name\n captain_points = player_datum[1]\n if player_datum[2] > 0:\n captain_played = True\n elif player_datum[0] == vice_captain_id:\n vice_captain_name = player_name\n vice_captain_points = player_datum[1]\n if player_datum[2] > 0:\n vice_captain_played = True\n\n # subtract clean sheets from MID's and FWD's for general_number and ignore goals conceded\n if position == 3 or position == 4:\n table_data.general_number[week - 1][6] -= player_datum[5]\n table_data.general_number[week - 1][8] -= player_datum[7]\n\n # Populate general number table\n table_data.general_number[week - 1][2:15] = [sum(n) for n in zip(\n table_data.general_number[week - 1][2:15], player_datum[1:14])]\n\n # Populate general points table\n table_data.general_points[week - 1][2] += player_datum[1] # points\n if player_datum[2] == 0: # minutes\n table_data.general_points[week - 1][3] += 0\n elif player_datum[2] < 60:\n table_data.general_points[week - 1][3] += MINUTES_LESS_THAN_SIXTY_VALUE\n else:\n table_data.general_points[week - 1][3] += MINUTES_SIXTY_PLUS_VALUE\n\n if position == 1 or position == 2: # goals\n table_data.general_points[week - 1][4] += player_datum[3] * GOAL_GK_DEF_VALUE\n elif position == 3:\n table_data.general_points[week - 1][4] += player_datum[3] * GOAL_MID_VALUE\n else:\n table_data.general_points[week - 1][4] += player_datum[3] * GOAL_FWD_VALUE\n\n table_data.general_points[week - 1][5] += player_datum[4] * ASSIST_VALUE # assists\n\n if position == 1 or position == 2: # clean sheets\n table_data.general_points[week - 1][6] += player_datum[5] * CLEAN_SHEET_GK_DEF_VALUE\n elif position == 3:\n table_data.general_points[week - 1][6] += player_datum[5] * CLEAN_SHEET_MID_VALUE\n\n table_data.general_points[week - 1][7] += math.floor(player_datum[6] / SAVES_DIVIDER) # saves\n\n if position == 1 or position == 2: # goals conc\n table_data.general_points[week - 1][8] += math.ceil(player_datum[7] / GOALS_CONCEDED_DIVIDER)\n\n table_data.general_points[week - 1][9] += player_datum[8] * PENALTIES_SAVED_VALUE # penes saved\n table_data.general_points[week - 1][10] += player_datum[9] * YELLOW_CARDS_VALUE # yellows\n table_data.general_points[week - 1][11] += player_datum[10] * RED_CARDS_VALUE # reds\n table_data.general_points[week - 1][12] += player_datum[11] * PENALTIES_MISSED_VALUE # pens missed\n table_data.general_points[week - 1][13] += player_datum[12] * OWN_GOALS_VALUE # own goals\n table_data.general_points[week - 1][14] += player_datum[13] # bonus points\n\n player_points_dict[player_name] += player_datum[1] * player_id[1]\n\n if player_datum[1] > mvp_points:\n mvp_points = player_datum[1]\n mvp_name = player_name\n\n if position == 1:\n table_data.positions[week - 1][4] += price\n table_data.positions[week - 1][5] += player_datum[1]\n elif position == 2:\n table_data.positions[week - 1][6] += price\n table_data.positions[week - 1][7] += player_datum[1]\n formation[0] += 1\n elif position == 3:\n table_data.positions[week - 1][8] += price\n table_data.positions[week - 1][9] += player_datum[1]\n formation[1] += 1\n elif position == 4:\n table_data.positions[week - 1][10] += price\n table_data.positions[week - 1][11] += player_datum[1]\n formation[2] += 1\n else:\n utils.update_weekly_table()\n get_stats(manager_id)\n\n table_data.positions[week - 1][4] = round(table_data.positions[week - 1][4], 1)\n table_data.positions[week - 1][6] = round(table_data.positions[week - 1][6], 1)\n table_data.positions[week - 1][8] = round(table_data.positions[week - 1][8], 1)\n table_data.positions[week - 1][10] = round(table_data.positions[week - 1][10], 1)\n\n for player_id in bench_ids:\n player_id_string = str(player_id)\n\n c.execute('SELECT webname, firstname, secondname, position FROM \"{}\" WHERE id = {}'\n .format(player_table, player_id_string))\n result = c.fetchone()\n\n # set name equal to first second + second name or webname if webname different to second name\n if result[0] == result[2]:\n player_name = result[1] + ' ' + result[2]\n else:\n player_name = result[0]\n position = result[3]\n\n if player_name not in player_points_dict:\n player_points_dict[player_name] = 0\n player_apps_xv_dict[player_name] = 0\n\n player_apps_xv_dict[player_name] += 1\n\n c.execute('SELECT * FROM \"{}\" WHERE id = {}'.format(weekly_table, player_id_string))\n player_datum = c.fetchone()\n\n if player_datum is not None:\n price = player_datum[14] / 1.0\n if player_name not in price_dict:\n price_dict[player_name] = [price, 1]\n else:\n price_dict[player_name][0] += price\n price_dict[player_name][1] += 1\n table_data.positions[week - 1][12] += price\n\n if player_datum[0] == captain_id:\n captain_name = player_name\n captain_points = player_datum[1]\n if player_datum[2] > 0:\n captain_played = True\n elif player_datum[0] == vice_captain_id:\n vice_captain_name = player_name\n vice_captain_points = player_datum[1]\n if player_datum[2] > 0:\n vice_captain_played = True\n\n if player_datum[1] > mvp_points:\n mvp_points = player_datum[1]\n mvp_name = player_name\n\n if player_datum[2] > 0:\n points_list.append([player_datum[1], position, player_name]) # points, position, player_name\n bench_points += player_datum[1]\n\n table_data.positions[week - 1][12] = round(table_data.positions[week - 1][12], 1)\n\n string_formation = '4-4-2' # default formation if db not updated\n if formation == [5, 4, 1]:\n string_formation = '5-4-1'\n elif formation == [5, 3, 2]:\n string_formation = '5-3-2'\n elif formation == [5, 2, 3]:\n string_formation = '5-2-3'\n elif formation == [4, 5, 1]:\n string_formation = '4-5-1'\n elif formation == [4, 4, 2]:\n string_formation = '4-4-2'\n elif formation == [4, 3, 3]:\n string_formation = '4-3-3'\n elif formation == [3, 5, 2]:\n string_formation = '3-5-2'\n elif formation == [3, 4, 3]:\n string_formation = '3-4-3'\n\n formation_dict[string_formation] += 1\n table_data.positions[week - 1][2] = string_formation\n\n team_value = round(total_value, 1)\n table_data.positions[week - 1][3] = team_value\n\n max_points_on_pitch = 0\n points_list.sort()\n points_list = points_list[::-1]\n max_points_team = []\n\n if not bench_boost:\n try:\n max_points_on_pitch += next(item[0] for item in points_list if item[1] == 1) # 1 goalkeeper\n max_points_team.append(next(item for item in points_list if item[1] == 1))\n points_list.remove(next(item for item in points_list if item[1] == 1))\n points_list.remove(next(item for item in points_list if item[1] == 1))\n except StopIteration:\n ''\n if len(max_points_team) < 1:\n try:\n max_points_team.append(next(item for item in second_points_list if item[1] == 1))\n second_points_list.remove(next(item for item in second_points_list if item[1] == 1))\n except StopIteration:\n ''\n\n for i in range(3): # 3 defenders\n try:\n max_points_on_pitch += next(item[0] for item in points_list if item[1] == 2)\n max_points_team.append(next(item for item in points_list if item[1] == 2))\n points_list.remove(next(item for item in points_list if item[1] == 2))\n except StopIteration:\n ''\n while len(max_points_team) < 4:\n try:\n max_points_team.append(next(item for item in second_points_list if item[1] == 2))\n second_points_list.remove(next(item for item in second_points_list if item[1] == 2))\n except StopIteration:\n ''\n\n for i in range(2): # 2 midfielders\n try:\n max_points_on_pitch += next(item[0] for item in points_list if item[1] == 3)\n max_points_team.append(next(item for item in points_list if item[1] == 3))\n points_list.remove(next(item for item in points_list if item[1] == 3))\n except StopIteration:\n ''\n while len(max_points_team) < 6:\n try:\n max_points_team.append(next(item for item in second_points_list if item[1] == 3))\n second_points_list.remove(next(item for item in second_points_list if item[1] == 3))\n except StopIteration:\n ''\n\n try:\n max_points_on_pitch += next(item[0] for item in points_list if item[1] == 4) # 1 forward\n max_points_team.append(next(item for item in points_list if item[1] == 4))\n points_list.remove(next(item for item in points_list if item[1] == 4))\n except StopIteration:\n ''\n while len(max_points_team) < 7:\n try:\n max_points_team.append(next(item for item in second_points_list if item[1] == 4))\n second_points_list.remove(next(item for item in second_points_list if item[1] == 4))\n except StopIteration:\n ''\n\n for i in range(4): # 4 remaining players\n try:\n max_points_on_pitch += next(item[0] for item in points_list)\n max_points_team.append(next(item for item in points_list))\n points_list.remove(next(item for item in points_list))\n except StopIteration:\n ''\n while len(max_points_team) < 11:\n try:\n max_points_team.append(next(item for item in second_points_list))\n second_points_list.remove(next(item for item in second_points_list))\n except StopIteration:\n ''\n\n bench_potential_lost = max_points_on_pitch - points_on_pitch\n else:\n while len(points_list) > 0:\n try:\n max_points_team.append(next(item for item in points_list))\n points_list.remove(next(item for item in points_list))\n except StopIteration:\n ''\n while len(second_points_list) > 0:\n try:\n max_points_team.append(next(item for item in second_points_list))\n second_points_list.remove(next(item for item in second_points_list))\n except StopIteration:\n ''\n bench_potential_lost = 0\n\n if bench_potential_lost < 0:\n bench_potential_lost = 0\n\n # assign the captain in max team and then sort by position\n if max_points_team:\n max_points_team.sort()\n max_points_team[-1][2] = max_points_team[-1][2] + ' (C)'\n max_points_team[-1][0] = max_points_team[-1][0] * captain_multiplier\n max_points_team = sorted(max_points_team, key=lambda l: l[1])\n for player in max_points_team:\n if player[1] == 1:\n player[1] = 'GK'\n elif player[1] == 2:\n player[1] = 'DEF'\n elif player[1] == 3:\n player[1] = 'MID'\n else:\n player[1] = 'FWD'\n\n if captain_played or not vice_captain_played:\n table_data.team_selection[week - 1][4] = captain_name\n table_data.team_selection[week - 1][5] = captain_points * captain_multiplier\n if captain_name not in player_captain_dict:\n player_captain_dict[captain_name] = 0\n player_captain_dict[captain_name] += 1\n else:\n table_data.team_selection[week - 1][4] = vice_captain_name\n table_data.team_selection[week - 1][5] = vice_captain_points * captain_multiplier\n captain_points = vice_captain_points\n if vice_captain_name not in player_captain_dict:\n player_captain_dict[vice_captain_name] = 0\n player_captain_dict[vice_captain_name] += 1\n\n table_data.team_selection[week - 1][6] = mvp_name\n table_data.team_selection[week - 1][7] = mvp_points\n table_data.team_selection[week - 1][8] = (mvp_points - captain_points) * (captain_multiplier - 1)\n table_data.team_selection[week - 1][9] = bench_points\n table_data.team_selection[week - 1][10] = bench_potential_lost\n table_data.team_selection[week - 1][11] = int(table_data.general_points[week - 1][2] +\n ((captain_points * captain_multiplier) - captain_points)\n - table_data.team_selection[week - 1][3])\n table_data.team_selection[week - 1][13] = table_data.team_selection[week - 1][8] +\\\n table_data.team_selection[week - 1][10]\n table_data.team_selection[week - 1][12] = table_data.team_selection[week - 1][11] +\\\n table_data.team_selection[week - 1][13]\n\n max_points_team = [table_data.team_selection[week - 1][12]] + max_points_team # total points\n max_points_team = [table_data.team_selection[week - 1][3] * -1] + max_points_team # transfer cost\n max_points_team = [table_data.team_selection[week - 1][12] # total points - tc\n + table_data.team_selection[week - 1][3]] + max_points_team\n max_points_team = [week] + max_points_team\n\n table_data.max_teams.append(max_points_team)\n\n week += 1\n except HTTPError:\n week += 1\n\n table_data.general_number_totals = [n for n in zip(*table_data.general_number)][2:16]\n table_data.general_number_totals = [sum(n) for n in table_data.general_number_totals]\n table_data.general_points_totals = [n for n in zip(*table_data.general_points)][2:16]\n table_data.general_points_totals = [sum(n) for n in table_data.general_points_totals]\n\n table_data.positions_totals = [0] * 10\n table_data.positions_totals[0] = round(sum(entry[3] for entry in table_data.positions) / active_weeks, 1)\n table_data.positions_totals[1] = round(sum(entry[4] for entry in table_data.positions) / active_weeks, 1)\n table_data.positions_totals[2] = sum(entry[5] for entry in table_data.positions)\n table_data.positions_totals[3] = round(sum(entry[6] for entry in table_data.positions) / active_weeks, 1)\n table_data.positions_totals[4] = sum(entry[7] for entry in table_data.positions)\n table_data.positions_totals[5] = round(sum(entry[12] for entry in table_data.positions) / active_weeks, 1)\n table_data.positions_totals[6] = round(sum(entry[8] for entry in table_data.positions) / active_weeks, 1)\n table_data.positions_totals[7] = sum(entry[9] for entry in table_data.positions)\n table_data.positions_totals[8] = round(sum(entry[10] for entry in table_data.positions) / active_weeks, 1)\n table_data.positions_totals[9] = sum(entry[11] for entry in table_data.positions)\n\n table_data.team_selection_totals = [0]*8\n table_data.team_selection_totals[0] = sum(entry[3] for entry in table_data.team_selection) # transfer cost\n table_data.team_selection_totals[1] = sum(entry[5] for entry in table_data.team_selection) # captain points\n table_data.team_selection_totals[2] = sum(entry[7] for entry in table_data.team_selection) # mvp total\n table_data.team_selection_totals[3] = sum(entry[8] for entry in table_data.team_selection) # captain lost\n table_data.team_selection_totals[4] = sum(entry[9] for entry in table_data.team_selection) # bench points\n table_data.team_selection_totals[5] = sum(entry[10] for entry in table_data.team_selection) # bench lost\n table_data.team_selection_totals[6] = sum(entry[12] for entry in table_data.team_selection) # max possible\n table_data.team_selection_totals[7] = sum(entry[13] for entry in table_data.team_selection) # all lost\n\n table_data.squad_stats_players = []\n for player in player_apps_xv_dict:\n name = player\n weeks_in_xi = 0\n weeks_in_xv = player_apps_xv_dict[player]\n weeks_captain = 0\n points = 0\n player_value = round(price_dict[player][0] / price_dict[player][1], 1)\n\n if player in player_apps_xi_dict:\n weeks_in_xi = player_apps_xi_dict[player]\n if player in player_captain_dict:\n weeks_captain = player_captain_dict[player]\n if player in player_points_dict:\n points = player_points_dict[player]\n\n # TODO fix negative points ppg & vapm\n points_per_game = 0.0\n if weeks_in_xi != 0:\n points_per_game = round(points / weeks_in_xi, 1)\n\n value_added_per_million = 0.0\n if weeks_in_xi != 0:\n value_added_per_million = round((points_per_game - 2) / player_value, 2)\n\n table_data.squad_stats_players.append([name, weeks_in_xi, weeks_in_xv, weeks_captain, points,\n points_per_game, value_added_per_million])\n\n table_data.squad_stats_teams = []\n for team in teams_dict:\n table_data.squad_stats_teams.append([team, teams_dict[team]])\n\n table_data.headers = [0] * 7\n table_data.headers[0] = sum(entry[11] for entry in table_data.team_selection)\n table_data.headers[1] = highest_points\n table_data.headers[2] = highest_rank\n table_data.headers[3] = max(player_captain_dict, key=player_captain_dict.get)\n table_data.headers[4] = max(player_points_dict, key=player_points_dict.get)\n table_data.headers[5] = player_points_dict[table_data.headers[4]]\n table_data.headers[6] = max(formation_dict, key=formation_dict.get)\n\n return table_data\n","sub_path":"fplmystats/utils/manager_utils.py","file_name":"manager_utils.py","file_ext":"py","file_size_in_byte":31475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"483514108","text":"# Runtime: 76ms\n\nclass Solution(object):\n\tdef flipAndInvertImage(self, A):\n\t\t\"\"\"\n\t\t:type A: List[List[int]]\n\t\t:rtype: List[List[int]]\n\t\t\"\"\"\n\t\tif len(A) == 0:\n\t\t\treturn A\n\t\tres = []\n\t\tfor row in A:\n\t\t\tres.append([]) # 每行先加一个空list\n\t\t\tfor col in row[::-1]:\n\t\t\t\ttmp = 1 - col # 实现很简单\n\t\t\t\tres[-1].append(tmp)\n\t\treturn res","sub_path":"python/832 Flipping an Image.py","file_name":"832 Flipping an Image.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"49421315","text":"# coding=utf-8\n__author__ = 'apple'\nfrom __future__ import division #实现精确的除法,例如4/3=1.333333\n\n'''\n@region 创建增删\n'''\n\n'''\n@region 索引遍历\n'''\n\n'''\n@region 统计操作\n'''\n\n\ndef less_average(score):\n num = len(score)\n sum_score = sum(score)\n ave_num = sum_score / num\n less_ave = [i for i in score if i < ave_num]\n return len(less_ave)\n\n'''\n@region 类型转换\n'''","sub_path":"Tutorials/UPenn-CIT590/HW4/hw4/list_exercises.py","file_name":"list_exercises.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"175080690","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\n\nfrom collections import namedtuple\nfrom matplotlib import pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\n# import scipy.misc\nimport imageio\nfrom PIL import Image\nimport random\nimport os\n\n\n#############################\n # global variables #\n#############################\nroot_dir = \"/content/drive/My Drive/\"\n\nlabel_dir = os.path.join(root_dir, \"gtFine\")\ntrain_dir = os.path.join(label_dir, \"train\")\nval_dir = os.path.join(label_dir, \"val\")\ntest_dir = os.path.join(label_dir, \"test\")\n\n# create dir for label index\nlabel_idx_dir = os.path.join(root_dir, \"Labeled_idx\")\ntrain_idx_dir = os.path.join(label_idx_dir, \"train\")\nval_idx_dir = os.path.join(label_idx_dir, \"val\")\ntest_idx_dir = os.path.join(label_idx_dir, \"test\")\nfor dir in [train_idx_dir, val_idx_dir, test_idx_dir]:\n if not os.path.exists(dir):\n os.makedirs(dir)\n\npath_train_file = os.path.join(root_dir, \"train.csv\")\npath_val_file = os.path.join(root_dir, \"val.csv\")\npath_test_file = os.path.join(root_dir, \"test.csv\")\n\nwidth, height = 1024, 512\n\ncolor2index = {}\n\nLabel = namedtuple('Label', [\n 'name',\n 'id',\n 'trainId',\n 'category',\n 'categoryId',\n 'hasInstances',\n 'ignoreInEval',\n 'color'])\n\nlabels = [\n # name id trainId category catId hasInstances ignoreInEval color\n Label( 'unlabeled' , 0 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ),\n Label( 'ego vehicle' , 1 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ),\n Label( 'rectification border' , 2 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ),\n Label( 'out of roi' , 3 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ),\n Label( 'static' , 4 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ),\n Label( 'dynamic' , 5 , 255 , 'void' , 0 , False , True , (111, 74, 0) ),\n Label( 'ground' , 6 , 255 , 'void' , 0 , False , True , ( 81, 0, 81) ),\n Label( 'road' , 7 , 1 , 'flat' , 1 , False , False , (128, 64,128) ),\n Label( 'sidewalk' , 8 , 2 , 'flat' , 1 , False , False , (244, 35,232) ),\n Label( 'parking' , 9 , 255 , 'flat' , 1 , False , True , (250,170,160) ),\n Label( 'rail track' , 10 , 255 , 'flat' , 1 , False , True , (230,150,140) ),\n Label( 'building' , 11 , 3 , 'construction' , 2 , False , False , ( 70, 70, 70) ),\n Label( 'wall' , 12 , 4 , 'construction' , 2 , False , False , (102,102,156) ),\n Label( 'fence' , 13 , 5 , 'construction' , 2 , False , False , (190,153,153) ),\n Label( 'guard rail' , 14 , 255 , 'construction' , 2 , False , True , (180,165,180) ),\n Label( 'bridge' , 15 , 255 , 'construction' , 2 , False , True , (150,100,100) ),\n Label( 'tunnel' , 16 , 255 , 'construction' , 2 , False , True , (150,120, 90) ),\n Label( 'pole' , 17 , 6 , 'object' , 3 , False , False , (153,153,153) ),\n Label( 'polegroup' , 18 , 255 , 'object' , 3 , False , True , (153,153,153) ),\n Label( 'traffic light' , 19 , 7 , 'object' , 3 , False , False , (250,170, 30) ),\n Label( 'traffic sign' , 20 , 8 , 'object' , 3 , False , False , (220,220, 0) ),\n Label( 'vegetation' , 21 , 9 , 'nature' , 4 , False , False , (107,142, 35) ),\n Label( 'terrain' , 22 , 10 , 'nature' , 4 , False , False , (152,251,152) ),\n Label( 'sky' , 23 , 11 , 'sky' , 5 , False , False , ( 70,130,180) ),\n Label( 'person' , 24 , 12 , 'human' , 6 , True , False , (220, 20, 60) ),\n Label( 'rider' , 25 , 13 , 'human' , 6 , True , False , (255, 0, 0) ),\n Label( 'car' , 26 , 14 , 'vehicle' , 7 , True , False , ( 0, 0,142) ),\n Label( 'truck' , 27 , 15 , 'vehicle' , 7 , True , False , ( 0, 0, 70) ),\n Label( 'bus' , 28 , 16 , 'vehicle' , 7 , True , False , ( 0, 60,100) ),\n Label( 'caravan' , 29 , 255 , 'vehicle' , 7 , True , True , ( 0, 0, 90) ),\n Label( 'trailer' , 30 , 255 , 'vehicle' , 7 , True , True , ( 0, 0,110) ),\n Label( 'train' , 31 , 17 , 'vehicle' , 7 , True , False , ( 0, 80,100) ),\n Label( 'motorcycle' , 32 , 18 , 'vehicle' , 7 , True , False , ( 0, 0,230) ),\n Label( 'bicycle' , 33 , 19 , 'vehicle' , 7 , True , False , (119, 11, 32) ),\n Label( 'license plate' , -1 , -1 , 'vehicle' , 7 , False , True , ( 0, 0,142) ),\n]\n\n\ndef parse_label():\n # change label to class index\n print(\"====================\\n generating index dict\")\n color2index[(0,0,0)] = 0 # add an void class \n for obj in labels:\n if obj.ignoreInEval:\n continue\n idx = obj.trainId\n # label = obj.name\n color = obj.color\n color2index[color] = idx\n print(\"{}:{}\".format(color, idx))\n print(\"====================\\n\")\n\n # parse train, val, test data \n for label_dir, index_dir, path_csv_file in zip([train_dir, val_dir, test_dir], [train_idx_dir, val_idx_dir, test_idx_dir], [path_train_file, path_val_file, path_test_file]):\n fout_csv = open(path_csv_file, \"w\")\n fout_csv.write(\"img,label\\n\")\n for city in os.listdir(label_dir):\n city_dir = os.path.join(label_dir, city)\n city_idx_dir = os.path.join(index_dir, city)\n data_dir = city_dir.replace(\"gtFine\", \"leftImg8bit\")\n if not os.path.exists(city_idx_dir):\n os.makedirs(city_idx_dir)\n filenames = os.listdir(city_dir)\n filenames.sort()\n for filename in filenames:\n if 'color' not in filename:\n continue\n lab_name = os.path.join(city_idx_dir, filename)\n if \"gtFine_color\" in filename:\n img_name = filename.split(\"gtFine_color\")[0] + \"leftImg8bit.png\"\n else:\n img_name = filename.split(\"gtCoarse_color\")[0] + \"leftImg8bit.png\"\n\n img_name = os.path.join(data_dir, img_name)\n fout_csv.write(\"{},{}.npy\\n\".format(img_name, lab_name))\n\n if os.path.exists(lab_name + '.npy'):\n print(\"Skip %s\" % (filename))\n continue\n print(\"Parse %s\" % (filename))\n img_path = os.path.join(city_dir, filename)\n ## img = scipy.misc.imread(img, mode='RGB') ## imread is removed in SciPy 1.2.0\n ## print(\"imageName: \"+ img+ \"\\n\")\n img = imageio.imread(img_path)\n height, width, _ = img.shape\n idx_mat = np.zeros((height, width))\n numNoIdx = 0\n for h in range(height):\n for w in range(width):\n color = tuple(img[h, w])[:3] # dono why the tuple length is FOUR, last element is 255???\n try:\n index = color2index[color]\n idx_mat[h, w] = index\n except:\n # no index, assign to void\n idx_mat[h, w] = 20\n numNoIdx += 1\n idx_mat = idx_mat.astype(np.uint8)\n np.save(lab_name, idx_mat)\n print(\" Finish %s, %d with no index\" % (filename, numNoIdx))\n # print(dictIdx)\n # print(\"\\n\")\n\ndef parse_imageNlabel():\n for label_dir, index_dir, path_csv_file in zip([train_dir, val_dir, test_dir], [train_idx_dir, val_idx_dir, test_idx_dir], [path_train_file, path_val_file, path_test_file]):\n fout_csv = open(path_csv_file, \"w\")\n fout_csv.write(\"img,label\\n\")\n for city in os.listdir(label_dir):\n city_dir = os.path.join(label_dir, city)\n city_idx_dir = os.path.join(index_dir, city)\n data_dir = city_dir.replace(\"gtFine\", \"leftImg8bit\")\n if not os.path.exists(city_idx_dir):\n os.makedirs(city_idx_dir)\n filenames = os.listdir(city_dir)\n filenames.sort()\n for filename in filenames:\n if 'labelIds' not in filename:\n continue\n lab_name = os.path.join(city_idx_dir, filename)\n if \"gtFine_labelIds\" in filename:\n img_name = filename.split(\"gtFine_labelIds\")[0] + \"leftImg8bit.png\"\n else:\n img_name = filename.split(\"gtCoarse_labelIds\")[0] + \"leftImg8bit.png\"\n\n img_name = os.path.join(data_dir, img_name)\n fout_csv.write(\"{},{}.npy\\n\".format(img_name, lab_name))\n\n if os.path.exists(lab_name + '.npy'):\n print(\"Skip %s\" % (filename))\n continue\n print(\"Parse %s\" % (filename))\n\n # # lableID\n img_path = os.path.join(city_dir, filename)\n ## img = scipy.misc.imread(img, mode='RGB') ## imread is removed in SciPy 1.2.0\n ## print(\"imageName: \"+ img+ \"\\n\")\n image = Image.open(img_path)\n # size = image.size\n # width, height = int(size[0] / 2), int(size[1] / 2)\n if not image.size == (width, height):\n image = image.resize((width, height), Image.NEAREST)\n idx_mat = np.array(image).astype(np.uint8)\n np.save(lab_name, idx_mat)\n # # color image\n imgColor = Image.open(img_name)\n if not imgColor.size == (width, height):\n imgColor = imgColor.resize((width, height), Image.NEAREST)\n driver = img_name.split('.')[-1] # format to save\n imgColor.save(img_name,driver)\n print(\" Finish %s\" % (filename))\n\n'''debug function'''\ndef imshow(img, title=None):\n try:\n img = mpimg.imread(img)\n imgplot = plt.imshow(img)\n except:\n plt.imshow(img, interpolation='nearest')\n\n if title is not None:\n plt.title(title)\n \n plt.show()\n\n\nif __name__ == '__main__':\n # parse_label()\n parse_imageNlabel()","sub_path":"python/Cityscapes_utils.py","file_name":"Cityscapes_utils.py","file_ext":"py","file_size_in_byte":11799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"327081770","text":"#!/usr/bin/env python\n#coding=utf-8\n\n# full permutation\ndef permute(sequence):\n length = len(sequence)\n if length == 0: return []\n if length == 1: return [sequence]\n\n permutations = []\n for index, value in enumerate(sequence):\n _sequence = sequence[:index] + sequence[index+1:]\n _permutations = permute(_sequence)\n [permutations.append([value] + permutation) \\\n for permutation in _permutations]\n return permutations\n\n","sub_path":"permutation.py","file_name":"permutation.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"265037914","text":"#\n# @lc app=leetcode.cn id=915 lang=python3\n#\n# [915] 分割数组\n#\n# https://leetcode-cn.com/problems/partition-array-into-disjoint-intervals/description/\n#\n# algorithms\n# Medium (45.17%)\n# Likes: 54\n# Dislikes: 0\n# Total Accepted: 6.4K\n# Total Submissions: 14.3K\n# Testcase Example: '[5,0,3,8,6]'\n#\n# 给定一个数组 A,将其划分为两个不相交(没有公共元素)的连续子数组 left 和 right, 使得:\n# \n# \n# left 中的每个元素都小于或等于 right 中的每个元素。\n# left 和 right 都是非空的。\n# left 要尽可能小。\n# \n# \n# 在完成这样的分组后返回 left 的长度。可以保证存在这样的划分方法。\n# \n# \n# \n# 示例 1:\n# \n# 输入:[5,0,3,8,6]\n# 输出:3\n# 解释:left = [5,0,3],right = [8,6]\n# \n# \n# 示例 2:\n# \n# 输入:[1,1,1,0,6,12]\n# 输出:4\n# 解释:left = [1,1,1,0],right = [6,12]\n# \n# \n# \n# \n# 提示:\n# \n# \n# 2 <= A.length <= 30000\n# 0 <= A[i] <= 10^6\n# 可以保证至少有一种方法能够按题目所描述的那样对 A 进行划分。\n# \n# \n# \n# \n#\n\n# @lc code=start\nclass Solution:\n def partitionDisjoint(self, A: List[int]) -> int:\n leftMax = A[0]\n mx = A[0]\n pos = 0\n for i in range(len(A)) :\n mx = max(mx, A[i])\n if A[i] >= leftMax : continue\n pos = i\n leftMax = mx\n return pos + 1\n# @lc code=end\n\n","sub_path":"915.分割数组.py","file_name":"915.分割数组.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"413926961","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[17]:\n\n\nimport os\nimport joblib\nimport numpy as np\nimport pandas as pd\nimport librosa\nimport matplotlib.pyplot as plt\n# import tensorflow as tf\nimport torch\nfrom torch import nn\nimport IPython\nfrom IPython.display import Audio\nfrom IPython.display import Image\n# from tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, Activation\n# from tensorflow.keras.models import Sequential\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom config import CHECKPOINTS_DIR_PATH\n\n\n# In[3]:\n\n\n##### LOAD #########\n# choose load file name \nfilename = 'features_labels.npy'\n\n# open file in read mode and read data \nwith open(filename, 'rb') as f:\n X_train = np.load(f)\n X_valid = np.load(f)\n X_test = np.load(f)\n y_train = np.load(f)\n y_valid = np.load(f)\n y_test = np.load(f)\n\n# Check that we've recovered the right data\nprint(f'X_train:{X_train.shape}, y_train:{y_train.shape}')\nprint(f'X_valid:{X_valid.shape}, y_valid:{y_valid.shape}')\nprint(f'X_test:{X_test.shape}, y_test:{y_test.shape}')\n\n\n# In[4]:\n\n\n#change nn.sequential to take dict to make more readable \n\nclass parallel_all_you_want(nn.Module):\n # Define all layers present in the network\n def __init__(self,num_emotions):\n super().__init__() \n \n ################ TRANSFORMER BLOCK #############################\n # maxpool the input feature map/tensor to the transformer \n # a rectangular kernel worked better here for the rectangular input spectrogram feature map/tensor\n self.transformer_maxpool = nn.MaxPool2d(kernel_size=[1,4], stride=[1,4])\n \n # define single transformer encoder layer\n # self-attention + feedforward network from \"Attention is All You Need\" paper\n # 4 multi-head self-attention layers each with 40-->512--->40 feedforward network\n transformer_layer = nn.TransformerEncoderLayer(\n d_model=40, # input feature (frequency) dim after maxpooling 40*282 -> 40*70 (MFC*time)\n nhead=4, # 4 self-attention layers in each multi-head self-attention layer in each encoder block\n dim_feedforward=512, # 2 linear layers in each encoder block's feedforward network: dim 40-->512--->40\n dropout=0.4, \n activation='relu' # ReLU: avoid saturation/tame gradient/reduce compute time\n )\n \n # I'm using 4 instead of the 6 identical stacked encoder layrs used in Attention is All You Need paper\n # Complete transformer block contains 4 full transformer encoder layers (each w/ multihead self-attention+feedforward)\n self.transformer_encoder = nn.TransformerEncoder(transformer_layer, num_layers=4)\n \n ############### 1ST PARALLEL 2D CONVOLUTION BLOCK ############\n # 3 sequential conv2D layers: (1,40,282) --> (16, 20, 141) -> (32, 5, 35) -> (64, 1, 8)\n self.conv2Dblock1 = nn.Sequential(\n \n # 1st 2D convolution layer\n nn.Conv2d(\n in_channels=1, # input volume depth == input channel dim == 1\n out_channels=16, # expand output feature map volume's depth to 16\n kernel_size=3, # typical 3*3 stride 1 kernel\n stride=1,\n padding=1\n ),\n nn.BatchNorm2d(16), # batch normalize the output feature map before activation\n nn.ReLU(), # feature map --> activation map\n nn.MaxPool2d(kernel_size=2, stride=2), #typical maxpool kernel size\n nn.Dropout(p=0.3), #randomly zero 30% of 1st layer's output feature map in training\n \n # 2nd 2D convolution layer identical to last except output dim, maxpool kernel\n nn.Conv2d(\n in_channels=16, \n out_channels=32, # expand output feature map volume's depth to 32\n kernel_size=3,\n stride=1,\n padding=1\n ),\n nn.BatchNorm2d(32),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=4, stride=4), # increase maxpool kernel for subsequent filters\n nn.Dropout(p=0.3), \n \n # 3rd 2D convolution layer identical to last except output dim\n nn.Conv2d(\n in_channels=32,\n out_channels=64, # expand output feature map volume's depth to 64\n kernel_size=3,\n stride=1,\n padding=1\n ),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=4, stride=4),\n nn.Dropout(p=0.3),\n )\n ############### 2ND PARALLEL 2D CONVOLUTION BLOCK ############\n # 3 sequential conv2D layers: (1,40,282) --> (16, 20, 141) -> (32, 5, 35) -> (64, 1, 8)\n self.conv2Dblock2 = nn.Sequential(\n \n # 1st 2D convolution layer\n nn.Conv2d(\n in_channels=1, # input volume depth == input channel dim == 1\n out_channels=16, # expand output feature map volume's depth to 16\n kernel_size=3, # typical 3*3 stride 1 kernel\n stride=1,\n padding=1\n ),\n nn.BatchNorm2d(16), # batch normalize the output feature map before activation\n nn.ReLU(), # feature map --> activation map\n nn.MaxPool2d(kernel_size=2, stride=2), #typical maxpool kernel size\n nn.Dropout(p=0.3), #randomly zero 30% of 1st layer's output feature map in training\n \n # 2nd 2D convolution layer identical to last except output dim, maxpool kernel\n nn.Conv2d(\n in_channels=16, \n out_channels=32, # expand output feature map volume's depth to 32\n kernel_size=3,\n stride=1,\n padding=1\n ),\n nn.BatchNorm2d(32),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=4, stride=4), # increase maxpool kernel for subsequent filters\n nn.Dropout(p=0.3), \n \n # 3rd 2D convolution layer identical to last except output dim\n nn.Conv2d(\n in_channels=32,\n out_channels=64, # expand output feature map volume's depth to 64\n kernel_size=3,\n stride=1,\n padding=1\n ),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=4, stride=4),\n nn.Dropout(p=0.3),\n )\n\n ################# FINAL LINEAR BLOCK ####################\n # Linear softmax layer to take final concatenated embedding tensor \n # from parallel 2D convolutional and transformer blocks, output 8 logits \n # Each full convolution block outputs (64*1*8) embedding flattened to dim 512 1D array \n # Full transformer block outputs 40*70 feature map, which we time-avg to dim 40 1D array\n # 512*2+40 == 1064 input features --> 8 output emotions \n self.fc1_linear = nn.Linear(512*2+40,num_emotions) \n \n ### Softmax layer for the 8 output logits from final FC linear layer \n self.softmax_out = nn.Softmax(dim=1) # dim==1 is the freq embedding\n \n # define one complete parallel fwd pass of input feature tensor thru 2*conv+1*transformer blocks\n def forward(self,x):\n \n ############ 1st parallel Conv2D block: 4 Convolutional layers ############################\n # create final feature embedding from 1st convolutional layer \n # input features pased through 4 sequential 2D convolutional layers\n conv2d_embedding1 = self.conv2Dblock1(x) # x == N/batch * channel * freq * time\n \n # flatten final 64*1*8 feature map from convolutional layers to length 512 1D array \n # skip the 1st (N/batch) dimension when flattening\n conv2d_embedding1 = torch.flatten(conv2d_embedding1, start_dim=1) \n \n ############ 2nd parallel Conv2D block: 4 Convolutional layers #############################\n # create final feature embedding from 2nd convolutional layer \n # input features pased through 4 sequential 2D convolutional layers\n conv2d_embedding2 = self.conv2Dblock2(x) # x == N/batch * channel * freq * time\n \n # flatten final 64*1*8 feature map from convolutional layers to length 512 1D array \n # skip the 1st (N/batch) dimension when flattening\n conv2d_embedding2 = torch.flatten(conv2d_embedding2, start_dim=1) \n \n \n ########## 4-encoder-layer Transformer block w/ 40-->512-->40 feedfwd network ##############\n # maxpool input feature map: 1*40*282 w/ 1*4 kernel --> 1*40*70\n x_maxpool = self.transformer_maxpool(x)\n\n # remove channel dim: 1*40*70 --> 40*70\n x_maxpool_reduced = torch.squeeze(x_maxpool,1)\n \n # convert maxpooled feature map format: batch * freq * time ---> time * batch * freq format\n # because transformer encoder layer requires tensor in format: time * batch * embedding (freq)\n x = x_maxpool_reduced.permute(2,0,1) \n \n # finally, pass reduced input feature map x into transformer encoder layers\n transformer_output = self.transformer_encoder(x)\n \n # create final feature emedding from transformer layer by taking mean in the time dimension (now the 0th dim)\n # transformer outputs 2x40 (MFCC embedding*time) feature map, take mean of columns i.e. take time average\n transformer_embedding = torch.mean(transformer_output, dim=0) # dim 40x70 --> 40\n \n ############# concatenate freq embeddings from convolutional and transformer blocks ######\n # concatenate embedding tensors output by parallel 2*conv and 1*transformer blocks\n complete_embedding = torch.cat([conv2d_embedding1, conv2d_embedding2,transformer_embedding], dim=1) \n\n ######### final FC linear layer, need logits for loss #########################\n output_logits = self.fc1_linear(complete_embedding) \n \n ######### Final Softmax layer: use logits from FC linear, get softmax for prediction ######\n output_softmax = self.softmax_out(output_logits)\n \n # need output logits to compute cross entropy loss, need softmax probabilities to predict class\n return output_logits, output_softmax\n\n\n# In[5]:\n\n\nemotions_dict ={\n '0':'neutral',\n '1':'calm',\n '2':'happy',\n '3':'sad',\n '4':'angry',\n '5':'fearful',\n '6':'disgust',\n '7':'surprised'\n}\n\n\n# In[7]:\n\n\nget_ipython().system('pip install torchsummary')\n\n\n# In[9]:\n\n\nfrom torchsummary import summary\n\n# need device to instantiate model\ndevice = 'cpu'\n\n# instantiate model for 8 emotions and move to GPU \nmodel = parallel_all_you_want(len(emotions_dict)).to(device)\n\n# include input feature map dims in call to summary()\nsummary(model, input_size=(1,40,282))\n\n\n# In[10]:\n\n\n# define loss function; CrossEntropyLoss() fairly standard for multiclass problems \ndef criterion(predictions, targets): \n return nn.CrossEntropyLoss()(input=predictions, target=targets)\n\n\n# In[11]:\n\n\noptimizer = torch.optim.SGD(model.parameters(),lr=0.01, weight_decay=1e-3, momentum=0.8)\n\n\n# In[12]:\n\n\n# define function to create a single step of the training phase\ndef make_train_step(model, criterion, optimizer):\n \n # define the training step of the training phase\n def train_step(X,Y):\n \n # forward pass\n output_logits, output_softmax = model(X)\n predictions = torch.argmax(output_softmax,dim=1)\n accuracy = torch.sum(Y==predictions)/float(len(Y))\n \n # compute loss on logits because nn.CrossEntropyLoss implements log softmax\n loss = criterion(output_logits, Y) \n \n # compute gradients for the optimizer to use \n loss.backward()\n \n # update network parameters based on gradient stored (by calling loss.backward())\n optimizer.step()\n \n # zero out gradients for next pass\n # pytorch accumulates gradients from backwards passes (convenient for RNNs)\n optimizer.zero_grad() \n \n return loss.item(), accuracy*100\n return train_step\n\n\n# In[13]:\n\n\ndef make_validate_fnc(model,criterion):\n def validate(X,Y):\n \n # don't want to update any network parameters on validation passes: don't need gradient\n # wrap in torch.no_grad to save memory and compute in validation phase: \n with torch.no_grad(): \n \n # set model to validation phase i.e. turn off dropout and batchnorm layers \n model.eval()\n \n # get the model's predictions on the validation set\n output_logits, output_softmax = model(X)\n predictions = torch.argmax(output_softmax,dim=1)\n\n # calculate the mean accuracy over the entire validation set\n accuracy = torch.sum(Y==predictions)/float(len(Y))\n \n # compute error from logits (nn.crossentropy implements softmax)\n loss = criterion(output_logits,Y)\n \n return loss.item(), accuracy*100, predictions\n return validate\n\n\n# In[14]:\n\n\ndef make_save_checkpoint(): \n def save_checkpoint(optimizer, model, epoch, filename):\n checkpoint_dict = {\n 'optimizer': optimizer.state_dict(),\n 'model': model.state_dict(),\n 'epoch': epoch\n }\n torch.save(checkpoint_dict, filename)\n return save_checkpoint\n\ndef load_checkpoint(optimizer, model, filename):\n checkpoint_dict = torch.load(filename)\n epoch = checkpoint_dict['epoch']\n model.load_state_dict(checkpoint_dict['model'])\n if optimizer is not None:\n optimizer.load_state_dict(checkpoint_dict['optimizer'])\n return epoch\n\n\n# In[23]:\n\n\n# get training set size to calculate # iterations and minibatch indices\ntrain_size = X_train.shape[0]\n\n# pick minibatch size (of 32... always)\nminibatch = 32\n\n# set device to GPU\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nprint(f'{device} selected')\n\n# instantiate model and move to GPU for training\nmodel = parallel_all_you_want(num_emotions=len(emotions_dict)).to(device) \nprint('Number of trainable params: ',sum(p.numel() for p in model.parameters()) )\n\n# encountered bugs in google colab only, unless I explicitly defined optimizer in this cell...\noptimizer = torch.optim.SGD(model.parameters(),lr=0.01, weight_decay=1e-3, momentum=0.8)\n\n# instantiate the checkpoint save function\nsave_checkpoint = make_save_checkpoint()\n\n# instantiate the training step function \ntrain_step = make_train_step(model, criterion, optimizer=optimizer)\n\n# instantiate the validation loop function\nvalidate = make_validate_fnc(model,criterion)\n\n# instantiate lists to hold scalar performance metrics to plot later\ntrain_losses=[]\nvalid_losses = []\n\n# create training loop for one complete epoch (entire training set)\ndef train(optimizer, model, num_epochs, X_train, Y_train, X_valid, Y_valid):\n\n for epoch in range(num_epochs):\n \n # set model to train phase\n model.train() \n \n # shuffle entire training set in each epoch to randomize minibatch order\n train_indices = np.random.permutation(train_size) \n \n # shuffle the training set for each epoch:\n X_train = X_train[train_indices,:,:,:] \n Y_train = Y_train[train_indices]\n\n # instantiate scalar values to keep track of progress after each epoch so we can stop training when appropriate \n epoch_acc = 0 \n epoch_loss = 0\n num_iterations = int(train_size / minibatch)\n \n # create a loop for each minibatch of 32 samples:\n for i in range(num_iterations):\n \n # we have to track and update minibatch position for the current minibatch\n # if we take a random batch position from a set, we almost certainly will skip some of the data in that set\n # track minibatch position based on iteration number:\n batch_start = i * minibatch \n # ensure we don't go out of the bounds of our training set:\n batch_end = min(batch_start + minibatch, train_size) \n # ensure we don't have an index error\n actual_batch_size = batch_end-batch_start \n \n # get training minibatch with all channnels and 2D feature dims\n X = X_train[batch_start:batch_end,:,:,:] \n # get training minibatch labels \n Y = Y_train[batch_start:batch_end] \n\n # instantiate training tensors\n X_tensor = torch.tensor(X, device=device).float() \n Y_tensor = torch.tensor(Y, dtype=torch.long,device=device)\n \n # Pass input tensors thru 1 training step (fwd+backwards pass)\n loss, acc = train_step(X_tensor,Y_tensor) \n \n # aggregate batch accuracy to measure progress of entire epoch\n epoch_acc += acc * actual_batch_size / train_size\n epoch_loss += loss * actual_batch_size / train_size\n \n # keep track of the iteration to see if the model's too slow\n print('\\r'+f'Epoch {epoch}: iteration {i}/{num_iterations}',end='')\n \n # create tensors from validation set\n X_valid_tensor = torch.tensor(X_valid,device=device).float()\n Y_valid_tensor = torch.tensor(Y_valid,dtype=torch.long,device=device)\n \n # calculate validation metrics to keep track of progress; don't need predictions now\n valid_loss, valid_acc, _ = validate(X_valid_tensor,Y_valid_tensor)\n \n # accumulate scalar performance metrics at each epoch to track and plot later\n train_losses.append(epoch_loss)\n valid_losses.append(valid_loss)\n \n # Save checkpoint of the model\n checkpoint_filename = CHECKPOINTS_DIR_PATH + 'parallel_all_you_wantFINAL-{:03d}.pkl'.format(epoch)\n save_checkpoint(optimizer, model, epoch, checkpoint_filename)\n \n # keep track of each epoch's progress\n print(f'\\nEpoch {epoch} --- loss:{epoch_loss:.3f}, Epoch accuracy:{epoch_acc:.2f}%, Validation loss:{valid_loss:.3f}, Validation accuracy:{valid_acc:.2f}%')\n\n\n# In[25]:\n\n\n# choose number of epochs higher than reasonable so we can manually stop training \nnum_epochs = 25\n\n# train it!\ntrain(optimizer, model, num_epochs, X_train, y_train, X_valid, y_valid)\n\n\n# In[26]:\n\n\nplt.title('Loss Curve for Parallel is All You Want Model')\nplt.ylabel('Loss', fontsize=16)\nplt.xlabel('Epoch', fontsize=16)\nplt.plot(train_losses[:],'b')\nplt.plot(valid_losses[:],'r')\nplt.legend(['Training loss','Validation loss'])\nplt.show()\n\n\n# In[27]:\n\n\n# pick load folder \nload_folder = CHECKPOINTS_DIR_PATH \n\n# pick the epoch to load\nepoch = '020'\nmodel_name = f'parallel_all_you_wantFINAL-{epoch}.pkl'\n\n# make full load path\nload_path = os.path.join(load_folder, model_name)\n\n## instantiate empty model and populate with params from binary \nmodel = parallel_all_you_want(len(emotions_dict))\nload_checkpoint(optimizer, model, load_path)\n\nprint(f'Loaded model from {load_path}')\n\n\n# In[41]:\n\n\n# reinitialize validation function with model from chosen checkpoint\nvalidate = make_validate_fnc(model,criterion)\n\n# Convert 4D test feature set array to tensor and move to GPU\nX_test_tensor = torch.tensor(X_test,device=device).float()\n# Convert 4D test label set array to tensor and move to GPU\ny_test_tensor = torch.tensor(y_test,dtype=torch.long,device=device)\n\n# Get the model's performance metrics using the validation function we defined\ntest_loss, test_acc, predicted_emotions = validate(X_test_tensor,y_test_tensor)\n\nprint(f'Test accuracy is {test_acc:.2f}%')\n\n\n# In[42]:\n\n\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sn\n\n# because model tested on GPU, move prediction tensor to CPU then convert to array\npredicted_emotions = predicted_emotions.cpu().numpy()\n# use labels from test set\nemotions_groundtruth = y_test\n\n# build confusion matrix and normalized confusion matrix\nconf_matrix = confusion_matrix(emotions_groundtruth, predicted_emotions)\nconf_matrix_norm = confusion_matrix(emotions_groundtruth, predicted_emotions,normalize='true')\n\n# set labels for matrix axes from emotions\nemotion_names = [emotion for emotion in emotions_dict.values()]\n\n# make a confusion matrix with labels using a DataFrame\nconfmatrix_df = pd.DataFrame(conf_matrix, index=emotion_names, columns=emotion_names)\nconfmatrix_df_norm = pd.DataFrame(conf_matrix_norm, index=emotion_names, columns=emotion_names)\n\n# plot confusion matrices\nplt.figure(figsize=(16,6))\nsn.set(font_scale=1.8) # emotion label and title size\nplt.subplot(1,2,1)\nplt.title('Confusion Matrix')\nsn.heatmap(confmatrix_df, annot=True, annot_kws={\"size\": 11}) #annot_kws is value font\nplt.subplot(1,2,2)\nplt.title('Normalized Confusion Matrix')\nsn.heatmap(confmatrix_df_norm, annot=True, annot_kws={\"size\": 11}) #annot_kws is value font\n\nplt.show()\n\n","sub_path":"Model/neural_network.py","file_name":"neural_network.py","file_ext":"py","file_size_in_byte":21047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"565652820","text":"from model.Servicemodel import ServiceRecord\n\n\nclass PickuphostCrawler():\n def __init__(self):\n pass\n def parsing(self, response):\n return self.crawl(response,self.category,self.servicename)\n def crawl(self, response, category, servicename):\n self.category = category\n self.servicename = servicename\n reviews = []\n #http://pickuphost.com/review/bluehost/#customer_review_shap\n for node in response.xpath(\"//div[@class='one_rew']/div[@class='rewiwer_post']/span\"):\n reviews.append(node.xpath('string()').extract());\n ratings = response.xpath(\"//div[@class='col-md-12 avg_ratting_bg text-center']/div[@class='avg_ratting text-center']/text()\").extract()\n headings = response.xpath(\"//div[@id='rew_replace_div']/div[@class='one_rew']/h4/b/text()\").extract()\n dates = response.xpath(\"//div[@id='rew_replace_div']/div[@class='one_rew']/span[@class='rewiwer_data']/span[2]/text()\").extract()\n authors = response.xpath(\"//div[@id='rew_replace_div']/div[@class='one_rew']/span[@class='rewiwer_data']/span[1]/text()\").extract()\n name = response.xpath(\"//div[@class='navbar-header']/a/@href\").extract()\n website_name = name[0].split(\".\")[0].split(\"/\")[-1]\n for item in range(1, len(reviews)):\n servicename1 = ServiceRecord(response.url, ratings[item], headings[item], dates[item], authors[item], category,\n servicename, reviews[item],\"\",website_name);\n servicename1.save()\n next_page = response.xpath(\"//div[@class='row']/div[@class='col-lg-8 col-lg-offset-3']/ul[@class='pagecount']/li[8]/a[@class='next page-numbers custom_page_link']/@href\").extract()\n if next_page is not None:\n next_page_url = \"\".join(next_page)\n if next_page_url and next_page_url.strip():\n print(type(next_page_url))\n print(next_page_url)\n # yield Request(url=next_page_url, callback=self.parse, dont_filter=True)\n yield response.follow(next_page_url, callback=self.parsing)\n","sub_path":"services/PickuphostCrawler.py","file_name":"PickuphostCrawler.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"620995432","text":"import tornado, time\nfrom tornado import web, gen, httpclient, httpserver, ioloop\nfrom tornado.concurrent import Future\n\n\n@tornado.gen.coroutine\ndef sl():\n yield tornado.gen.sleep(2)\n time.sleep(2)\n return 666\n\n\n\n\nclass AsyncResponseHandler(tornado.web.RequestHandler):\n @tornado.web.asynchronous\n @tornado.gen.coroutine\n def get(self):\n print(\"开始\")\n ret = yield sl()\n print(ret)\n print(\"结束\")\n self.write(\"ok\")\n\n\n# Our URL Mappings\nhandlers = [\n (r\"/a\", AsyncResponseHandler),\n]\n\n\ndef main():\n settings = {\n \"login_url\": \"http://www.baidu.com\",\n \"autoreload\": True\n }\n\n # Setup app and HTTP server\n application = tornado.web.Application(handlers, **settings)\n http_server = tornado.httpserver.HTTPServer(application)\n http_server.listen(8000)\n\n # Start ioloop\n tornado.ioloop.IOLoop.instance().start()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"test/tornado_auth_test.py","file_name":"tornado_auth_test.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"529595883","text":"import hashlib\n\ndef read_from_file_by_chunk(file_name, chunk_size=2**14):\n \"\"\" Read bytes from a file in chunks. \"\"\"\n with open(file_name, 'rb') as f:\n while True:\n chunk = f.read(chunk_size)\n if chunk:\n yield chunk\n else:\n break\n\ndef get_file_md5_hash_by_chunk(file_name, chunk_size=2**14):\n \"\"\" Returns file MD5 hash in chunks. \"\"\"\n md5_hash = hashlib.md5()\n\n for chunk in read_from_file_by_chunk(file_name, chunk_size):\n md5_hash.update(chunk)\n\n return md5_hash.hexdigest()\n\ndef validate_file_md5_hash_by_chunk(file_name, target_hash, chunk_size=2**14):\n \"\"\" Returns True if file MD5 hash matches the provided one, False otherwise. \"\"\"\n if get_file_md5_hash_by_chunk(file_name, chunk_size) == target_hash:\n return True\n return False\n","sub_path":"How_To_Transfer_File/file_transfer_util.py","file_name":"file_transfer_util.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"572522584","text":"#------------------------------------------------------------------------------\n# Copyright (c) 2012, Enthought, Inc.\n# All rights reserved.\n#------------------------------------------------------------------------------\nfrom abstract_image import AbstractImage\nfrom base64 import b64encode, b64decode\n\n_FORMATS = ['indexed8', 'rgba32', 'rgb32']\n\nclass ImageFromArray(AbstractImage):\n \"\"\" A subclass of AbstractImage that allows the user to read in an image\n from a bytearray.\n\n \"\"\"\n def __init__(self, data, size, img_format, color_table=None):\n \"\"\" Store the array as the image data. img_format must be one of the\n values specified above (case-insensitive). color_table is an optional\n list of RGB tuples.\n\n \"\"\"\n self._data = data\n self._size = size\n self._color_table = color_table\n\n img_format = img_format.lower()\n if img_format not in _FORMATS:\n raise Exception(\"A value of '%s' was specified for the image format. \"\n \"The value must one of the following: %s\" % (img_format, _FORMATS))\n self._format = img_format\n\n def as_dict(self):\n \"\"\" Return the image as a JSON-serializable dict\n\n \"\"\"\n img_dict = {\n 'data' : b64encode(self._data),\n 'format' : self._format,\n 'size' : self._size,\n 'color_table' : self._color_table\n }\n return img_dict\n\n @staticmethod\n def from_dict(image_dict):\n \"\"\" Receive a JSON representation of an image and convert it into the\n appropriate Python object\n\n \"\"\"\n data = b64decode(image_dict['data'])\n size = image_dict['size']\n img_format = image_dict['format']\n color_table = image_dict['color_table']\n return ImageFromArray(data, size, img_format, color_table)\n","sub_path":"enaml/noncomponents/image/image_from_array.py","file_name":"image_from_array.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"293060573","text":"#!/usr/local/bin/python3\n# Condicoes02.01\n# Uso do import datetime para trabalhar com formatos e condiçoes com datas\n\nimport datetime\ntoday = datetime.date.today()\nano = int(input('Digite o ano de fabricação do seu carro: '))\ndate = today.year\nnovo = (date - 3)\n\nif ano >= novo:\n print('Seu carro é novo!')\nelse:\n print('Seu carro é velho!')","sub_path":"python_zumbis/01.condicao04_1.py","file_name":"01.condicao04_1.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"106951570","text":"\"\"\"\nThis definitions.py file has all function definitions for the project 3 jupyter notebook.\n\"\"\"\n# import librareis\nimport numpy as np\nimport pandas as pd\nimport datetime\nfrom datetime import datetime, timedelta\n\n\"\"\"\nThis function, boolStart, finds start points and returns an array of boolean.\n\nWhen two points have a gap that is more than 10mins(600 seconds). The model assumes two are different journey.\n\"\"\"\n\ndef boolStart(data):\n fmt = '%Y-%m-%d %H:%M:%S'\n temp = []\n preStamp = datetime.strptime('2018-5-1 00:00:00', fmt) # only for finding first data\n preId = 0\n for stamp, mId in zip(data['event_timestamp'], data['machine_id']):\n timediff = abs((preStamp - stamp).total_seconds())\n if(preStamp == datetime.strptime('2018-5-1 00:00:00', fmt)): # for the first data\n temp.append(True)\n preStamp = stamp\n preId = mId\n elif(timediff > 600): # if there is a gap more than 10 mins, this is regarded as a start point\n temp.append(True)\n preStamp = stamp\n preId = mId\n elif(preId != mId): # if machine IDs are different, this is also regarded as a start point\n temp.append(True)\n preStamp = stamp\n preId = mId\n else :\n temp.append(False) \n preStamp = stamp\n preId = mId\n return temp\n\n\"\"\"\nThe function, makeJourneyDf, makes raw data into a dataframe by journey.\nThis function returns a dataframe.\n\"\"\"\n\ndef makeJourneyDf(data):\n start_time = []\n end_time = []\n time_ave_gap = []\n machine_id = []\n is_Heavy = [] # boolean value\n speed_temp = [] # store all speed values temporary to calculate mean and standard deviation\n speed_ave = [] # mean of speed \n speed_std = [] # std of speed\n start_lat_arr = [] \n start_lon_arr = []\n end_lat_arr = []\n end_lon_arr = []\n counts = [] # shows how many GPS data a journey has\n count = 0\n max_speed_gap = []\n sum_speed = 0\n for time, mId, heavy, speed, lat, lon, boolStart, boolEnd in zip(data['event_timestamp'], data['machine_id'], data['vehicle_weight_type'], data['speed_gps_kph'], data['latitude'], data['longitude'], data['start_point'], data['end_point']):\n if(boolStart and not boolEnd):\n start_time.append(time)\n machine_id.append(mId)\n speed_temp = []\n time_temp = []\n count =1\n if(heavy == 'HEAVY'):\n is_Heavy.append(True)\n else :\n is_Heavy.append(False)\n start_lat_arr.append(lat)\n start_lon_arr.append(lon)\n speed_temp.append(speed)\n time_temp.append(time)\n elif(not boolStart) and (not boolEnd):\n count += 1\n speed_temp.append(speed)\n time_temp.append(time)\n elif(not boolStart) and (boolEnd):\n count += 1\n speed_temp.append(speed)\n time_temp.append(time)\n end_lat_arr.append(lat)\n end_lon_arr.append(lon)\n end_time.append(time)\n counts.append(count)\n speed_ave.append(np.mean(speed_temp))\n speed_std.append(np.std(speed_temp))\n max_speed_gap.append(np.diff(speed_temp).max())\n time_ave_gap.append(np.diff(time_temp).mean().total_seconds())\n count = 0\n elif(boolStart) and (boolEnd):\n start_time.append(time)\n end_time.append(time)\n machine_id.append(mId)\n sum_speed = speed\n count=1\n if(heavy == 'HEAVY'):\n is_Heavy.append(True)\n else :\n is_Heavy.append(False)\n start_lat_arr.append(lat)\n start_lon_arr.append(lon)\n end_lat_arr.append(lat)\n end_lon_arr.append(lon)\n speed_ave.append(speed)\n speed_std.append(0.0)\n max_speed_gap.append(0.0)\n time_ave_gap.append(0.0)\n counts.append(count)\n \n duration_arr = []\n for i in range(len(start_time)):\n diff = (start_time[i]-end_time[i]).total_seconds()\n duration_arr.append(abs(diff))\n\n # check a journey was northward or southward\n is_northing = []\n for i in range(len(start_lat_arr)):\n if(start_lat_arr[i]-end_lat_arr[i])>0:\n is_northing.append(False)\n else:\n is_northing.append(True)\n # make a dataframe\n dfjourney = pd.DataFrame()\n dfjourney['is_northing'] = is_northing\n dfjourney['start_time'] = start_time\n dfjourney['end_time'] = end_time \n dfjourney['duration_second'] = duration_arr\n dfjourney['machine_id'] = machine_id\n dfjourney['is_heavy'] = is_Heavy\n dfjourney['average_GPS_speed'] = speed_ave\n dfjourney['GPS_speed_std'] = speed_std\n dfjourney['Max_speed_gap'] = max_speed_gap\n dfjourney['average_time_gap'] = time_ave_gap\n dfjourney['start_latitude'] = start_lat_arr\n dfjourney['start_longitude'] = start_lon_arr\n dfjourney['end_latitude'] = end_lat_arr\n dfjourney['end_longitude'] = end_lon_arr\n dfjourney['number_data'] = counts\n return dfjourney\n \n\"\"\"\nThe function, findClosestData, finds the weather conditions at the nearest data from start time\nReturns an array of string\nString values are only 'Rain', 'Drizzle', 'Clouds', 'Clear'\n\"\"\"\ndef findClosestData(start, w):\n temp_weather = []\n for time in start:\n prediff = 999999.0\n str = ''\n for w_time, weather in zip(start, w):\n timediff = abs((time-w_time).total_seconds())\n if timediff < prediff :\n str = weather\n prediff = timediff\n temp_weather.append(str)\n return temp_weather\n\n\"\"\"\nThe function, weatherDummy, converts string values into dummy values. \nRain: 4, Drizzle: 3, Clouds: 2, Clear: 1\nReturns an array of integer\n\"\"\"\ndef weatherDummy(data):\n temp_weather = []\n for str in data:\n if str=='Rain':\n temp_weather.append(4)\n elif str=='Drizzle':\n temp_weather.append(3)\n elif str=='Clouds':\n temp_weather.append(2)\n elif str=='Clear':\n temp_weather.append(1)\n return temp_weather\n\n\"\"\"\nThe function, converNZDT, converts UTC time into New Zealand date time adding 13 hours.\nReturns an array of datetime.\n\"\"\"\n\ndef convertNZDT(data):\n temp_time = []\n for t in data:\n t = t.replace(' +0000 UTC', '')\n t = datetime.strptime(t, '%Y-%m-%d %H:%M:%S')\n t = t + timedelta(hours=13)\n temp_time.append(t)\n return temp_time\n\n\"\"\"\nThe function, diffRate, calculates differences between estimate time in traffic condition and actual time, \nand divides by actual time.\nTherefore, diffRate positive means the vehicle arrived earlier than expected by Google Maps.\nThe function returns an array of float.\n\"\"\"\n\ndef diffRate(time, timeTraffic):\n temp_diff_rate=[]\n for act, est in zip(time, timeTraffic):\n diff = est - act\n temp_diff_rate.append(float((diff)/act))\n return temp_diff_rate\n\n\"\"\"\nThe function, calculateAveSpeed, calculates average speed using distance from Google Maps and actual duration time.\nReturns an array of float\n\"\"\"\n\ndef calculateAveSpeed(time, dist):\n speed_array = []\n for time, distance in zip(time, dist):\n speed_array.append(float (distance/time*3600/1000))\n return speed_array\n\n\"\"\"\nThe function, boolJamTime, checks whether a journey started at congested time or not.\nHere are congested times.\nNorthwards: only from 6 to 10 AM.\nSouthwards: both, from 6 to 10 AM and from 13:30 to 18:30.\nReturns an array of boolean.\n\"\"\"\n\ndef boolJamTime(start_time, northward):\n start1 = datetime.strptime(\"06:00:00\",\"%H:%M:%S\").time()\n end1 = datetime.strptime(\"10:00:00\",\"%H:%M:%S\").time()\n start2 = datetime.strptime(\"13:30:00\",\"%H:%M:%S\").time()\n end2 = datetime.strptime(\"18:30:00\",\"%H:%M:%S\").time()\n temp = []\n for start, north in zip(start_time, northward):\n if north:\n if (start.time()>start2) and (start.time()start1) and (start.time()start2) and (start.time()/', views.StoryView.as_view(), name='story'),\n path('add-story/', views.AddStoryView.as_view(), name='newsStory'),\n path('/delete-story/', views.DeleteStoryView.as_view(), name='deleteStory'),\n path('/update-story/', views.UpdateStoryView.as_view(), name='updateStory'),\n path('/author/', views.AuthorView.as_view(), name='author'),\n]","sub_path":"she_codes_news/news/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"14127874","text":"#!/usr/bin/env python3\n\ndef is_palin(x):\n s = str(x)\n return s == s[::-1]\n\ndef is_lychrel(n):\n for i in range(50):\n n += int(str(n)[::-1])\n if is_palin(n):\n return False\n return True\n\ncount = 0\nfor i in range(10000):\n if is_lychrel(i):\n count += 1\nprint(count)\n","sub_path":"55.py","file_name":"55.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"310726432","text":"from __future__ import unicode_literals\n\nimport csv\nfrom decimal import Decimal\nimport re\nimport arrow\n\nfrom django.db.models.fields import DecimalField, DateTimeField\nfrom raven.contrib.django.raven_compat.models import client\n\nfrom .models import Pledge, BankTransaction, PartnerCharity, PaymentMethod\n\n\nFIELD_MAP = [\n # (django_field_name, drupal_field_name)\n ('id', 'webform_serial'),\n ('completed_time', 'webform_completed_time'),\n ('ip', 'webform_ip_address'),\n ('drupal_uid', 'webform_uid'),\n ('drupal_username', 'webform_username'),\n ('drupal_preferred_donation_method', 'preferred_donation_method'),\n ('reference', 'transactionref'),\n ('recipient_org', 'recipient_org'),\n ('amount', 'donation_amount'),\n ('first_name', 'ea_donor_name'),\n ('last_name', 'ea_donor_last_name'),\n ('email', 'email'),\n ('subscribe_to_updates', 'Stay in touch (receive occasional emails with important updates, new research, and events near you)'),\n ('recurring', 'I want to set up recurring donations through my bank'),\n ('recurring_frequency', 'recurring_donation_frequency'),\n ('publish_donation', \"Stay in touch (receive occasional emails with important updates, new research, and events near you)\"),\n ('how_did_you_hear_about_us', 'how_did_you_hear_about_us'),\n ('share_with_givewell',\n 'Share my email address and information about my donation with GiveWell. (GiveWell will not share your information with any third parties.)'),\n ('share_with_gwwc',\n 'Share my email address and information about my donation with Giving What We Can. (Giving What We Can will not share your information with any third parties.)'),\n ('share_with_tlycs',\n 'Share my email address and information about my donation with The Life You Can Save. (The Life You Can Save will not share your information with any third parties.)'),\n]\n\n\ndef import_from_drupal(donations_file):\n with donations_file.file as csvfile:\n csv_reader = csv.reader(csvfile)\n # get rid of crap at start\n for row in csv_reader:\n if row and row[0] == 'webform_serial':\n break\n headers = row\n pledges = [dict(zip(headers, row)) for row in csv_reader]\n\n existing_pledges = Pledge.objects.values_list('id', flat=True)\n\n recipient_orgs_map = {partner_charity.name: partner_charity for partner_charity in PartnerCharity.objects.all()}\n\n for pledge in pledges:\n if pledge['webform_serial'] in existing_pledges:\n continue # already imported\n\n try:\n kwargs = {}\n for (django_field, drupal_field) in FIELD_MAP:\n field_type = type(Pledge._meta.get_field_by_name(django_field)[0])\n\n value = pledge[drupal_field]\n\n # We only need to manually convert the following fields\n if field_type == DecimalField:\n value = re.sub('[a-zA-Z\\$ /,]', '', value)\n value = Decimal(value)\n elif field_type == DateTimeField:\n value = arrow.get(value, 'MM/DD/YYYY - HH:mm').datetime\n elif django_field == 'recipient_org':\n value = recipient_orgs_map[value]\n\n kwargs[django_field] = value\n\n # We deleted this field in drupal. Just pretend that we didn't for now.\n kwargs['payment_method'] = PaymentMethod.BANK\n\n Pledge(**kwargs).save()\n except Exception: # Deliberately broad\n client.captureException()\n\n\ndef reconcile_imported_pledges():\n # well, actually, just reconcile everything\n references = Pledge.objects.values_list('reference', flat=True)\n transactions_we_can_reconcile = BankTransaction.objects.filter(pledge__isnull=True,\n do_not_reconcile=False,\n reference__in=references)\n for transaction in transactions_we_can_reconcile:\n transaction.save() # Triggers everything\n","sub_path":"donation/drupal_import.py","file_name":"drupal_import.py","file_ext":"py","file_size_in_byte":4064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"121040865","text":"from util import *\n# input: a list of slices\n# output:\n# \ta list of line segments\n# \tall in a single frame of reference\ndef layout(slices, margin):\n\tsegments = []\n\n\toffset = [margin,margin]\n\tfor slice in slices:\n\t\tminReach = min_from_segments(slice.segments)\n\t\tmaxReach = max_from_segments(slice.segments)\n\t\trange = diff(maxReach, minReach)\n\n\t\tfor segment in slice.segments:\n\t\t\tpointA = add(diff(segment[0], minReach), offset)\n\t\t\tpointB = add(diff(segment[1], minReach), offset)\n\t\t\tsegments.append( (pointA, pointB) )\n\n\t\toffset[0] += range[0] + margin\n\n\treturn segments\n\ndef min_from_segments(segments):\n\tminX = float(\"inf\")\n\tminY = float(\"inf\")\n\tfor segment in segments:\n\t\tpointA = segment[0]\n\t\tpointB = segment[1]\n\t\tminX = min(minX, pointA[0])\n\t\tminX = min(minX, pointB[0])\n\t\tminY = min(minY, pointA[0])\n\t\tminY = min(minY, pointB[0])\n\n\treturn (minX, minY)\n\ndef max_from_segments(segments):\n\tmaxX = -float(\"inf\")\n\tmaxY = -float(\"inf\")\n\n\tfor segment in segments:\n\t\tpointA = segment[0]\n\t\tpointB = segment[1]\n\t\tmaxX = max(maxX, pointA[0])\n\t\tmaxX = max(maxX, pointB[0])\n\t\tmaxY = max(maxY, pointA[0])\n\t\tmaxY = max(maxY, pointB[0])\n\n\treturn (maxX, maxY)","sub_path":"layout.py","file_name":"layout.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"30703305","text":"# Let's play with the *args pattern.\n# Create a function named multiply that takes any number of arguments.\n# Return the product (multiplied value) of all of the supplied arguments.\n# The type of argument shouldn't matter.\n# Slices might come in handy for this one.\n\n\ndef multiply(*args):\n multipliers = list(args[:])\n while len(multipliers) > 1:\n a = multipliers.pop(0)\n b = multipliers.pop(0)\n total = (a * b)\n multipliers.insert(0, total)\n return multipliers[0]\n\nprint(multiply(5, 4, 3, 2, 6))\n","sub_path":"Py_Treehouse/T_Py_U1_Collections/Tuples/twoples.py","file_name":"twoples.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"558443659","text":"# -*- coding: utf-8 -*-\nfrom django.core.management.base import BaseCommand\n\nfrom pages.models import Page, PageRelation\n\n\nclass Command(BaseCommand):\n \"\"\"\n Command used to populate PageRelation model\n \"\"\"\n\n def handle(self, **options):\n for p in Page.objects.all():\n for r in p.related.all():\n rp = PageRelation(page=p, related=r, order=0)\n rp.save()\n","sub_path":"{{cookiecutter.project_name}}/blog/management/commands/m_through.py","file_name":"m_through.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"266567850","text":"#!/usr/bin/env pytest\n###############################################################################\n# $Id$\n#\n# Project: GDAL/OGR Test Suite\n# Purpose: Test /vsiaz\n# Author: Even Rouault \n#\n###############################################################################\n# Copyright (c) 2017 Even Rouault \n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n###############################################################################\n\nfrom osgeo import gdal\n\n\nimport gdaltest\nimport pytest\n\npytestmark = pytest.mark.skipif(not gdaltest.built_against_curl(), reason=\"GDAL not built against curl\")\n\n\ndef open_for_read(uri):\n \"\"\"\n Opens a test file for reading.\n \"\"\"\n return gdal.VSIFOpenExL(uri, 'rb', 1)\n\n###############################################################################\n@pytest.fixture(autouse=True, scope='module')\ndef startup_and_cleanup():\n\n az_vars = {}\n for var in ('AZURE_STORAGE_CONNECTION_STRING', 'AZURE_STORAGE_ACCOUNT',\n 'AZURE_STORAGE_ACCESS_KEY', 'AZURE_SAS', 'AZURE_NO_SIGN_REQUEST'):\n az_vars[var] = gdal.GetConfigOption(var)\n if az_vars[var] is not None:\n gdal.SetConfigOption(var, \"\")\n\n assert gdal.GetSignedURL('/vsiaz/foo/bar') is None\n\n yield\n\n for var in az_vars:\n gdal.SetConfigOption(var, az_vars[var])\n\n###############################################################################\n# Error cases\n\n\ndef test_vsiaz_real_server_errors():\n\n if not gdaltest.built_against_curl():\n pytest.skip()\n\n # Missing AZURE_STORAGE_ACCOUNT\n gdal.ErrorReset()\n with gdaltest.error_handler():\n f = open_for_read('/vsiaz/foo/bar')\n assert f is None and gdal.VSIGetLastErrorMsg().find('AZURE_STORAGE_ACCOUNT') >= 0\n\n gdal.ErrorReset()\n with gdaltest.error_handler():\n f = open_for_read('/vsiaz_streaming/foo/bar')\n assert f is None and gdal.VSIGetLastErrorMsg().find('AZURE_STORAGE_ACCOUNT') >= 0\n\n # Invalid AZURE_STORAGE_CONNECTION_STRING\n with gdaltest.config_option('AZURE_STORAGE_CONNECTION_STRING', 'invalid'):\n gdal.ErrorReset()\n with gdaltest.error_handler():\n f = open_for_read('/vsiaz/foo/bar')\n assert f is None\n\n # Missing AZURE_STORAGE_ACCESS_KEY\n gdal.ErrorReset()\n with gdaltest.config_options({'AZURE_STORAGE_ACCOUNT': 'AZURE_STORAGE_ACCOUNT',\n 'CPL_AZURE_VM_API_ROOT_URL': 'disabled'}):\n with gdaltest.error_handler():\n f = open_for_read('/vsiaz/foo/bar')\n assert f is None and gdal.VSIGetLastErrorMsg().find('AZURE_STORAGE_ACCESS_KEY') >= 0\n\n # AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY but invalid\n gdal.ErrorReset()\n with gdaltest.config_options({'AZURE_STORAGE_ACCOUNT': 'AZURE_STORAGE_ACCOUNT',\n 'AZURE_STORAGE_ACCESS_KEY': 'AZURE_STORAGE_ACCESS_KEY'}):\n with gdaltest.error_handler():\n f = open_for_read('/vsiaz/foo/bar.baz')\n if f is not None:\n if f is not None:\n gdal.VSIFCloseL(f)\n if gdal.GetConfigOption('APPVEYOR') is not None:\n return\n pytest.fail(gdal.VSIGetLastErrorMsg())\n\n gdal.ErrorReset()\n with gdaltest.error_handler():\n f = open_for_read('/vsiaz_streaming/foo/bar.baz')\n assert f is None, gdal.VSIGetLastErrorMsg()\n\n\n###############################################################################\n# Test AZURE_NO_SIGN_REQUEST=YES\n\n\ndef test_vsiaz_no_sign_request():\n\n if not gdaltest.built_against_curl():\n pytest.skip()\n\n with gdaltest.config_options({ 'AZURE_STORAGE_ACCOUNT': 'naipblobs', 'AZURE_NO_SIGN_REQUEST': 'YES'}):\n actual_url = gdal.GetActualURL('/vsiaz/naip/v002/al/2015/al_100cm_2015/30086/m_3008601_ne_16_1_20150804.tif')\n assert actual_url == 'https://naipblobs.blob.core.windows.net/naip/v002/al/2015/al_100cm_2015/30086/m_3008601_ne_16_1_20150804.tif'\n assert actual_url == gdal.GetSignedURL('/vsiaz/naip/v002/al/2015/al_100cm_2015/30086/m_3008601_ne_16_1_20150804.tif')\n\n f = open_for_read('/vsiaz/naip/v002/al/2015/al_100cm_2015/30086/m_3008601_ne_16_1_20150804.tif')\n if f is None:\n if gdaltest.gdalurlopen('https://naipblobs.blob.core.windows.net/naip/v002/al/2015/al_100cm_2015/30086/m_3008601_ne_16_1_20150804.tif') is None:\n pytest.skip('cannot open URL')\n pytest.fail()\n\n gdal.VSIFCloseL(f)\n\n assert 'm_3008601_ne_16_1_20150804.tif' in gdal.ReadDir('/vsiaz/naip/v002/al/2015/al_100cm_2015/30086/')\n\n###############################################################################\n# Test AZURE_SAS option\n\n\ndef test_vsiaz_sas():\n\n if not gdaltest.built_against_curl():\n pytest.skip()\n\n # See https://azure.microsoft.com/en-us/services/open-datasets/catalog/naip/ for the value of AZURE_SAS\n with gdaltest.config_options({ 'AZURE_STORAGE_ACCOUNT': 'naipblobs', 'AZURE_SAS': 'st=2019-07-18T03%3A53%3A22Z&se=2035-07-19T03%3A53%3A00Z&sp=rl&sv=2018-03-28&sr=c&sig=2RIXmLbLbiagYnUd49rgx2kOXKyILrJOgafmkODhRAQ%3D'}):\n actual_url = gdal.GetActualURL('/vsiaz/naip/v002/al/2015/al_100cm_2015/30086/m_3008601_ne_16_1_20150804.tif')\n assert actual_url == 'https://naipblobs.blob.core.windows.net/naip/v002/al/2015/al_100cm_2015/30086/m_3008601_ne_16_1_20150804.tif'\n assert gdal.GetSignedURL('/vsiaz/naip/v002/al/2015/al_100cm_2015/30086/m_3008601_ne_16_1_20150804.tif') == 'https://naipblobs.blob.core.windows.net/naip/v002/al/2015/al_100cm_2015/30086/m_3008601_ne_16_1_20150804.tif?st=2019-07-18T03%3A53%3A22Z&se=2035-07-19T03%3A53%3A00Z&sp=rl&sv=2018-03-28&sr=c&sig=2RIXmLbLbiagYnUd49rgx2kOXKyILrJOgafmkODhRAQ%3D'\n\n f = open_for_read('/vsiaz/naip/v002/al/2015/al_100cm_2015/30086/m_3008601_ne_16_1_20150804.tif')\n if f is None:\n if gdaltest.gdalurlopen('https://naipblobs.blob.core.windows.net/naip/v002/al/2015/al_100cm_2015/30086/m_3008601_ne_16_1_20150804.tif') is None:\n pytest.skip('cannot open URL')\n pytest.fail()\n\n gdal.VSIFCloseL(f)\n\n assert 'm_3008601_ne_16_1_20150804.tif' in gdal.ReadDir('/vsiaz/naip/v002/al/2015/al_100cm_2015/30086/')\n","sub_path":"autotest/gcore/vsiaz_real_instance_auto.py","file_name":"vsiaz_real_instance_auto.py","file_ext":"py","file_size_in_byte":7308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"193759859","text":"from flask import render_template\nfrom app import app\n\n@app.route(\"/\")\n@app.route(\"/index\")\ndef index():\n\tuser = {'username' : 'Chirag'}\n\tposts = [ {'author' : {'username' : 'Modi'}, 'body' : 'Be Patient'}, \n\t\t{'author' : {'username' : 'Tanu'}, 'body' : 'Focus on you goal\\'s'} ]\n\treturn render_template('index.html', title='Home', user=user, posts=posts)","sub_path":"microblog/app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"291374242","text":"import jax.numpy as np\nimport numpy as onp\nimport jax.random as random\nimport jax.scipy as sp\nfrom jax import grad, vmap, jacfwd, jit\nfrom jax.lax import stop_gradient\n\nfrom ngboost.distns import Normal, LogNormal\n\n\nclass Score(object):\n\n def __init__(self, seed=123):\n self.key = random.PRNGKey(seed=seed)\n\n def __call__(self, Forecast, Y):\n raise NotImplementedError\n\n def setup_distn(self, distn):\n self.distn = distn\n\n\nclass MLE(Score):\n\n def __init__(self, seed=123, K=128):\n super().__init__(seed=seed)\n self.metric_fn = jit(vmap(lambda p: self.distn(p).fisher_info()))\n self.sample_grad_fn = jit(vmap(grad(self._loglik_fn)))\n self.outer_product_fn = jit(vmap(lambda v: np.outer(v, v)))\n self.K = K\n\n def __call__(self, forecast, Y):\n return -forecast.logpdf(Y.squeeze())\n\n def metric(self, params, Y):\n if self.distn.has_fisher_info:\n return self.metric_fn(params)\n batch_size = len(params)\n var = 0\n for _ in range(self.K):\n self.key, subkey = random.split(self.key)\n grad = self.sample_grad_fn(params, random.split(subkey, batch_size))\n var += self.outer_product_fn(grad)\n return var / self.K\n\n def naturalize(self, params, grads):\n metric = self.metric_fn(params)\n nat_grads = onp.linalg.solve(metric, grads)\n weights = onp.power((grads * nat_grads).sum(axis=1, keepdims=True), -0.5)\n #return weights * nat_grads\n return nat_grads\n \n def _loglik_fn(self, params, key):\n sample = stop_gradient(self.distn(params).sample(key=key))\n return self.distn(params).logpdf(sample)\n\n\nclass MLE_SURV(MLE):\n\n def __init__(self, seed=123):\n super().__init__(seed=seed)\n\n def __call__(self, forecast, Y, eps=1e-5):\n E = Y['Event']\n T = Y['Time']\n cens = (1-E) * np.log(1 - forecast.cdf(T) + eps)\n uncens = E * forecast.logpdf(T)\n return -(cens + uncens)\n\nclass CRPS(Score):\n\n def __init__(self, K=32):\n super().__init__()\n self.metric_fn = jit(vmap(lambda p: self.distn(p).crps_metric()))\n self.K = K\n self.I_pos = self._I_pos\n self.I_neg = self._I_neg\n #self.I_pos = jit(self._I_pos)\n #self.I_neg = jit(self._I_neg)\n\n def _I_pos(self, params, U):\n axis = np.outer(np.linspace(0, 1, self.K)[1:], U)\n evals = self.distn(params).cdf(axis) ** 2\n return 0.5 * np.sum(evals[:self.K - 2] + evals[1:]) * U / self.K\n\n def _I_neg(self, params, U):\n axis = np.outer(np.linspace(0, 1, self.K)[1:], U)\n evals = (1 - self.distn(params).cdf(1 / axis) ** 2) / axis ** 2\n return 0.5 * np.sum(evals[:self.K - 2] + evals[1:]) * U / self.K\n\n def I_normal(self, Forecast, Y):\n S = Forecast.scale\n Y_std = (Y - Forecast.loc) / Forecast.scale\n norm2 = Normal([Forecast.loc, Forecast.scale / np.sqrt(2.)])\n ncdf = Forecast.cdf(Y)\n npdf = np.exp(Forecast.logpdf(Y))\n n2cdf = norm2.cdf(Y)\n return S * (Y_std * np.power(ncdf, 2) + 2 * ncdf * npdf * S -\n n2cdf / np.sqrt(np.pi))\n\n def __call__(self, forecast, Y):\n return forecast.crps(Y.squeeze())\n\n def metric(self, params, Y):\n if self.distn.has_crps_metric:\n return self.metric_fn(params)\n raise NotImplementedError\n\n def naturalize(self, params, grads):\n metric = self.metric_fn(params)\n nat_grads = onp.linalg.solve(metric, grads)\n weights = onp.power((grads * nat_grads).sum(axis=1, keepdims=True), -0.5)\n #return weights * nat_grads\n return nat_grads\n\n\nclass CRPS_SURV(CRPS):\n\n def __call__(self, forecast, Y):\n E = Y['Event']\n T = Y['Time']\n if isinstance(forecast, LogNormal):\n left = self.I_normal(Normal((forecast.loc, forecast.scale)), onp.log(T))\n right = self.I_normal(Normal((-forecast.loc, forecast.scale)), -onp.log(T))\n else:\n left = self.I_pos(forecast.params, T)\n right = self.I_neg(forecast.params, 1/T)\n return (left + E * right)\n\n","sub_path":"ngboost/scores.py","file_name":"scores.py","file_ext":"py","file_size_in_byte":4166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"263258351","text":"from enum import Enum\nfrom typing import Dict, Tuple, Union, Any\nimport logging\n\nimport simplejson as json\n\nfrom parser.download_current import download_current_flights_list, \\\n FlightStatusEnum, PLAN_URL\nfrom scripts.utils import get_db_conn, update_data, insert_data\n\n\nclass ChangeTypeEnum(Enum):\n DELETED = 1\n NEW = 2\n DATA_UPDATED = 3\n\n\ndef compare_downloaded_with_saved(user: dict, db_conn=None) -> Dict[int, tuple]:\n flights_changes = {}\n\n def compare(conn):\n cur = conn.cursor()\n new_data = download_current_flights_list(user)\n cur.execute(\n \"\"\"\n SELECT id, status, data FROM flights WHERE aviabit_user='{}'\n \"\"\".format(user['USERNAME'])\n )\n fetched_data = cur.fetchall()\n saved_data = {flight_id: (flight_status, flight_data)\n for flight_id, flight_status, flight_data\n in fetched_data} if fetched_data else {}\n for key in new_data.keys():\n if key not in saved_data:\n flights_changes[key] = (\n ChangeTypeEnum.NEW.value,\n new_data[key]\n )\n insert_data(user, {key: new_data[key]}, cur)\n logging.debug(\n \"\\n[DEBUG]NEW FLIGHT\"\n \"\\n[DEBUG]DATA - {}\".format(json.dumps(new_data[key]))\n )\n else:\n if saved_data[key] != new_data[key]:\n if saved_data[key][0] != new_data[key][0] \\\n and saved_data[key][1] == new_data[key][1]:\n pass\n logging.debug(\n \"\\n[DEBUG]STATUS CHANGED\"\n \"\\n[DEBUG]SAVED DATA - {}\"\n \"\\n[DEBUG]NEW DATA - {}\".format(\n json.dumps(saved_data[key]),\n json.dumps(new_data[key]))\n )\n else:\n flights_changes[key] = (\n ChangeTypeEnum.DATA_UPDATED.value,\n new_data[key],\n saved_data[key]\n )\n logging.debug(\n \"\\n[DEBUG]FLIGHT DATA CHANGED\"\n \"\\n[DEBUG]SAVED DATA - {}\"\n \"\\n[DEBUG]NEW DATA - {}\".format(\n json.dumps(saved_data[key]),\n json.dumps(new_data[key]))\n )\n update_data(user, {key: new_data[key]}, cur)\n for key in saved_data.keys():\n if key not in new_data:\n if (saved_data[key][0] not in\n (FlightStatusEnum.COMPLETED.value, FlightStatusEnum.IN_PROGRESS.value) and\n 'flight_number' in saved_data[key][1] and not\n saved_data[key][1]['flight_number'].startswith('~РЕЗ')):\n flights_changes[key] = (\n ChangeTypeEnum.DELETED.value,\n saved_data[key]\n )\n logging.debug(\n \"\\n[DEBUG]FLIGHT CANCELLED\"\n \"\\n[DEBUG]SAVED DATA - {}\".format(\n json.dumps(saved_data[key]))\n )\n cur.execute(\n \"\"\"\n DELETE FROM flights\n WHERE id = '{}' AND aviabit_user='{}'\n \"\"\".format(key, user['USERNAME'])\n )\n\n if db_conn:\n compare(db_conn)\n else:\n with get_db_conn() as db_conn:\n compare(db_conn)\n return flights_changes\n\n\ndef get_change_data(data: Tuple[int, Union[dict, Any]]):\n new_data = data[1][1]\n\n # normal flight record\n if data[1][0] is not None:\n if data[0] == ChangeTypeEnum.NEW.value:\n subject = 'Новый рейс {}, {}, {}-{}!'.format(\n new_data['flight_number'],\n new_data['flight_date'],\n new_data['flight_from'],\n new_data['flight_to']\n )\n body_data = [\n 'Номер рейса: {}\\n'.format(new_data['flight_number']),\n 'Когда: {}\\n'.format(new_data['flight_date']),\n 'Из: {}\\n'.format(new_data['flight_from']),\n 'В: {}\\n'.format(new_data['flight_to']),\n 'Планируемое время вылета: {}\\n'.format(new_data['flight_plan_time_from']),\n 'Планируемое время прилета: {}\\n'.format(new_data['flight_plan_time_to']),\n 'Тип самолета: {}\\n'.format(new_data['flight_plane_type']),\n 'Бортовой номер: {}\\n'.format(new_data['flight_plane_number']),\n 'Пилоты:\\n {}\\n'.format('\\n '.join(new_data['flight_pilots'])),\n 'Экипаж:\\n {}\\n'.format('\\n '.join(new_data['flight_cabin_crew']))\n ]\n elif data[0] == ChangeTypeEnum.DELETED.value:\n subject = 'Отмена рейса {}, {}, {}-{}!'.format(\n new_data['flight_number'],\n new_data['flight_date'],\n new_data['flight_from'],\n new_data['flight_to']\n )\n body_data = [\n 'Номер рейса: {}\\n'.format(new_data['flight_number']),\n 'Когда: {}\\n'.format(new_data['flight_date']),\n 'Из: {}\\n'.format(new_data['flight_from']),\n 'В: {}\\n'.format(new_data['flight_to']),\n 'Планируемое время вылета: {}\\n'.format(new_data['flight_plan_time_from']),\n 'Планируемое время прилета: {}\\n'.format(new_data['flight_plan_time_to']),\n 'Тип самолета: {}\\n'.format(new_data['flight_plane_type']),\n 'Бортовой номер: {}\\n'.format(new_data['flight_plane_number']),\n 'Пилоты:\\n {}\\n'.format('\\n '.join(new_data['flight_pilots'])),\n 'Экипаж:\\n {}\\n'.format('\\n '.join(new_data['flight_cabin_crew']))\n ]\n elif data[0] == ChangeTypeEnum.DATA_UPDATED.value:\n old_data = data[2][1]\n subject = 'Обновлен рейс {}, {}, {}-{}!'.format(\n new_data['flight_number'],\n new_data['flight_date'],\n old_data['flight_from'],\n old_data['flight_to']\n )\n body_data = []\n if new_data['flight_number'] != old_data['flight_number']:\n body_data.append('Старый номер рейса:\\n{}\\n'.format(old_data['flight_number']))\n body_data.append('Новый номер рейса:\\n{}\\n'.format(new_data['flight_number']))\n if new_data['flight_date'] != old_data['flight_date']:\n body_data.append('Старая дата вылета:\\n{}\\n'.format(old_data['flight_date']))\n body_data.append('Новая дата вылета:\\n{}\\n'.format(new_data['flight_date']))\n if new_data['flight_from'] != old_data['flight_from']:\n body_data.append('Старый аэропорт отправления:\\n{}\\n'.format(old_data['flight_from']))\n body_data.append('Новый аэропорт отправления:\\n{}\\n'.format(new_data['flight_from']))\n if new_data['flight_to'] != old_data['flight_to']:\n body_data.append('Старый аэропорт назначения:\\n{}\\n'.format(old_data['flight_to']))\n body_data.append('Новый аэропорт назначения:\\n{}\\n'.format(new_data['flight_to']))\n if new_data['flight_plan_time_from'] != old_data['flight_plan_time_from']:\n body_data.append('Старое планируемое время вылета:\\n{}\\n'.format(old_data['flight_plan_time_from']))\n body_data.append('Новое планируемое время вылета:\\n{}\\n'.format(new_data['flight_plan_time_from']))\n if new_data['flight_plan_time_to'] != old_data['flight_plan_time_to']:\n body_data.append('Старое планируемое время прилета:\\n{}\\n'.format(old_data['flight_plan_time_to']))\n body_data.append('Новое планируемое время прилета:\\n{}\\n'.format(new_data['flight_plan_time_to']))\n if new_data['flight_plane_type'] != old_data['flight_plane_type']:\n body_data.append('Старый тип самолета:\\n{}\\n'.format(old_data['flight_plane_type']))\n body_data.append('Новый тип самолета:\\n{}\\n'.format(new_data['flight_plane_type']))\n if new_data['flight_plane_number'] != old_data['flight_plane_number']:\n body_data.append('Старый бортовой номер: \\n{}\\n'.format(old_data['flight_plane_number']))\n body_data.append('Новый бортовой номер: \\n{}\\n'.format(new_data['flight_plane_number']))\n if new_data['flight_pilots'] != old_data['flight_pilots']:\n removed = set(old_data['flight_pilots']) - set(new_data['flight_pilots'])\n added = set(new_data['flight_pilots']) - set(old_data['flight_pilots'])\n body_data.append('Измнения в составе пилотов:\\n')\n if added:\n for item in added:\n body_data.append(f'+ {item}\\n')\n if removed:\n for item in removed:\n body_data.append(f'- {item}\\n')\n body_data.append('\\nТекущий состав пилотов:\\n')\n body_data.append('\\n'.join(new_data['flight_pilots']))\n if new_data['flight_cabin_crew'] != old_data['flight_cabin_crew']:\n removed = set(old_data['flight_cabin_crew']) - set(new_data['flight_cabin_crew'])\n added = set(new_data['flight_cabin_crew']) - set(old_data['flight_cabin_crew'])\n body_data.append('Изменения в составе экипажа:\\n')\n if added:\n for item in added:\n body_data.append(f'+ {item}\\n')\n if removed:\n for item in removed:\n body_data.append(f'- {item}\\n')\n body_data.append('\\nТекущий состав экипажа:\\n')\n body_data.append('\\n'.join(new_data['flight_cabin_crew']))\n else:\n subject = 'В оповещениях что-то сломалось!'\n body_data = ['Вам лучше проверить план вручную.']\n\n # non-flight record\n else:\n if data[0] == ChangeTypeEnum.NEW.value:\n subject = f\"Новое событие: {new_data['what']} {new_data['start']}-{new_data['end']}!\"\n body_data = [\n f\"Событие: {new_data['what']}\\n\",\n f\"Начало: {new_data['start']}\\n\",\n f\"Конец: {new_data['end']}\\n\",\n f\"Причина: {new_data.get('reason', '-')}\\n\",\n ]\n if 'additional_info' in new_data:\n body_data.append('\\nДополнительная информация:\\n')\n for line in new_data['additional_info']:\n body_data.append(line)\n body_data.append('\\n')\n\n elif data[0] == ChangeTypeEnum.DELETED.value:\n old_data = data[2][1]\n subject = f\"Отмена: {old_data['what']} {old_data['start']}-{old_data['end']}!\"\n body_data = [\n f\"Отменено событие: {old_data['what']}\\n\",\n f\"Начало: {old_data['start']}\\n\",\n f\"Конец: {old_data['end']}\\n\",\n f\"Причина: {old_data['reason']}\\n\",\n ]\n elif data[0] == ChangeTypeEnum.DATA_UPDATED.value:\n old_data = data[2][1]\n body_data = []\n subject = f\"Обновлено событие - {new_data['what']} {new_data['start']}-{new_data['end']}\"\n if new_data['start'] != old_data['start']:\n body_data.append('\\nИзменение времени начала:\\n')\n body_data.append(f\"+ {new_data['start']}\\n\")\n body_data.append(f\"- {old_data['start']}\\n\")\n if new_data['end'] != old_data['end']:\n body_data.append('\\nИзменение времени начала:\\n')\n body_data.append(f\"+ {new_data['end']}\\n\")\n body_data.append(f\"- {old_data['end']}\\n\")\n if 'reason' in new_data and 'reason' in old_data:\n if new_data['reason'] != old_data['reason']:\n body_data.append('\\nИзменение причины:\\n')\n body_data.append(f\"+ {new_data['reason']}\\n\")\n body_data.append(f\"- {old_data['reason']}\\n\")\n if 'additional_info' in new_data and (new_data['additional_info'] != old_data['additional_info']):\n body_data.append('\\nИзмененная дополнительная информация:\\n')\n for line in new_data['additional_info']:\n body_data.append(line)\n body_data.append('\\n')\n\n body_data.append(f'\\n\\nТекущий список рейсов: {PLAN_URL}')\n\n return subject, body_data\n","sub_path":"parser/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":13769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"265512722","text":"# TMD_Scales\n\"\"\" 1. Get physicochemical scales\n 2. Normalize physicochemical scales\"\"\"\nimport pandas as pd\nimport os\nimport AA_Index_Dictionary as scale\nimport Configfile as config\n\n# Folder\nfolder_scales = config.folder_scales\nfolder_norm_scales = os.path.join(folder_scales, '/AA_Scales/Normalized_Scales/')\na_description = config.a_description\ns_description = config.s_description\nfile_list = config.file_list\nAA_code = config.AA_code\nall_scales_df, all_scales_dict = scale.get_scales(a_description, file_list, AA_code)\nall_descriptions_df, all_descriptions_dict = scale.get_description(a_description, s_description)\n\n# I Helper Functions\n\n# II Main Functions\n\n# 1. Normalize Scales\ndef get_norm_scales():\n \"\"\"Get normalized scales as df and dict\"\"\"\n norm_scale_list = []\n norm_scale_dict = {}\n for i in all_scales_df:\n norm_scale_dict[i] = {}\n # 1. Convert all values of series to float\n series = all_scales_df.loc[:, i].apply(lambda x: float(x))\n # 2. Min_Max_Normalization function\n min = (series.min())\n max = (series.max())\n dist = (abs(min - max))\n f = lambda x: ((float(x) - min) / dist).round(decimals=5)\n # 3. Normalize all elements\n normalized_scale = all_scales_df.loc[:, i].apply(f)\n # 4. Save scale series in list\n norm_scale_list.append(normalized_scale)\n # 5a. Convert scale series in dict & save in dict\n norm_scale_dict[i] = normalized_scale.to_dict()\n\n # 5b. Merge scale series to one dataframe and save\n norm_scale_df = pd.concat(norm_scale_list, axis=1)\n # norm_scale_df.to_excel(folder_norm_scales + 'all_scales_norm.xlsx')\n\n return norm_scale_df, norm_scale_dict\n\n\n# 2 Get class of amino acid group\n# 1. Import files of sequence\ndef import_excel_seq(file):\n \"\"\"Import of Sequences in excel sheet via pandas\n returns Sequence and Name of UniprotID\n a) Length of dictionary different to number of IDs, if some IDs equal\n b) If no ID (else) comment out, because wrong counter possible\"\"\"\n df = pd.read_excel(file)\n count = 0\n id_sequence = {}\n id_name = {}\n for i in df[\"UniprotID\"]:\n seq_nan = (\n str(df[\"N-Ter-6\"][count])\n + str(df[\"N-Ter\"][count])\n + str(df[\"TMD\"][count])\n + str(df[\"C-Ter-3\"][count])\n + str(df[\"C-Ter-6\"][count])\n )\n seq = seq_nan.replace(\"nan\", \"\") # nan (no value) replaced by \"\"\n id_sequence[df[\"UniprotID\"][count]] = seq\n id_name[df[\"UniprotID\"][count]] = df[\"Name\"][count]\n count += 1\n\n return (id_sequence, id_name, df)\n\n\n# 2.2 Get average amino acid distribution\ndef get_average_aa_distribution(file):\n \"\"\" Get average amino acid distribution\n for one homogeneous data set\n (meaning either sub or non-sub)\"\"\"\n # 1. Get one list of amino acids of all sequences\n id_sequence, id_name, df_sequence = import_excel_seq(file)\n id_seq_series = pd.Series(id_sequence)\n aa_list = []\n for seq in id_seq_series:\n for aa in seq:\n aa_list.append(aa)\n\n # 2. Count amino acids in list\n aa_series = pd.Series(aa_list)\n aa_distrib = (aa_series.value_counts()) # Count of values\n aa_distrib_per_tmd = aa_distrib.div(len(id_seq_series)).round(3) # Normalized by number of Proteins\n aa_distrib_per_aa = aa_distrib.div(len(aa_series)).round(3)\n\n return aa_distrib_per_tmd, aa_distrib_per_aa\n\n\n# 2.3 Groups of amino acids (Tyler)\nclass AA_Group:\n def __init__(self, name):\n self.name = \"Groups of amino acids by Taoyler\"\n\n # 1. Get dicitonary of classes\n \"\"\"\n polar_neutral = {aa: \"polar_neutral\" for aa in ['S', 'T', 'C', 'Q', 'N', 'Y']}\n nonpolar = {aa: \"nonpolar\" for aa in ['P', 'M', 'A', 'L', 'I', 'V', 'W', 'F', 'G']}\n acid = {aa: \"acid\" for aa in ['E', 'D']}\n basic = {aa: \"basic\" for aa in ['H', 'R', 'K']} \n \"\"\"\n polar_neutral = {aa: \"Polar\" for aa in ['S', 'T', 'C', 'Q', 'N', 'G']}\n aromatic = {aa: \"Aromatic\" for aa in ['W', 'F', 'Y']}\n nonpolar = {aa: \"Nonpolar\" for aa in ['P', 'M', 'A', 'L', 'I', 'V']}\n acid = {aa: \"Acid\" for aa in ['E', 'D']}\n basic = {aa: \"Basic\" for aa in ['H', 'R', 'K']}\n\n list_dict = [nonpolar, acid, basic]\n\n def merge_dicts(dictionary, list_dict):\n \"\"\"Helper function: Merge of two dictionaries\"\"\"\n z = dictionary.copy()\n for i in list_dict:\n z.update(i)\n return z\n\n aa_classes = merge_dicts(polar_neutral, list_dict)\n\n # 2. Get information about classes\n def aa_destribution_description(self, file):\n aa_distrib_normal, aa_distrib_aa = get_average_aa_distribution(file) # normalized amino acid\n aa_distrib_dict = aa_distrib_normal.to_dict()\n aa_distrib_df = pd.DataFrame(aa_distrib_dict, index=[1, 2]).iloc[1, :]\n description = aa_distrib_df.groupby(self.aa_classes).describe().round(2) # Description of classification\n return description\n\n # Classes dictionary\n\n# III Summary Functions\n\n# IV Test Functions\ndef main():\n # Issue ad missing number\n norm_scale_df, norm_scale_dict = get_norm_scales()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"TMD_Scales.py","file_name":"TMD_Scales.py","file_ext":"py","file_size_in_byte":5205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"60092306","text":"# PROBLEM 1\n# Create a variable that holds the value of your first name.\nfirst_name = \"Brendan\"\n\n# PROBLEM 2\n# Create a variable that holds the value of your favorite number.\nfav_number = 4\n\n# PROBLEM 3\n# Create a variable that holds a boolean value representing if your hair is brown.\nbrown_hair = False\n\n# PROBLEM 4\n# Print your first name, by printing the variable created in problem 1.\nprint(first_name)\n\n# PROBLEM 5\n# Create a variable called `loves_code` and set it equal to true. \n# Check to see if `loves_code` is equal to true or false. \n# If it is true, print \"I love to code!\"\n# If it is not, print \"Coding has it's challenges.\"\nloves_code = True\n\nif loves_code == True:\n print(\"I love to code!\")\nelse: \n print(\"Coding has its challenges.\")\n\n# PROBLEM 6\n# Create an array called `colors` and set it equal to a list of at least five colors.\ncolors = [\"blue\", \"green\", \"orange\", \"yellow\", \"purple\"]\n\n# Problem 7\n# Using bracket syntax, print out the last item in your colors array.\nprint(colors[4])\n\n# For problems 8-9, use the following line of code:\nnumbers = [1,2,3,4,5,6,7,8,9,10]\n\n# Problem 8\n# Use a for-in loop to iterate over the `numbers` array and print each number.\nfor number in numbers:\n print(number)\n\n# Problem 9\n# Create an empty array called `even_numbers`.\n# Use a for-in loop to iterate over the `numbers` array, and if a number is even, add it to the `even_numbers` array.\neven_numbers = []\n\nfor number in numbers:\n if number % 2 == 0:\n even_numbers.append(number)\n\nprint(even_numbers)\n\n# Problem 10\n# Do not edit the code below.\nscore = 74\n# Do not edit the code above.\n\n# Determine if the letter grade of the given variable 'score'. If the variable is a 90 or above, console-log an 'A', between 80 and 89, console-log a 'B', between 70 and 79, 'C', between 60 and 69, 'D', and anything below 60 should console-log an 'F'.\nif score >= 90:\n print(\"A\")\nelif score >= 80 and score < 90:\n print(\"B\")\nelif score >= 70 and score < 80:\n print(\"C\")\nelif score >= 60 and score < 70:\n print(\"D\")\nelse:\n print(\"F\")\n\n# Problem 11\n# Create a variable called 'changeMyMind' and set it equal to true. \n# Check to see if changeMyMind is set to true or false, if it is true, change the status to false, if it is false, change the status to true.\nchange_my_mind = True\nif change_my_mind == True:\n change_my_mind = False\nelse:\n change_my_mind = True\n# print(change_my_mind)\n# ADVANCED\n\n# For problems 12-15, use the following line of code:\nfriends = ['Joe', 'Sally', 'Camilo', 'Perry', 'Susan']\n\n# Problem 12\n# Research to find the Python method that allows you to add an element to the end of the array (similar to push() in javascript), then add a name to the end of the `friends` array.\nfriends.append('George')\n# print(friends)\n# Problem 13\n# Print out the total amount of elements in the `friends` array. The Python method you are looking for is similar to the javascript property `.length`.\nlen(friends)\n# print(len(friends))\n# Problem 14\n# Add a name into the third position in the array (index 2). Make sure you are not overwriting the value that is already there.\nfriends.insert(2, \"Harold\")\n# print(friends)\n# Problem 15\n# Remove the last item in the array (try to think about how you can do this dynamically, meaning, if the array contents were to change, your code would still work).\nfriends.pop()\n# print(friends)","sub_path":"starter.py","file_name":"starter.py","file_ext":"py","file_size_in_byte":3382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"547346527","text":"# Copyright 2017 Mirantis, Inc.\n# All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom django.template.defaultfilters import title\nfrom django.urls import reverse\nfrom django.utils.http import urlencode\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\nfrom django.utils.translation import pgettext_lazy\nfrom horizon import exceptions\nfrom horizon import tables\nfrom horizon.utils import filters\n\nfrom manila_ui.api import manila\n\n\nclass UpdateShareGroupSnapshot(tables.LinkAction):\n name = \"update_share_group_snapshot\"\n verbose_name = _(\"Update\")\n url = \"horizon:project:share_group_snapshots:update\"\n classes = (\"ajax-modal\", \"btn-camera\")\n\n def allowed(self, request, share_group_snapshot=None):\n return share_group_snapshot.status in (\"available\", \"error\")\n\n\nclass CreateShareGroupSnapshot(tables.LinkAction):\n name = \"create_share_group_snapshot\"\n verbose_name = _(\"Create Share Group Snapshot\")\n url = \"horizon:project:share_group_snapshots:create\"\n classes = (\"ajax-modal\", \"btn-camera\")\n\n def allowed(self, request, share_group=None):\n self.verbose_name = _(\"Create Share Group Snapshot\")\n classes = [c for c in self.classes if c != \"disabled\"]\n self.classes = classes\n return share_group.status == \"available\"\n\n\nclass CreateShareGroupFromSnapshot(tables.LinkAction):\n name = \"create_share_group_from_snapshot\"\n verbose_name = _(\"Create Share Group\")\n url = \"horizon:project:share_groups:create\"\n classes = (\"ajax-modal\", \"btn-camera\")\n\n def get_link_url(self, datum):\n base_url = reverse(self.url)\n params = urlencode({\n \"snapshot_id\": self.table.get_object_id(datum)})\n return \"?\".join([base_url, params])\n\n def allowed(self, request, share_group=None):\n return share_group.status == \"available\"\n\n\nclass ShareGroupSnapshotShareGroupNameColumn(tables.Column):\n def get_link_url(self, snapshot):\n return reverse(self.link, args=(snapshot.share_group_id,))\n\n\nclass DeleteShareGroupSnapshot(tables.DeleteAction):\n\n @staticmethod\n def action_present(count):\n return ngettext_lazy(\n u\"Delete Share Group Snapshot\",\n u\"Delete Share Group Snapshots\",\n count\n )\n\n @staticmethod\n def action_past(count):\n return ngettext_lazy(\n u\"Deleted Share Group Snapshot\",\n u\"Deleted Share Group Snapshots\",\n count\n )\n\n def delete(self, request, obj_id):\n obj = self.table.get_object_by_id(obj_id)\n name = self.table.get_object_display(obj)\n try:\n manila.share_group_snapshot_delete(request, obj_id)\n except Exception:\n msg = _('Unable to delete share group snapshot \"%s\". '\n 'One or more share groups depend on it.')\n exceptions.handle(self.request, msg % name)\n raise\n\n def allowed(self, request, snapshot=None):\n if snapshot:\n return snapshot.status.lower() in ('available', 'error')\n return True\n\n\nclass UpdateShareGroupSnapshotRow(tables.Row):\n ajax = True\n\n def get_data(self, request, share_group_snapshot_id):\n snapshot = manila.share_group_snapshot_get(\n request, share_group_snapshot_id)\n if not snapshot.name:\n snapshot.name = share_group_snapshot_id\n return snapshot\n\n\nclass ShareGroupSnapshotsTable(tables.DataTable):\n STATUS_CHOICES = (\n (\"available\", True),\n (\"creating\", None),\n (\"error\", False),\n )\n STATUS_DISPLAY_CHOICES = (\n (\"available\",\n pgettext_lazy(\"Current status of snapshot\", u\"Available\")),\n (\"creating\", pgettext_lazy(\"Current status of snapshot\", u\"Creating\")),\n (\"error\", pgettext_lazy(\"Current status of snapshot\", u\"Error\")),\n )\n name = tables.WrappingColumn(\n \"name\", verbose_name=_(\"Name\"),\n link=\"horizon:project:share_group_snapshots:detail\")\n description = tables.Column(\n \"description\",\n verbose_name=_(\"Description\"),\n truncate=40)\n created_at = tables.Column(\n \"created_at\",\n verbose_name=_(\"Created at\"),\n filters=(\n filters.parse_isotime,\n ))\n status = tables.Column(\n \"status\",\n filters=(title,),\n verbose_name=_(\"Status\"),\n status=True,\n status_choices=STATUS_CHOICES,\n display_choices=STATUS_DISPLAY_CHOICES)\n source = ShareGroupSnapshotShareGroupNameColumn(\n \"share_group\",\n verbose_name=_(\"Source\"),\n link=\"horizon:project:share_groups:detail\")\n\n def get_object_display(self, obj):\n return obj.name\n\n class Meta(object):\n name = \"share_group_snapshots\"\n verbose_name = _(\"Share Group Snapshots\")\n status_columns = [\"status\"]\n row_class = UpdateShareGroupSnapshotRow\n table_actions = (\n tables.NameFilterAction,\n DeleteShareGroupSnapshot,\n )\n row_actions = (\n CreateShareGroupFromSnapshot,\n UpdateShareGroupSnapshot,\n DeleteShareGroupSnapshot,\n )\n","sub_path":"manila_ui/dashboards/project/share_group_snapshots/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":5708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"74312021","text":"# -*- coding: utf-8 -*-\n\n\nfrom datetime import datetime\n\nfrom django.core.exceptions import ValidationError, ImproperlyConfigured\nfrom django.db import models\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nfrom django.utils.text import slugify\nfrom mock import MagicMock, patch\nfrom faker import Faker\n\nfrom core.tests.test_models import TestSlugifiedName\nfrom core.utils import (validate_file_upload_size, get_max_mb,\n randomize_filename, user_directory_path,\n profile_pics_upload_path, hiker_photos_upload_path,\n hike_directory_path, hike_photo_upload_path,\n trail_map_upload_path, get_file_attr,\n validate_file_has_extension, unique_slugify,\n unicode_by_title_hike_or_date, truncate_slug_text)\n\nfrom hikers.tests.factories import HikerFactory\n\n\nclass TestSlugifying(models.Model):\n name = models.CharField(max_length=25)\n slug = models.SlugField(blank=True)\n\n class Meta:\n app_label = 'core'\n\n\nclass CoreUtilsTests(TestCase):\n\n def test_get_file_attr(self):\n mock_upload_obj = 'CharField'\n with self.assertRaises(ImproperlyConfigured):\n get_file_attr(mock_upload_obj)\n\n mock_upload_obj = MagicMock()\n mock_upload_obj.file = MagicMock()\n self.assertEquals(get_file_attr(mock_upload_obj), mock_upload_obj.file)\n\n @patch('core.utils.get_file_attr')\n @patch('core.utils.get_max_mb')\n def test_validate_file_upload_size(self, mock_max_mb, mock_file_attr):\n mock_upload_obj = MagicMock()\n mock_file = MagicMock()\n mock_file.size = 6 * 1024 * 1024\n mock_file_attr.return_value = mock_file\n mock_max_mb.return_value = 5\n with self.assertRaises(ValidationError):\n validate_file_upload_size(mock_upload_obj)\n\n @override_settings(MAX_UPLOAD_SIZE_IN_MB=4)\n def test_get_max_mb_with_settings(self):\n mb_size = None\n self.assertEquals(get_max_mb(mb_size), 4)\n mb_size = 3\n self.assertEquals(get_max_mb(mb_size), 3)\n mb_size = 5\n self.assertEquals(get_max_mb(mb_size), 4)\n\n def test_get_max_nb_without_settings(self):\n mb_size = None\n with self.assertRaises(ImproperlyConfigured):\n get_max_mb(mb_size)\n mb_size = 7\n self.assertEquals(get_max_mb(mb_size), mb_size)\n\n def test_randomize_filename(self):\n name = 'myrandomfile'\n ext = 'jpg'\n filename = '{}.{}'.format(name, ext)\n self.assertNotIn(name, randomize_filename(filename))\n self.assertIn(ext, randomize_filename(filename))\n\n @patch('core.utils.get_file_attr')\n def test_validate_file_ext(self, mock_file_attr):\n name = 'myrandomfile'\n mock_upload_obj = MagicMock()\n mock_file = MagicMock()\n mock_file.name = name\n mock_file_attr.return_value = mock_file\n with self.assertRaises(ValidationError):\n validate_file_has_extension(mock_upload_obj)\n\n def test_user_directory_path(self):\n instance = TestSlugifiedName()\n with self.assertRaises(ImproperlyConfigured):\n user_directory_path(instance)\n\n instance = HikerFactory()\n self.assertIn(instance.slug, user_directory_path(instance))\n\n instance = MagicMock()\n instance.hiker = MagicMock()\n instance.hiker.slug = 'hiker-slug'\n self.assertIn(instance.hiker.slug, user_directory_path(instance))\n\n @patch('core.utils.user_directory_path')\n @patch('core.utils.randomize_filename')\n def test_profile_pics_upload_path(self, mock_file_name, mock_path):\n mock_file_name.return_value = 'file-name'\n mock_path.return_value = 'user/path'\n self.assertIn('profile_pics',\n profile_pics_upload_path('instance', 'filename'))\n\n @patch('core.utils.user_directory_path')\n @patch('core.utils.randomize_filename')\n def test_hiker_photos_upload_path(self, mock_file_name, mock_path):\n mock_file_name.return_value = 'file-name'\n mock_path.return_value = 'user/path'\n self.assertIn('hike_photos',\n hiker_photos_upload_path('instance', 'filename'))\n\n def test_hike_directory_path(self):\n instance = TestSlugifiedName()\n with self.assertRaises(ImproperlyConfigured):\n hike_directory_path(instance)\n instance = MagicMock()\n instance.hike = MagicMock()\n instance.hike.slug = 'hike-slug'\n instance.hike.trailhead = MagicMock()\n instance.hike.trailhead.slug = 'trailhead-slug'\n instance.hike.trailhead.region = MagicMock()\n instance.hike.trailhead.region.slug = 'region-slug'\n self.assertIn('hikes', hike_directory_path(instance))\n\n @patch('core.utils.hike_directory_path')\n @patch('core.utils.randomize_filename')\n def test_trail_map_upload_path(self, mock_file_name, mock_path):\n mock_file_name.return_value = 'file-name'\n mock_path.return_value = 'hike/path'\n self.assertIn('trail_maps',\n trail_map_upload_path('instance', 'filename'))\n\n @patch('core.utils.hike_directory_path')\n @patch('core.utils.randomize_filename')\n def test_hike_photo_upload_path(self, mock_file_name, mock_path):\n mock_file_name.return_value = 'file-name'\n mock_path.return_value = 'hike/path'\n self.assertIn('photos',\n hike_photo_upload_path('instance', 'filename'))\n\n def test_unique_slugify(self):\n name = 'Non-unique name'\n slug1 = TestSlugifying.objects.create(name=name)\n slug2 = TestSlugifying.objects.create(name=name)\n slugqs = TestSlugifying.objects.all()\n unique_slug = unique_slugify(slugqs, name)\n self.assertEquals(slugify(name), unique_slug)\n slug1.slug = unique_slug\n slug1.save()\n unique_slug2 = unique_slugify(slugqs, name)\n self.assertIn('1', unique_slug2)\n slug2.slug = slugify('{}-{}'.format(name, 2))\n slug2.save()\n unique_slug3 = unique_slugify(slugqs, name)\n self.assertIn('3', unique_slug3)\n\n def test_unicode_by_title_hike_or_date(self):\n\n class TestBadUnicodeMethod(models.Model):\n foo = models.CharField(max_length=25)\n\n def __unicode__(self):\n return unicode_by_title_hike_or_date(self)\n\n obj = TestBadUnicodeMethod(foo='bar')\n with self.assertRaises(ImproperlyConfigured):\n obj.__unicode__()\n\n date_fmt = '%Y-%m-%d'\n uni_date = datetime.today().strftime(date_fmt)\n obj = MagicMock()\n obj.title = 'Title'\n obj.hike.name = 'Hike Name'\n self.assertIn(obj.title, unicode_by_title_hike_or_date(obj))\n self.assertIn(obj.hike.name, unicode_by_title_hike_or_date(obj))\n\n obj.hike = None\n obj.created = datetime.today()\n self.assertIn(obj.title, unicode_by_title_hike_or_date(obj))\n self.assertIn(obj.created.strftime(date_fmt),\n unicode_by_title_hike_or_date(obj))\n\n obj.title = ''\n obj.hike = MagicMock()\n obj.hike.name = 'New Hike Name'\n self.assertIn(obj.hike.name, unicode_by_title_hike_or_date(obj))\n self.assertIn(obj.created.strftime(date_fmt),\n unicode_by_title_hike_or_date(obj))\n\n obj.pk = ''\n obj.title = ''\n obj.hike = None\n obj.created = None\n self.assertIn(uni_date, unicode_by_title_hike_or_date(obj))\n\n def test_truncate_slug_text(self):\n fake = Faker()\n begin = fake.text(max_nb_chars=200)\n mid1 = fake.text(max_nb_chars=25)\n mid2 = fake.text(max_nb_chars=25)\n date_fmt = '%Y-%m-%d'\n end_date = datetime.today().strftime(date_fmt)\n slug_text = fake.text(max_nb_chars=50)\n self.assertEquals(slug_text, truncate_slug_text(slug_text))\n\n slug_from_begin = truncate_slug_text(begin)\n self.assertNotEquals(begin, slug_from_begin)\n self.assertIn(slug_from_begin, begin)\n self.assertTrue(len(slug_from_begin) <= 50)\n\n slug_text = '{} - {}'.format(begin, end_date)\n slug_from_begin_date = truncate_slug_text(slug_text)\n self.assertIn(end_date, slug_from_begin_date)\n self.assertTrue(len(slug_from_begin_date) <= 50)\n\n slug_text = '{} - {} - {} - {}'.format(begin, mid1, mid2, end_date)\n slug_from_many = truncate_slug_text(slug_text)\n self.assertIn(mid1[:9], slug_from_many)\n self.assertNotIn(mid2[:9], slug_from_many)\n self.assertTrue(len(slug_from_many) <= 50)\n","sub_path":"core/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":8684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"192073262","text":"from .verilog_modeling import Bel, Site\n\n\ndef get_clb_site(db, grid, tile, site):\n \"\"\" Return the prjxray.tile.Site object for the given CLB site. \"\"\"\n gridinfo = grid.gridinfo_at_tilename(tile)\n tile_type = db.get_tile_type(gridinfo.tile_type)\n\n sites = sorted(tile_type.get_instance_sites(gridinfo), key=lambda x: x.x)\n\n return sites[int(site[-1])]\n\n\ndef get_lut_init(site, lut):\n \"\"\" Return the INIT value for the specified LUT. \"\"\"\n init = site.decode_multi_bit_feature('{}LUT.INIT'.format(lut))\n return \"64'b{:064b}\".format(init)\n\n\ndef get_shifted_lut_init(site, lut, shift=0):\n \"\"\" Return the shifted INIT value as integer. The init input is a string.\"\"\"\n init = get_lut_init(site, lut)\n int_init = int(init.split('b')[-1], 2)\n\n return int_init << shift\n\n\ndef create_lut(site, lut):\n \"\"\" Create the BEL for the specified LUT. \"\"\"\n bel = Bel('LUT6_2', lut + 'LUT', priority=3)\n bel.set_bel(lut + '6LUT')\n\n for idx in range(6):\n site.add_sink(bel, 'I{}'.format(idx), '{}{}'.format(lut, idx + 1))\n\n site.add_internal_source(bel, 'O6', lut + 'O6')\n site.add_internal_source(bel, 'O5', lut + 'O5')\n\n return bel\n\n\ndef get_srl32_init(site, srl):\n\n lut_init = get_lut_init(site, srl)\n bits = lut_init.replace(\"64'b\", \"\")\n\n assert bits[1::2] == bits[::2]\n\n return \"32'b{}\".format(bits[::2])\n\n\ndef create_srl32(site, srl):\n bel = Bel('SRLC32E', srl + 'SRL', priority=2)\n bel.set_bel(srl + '6LUT')\n\n site.add_sink(bel, 'CLK', 'CLK')\n site.add_sink(bel, 'D', '{}I'.format(srl))\n\n for idx in range(5):\n site.add_sink(bel, 'A[{}]'.format(idx), '{}{}'.format(srl, idx + 2))\n\n site.add_internal_source(bel, 'Q', srl + 'O6')\n\n return bel\n\n\ndef get_srl16_init(site, srl):\n \"\"\"\n Decodes SRL16 INIT parameter. Returns two initialization strings, each one\n for one of two SRL16s.\n \"\"\"\n\n lut_init = get_lut_init(site, srl)\n bits = lut_init.replace(\"64'b\", \"\")\n\n assert bits[1::2] == bits[::2]\n\n srl_init = bits[::2]\n return \"16'b{}\".format(srl_init[:16]), \"16'b{}\".format(srl_init[16:])\n\n\ndef create_srl16(site, srl, srl_type, part):\n \"\"\"\n Create an instance of SRL16 bel. Either for \"x6LUT\" or for \"x5LUT\"\n depending on the part parameter.\n \"\"\"\n\n assert part == '5' or part == '6'\n\n bel = Bel(srl_type, srl + part + 'SRL', priority=2)\n bel.set_bel(srl + part + 'LUT')\n\n site.add_sink(bel, 'CLK', 'CLK')\n\n if part == '5':\n site.add_sink(bel, 'D', '{}I'.format(srl))\n if part == '6':\n site.add_sink(bel, 'D', '{}X'.format(srl))\n\n for idx in range(4):\n site.add_sink(bel, 'A{}'.format(idx), '{}{}'.format(srl, idx + 2))\n\n site.add_internal_source(bel, 'Q', srl + 'O' + part)\n\n return bel\n\n\ndef decode_dram(site):\n \"\"\" Decode the modes of each LUT in the slice based on set features.\n\n Returns dictionary of lut position (e.g. 'A') to lut mode.\n \"\"\"\n lut_ram = {}\n lut_small = {}\n for lut in 'ABCD':\n lut_ram[lut] = site.has_feature('{}LUT.RAM'.format(lut))\n lut_small[lut] = site.has_feature('{}LUT.SMALL'.format(lut))\n\n di = {}\n for lut in 'ABC':\n di[lut] = site.has_feature('{}LUT.DI1MUX.{}I'.format(lut, lut))\n\n lut_modes = {}\n if site.has_feature('WA8USED'):\n assert site.has_feature('WA7USED')\n assert lut_ram['A']\n assert lut_ram['B']\n assert lut_ram['C']\n assert lut_ram['D']\n\n lut_modes['A'] = 'RAM256X1S'\n lut_modes['B'] = 'RAM256X1S'\n lut_modes['C'] = 'RAM256X1S'\n lut_modes['D'] = 'RAM256X1S'\n return lut_modes\n\n if site.has_feature('WA7USED'):\n if not lut_ram['A']:\n assert not lut_ram['B']\n assert lut_ram['C']\n assert lut_ram['D']\n lut_modes['A'] = 'LUT'\n lut_modes['B'] = 'LUT'\n lut_modes['C'] = 'RAM128X1S'\n lut_modes['D'] = 'RAM128X1S'\n\n return lut_modes\n\n assert lut_ram['B']\n\n if di['B']:\n lut_modes['A'] = 'RAM128X1S'\n lut_modes['B'] = 'RAM128X1S'\n lut_modes['C'] = 'RAM128X1S'\n lut_modes['D'] = 'RAM128X1S'\n else:\n assert lut_ram['B']\n assert lut_ram['C']\n assert lut_ram['D']\n\n lut_modes['A'] = 'RAM128X1D'\n lut_modes['B'] = 'RAM128X1D'\n lut_modes['C'] = 'RAM128X1D'\n lut_modes['D'] = 'RAM128X1D'\n\n return lut_modes\n\n all_ram = all(lut_ram[lut] for lut in 'ABCD')\n all_small = all(lut_small[lut] for lut in 'ABCD')\n\n if all_ram and not all_small:\n return {'D': 'RAM64M'}\n elif all_ram and all_small:\n return {'D': 'RAM32M'}\n else:\n # Remaining modes:\n # RAM32X1S, RAM32X1D, RAM64X1S, RAM64X1D\n remaining = set('ABCD')\n\n for lut in 'AC':\n if lut_ram[lut] and di[lut]:\n remaining.remove(lut)\n\n if lut_small[lut]:\n lut_modes[lut] = 'RAM32X1S'\n else:\n lut_modes[lut] = 'RAM64X1S'\n\n for lut in 'BD':\n if not lut_ram[lut]:\n continue\n\n minus_one = chr(ord(lut) - 1)\n if minus_one in remaining:\n if lut_ram[minus_one]:\n remaining.remove(lut)\n remaining.remove(minus_one)\n if lut_small[lut]:\n lut_modes[lut] = 'RAM32X1D'\n lut_modes[minus_one] = 'RAM32X1D'\n else:\n lut_modes[lut] = 'RAM64X1D'\n lut_modes[minus_one] = 'RAM64X1D'\n\n if lut in remaining:\n remaining.remove(lut)\n if lut_small[lut]:\n lut_modes[lut] = 'RAM32X1S'\n else:\n lut_modes[lut] = 'RAM64X1S'\n\n for lut in remaining:\n lut_modes[lut] = 'LUT'\n\n return lut_modes\n\n\ndef ff_bel(site, lut, ff5):\n \"\"\" Returns FF information for given FF.\n\n site (Site): Site object\n lut (str): FF in question (e.g. 'A')\n ff5 (bool): True if the 5FF versus the FF.\n\n Returns tuple of (module name, clock pin, clock enable pin, reset pin,\n init parameter).\n\n \"\"\"\n ffsync = site.has_feature('FFSYNC')\n latch = site.has_feature('LATCH') and not ff5\n zrst = site.has_feature('{}{}FF.ZRST'.format(lut, '5' if ff5 else ''))\n zini = site.has_feature('{}{}FF.ZINI'.format(lut, '5' if ff5 else ''))\n init = int(not zini)\n\n if latch:\n assert not ffsync\n\n return {\n (False, False, False): ('FDPE', 'C', 'CE', 'PRE', init),\n (True, False, False): ('FDSE', 'C', 'CE', 'S', init),\n (True, False, True): ('FDRE', 'C', 'CE', 'R', init),\n (False, False, True): ('FDCE', 'C', 'CE', 'CLR', init),\n (False, True, True): ('LDCE', 'G', 'GE', 'CLR', init),\n (False, True, False): ('LDPE', 'G', 'GE', 'PRE', init),\n }[(ffsync, latch, zrst)]\n\n\ndef cleanup_carry4(top, site):\n \"\"\" Performs post-routing cleanups of CARRY4 bel required for SLICE.\n\n Cleanups:\n - Detect if CARRY4 is required. If not, remove from site.\n - Remove connections to CARRY4 that are not in used (e.g. if C[3] and\n CO[3] are not used, disconnect S[3] and DI[2]).\n \"\"\"\n\n carry4 = site.maybe_get_bel('CARRY4')\n if carry4 is not None:\n\n # Simplest check is if the CARRY4 has output in used by either the OUTMUX\n # or the FFMUX, if any of these muxes are enable, CARRY4 must remain.\n co_in_use = [False for _ in range(4)]\n o_in_use = [False for _ in range(4)]\n for idx, lut in enumerate('ABCD'):\n if site.has_feature('{}FFMUX.XOR'.format(lut)):\n o_in_use[idx] = True\n\n if site.has_feature('{}FFMUX.CY'.format(lut)):\n co_in_use[idx] = True\n\n if site.has_feature('{}OUTMUX.XOR'.format(lut)):\n o_in_use[idx] = True\n\n if site.has_feature('{}OUTMUX.CY'.format(lut)):\n co_in_use[idx] = True\n\n # No outputs in the SLICE use CARRY4, check if the COUT line is in use.\n for sink in top.find_sinks_from_source(site, 'COUT'):\n co_in_use[idx] = True\n break\n\n for idx in [3, 2, 1, 0]:\n if co_in_use[idx] or o_in_use[idx]:\n for odx in range(idx):\n co_in_use[odx] = True\n o_in_use[odx] = True\n\n break\n\n if not any(co_in_use) and not any(o_in_use):\n # No outputs in use, remove entire BEL\n top.remove_bel(site, carry4)\n else:\n pass\n \"\"\"\n for idx in range(4):\n if not o_in_use[idx] and not co_in_use[idx]:\n sink_wire_pkey = site.remove_internal_sink(\n carry4, 'S[{}]'.format(idx)\n )\n if sink_wire_pkey is not None:\n top.remove_sink(sink_wire_pkey)\n\n sink_wire_pkey = site.remove_internal_sink(\n carry4, 'DI[{}]'.format(idx)\n )\n if sink_wire_pkey is not None:\n top.remove_sink(sink_wire_pkey)\n \"\"\"\n\n\ndef cleanup_srl(top, site):\n \"\"\"Performs post-routing cleanups of SRLs required for SLICE.\n\n Cleanups:\n - For each LUT if in 2xSRL16 mode detect whether both SRL16 are used.\n removes unused ones.\n \"\"\"\n\n # Remove unused SRL16\n for i, row in enumerate(\"ABCD\"):\n\n # n5SRL, check O5\n srl = site.maybe_get_bel(\"{}5SRL\".format(row))\n if srl is not None:\n\n if not site.has_feature(\"{}OUTMUX.O5\".format(row)) and \\\n not site.has_feature(\"{}FFMUX.O5\".format(row)):\n top.remove_bel(site, srl)\n\n # n6SRL, check O6 and MC31\n srl = site.maybe_get_bel(\"{}6SRL\".format(row))\n if srl is not None:\n\n # nOUTMUX, nFFMUX\n noutmux_o6_used = site.has_feature(\"{}OUTMUX.O6\".format(row))\n nffmux_o6_used = site.has_feature(\"{}FFMUX.O6\".format(row))\n\n # nUSED\n nused_used = True\n sinks = list(top.find_sinks_from_source(site, row))\n if len(sinks) == 0:\n nused_used = False\n\n # n7MUX\n f7nmux_used = True\n if row in \"AB\" and site.maybe_get_bel(\"F7AMUX\") is None:\n f7nmux_used = False\n if row in \"CD\" and site.maybe_get_bel(\"F7BMUX\") is None:\n f7nmux_used = False\n\n # A6SRL MC31 output\n if row == \"A\":\n mc31_used = site.has_feature(\"DOUTMUX.MC31\") or \\\n site.has_feature(\"DFFMUX.MC31\")\n else:\n mc31_used = False\n\n # Remove if necessary\n anything_used = nused_used or noutmux_o6_used or nffmux_o6_used or\\\n f7nmux_used or mc31_used\n\n if not anything_used:\n top.remove_bel(site, srl)\n\n\ndef cleanup_dram(top, site):\n \"\"\"Performs post-routing cleanup of DRAMs for SLICEMs.\n\n Depending on the DRAM mode, the fake sinks are masked so that they\n are not present in the verilog output.\n \"\"\"\n lut_modes = decode_dram(site)\n\n if 'RAM128X1D' in lut_modes.values():\n ram128 = site.maybe_get_bel('RAM128X1D')\n for idx in range(6):\n site.mask_sink(ram128, 'ADDR_C[{}]'.format(idx))\n site.mask_sink(ram128, 'DATA_A[{}]'.format(idx))\n\n if 'RAM128X1S' in lut_modes.values():\n if lut_modes['D'] == 'RAM128X1S' and lut_modes['C'] == 'RAM128X1S':\n ram128 = site.maybe_get_bel('RAM128X1S_CD')\n for idx in range(6):\n site.mask_sink(ram128, 'ADDR_C{}'.format(idx))\n\n if 'B' in lut_modes.keys():\n if lut_modes['B'] == 'RAM128X1S' and lut_modes['A'] == 'RAM128X1S':\n ram128 = site.maybe_get_bel('RAM128X1S_AB')\n for idx in range(6):\n site.mask_sink(ram128, 'ADDR_A{}'.format(idx))\n\n if 'RAM256X1S' in lut_modes.values():\n ram256 = site.maybe_get_bel('RAM256X1S')\n\n site.mask_sink(ram256, 'AX')\n for idx in range(6):\n site.mask_sink(ram256, 'ADDR_C[{}]'.format(idx))\n site.mask_sink(ram256, 'ADDR_B[{}]'.format(idx))\n site.mask_sink(ram256, 'ADDR_A[{}]'.format(idx))\n\n\ndef cleanup_slice(top, site):\n \"\"\"Performs post-routing cleanups required for SLICE.\"\"\"\n\n # Cleanup CARRY4 stuff\n cleanup_carry4(top, site)\n\n # Cleanup SRL stuff\n cleanup_srl(top, site)\n\n # Cleanup DRAM stuff\n cleanup_dram(top, site)\n\n\ndef munge_ram32m_init(init):\n \"\"\" RAM32M INIT is interleaved, while the underlying data is not.\n\n INIT[::2] = INIT[:32]\n INIT[1::2] = INIT[32:]\n\n \"\"\"\n\n bits = init.replace(\"64'b\", \"\")[::-1]\n assert len(bits) == 64\n\n out_init = ['0' for _ in range(64)]\n out_init[::2] = bits[:32]\n out_init[1::2] = bits[32:]\n\n return \"64'b{}\".format(''.join(out_init[::-1]))\n\n\ndef di_mux(site, bel, di_port, lut):\n \"\"\" Implements DI1 mux. \"\"\"\n if lut == 'A':\n if site.has_feature('ALUT.DI1MUX.AI'):\n site.add_sink(bel, di_port, \"AI\")\n else:\n if site.has_feature('BLUT.DI1MUX.BI'):\n site.add_sink(bel, di_port, \"BI\")\n else:\n site.add_sink(bel, di_port, \"DI\")\n elif lut == 'B':\n if site.has_feature('BLUT.DI1MUX.BI'):\n site.add_sink(bel, di_port, \"BI\")\n else:\n site.add_sink(bel, di_port, \"DI\")\n elif lut == 'C':\n if site.has_feature('CLUT.DI1MUX.CI'):\n site.add_sink(bel, di_port, \"CI\")\n else:\n site.add_sink(bel, di_port, \"DI\")\n elif lut == 'D':\n site.add_sink(bel, di_port, \"DI\")\n else:\n assert False, lut\n\n\ndef process_slice(top, s):\n \"\"\" Convert SLICE features in Bel and Site objects.\n\n \"\"\"\n \"\"\"\n Available options:\n\n LUT/DRAM/SRL:\n SLICE[LM]_X[01].[ABCD]LUT.INIT[63:0]\n SLICEM_X0.[ABCD]LUT.RAM\n SLICEM_X0.[ABCD]LUT.SMALL\n SLICEM_X0.[ABCD]LUT.SRL\n\n FF:\n SLICE[LM]_X[01].[ABCD]5?FF.ZINI\n SLICE[LM]_X[01].[ABCD]5?FF.ZRST\n SLICE[LM]_X[01].CLKINV\n SLICE[LM]_X[01].FFSYNC\n SLICE[LM]_X[01].LATCH\n SLICE[LM]_X[01].CEUSEDMUX\n SLICE[LM]_X[01].SRUSEDMUX\n\n CARRY4:\n SLICE[LM]_X[01].PRECYINIT = AX|CIN|C0|C1\n\n Muxes:\n SLICE[LM]_X[01].CARRY4.ACY0\n SLICE[LM]_X[01].CARRY4.BCY0\n SLICE[LM]_X[01].CARRY4.CCY0\n SLICE[LM]_X[01].CARRY4.DCY0\n SLICE[LM]_X[01].[ABCD]5FFMUX.IN_[AB]\n SLICE[LM]_X[01].[ABCD]AFFMUX = [ABCD]X|CY|XOR|F[78]|O5|O6\n SLICE[LM]_X[01].[ABCD]OUTMUX = CY|XOR|F[78]|O5|O6|[ABCD]5Q\n SLICEM_X0.WA7USED\n SLICEM_X0.WA8USED\n SLICEM_X0.WEMUX.CE\n \"\"\"\n\n aparts = s[0].feature.split('.')\n site = Site(\n s, get_clb_site(top.db, top.grid, tile=aparts[0], site=aparts[1])\n )\n\n mlut = aparts[1].startswith('SLICEM')\n\n def connect_ce_sr(bel, ce, sr):\n if site.has_feature('CEUSEDMUX'):\n site.add_sink(bel, ce, 'CE')\n else:\n bel.connections[ce] = 1\n\n if site.has_feature('SRUSEDMUX'):\n site.add_sink(bel, sr, 'SR')\n else:\n bel.connections[sr] = 0\n\n IS_C_INVERTED = int(site.has_feature('CLKINV'))\n\n if mlut:\n if site.has_feature('WEMUX.CE'):\n WE = 'CE'\n else:\n WE = 'WE'\n\n if site.has_feature('DLUT.RAM'):\n # Must be a SLICEM to have RAM set.\n assert mlut\n else:\n for row in 'ABC':\n assert not site.has_feature('{}LUT.RAM'.format(row))\n\n muxes = set(('F7AMUX', 'F7BMUX', 'F8MUX'))\n\n luts = {}\n srls = {}\n\n # Add BELs for LUTs/RAMs\n if not site.has_feature('DLUT.RAM'):\n for row in 'ABCD':\n\n # SRL\n if site.has_feature('{}LUT.SRL'.format(row)):\n\n # Cannot have both SRL and DRAM\n assert not site.has_feature('{}LUT.RAM'.format(row))\n\n # SRL32\n if not site.has_feature('{}LUT.SMALL'.format(row)):\n srl = create_srl32(site, row)\n srl.parameters['INIT'] = get_srl32_init(site, row)\n\n site.add_sink(srl, 'CE', WE)\n\n if row == 'A' and site.has_feature('DOUTMUX.MC31'):\n site.add_internal_source(srl, 'Q31', 'AMC31')\n if row == 'A' and site.has_feature('DFFMUX.MC31'):\n site.add_internal_source(srl, 'Q31', 'AMC31')\n\n site.add_bel(srl)\n srls[row] = (srl, )\n\n # 2x SRL16\n else:\n\n srls[row] = []\n init = get_srl16_init(site, row)\n\n for i, part in enumerate(['5', '6']):\n\n # Determine whether to use SRL16E or SRLC16E\n srl_type = 'SRL16E'\n use_mc31 = False\n\n if part == '6':\n\n if row == 'A' and site.has_feature('DOUTMUX.MC31'):\n srl_type = 'SRLC16E'\n use_mc31 = True\n if row == 'A' and site.has_feature('DFFMUX.MC31'):\n srl_type = 'SRLC16E'\n use_mc31 = True\n\n if row == 'D' and site.has_feature(\n 'CLUT.DI1MUX.DI_DMC31'):\n srl_type = 'SRLC16E'\n if row == 'C' and site.has_feature(\n 'BLUT.DI1MUX.DI_CMC31'):\n srl_type = 'SRLC16E'\n if row == 'B' and site.has_feature(\n 'ALUT.DI1MUX.DI_BMC31'):\n srl_type = 'SRLC16E'\n\n # Create the SRL\n srl = create_srl16(site, row, srl_type, part)\n srl.parameters['INIT'] = init[i]\n\n site.add_sink(srl, 'CE', WE)\n\n if use_mc31 and srl_type == 'SRLC16E':\n site.add_internal_source(srl, 'Q15', 'AMC31')\n\n site.add_bel(srl, name=\"{}{}SRL\".format(row, part))\n srls[row].append(srl)\n\n srls[row] = tuple(srls[row])\n\n # LUT\n else:\n luts[row] = create_lut(site, row)\n luts[row].parameters['INIT'] = get_lut_init(site, row)\n site.add_bel(luts[row])\n else:\n # DRAM is active. Determine what BELs are in use.\n lut_modes = decode_dram(site)\n\n if lut_modes['D'] == 'RAM256X1S':\n ram256 = Bel('RAM256X1S', priority=3)\n site.add_sink(ram256, 'WE', WE)\n site.add_sink(ram256, 'WCLK', 'CLK')\n site.add_sink(ram256, 'D', 'DI')\n\n for idx in range(6):\n site.add_sink(\n ram256, 'A[{}]'.format(idx), \"D{}\".format(idx + 1)\n )\n # Add fake sinks as they need to be routed to\n site.add_sink(\n ram256, 'ADDR_C[{}]'.format(idx), \"C{}\".format(idx + 1)\n )\n site.add_sink(\n ram256, 'ADDR_B[{}]'.format(idx), \"B{}\".format(idx + 1)\n )\n site.add_sink(\n ram256, 'ADDR_A[{}]'.format(idx), \"A{}\".format(idx + 1)\n )\n\n site.add_sink(ram256, 'A[6]', \"CX\")\n site.add_sink(ram256, 'A[7]', \"BX\")\n site.add_internal_source(ram256, 'O', 'F8MUX_O')\n\n # Add fake sink to preserve routing thorugh AX pin.\n # The AX pin is used in the same net as for the CX pin.\n site.add_sink(ram256, 'AX', \"AX\")\n\n ram256.parameters['INIT'] = (\n get_shifted_lut_init(site, 'D')\n | get_shifted_lut_init(site, 'C', 64)\n | get_shifted_lut_init(site, 'B', 128)\n | get_shifted_lut_init(site, 'A', 192)\n )\n\n site.add_bel(ram256, name=\"RAM256X1S\")\n\n muxes = set()\n\n del lut_modes['A']\n del lut_modes['B']\n del lut_modes['C']\n del lut_modes['D']\n elif lut_modes['D'] == 'RAM128X1S':\n ram128 = Bel('RAM128X1S', name='RAM128X1S_CD', priority=3)\n site.add_sink(ram128, 'WE', WE)\n site.add_sink(ram128, 'WCLK', \"CLK\")\n site.add_sink(ram128, 'D', \"DI\")\n\n for idx in range(6):\n site.add_sink(ram128, 'A{}'.format(idx), \"D{}\".format(idx + 1))\n # Add fake sink to route through the C[N] pins\n site.add_sink(\n ram128, 'ADDR_C{}'.format(idx), \"C{}\".format(idx + 1)\n )\n\n site.add_sink(ram128, 'A6', \"CX\")\n site.add_internal_source(ram128, 'O', 'F7BMUX_O')\n\n ram128.parameters['INIT'] = (\n get_shifted_lut_init(site, 'D')\n | get_shifted_lut_init(site, 'C', 64)\n )\n\n site.add_bel(ram128, name='RAM128X1S_CD')\n muxes.remove('F7BMUX')\n\n del lut_modes['C']\n del lut_modes['D']\n\n if lut_modes['B'] == 'RAM128X1S':\n ram128 = Bel('RAM128X1S', name='RAM128X1S_AB', priority=4)\n site.add_sink(ram128, 'WE', WE)\n site.add_sink(ram128, 'WCLK', \"CLK\")\n site.add_sink(ram128, 'D', \"BI\")\n\n for idx in range(6):\n site.add_sink(\n ram128, 'A{}'.format(idx), \"B{}\".format(idx + 1)\n )\n # Add fake sink to route through the A[N] pins\n site.add_sink(\n ram128, 'ADDR_A{}'.format(idx), \"A{}\".format(idx + 1)\n )\n\n site.add_sink(ram128, 'A6', \"AX\")\n\n site.add_internal_source(ram128, 'O', 'F7AMUX_O')\n\n ram128.parameters['INIT'] = (\n get_shifted_lut_init(site, 'B')\n | get_shifted_lut_init(site, 'A', 64)\n )\n\n site.add_bel(ram128, name='RAM128X1S_AB')\n\n muxes.remove('F7AMUX')\n\n del lut_modes['A']\n del lut_modes['B']\n\n elif lut_modes['D'] == 'RAM128X1D':\n ram128 = Bel('RAM128X1D', priority=3)\n\n site.add_sink(ram128, 'WE', WE)\n site.add_sink(ram128, 'WCLK', \"CLK\")\n site.add_sink(ram128, 'D', \"DI\")\n\n for idx in range(6):\n site.add_sink(\n ram128, 'A[{}]'.format(idx), \"D{}\".format(idx + 1)\n )\n # Add fake sink to route through the C[N] pins\n site.add_sink(\n ram128, 'ADDR_C[{}]'.format(idx), \"C{}\".format(idx + 1)\n )\n site.add_sink(\n ram128, 'DPRA[{}]'.format(idx), \"B{}\".format(idx + 1)\n )\n # Add fake sink to route through the A[N] pins\n site.add_sink(\n ram128, 'DATA_A[{}]'.format(idx), \"A{}\".format(idx + 1)\n )\n\n site.add_sink(ram128, 'A[6]', \"CX\")\n site.add_sink(ram128, 'DPRA[6]', \"AX\")\n\n site.add_internal_source(ram128, 'SPO', 'F7BMUX_O')\n site.add_internal_source(ram128, 'DPO', 'F7AMUX_O')\n\n ram128.parameters['INIT'] = (\n get_shifted_lut_init(site, 'D')\n | get_shifted_lut_init(site, 'C', 64)\n )\n\n other_init = (\n get_shifted_lut_init(site, 'B')\n | get_shifted_lut_init(site, 'A', 64)\n )\n\n assert ram128.parameters['INIT'] == other_init\n\n site.add_bel(ram128, name=\"RAM128X1D\")\n\n muxes.remove('F7AMUX')\n muxes.remove('F7BMUX')\n\n del lut_modes['A']\n del lut_modes['B']\n del lut_modes['C']\n del lut_modes['D']\n elif lut_modes['D'] == 'RAM64M':\n del lut_modes['D']\n\n ram64m = Bel('RAM64M', name='RAM64M', priority=3)\n\n site.add_sink(ram64m, 'WE', WE)\n site.add_sink(ram64m, 'WCLK', \"CLK\")\n\n di_mux(site, ram64m, 'DIA', 'A')\n di_mux(site, ram64m, 'DIB', 'B')\n di_mux(site, ram64m, 'DIC', 'C')\n di_mux(site, ram64m, 'DID', 'D')\n\n for lut in 'ABCD':\n for idx in range(6):\n site.add_sink(\n ram64m, 'ADDR{}[{}]'.format(lut, idx),\n \"{}{}\".format(lut, idx + 1)\n )\n\n site.add_internal_source(ram64m, 'DO' + lut, lut + \"O6\")\n\n ram64m.parameters['INIT_' + lut] = get_lut_init(site, lut)\n\n site.add_bel(ram64m)\n elif lut_modes['D'] == 'RAM32M':\n del lut_modes['D']\n\n ram32m = Bel('RAM32M', name='RAM32M', priority=3)\n\n site.add_sink(ram32m, 'WE', WE)\n site.add_sink(ram32m, 'WCLK', \"CLK\")\n\n di_mux(site, ram32m, 'DIA[0]', 'A')\n di_mux(site, ram32m, 'DIB[0]', 'B')\n di_mux(site, ram32m, 'DIC[0]', 'C')\n di_mux(site, ram32m, 'DID[0]', 'D')\n\n for lut in 'ABCD':\n site.add_sink(ram32m, 'DI{}[1]'.format(lut), lut + \"X\")\n site.add_internal_source(\n ram32m, 'DO{}[1]'.format(lut), lut + \"O6\"\n )\n\n site.add_internal_source(\n ram32m, 'DO{}[0]'.format(lut), lut + \"O5\"\n )\n\n for idx in range(5):\n site.add_sink(\n ram32m, 'ADDR{}[{}]'.format(lut, idx),\n \"{}{}\".format(lut, idx + 1)\n )\n\n ram32m.parameters['INIT_' + lut] = munge_ram32m_init(\n get_lut_init(site, lut)\n )\n\n site.add_bel(ram32m)\n\n for priority, lut in zip([4, 3], 'BD'):\n if lut not in lut_modes:\n continue\n\n minus_one = chr(ord(lut) - 1)\n\n if lut_modes[lut] == 'RAM64X1D':\n assert lut_modes[minus_one] == lut_modes[lut]\n\n ram64 = Bel(\n 'RAM64X1D',\n name='RAM64X1D_' + minus_one + lut,\n priority=priority\n )\n ram64.set_bel(minus_one + '6LUT')\n\n site.add_sink(ram64, 'WE', WE)\n site.add_sink(ram64, 'WCLK', \"CLK\")\n di_mux(site, ram64, 'D', lut)\n\n for idx in range(6):\n site.add_sink(\n ram64, 'A{}'.format(idx), \"{}{}\".format(lut, idx + 1)\n )\n site.add_sink(\n ram64, 'DPRA{}'.format(idx),\n \"{}{}\".format(minus_one, idx + 1)\n )\n\n site.add_internal_source(ram64, 'SPO', lut + \"O6\")\n site.add_internal_source(ram64, 'DPO', minus_one + \"O6\")\n\n ram64.parameters['INIT'] = get_lut_init(site, lut)\n other_init = get_lut_init(site, minus_one)\n\n assert ram64.parameters['INIT'] == other_init\n\n site.add_bel(ram64)\n\n del lut_modes[lut]\n del lut_modes[minus_one]\n elif lut_modes[lut] == 'RAM32X1D':\n ram32 = [\n Bel(\n 'RAM32X1D',\n name='RAM32X1D_{}_{}'.format(lut, idx),\n priority=priority\n ) for idx in range(2)\n ]\n\n for idx in range(2):\n site.add_sink(ram32[idx], 'WE', WE)\n site.add_sink(ram32[idx], 'WCLK', \"CLK\")\n for aidx in range(5):\n site.add_sink(\n ram32[idx], 'A{}'.format(aidx),\n \"{}{}\".format(lut, aidx + 1)\n )\n site.add_sink(\n ram32[idx], 'DPRA{}'.format(aidx),\n \"{}{}\".format(minus_one, aidx + 1)\n )\n\n site.add_sink(ram32[0], 'D', lut + \"X\")\n site.add_internal_source(ram32[0], 'SPO', lut + \"O6\")\n site.add_internal_source(ram32[0], 'DPO', minus_one + \"O6\")\n ram32[0].set_bel('{}6LUT'.format(lut))\n\n di_mux(site, ram32[1], 'D', lut)\n site.add_internal_source(ram32[1], 'SPO', lut + \"O5\")\n site.add_internal_source(ram32[1], 'DPO', minus_one + \"O5\")\n ram32[1].set_bel('{}5LUT'.format(lut))\n\n lut_init = get_lut_init(site, lut)\n other_init = get_lut_init(site, minus_one)\n assert lut_init == other_init\n\n bits = lut_init.replace(\"64'b\", \"\")\n assert len(bits) == 64\n ram32[0].parameters['INIT'] = \"32'b{}\".format(bits[:32])\n ram32[1].parameters['INIT'] = \"32'b{}\".format(bits[32:])\n\n site.add_bel(ram32[0])\n site.add_bel(ram32[1])\n\n del lut_modes[lut]\n del lut_modes[minus_one]\n\n for priority, lut in zip([6, 5, 4, 3], 'ABCD'):\n if lut not in lut_modes:\n continue\n\n if lut_modes[lut] == 'LUT':\n luts[lut] = create_lut(site, lut)\n luts[lut].parameters['INIT'] = get_lut_init(site, lut)\n site.add_bel(luts[lut])\n elif lut_modes[lut] == 'RAM64X1S':\n ram64 = Bel(\n 'RAM64X1S', name='RAM64X1S_' + lut, priority=priority\n )\n\n site.add_sink(ram64, 'WE', WE)\n site.add_sink(ram64, 'WCLK', \"CLK\")\n di_mux(site, ram64, 'D', lut)\n\n for idx in range(6):\n site.add_sink(\n ram64, 'A{}'.format(idx), \"{}{}\".format(lut, idx + 1)\n )\n\n site.add_internal_source(ram64, 'O', lut + \"O6\")\n\n ram64.parameters['INIT'] = get_lut_init(site, lut)\n\n site.add_bel(ram64)\n elif lut_modes[lut] == 'RAM32X1S':\n ram32 = [\n Bel(\n 'RAM32X1S',\n name='RAM32X1S_{}_{}'.format(lut, idx),\n priority=priority\n ) for idx in range(2)\n ]\n\n for idx in range(2):\n site.add_sink(ram32[idx], 'WE', WE)\n site.add_sink(ram32[idx], 'WCLK', \"CLK\")\n for aidx in range(5):\n site.add_sink(\n ram32[idx], 'A{}'.format(aidx),\n \"{}{}\".format(lut, aidx + 1)\n )\n\n site.add_sink(ram32[0], 'D', lut + \"X\")\n site.add_internal_source(ram32[0], 'O', lut + \"O6\")\n ram32[0].set_bel('{}6LUT'.format(lut))\n\n di_mux(site, ram32[1], 'D', lut)\n site.add_internal_source(ram32[1], 'O', lut + \"O5\")\n ram32[1].set_bel('{}5LUT'.format(lut))\n\n lut_init = get_lut_init(site, lut)\n\n bits = lut_init.replace(\"64'b\", \"\")\n assert len(bits) == 64\n ram32[0].parameters['INIT'] = \"32'b{}\".format(bits[:32])\n ram32[1].parameters['INIT'] = \"32'b{}\".format(bits[32:])\n\n site.add_bel(ram32[0])\n site.add_bel(ram32[1])\n else:\n assert False, lut_modes[lut]\n\n # Detect SRL chains\n srl_chains = set()\n\n if \"D\" in srls and \"C\" in srls and site.has_feature('CLUT.DI1MUX.DI_DMC31'\n ):\n srl_chains.add(\"DC\")\n\n if \"C\" in srls and \"B\" in srls and site.has_feature('BLUT.DI1MUX.DI_CMC31'\n ):\n srl_chains.add(\"CB\")\n\n if \"B\" in srls and \"A\" in srls and site.has_feature(\n 'ALUT.DI1MUX.BDI1_BMC31'):\n srl_chains.add(\"BA\")\n\n # SRL chain connections\n for chain in srl_chains:\n src = chain[0]\n dst = chain[1]\n\n if site.has_feature(\"{}LUT.SMALL\".format(src)):\n q = \"Q15\"\n else:\n q = \"Q31\"\n\n site.add_internal_source(srls[src][-1], q, '{}MC31'.format(src))\n srls[dst][0].connections['D'] = '{}MC31'.format(src)\n\n need_f8 = site.has_feature('BFFMUX.F8') or site.has_feature('BOUTMUX.F8')\n need_f7a = site.has_feature('AFFMUX.F7') or site.has_feature('AOUTMUX.F7')\n need_f7b = site.has_feature('CFFMUX.F7') or site.has_feature('COUTMUX.F7')\n\n if need_f8:\n need_f7a = True\n need_f7b = True\n\n for mux in sorted(muxes):\n if mux == 'F7AMUX':\n if not need_f8 and not need_f7a:\n continue\n else:\n bel_type = 'MUXF7'\n opin = 'O'\n\n f7amux = Bel(bel_type, 'MUXF7A', priority=7)\n f7amux.set_bel('F7AMUX')\n\n site.connect_internal(f7amux, 'I0', 'BO6')\n site.connect_internal(f7amux, 'I1', 'AO6')\n site.add_sink(f7amux, 'S', 'AX')\n\n site.add_internal_source(f7amux, opin, 'F7AMUX_O')\n\n site.add_bel(f7amux)\n elif mux == 'F7BMUX':\n if not need_f8 and not need_f7b:\n continue\n else:\n bel_type = 'MUXF7'\n opin = 'O'\n\n f7bmux = Bel(bel_type, 'MUXF7B', priority=7)\n f7bmux.set_bel('F7BMUX')\n\n site.connect_internal(f7bmux, 'I0', 'DO6')\n site.connect_internal(f7bmux, 'I1', 'CO6')\n site.add_sink(f7bmux, 'S', 'CX')\n\n site.add_internal_source(f7bmux, opin, 'F7BMUX_O')\n\n site.add_bel(f7bmux)\n elif mux == 'F8MUX':\n if not need_f8:\n continue\n else:\n bel_type = 'MUXF8'\n opin = 'O'\n\n f8mux = Bel(bel_type, priority=7)\n\n site.connect_internal(f8mux, 'I0', 'F7BMUX_O')\n site.connect_internal(f8mux, 'I1', 'F7AMUX_O')\n site.add_sink(f8mux, 'S', 'BX')\n\n site.add_internal_source(f8mux, opin, 'F8MUX_O')\n\n site.add_bel(f8mux)\n else:\n assert False, mux\n\n can_have_carry4 = True\n for lut in 'ABCD':\n if site.has_feature(lut + 'O6') or site.has_feature(lut + 'LUT.RAM'):\n can_have_carry4 = False\n break\n\n if len(srls) != 0:\n can_have_carry4 = False\n\n if can_have_carry4:\n bel = Bel('CARRY4', priority=1)\n\n for idx in range(4):\n lut = chr(ord('A') + idx)\n if site.has_feature('CARRY4.{}CY0'.format(lut)):\n source = lut + 'O5'\n site.connect_internal(bel, 'DI[{}]'.format(idx), source)\n else:\n site.add_sink(bel, 'DI[{}]'.format(idx), lut + 'X')\n\n source = lut + 'O6'\n\n site.connect_internal(bel, 'S[{}]'.format(idx), source)\n\n site.add_internal_source(bel, 'O[{}]'.format(idx), lut + '_XOR')\n\n co_pin = 'CO[{}]'.format(idx)\n if idx == 3:\n site.add_source(bel, co_pin, 'COUT')\n site.add_internal_source(bel, co_pin, lut + '_CY')\n\n if site.has_feature('PRECYINIT.AX'):\n site.add_sink(bel, 'CYINIT', 'AX')\n bel.connections['CI'] = 0\n\n elif site.has_feature('PRECYINIT.C0'):\n bel.connections['CYINIT'] = 0\n bel.connections['CI'] = 0\n\n elif site.has_feature('PRECYINIT.C1'):\n bel.connections['CYINIT'] = 1\n bel.connections['CI'] = 0\n\n elif site.has_feature('PRECYINIT.CIN'):\n bel.connections['CYINIT'] = 0\n site.add_sink(bel, 'CI', 'CIN')\n\n else:\n assert False\n\n site.add_bel(bel, name='CARRY4')\n\n ff5_bels = {}\n for lut in 'ABCD':\n if site.has_feature('{}OUTMUX.{}5Q'.format(lut, lut)) or \\\n site.has_feature('{}5FFMUX.IN_A'.format(lut)) or \\\n site.has_feature('{}5FFMUX.IN_B'.format(lut)):\n # 5FF in use, emit\n name, clk, ce, sr, init = ff_bel(site, lut, ff5=True)\n ff5 = Bel(name, \"{}5_{}\".format(lut, name))\n ff5_bels[lut] = ff5\n ff5.set_bel(lut + '5FF')\n\n if site.has_feature('{}5FFMUX.IN_A'.format(lut)):\n site.connect_internal(ff5, 'D', lut + 'O5')\n elif site.has_feature('{}5FFMUX.IN_B'.format(lut)):\n site.add_sink(ff5, 'D', lut + 'X')\n\n site.add_sink(ff5, clk, \"CLK\")\n\n connect_ce_sr(ff5, ce, sr)\n\n site.add_internal_source(ff5, 'Q', lut + '5Q')\n ff5.parameters['INIT'] = init\n\n if name in ['LDCE', 'LDPE']:\n ff5.parameters['IS_G_INVERTED'] = IS_C_INVERTED\n else:\n ff5.parameters['IS_C_INVERTED'] = IS_C_INVERTED\n\n site.add_bel(ff5)\n\n for lut in 'ABCD':\n name, clk, ce, sr, init = ff_bel(site, lut, ff5=False)\n ff = Bel(name, \"{}_{}\".format(lut, name))\n ff.set_bel(lut + 'FF')\n\n if site.has_feature('{}FFMUX.{}X'.format(lut, lut)):\n site.add_sink(ff, 'D', lut + 'X')\n\n elif lut == 'A' and site.has_feature('AFFMUX.F7'):\n site.connect_internal(ff, 'D', 'F7AMUX_O')\n\n elif lut == 'C' and site.has_feature('CFFMUX.F7'):\n site.connect_internal(ff, 'D', 'F7BMUX_O')\n\n elif lut == 'B' and site.has_feature('BFFMUX.F8'):\n site.connect_internal(ff, 'D', 'F8MUX_O')\n\n elif lut == 'D' and site.has_feature('DFFMUX.MC31'):\n site.connect_internal(ff, 'D', 'AMC31')\n\n elif site.has_feature('{}FFMUX.O5'.format(lut)):\n site.connect_internal(ff, 'D', lut + 'O5')\n\n elif site.has_feature('{}FFMUX.O6'.format(lut)):\n site.connect_internal(ff, 'D', lut + 'O6')\n\n elif site.has_feature('{}FFMUX.CY'.format(lut)):\n assert can_have_carry4\n site.connect_internal(ff, 'D', lut + '_CY')\n\n elif site.has_feature('{}FFMUX.XOR'.format(lut)):\n assert can_have_carry4\n site.connect_internal(ff, 'D', lut + '_XOR')\n else:\n continue\n\n site.add_source(ff, 'Q', lut + 'Q')\n site.add_sink(ff, clk, \"CLK\")\n\n connect_ce_sr(ff, ce, sr)\n\n ff.parameters['INIT'] = init\n\n if name in ['LDCE', 'LDPE']:\n ff.parameters['IS_G_INVERTED'] = IS_C_INVERTED\n else:\n ff.parameters['IS_C_INVERTED'] = IS_C_INVERTED\n\n site.add_bel(ff)\n\n for lut in 'ABCD':\n if lut + 'O6' in site.internal_sources:\n site.add_output_from_internal(lut, lut + 'O6')\n\n for lut in 'ABCD':\n output_wire = lut + 'MUX'\n if site.has_feature('{}OUTMUX.{}5Q'.format(lut, lut)):\n site.add_output_from_internal(output_wire, lut + '5Q')\n\n elif lut == 'A' and site.has_feature('AOUTMUX.F7'):\n site.add_output_from_internal(output_wire, 'F7AMUX_O')\n\n elif lut == 'C' and site.has_feature('COUTMUX.F7'):\n site.add_output_from_internal(output_wire, 'F7BMUX_O')\n\n elif lut == 'B' and site.has_feature('BOUTMUX.F8'):\n site.add_output_from_internal(output_wire, 'F8MUX_O')\n\n elif site.has_feature('{}OUTMUX.O5'.format(lut)):\n site.add_output_from_internal(output_wire, lut + 'O5')\n\n elif site.has_feature('{}OUTMUX.O6'.format(lut)):\n # Note: There is a dedicated O6 output. Fixed routing requires\n # treating xMUX.O6 as a routing connection.\n site.add_output_from_output(output_wire, lut)\n\n elif site.has_feature('{}OUTMUX.CY'.format(lut)):\n assert can_have_carry4\n site.add_output_from_internal(output_wire, lut + '_CY')\n\n elif site.has_feature('{}OUTMUX.XOR'.format(lut)):\n assert can_have_carry4\n site.add_output_from_internal(output_wire, lut + '_XOR')\n else:\n continue\n\n if site.has_feature('DOUTMUX.MC31'):\n site.add_output_from_internal('DMUX', 'AMC31')\n\n site.set_post_route_cleanup_function(cleanup_slice)\n top.add_site(site)\n\n\ndef process_clb(conn, top, tile_name, features):\n slices = {\n '0': [],\n '1': [],\n }\n\n for f in features:\n parts = f.feature.split('.')\n\n if not parts[1].startswith('SLICE'):\n continue\n\n slices[parts[1][-1]].append(f)\n\n for s in slices:\n if len(slices[s]) > 0:\n process_slice(top, slices[s])\n","sub_path":"xc/xc7/fasm2bels/clb_models.py","file_name":"clb_models.py","file_ext":"py","file_size_in_byte":41149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"592288006","text":"import argparse\nimport csv\nimport pandas as pd\nfrom conceptnet5.vectors import standardized_concept_uri\nimport numpy as np\nfrom tqdm import tqdm\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"inputtext\",\n help=\"Text vectors that will be converted to hdf\",\n default=\"cleaned_corpus.txt\")\n parser.add_argument(\"outputhdf\",default=\"original_ft.hd5clean\",\n help=\"The output hdf file\")\n parser.add_argument(\"--limit\",default=200000,\n help=\"Limit of vectors to load\",\n type=int)\n parser.add_argument(\"-sf\",default=False, action='store_true')\n args = parser.parse_args()\n\n input_filename = args.inputtext\n output_filename = args.outputhdf\n\n count = 0\n prefix = \"\"\n indexes = []\n vectors = []\n if args.limit is not None:\n limit = args.limit\n skip_first = args.sf\n\n with open(input_filename,encoding=\"utf-8\") as vec_file:\n for line in tqdm(vec_file):\n count+=1\n if skip_first: skip_first=False\n if count == limit:\n print(\"Reached limit\",limit)\n break\n word = line.strip().split(\" \")[0]\n word = prefix+word\n vec = []\n for element in line.strip().split(\" \")[1:]:\n vec.append(float(element))\n indexes.append(word)\n vectors.append(np.array(vec))\n if count%10000==0:\n print(count)\n print(\"Outputting df\")\n df = pd.DataFrame(index=indexes,data=vectors)\n df.to_hdf(output_filename,\"mat\")\n print(\"Finished\")\n\n","sub_path":"fasttext_model/convert_vec_to_hdf.py","file_name":"convert_vec_to_hdf.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"317415194","text":"\"\"\"Toolkit for various operations in Zenodo.\"\"\"\n####\n#### Toolkit for various operations in Zenodo.\n#### This toolkit should be safe to use with jq.\n####\n#### Example usage to operate in Zenodo:\n#### python3 ./scripts/zenodo-ops.py --help\n#### python3 ./scripts/zenodo-ops.py --verbose --sandbox --token abc --action list\n#### python3 ./scripts/zenodo-ops.py --verbose --sandbox --token abc --action files --deposition 123\n####\n\n## Standard imports.\nimport sys\nimport argparse\nimport logging\nimport os\nimport json\nimport requests\n\n## Logger basic setup.\nlogging.basicConfig(level=logging.INFO)\nLOG = logging.getLogger('zenodo-ops')\nLOG.setLevel(logging.WARNING)\n\ndef die_screaming(instr):\n \"\"\"Make sure we exit in a way that will get Jenkins's attention.\"\"\"\n LOG.error(instr)\n sys.exit(1)\n\ndef main():\n \"\"\"The main runner for our script.\"\"\"\n\n ## Deal with incoming.\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument('-v', '--verbose', action='store_true',\n help='More verbose output')\n parser.add_argument('-t', '--token',\n help='The token (access key) to use for commands.')\n parser.add_argument('-s', '--sandbox', action='store_true',\n help='If used, will aim at the sandbox server.')\n parser.add_argument('-a', '--action',\n help='The action to run: \"list\", \"files\", \"newdep\"')\n parser.add_argument('-d', '--deposition',\n help='[optional] The desposition number in an action.')\n parser.add_argument('-f', '--file',\n help='[optional] The local file to use in an action.')\n args = parser.parse_args()\n\n if args.verbose:\n LOG.setLevel(logging.INFO)\n LOG.info('Verbose: on')\n\n ## Ensure server URL.\n server_url = 'https://zenodo.org'\n if args.sandbox :\n server_url = 'https://sandbox.zenodo.org'\n LOG.info('Will use: ' + server_url)\n\n ## Ensure token.\n if not args.token:\n die_screaming('need a \"token\" argument')\n LOG.info('Will use token: ' + args.token)\n\n ## Ensure action.\n if not args.action:\n die_screaming('need an \"action\" argument')\n LOG.info('Will run action: ' + args.action)\n\n ## Ensure deposition number, return int.\n def get_deposition():\n if not args.deposition:\n die_screaming('need \"deposition\" argument')\n LOG.info('Will use deposition: ' + args.deposition)\n return int(args.deposition)\n\n ## Write informative reports to the log.\n def safe_json_report(response, report_list):\n print(json.dumps(response.json(), indent=4, sort_keys=True))\n LOG.info(\" http status code: \" + str(response.status_code))\n for d in response.json():\n LOG.info(' \"' + '\", \"'.join(str(d[x]) for x in report_list) + '\"')\n\n ## Main action verb drop-through.\n response = None\n if args.action == 'list':\n\n response = requests.get(server_url + '/api/deposit/depositions', params={'access_token': args.token})\n\n safe_json_report(response, ['id', 'title'])\n\n elif args.action == 'files':\n\n dep = get_deposition()\n\n response = requests.get(server_url + '/api/deposit/depositions/' + str(dep) + '/files', params={'access_token': args.token})\n\n safe_json_report(response, ['id', 'filename'])\n\n elif args.action == 'newempty':\n\n response = requests.post(server_url + '/api/deposit/depositions/' + str(dep) + '/files', params={'access_token': args.token})\n\n safe_json_report(response, ['id', 'filename'])\n\n## You saw it coming...\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/zenodo-ops.py","file_name":"zenodo-ops.py","file_ext":"py","file_size_in_byte":3731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"478116825","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 17 17:26:31 2019\n\n@author: sebas\n\"\"\"\n\nimport torch\nimport torchvision as tv\n\nfrom ae import AE\n\n\n\n# Autoencoders stacked\nclass AES(torch.nn.Module):\n def __init__(_, sizes): #sizes es una lista resp a la arquitectura profunda\n super().__init__()\n _.subnet = torch.nn.ModuleList() #lista para recuperar los parámetros de todas las RBM\n for i in range(len(sizes)-1):\n _.subnet.append( AE(sizes[i],sizes[i+1]) )\n\n\n def forward(_, x, depth=None):\n h = _.enc(x,depth)\n out = _.dec(h,depth)\n return out\n \n # enc y dec se pueden reemplazar por un torch Sequential: probarlo luego.\n def enc(_,x, depth=None):\n if depth is not None:\n for i in range(depth):\n x = _.subnet[i].enc(x)\n x = _.subnet[depth].enc(x)\n else:\n for i in range(len(_.subnet)):\n x = _.subnet[i].enc(x)\n# x = _.subnet[depth].enc(x)\n \n return x\n \n def dec(_,x, depth=None):\n if depth is not None:\n for i in range(depth):\n x = _.subnet[depth-i].dec(x)\n x = _.subnet[0].dec(x)\n else:\n for i in range(len(_.subnet)):\n x = _.subnet[len(_.subnet)-i].dec(x)\n return x\n\n\n# el Compose recibe una lista\ntransf = tv.transforms.Compose( [tv.transforms.ToTensor(), tv.transforms.Normalize([0.5],[0.5]) ] )\n\nB = 100\ntrn_data =tv.datasets.MNIST(root='./data', train = True, download = True, transform = transf) \ntst_data =tv.datasets.MNIST(root='./data', train = False, download = True, transform = transf)\ntrn_load =torch.utils.data.DataLoader(dataset = trn_data, batch_size = B, shuffle = True) # Suffle: que los datos est'en armados al azar. Lo mismo para ambos conjuntos.\ntst_load =torch.utils.data.DataLoader(dataset = tst_data, batch_size = B, shuffle = True)\n\n\nN = 28*28\nM = 64\n\n\nsizes = [N,M]\nmodel = AES(sizes)\noptim = torch.optim.SGD(model.parameters(), 0.1) #el último es el learning rate\ncostf = torch.nn.MSELoss()\n\nT = 1000\n#errorTotal = []\nmodel.train()\nfor depth in range(len(model.subnet)):\n for t in range(T):\n errorBatch = []\n for images, labels in trn_load:\n optim.zero_grad()\n# \n x = images.view(-1,N)\n## v0, vk = model(data, depth) #por defecto llama a forward\n y = model(x,depth)\n# \n error = costf(y,x) # el autoencoder chequea si el input es igual al output\n error.backward()\n## loss = rbm.free_energy(v0) - rbm.free_energy(vk)\n# \n## loss.backward()\n optim.step()\n# \n errorBatch.append(error.item())\n# \n errorEpoca = sum(errorBatch)#/len(error)\n## errorTotal.append(errorEpoca) #por si después quiero graficar error para cada época\n print('Depth', depth,'Época',t,'Error',errorEpoca)\n## print(Época',t,'Error',errorEpoca)\n# E = error.item()\n# \n# if t%100 == 0:\n# print(t,E)\n\n\n\n\nfor depth in range(len(model.subnet)):\n# ae = model.subnet[depth]\n# optim = torch.optim.SGD(ae.parameters(), 0.1) #el último es el learning rate\n \n# errorTotal = []\n for t in range(T):\n# errorBatch = []\n# for images, labels in trn_load:\n optim.zero_grad()\n \n# data = images.view(-1,28*28)\n# v0, vk = model(data, depth) #por defecto llama a forward. Voy entrenando cada vez más profundo.\n# loss = rbm.free_energy(v0) - rbm.free_energy(vk)\n \n# loss.backward()\n y = model(x,depth)\n \n error = costf(y,x) # el autoencoder chequea si el input es igual al output\n error.backward()\n optim.step()\n \n# errorBatch.append(loss.item())\n \n# errorEpoca = sum(errorBatch)#/len(error)\n errorEpoca = error.item()\n# errorTotal.append(errorEpoca) #por si después quiero graficar error para cada época\n if t%100 == 0:\n print('Depth', depth,'Época',t,'Error',errorEpoca)\n\n\n\n\n#\n#sizes = [28*28, 500, 500, 2000, 10]\n#model = DBN(sizes)\n#\n#B = 100\n#trn_data =tv.datasets.MNIST(root='./data', train = True, download = True, transform = tv.transforms.ToTensor()) # Primer par'ametro: En qu'e subdirectorio guardo los datos. Train son los datos de entrenamiento. Si no los tiene que los descargue. Transform: que los datos sean interpretados como tensores\n#tst_data =tv.datasets.MNIST(root='./data', train = False, download = True, transform = tv.transforms.ToTensor())\n#trn_load =torch.utils.data.DataLoader(dataset = trn_data, batch_size = B, shuffle = True) # Suffle: que los datos est'en armados al azar. Lo mismo para ambos conjuntos.\n#tst_load =torch.utils.data.DataLoader(dataset = tst_data, batch_size = B, shuffle = True)\n#\n#\n#T = 5 # cant de épocas\n#\n## primero (pre)entrenamos parcialmente cada RBM\n#for depth in range(len(model.subnet)):\n# rbm = model.subnet[depth]\n# optim = torch.optim.SGD(rbm.parameters(), 0.01) #el último es el learning rate\n# \n# errorTotal = []\n# for t in range(T):\n# errorBatch = []\n# for images, labels in trn_load:\n# optim.zero_grad()\n# \n# data = images.view(-1,28*28)\n# v0, vk = model(data, depth) #por defecto llama a forward\n# loss = rbm.free_energy(v0) - rbm.free_energy(vk)\n# \n# loss.backward()\n# optim.step()\n# \n# errorBatch.append(loss.item())\n# \n# errorEpoca = sum(errorBatch)#/len(error)\n# errorTotal.append(errorEpoca) #por si después quiero graficar error para cada época\n# print('Depth', depth,'Época',t,'Error',errorEpoca)\n# \n#\n##lincl = torch.nn.Linear(M,C) #M features y C clases\n#optim = torch.optim.Adam(model.parameters()) #entreno TODOS los parámetros del modeo, i.e. de TODAS las RBMs.\n#costf = torch.nn.CrossEntropyLoss()\n#\n##T2 = T\n#T2 = T*3\n#errorTotal = []\n#for t in range(T2):\n# errorBatch = []\n# for images, labels in trn_load:\n# optim.zero_grad()\n# \n# data = images.view(-1,28*28)\n# x, y = model(data)\n#\n# error = costf(y,labels)\n# \n# error.backward()\n# optim.step()\n# \n# errorBatch.append(error.item()) \n# \n# errorEpoca = sum(errorBatch)/len(errorBatch)\n# errorTotal.append(errorEpoca)\n# print('Época',t,'Error',errorEpoca)\n#\n#\n#\n#right, total = 0., 0.\n#with torch.no_grad():\n# for images, labels in tst_load:\n# x = images.view(-1,28*28)\n# bla, y = model(x)\n## y = lincl(hp)\n# right += (y.argmax(dim=1)==labels).sum().item()\n# total += len(labels)\n# \n#acc = right/total\n#print('Accuracy:',acc)","sub_path":"autoEncoders/ae_stacked_v3.py","file_name":"ae_stacked_v3.py","file_ext":"py","file_size_in_byte":6822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"292846654","text":"import socket \nimport threading\nimport os\nimport time\nimport hashlib\nfrom json import loads,dumps\n\n\nclass Node:\n\tdef __init__(self, host, port):\n\t\tself.stop = False\n\t\tself.host = host\n\t\tself.port = port\n\t\tself.M = 16\n\t\tself.N = 2**self.M\n\t\tself.key = self.hasher(host+str(port))\n\t\tthreading.Thread(target = self.listener).start()\n\t\tself.files = []\n\t\tself.backUpFiles = []\n\t\tif not os.path.exists(host+\"_\"+str(port)):\n\t\t\tos.mkdir(host+\"_\"+str(port))\n\t\t'''\n\t\t------------------------------------------------------------------------------------\n\t\tDO NOT EDIT ANYTHING ABOVE THIS LINE\n\t\t'''\n\t\t# Set value of the following variables appropriately to pass Intialization test\n\t\tself.successor = (self.host,self.port)\n\t\tself.predecessor = (self.host,self.port)\n\t\tself.backup_successor = (self.host, self.port)\n\t\t# additional state variables\n\t\tself.hash_id = self.hasher(self.host+str(self.port))\n\t\tself.start_pinging = True\n\t\t\n\t\tself.joined = False\n\t\tself.lookup_queries = {}\n\t\tself.file_lookups = {}\n\t\tthreading.Thread(target = self.pinger).start()\n\t\t\n\n\n\n\tdef hasher(self, key):\n\t\t'''\n\t\tDO NOT EDIT THIS FUNCTION.\n\t\tYou can use this function as follow:\n\t\t\tFor a node: self.hasher(node.host+str(node.port))\n\t\t\tFor a file: self.hasher(file)\n\t\t'''\n\t\treturn int(hashlib.md5(key.encode()).hexdigest(), 16) % self.N\n\n\n\tdef handleConnection(self, client, addr):\n\t\t'''\n\t\t Function to handle each inbound connection, called as a thread from the listener.\n\t\t'''\n\t\treq = client.recv(4096).decode(\"utf-8\")\n\t\treq_source_id = int(req.split(\"|\")[0])\n\t\treq_type = req.split(\"|\")[1]\n\t\tif req_type == \"join\":\n\t\t\tself.lookup_queries[req_source_id] = (req.split(\"|\")[2], int(req.split(\"|\")[3]))\n\t\t\tself.general_lookup(self.hash_id,req_source_id,self.host,self.port)\n\t\telif req_type == \"new_predecessor\":\n\t\t\tpredecessor = (req.split(\"|\")[2], int(req.split(\"|\")[3]))\n\t\t\tif(self.successor == self.predecessor and self.predecessor == (self.host,self.port)):\n\t\t\t\tclient.send(\"one_node\".encode())\n\t\t\t\tself.successor = predecessor\n\t\t\telse:\n\t\t\t\tself.start_pinging = True\n\t\t\t\n\t\t\tself.predecessor = predecessor\n\t\t\tself.files = self.files + self.backUpFiles\n\t\t\tself.backUpFiles = []\n\t\t\tclient.send(\" \".encode())\n\n\t\telif req_type == \"updated_predecessor_successor\":\n\t\t\tpred_succ_essor = self.predecessor[0] + \"|\" + str(self.predecessor[1]) + \"|\" + self.successor[0] + \"|\" + str(self.successor[1])\n\t\t\tclient.send(pred_succ_essor.encode()) \n\t\telif req_type == \"your_successor\":\n\t\t\tself.successor = (req.split(\"|\")[2], int(req.split(\"|\")[3]))\n\t\t\tself.joined = True\n\t\telif req_type == \"lookup\":\n\t\t\tself.general_lookup(self.hash_id,req_source_id,req.split(\"|\")[2], int(req.split(\"|\")[3]))\n\t\telif req_type == \"lookup_result\":\n\t\t\taddr = self.lookup_queries[req_source_id]\n\t\t\tif addr == (self.host,self.port):\n\t\t\t\tself.file_lookups[req_source_id] = [True,(req.split(\"|\")[2],int(req.split(\"|\")[3]))]\n\t\t\telse:\n\t\t\t\treply = str(self.hash_id) + \"|\" + \"your_successor\" + \"|\" + req.split(\"|\")[2] + \"|\" + req.split(\"|\")[3]\n\t\t\t\taddr = self.lookup_queries[req_source_id]\n\t\t\t\t#print(\"successor returned for\",addr,req.split(\"|\")[3])\n\t\t\t\t#print(addr,reply)\n\t\t\t\tself.send_message(addr,reply)\n\t\telif req_type == \"new_file\":\n\t\t\tfilename = req.split(\"|\")[2]\n\t\t\tself.files.append(filename)\n\t\t\tclient.send(\"ok\".encode(\"utf-8\"))\n\t\t\tself.recieveFile(client,self.host + \"_\" + str(self.port) + \"/\" + filename)\n\t\t\ttime.sleep(0.05)\n\t\t\tself.backup_to_successor(filename)\n\t\telif req_type == \"get_file\":\n\t\t\tfilename = req.split(\"|\")[2]\t\t\t\n\t\t\tif filename not in self.files:\n\t\t\t\tclient.send(\"404\".encode(\"utf-8\"))\n\t\t\telse:\n\t\t\t\tclient.send(\"ok\".encode(\"utf-8\"))\n\t\t\t\ttime.sleep(0.1)\n\t\t\t\tself.sendFile(client,self.host + \"_\" + str(self.port) + \"/\" + filename)\n\t\telif req_type == \"rehashfiles\":\n\t\t\tnode_id = req_source_id\n\t\t\tfile_hashes = []\n\t\t\tfiles_to_send = []\n\t\t\tfor file in self.files:\n\t\t\t\tfile_hashes.append(self.hasher(file))\n\t\t\ttotal_files = 0\n\t\t\tfor i in range(len(self.files)):\n\t\t\t\tif self.key > node_id:\n\t\t\t\t\tif file_hashes[i] > self.key and self.key > node_id:\n\t\t\t\t\t\ttotal_files += 1\n\t\t\t\t\t\tfiles_to_send.append(self.files[i])\t\n\t\t\t\t\t\tself.backUpFiles.append(self.files[i])\n\t\t\t\t\telif file_hashes[i] < node_id:\n\t\t\t\t\t\ttotal_files += 1\n\t\t\t\t\t\tfiles_to_send.append(self.files[i])\n\t\t\t\t\t\tself.backUpFiles.append(self.files[i])\n\t\t\t\telse:\n\t\t\t\t\tif self.key < node_id and file_hashes[i] > self.key and file_hashes[i] < node_id:\n\t\t\t\t\t\ttotal_files += 1\n\t\t\t\t\t\tfiles_to_send.append(self.files[i])\n\t\t\t\t\t\tself.backUpFiles.append(self.files[i])\n\n\n\t\t\t\t# if file_hashes[i] > self.key and self.key > node_id:\n\t\t\t\t# \ttotal_files += 1\n\t\t\t\t# \tfiles_to_send.append(self.files[i])\n\t\t\t\t# elif self.key < node_id and (file_hashes[i] > self.key and file_hashes[i] < node_id):\n\n\t\t\t\t# elif file_hashes[i] < node_id:\n\t\t\t\t# \ttotal_files += 1\n\t\t\t\t# \tfiles_to_send.append(self.files[i])\n\t\t\t\t\t\n\t\t\t#print(\"rehash send files\",len(files_to_send))\n\t\t\tres = str(total_files) + \"|\" +dumps(files_to_send)\n\t\t\tclient.send(str(res).encode(\"utf-8\"))\n\t\t\t#print(\"blocked rehash1\")\n\t\t\tfor file in files_to_send:\n\t\t\t\ttime.sleep(0.1)\n\t\t\t\tself.sendFile(client,self.host + \"_\" + str(self.port) + \"/\" + file)\n\t\t\t\tself.files.remove(file)\n\t\t\t#print(\"pass rehash\")\n\t\telif req_type == \"leaving_update_successor\":\n\t\t\tself.successor = (req.split(\"|\")[2], int(req.split(\"|\")[3]))\n\t\telif req_type == \"leaving_update_predecessor\":\n\t\t\tself.predecessor = (req.split(\"|\")[2], int(req.split(\"|\")[3]))\n\t\telif req_type == \"rehashing_to_you\":\n\t\t\tfiles_to_recv = req.split(\"|\")[2]\n\t\t\tfiles_to_recv = loads(files_to_recv)\n\t\t\tclient.send(\"send\".encode(\"utf-8\"))\n\t\t\t#print(\"length at recv:\", len(files_to_recv))\n\t\t\tfor file in files_to_recv:\n\t\t\t\tself.files.append(file)\n\t\t\t\t#print(\"leave-rehash\")\n\t\t\t\tself.recieveFile(client,self.host + \"_\" + str(self.port) + \"/\" + file)\n\t\t\tfor file in files_to_recv:\n\t\t\t\ttime.sleep(0.05)\n\t\t\t\tself.backup_to_successor(file)\n\t\telif req_type == \"backup_this_file\":\n\t\t\tfile_to_recv = req.split(\"|\")[2]\n\t\t\tclient.send(\"ok\".encode(\"utf-8\"))\n\t\t\tself.backUpFiles.append(file_to_recv)\n\t\t\tself.recieveFile(client, self.host + \"_\" + str(self.port) + \"/\" + file_to_recv)\n\t\tclient.close()\n\n\tdef listener(self):\n\t\t'''\n\t\tWe have already created a listener for you, any connection made by other nodes will be accepted here.\n\t\tFor every inbound connection we spin a new thread in the form of handleConnection function. You do not need\n\t\tto edit this function. If needed you can edit signature of handleConnection function, but nothing more.\n\t\t'''\n\t\tlistener = socket.socket()\n\t\tlistener.bind((self.host, self.port))\n\t\tlistener.listen(10)\n\t\twhile not self.stop:\n\t\t\tclient, addr = listener.accept()\n\t\t\tthreading.Thread(target = self.handleConnection, args = (client, addr)).start()\n\t\tprint (\"Shutting down node:\", self.host, self.port)\n\t\ttry:\n\t\t\tlistener.shutdown(2)\n\t\t\tlistener.close()\n\t\texcept:\n\t\t\tlistener.close()\n\n\tdef backup_to_successor(self,fileName):\n\t\tmsg = str(self.key) + \"|backup_this_file|\" +fileName\n\t\tsoc = socket.socket()\n\t\tsoc.connect(self.successor)\n\t\tsoc.send(msg.encode(\"utf-8\"))\n\t\tsoc.recv(2)\n\n\t\tself.sendFile(soc, self.host + \"_\" + str(self.port) + \"/\" + fileName)\n\n\n\n\tdef general_lookup(self,my_id,key,host, port):\n\t\tsuccessor_id = self.hasher(self.successor[0]+str(self.successor[1]))\n\t\tpredecessor_id = self.hasher(self.predecessor[0]+str(self.predecessor[1]))\n\t\t\n\t\t\t\n\t\tif key > predecessor_id and key < my_id:\n\t\t\treply = str(key) + \"|\" + \"lookup_result\" + \"|\" + self.host + \"|\" + str(self.port)\n\t\t\tself.send_message((host,port),reply)\n\t\telif my_id <= predecessor_id and (key < predecessor_id and key < my_id):\n\t\t\treply = str(key) + \"|\" + \"lookup_result\" + \"|\" + self.host + \"|\" + str(self.port)\n\t\t\tself.send_message((host,port),reply)\n\t\telif my_id <= predecessor_id and key > predecessor_id:\n\t\t\treply = str(key) + \"|\" + \"lookup_result\" + \"|\" + self.host + \"|\" + str(self.port)\n\t\t\tself.send_message((host,port),reply)\n\t\telse:\n\t\t\tlookup_req = str(key) + \"|\" + \"lookup\" + \"|\" + host + \"|\" + str(port)\n\t\t\tself.send_message(self.successor,lookup_req)\t\t\n\n\tdef join(self, joiningAddr):\n\t\t'''\n\t\tThis function handles the logic of a node joining. This function should do a lot of things such as:\n\t\tUpdate successor, predecessor, getting files, back up files. SEE MANUAL FOR DETAILS.\n\t\t'''\n\t\tif(type(joiningAddr) != str):\n\t\t\tjoin_req = str(self.hash_id) + \"|\" + \"join\" + \"|\" + self.host + \"|\" + str(self.port)\n\n\t\t\tself.send_message(joiningAddr,join_req)\n\t\t\twhile not self.joined:\n\t\t\t\tpass\n\t\t\t\n\t\t\t\n\t\t\tself.update_predecessor()\n\t\t\ttime.sleep(0.5)\n\t\t\trehash_req = str(self.hash_id) + \"|rehashfiles\"\n\t\t\tsoc = socket.socket()\n\t\t\tsoc.connect(self.successor)\n\t\t\tsoc.send(rehash_req.encode(\"utf-8\"))\n\t\t\t#print(\"blocked rehash2\")\n\t\t\tres = soc.recv(1024).decode(\"utf-8\")\n\t\t\t#print(\"/blocked rehash2\")\n\t\t\tres = res.split(\"|\")\n\t\t\ttotal_files = int(res[0])\n\t\t\tfiles = loads(res[1])\n\t\t\t#print(\"rehash recv files\",len(files))\n\t\t\tfor file in files:\n\t\t\t\tself.recieveFile(soc,self.host + \"_\" + str(self.port) + \"/\" + file)\n\t\t\t\tself.files.append(file)\n\t\t\t\n\t\t\t\t\n\n\n\t\t\t\n\t\t\n\n\tdef update_predecessor(self):\n\t\treq = str(str(self.hash_id) + \"|new_predecessor|\" + self.host + \"|\" + str(self.port))\n\t\tres = self.send_message_reply(self.successor,req)\n\t\tif res == \"one_node\":\n\t\t\tself.predecessor = self.successor\n\t\t\t\n\t#6435\n\tdef send_message_reply(self, addr, message):\n\t\treply = \"\"\n\t\ttry:\n\t\t\tsoc = socket.socket()\n\t\t\tsoc.connect(addr)\n\t\t\tsoc.send(message.encode(\"utf-8\"))\n\t\t\treply = soc.recv(1024).decode(\"utf-8\")\n\t\texcept:\n\t\t\tpass\n\t\treturn reply\n\t\t\n\tdef send_message(self, addr, message):\n\t\tsoc = socket.socket()\n\t\tsoc.connect(addr)\n\t\tsoc.send(message.encode(\"utf-8\"))\n\t\n\n\tdef pinger(self):\n\t\tno_reply_count = 0\n\t\twhile self.start_pinging and not self.stop:\n\t\t\ttime.sleep(0.5)\n\t\t\tif no_reply_count == 1:\n\t\t\t\tno_reply_count = 0\n\t\t\t#\tprint(\"\\n\\n\\nMY SUCCESSOR FAILED\\n\\n\\n\")\n\t\t\t\tself.successor = self.backup_successor\n\t\t\t\tself.update_predecessor()\n\t\t\tif self.successor != (self.host,self.port):\n\n\t\t\t\treq = str(self.hash_id) + \"|updated_predecessor_successor\"\n\t\t\t\tpredecessor = self.send_message_reply(self.successor,req)\n\t\t\t\tif predecessor != \"\":\n\t\t\t\t\tself.backup_successor = (predecessor.split(\"|\")[2],int(predecessor.split(\"|\")[3]))\n\n\t\t\t\t\tif (self.host,self.port) != (predecessor.split(\"|\")[0],int(predecessor.split(\"|\")[1])):\n\t\t\t\t\t\tself.successor = (predecessor.split(\"|\")[0],int(predecessor.split(\"|\")[1]))\n\t\t\t\t\t\tself.update_predecessor()\n\t\t\t\telse:\n\t\t\t\t\tno_reply_count+=1\n\n\n\n\n\n\tdef put(self, fileName):\n\t\t'''\n\t\tThis function should first find node responsible for the file given by fileName, then send the file over the socket to that node\n\t\tResponsible node should then replicate the file on appropriate node. SEE MANUAL FOR DETAILS. Responsible node should save the files\n\t\tin directory given by host_port e.g. \"localhost_20007/file.py\".\n\t\t'''\n\t\tfile_hash = self.hasher(fileName)\n\t\tself.lookup_queries[file_hash] = (self.host,self.port)\n\t\tself.file_lookups[file_hash] = [False,()]\n\t\tself.general_lookup(self.hash_id,file_hash,self.host,self.port)\n\t\twhile self.file_lookups[file_hash][0] != True:\n\t\t\tpass\n\n\t\tsoc = socket.socket()\n\t\tsoc.connect(self.file_lookups[file_hash][1])\n\t\treq = str(file_hash) + \"|new_file|\" + fileName\n\t\tsoc.send(req.encode(\"utf-8\"))\n\t\t#print(\"put block\")\n\t\tsoc.recv(1024)\n\t\t#print(\"/put block\")\n\t\tself.sendFile(soc,fileName)\n\t\t\n\tdef get(self, fileName):\n\t\t'''\n\t\tThis function finds node responsible for file given by fileName, gets the file from responsible node, saves it in current directory\n\t\ti.e. \"./file.py\" and returns the name of file. If the file is not present on the network, return None.\n\t\t'''\n\t\tfile_hash = self.hasher(fileName)\n\t\tself.lookup_queries[file_hash] = (self.host,self.port)\n\t\tself.file_lookups[file_hash] = [False,()]\n\t\tself.general_lookup(self.hash_id,file_hash,self.host,self.port)\n\t\twhile self.file_lookups[file_hash][0] != True:\n\t\t\t#print(\"blocked in get1\")\n\t\t\tpass\n\n\t\tsoc = socket.socket()\n\t\tsoc.connect(self.file_lookups[file_hash][1])\n\t\treq = str(file_hash) + \"|get_file|\" + fileName\n\t\tsoc.send(req.encode(\"utf-8\"))\n\t\t#print(\"get2\")\n\n\t\tavail = soc.recv(1024)\n\t\t#print(\"/get2\")\n\t\tif avail.decode(\"utf-8\") == \"404\":\n\t\t\treturn None\n\t\tself.recieveFile(soc,fileName)\n\t\treturn fileName\n\t\t\n\n\n\n\t\t\n\tdef leave(self):\n\t\t'''\n\t\tWhen called leave, a node should gracefully leave the network i.e. it should update its predecessor that it is leaving\n\t\tit should send its share of file to the new responsible node, close all the threads and leave. You can close listener thread\n\t\tby setting self.stop flag to True\n\t\t'''\n\t\tself.start_pinging = False\n\t\ttime.sleep(0.5)\n\t\tmsg = str(self.hash_id) + \"|leaving_update_successor|\" + self.successor[0] + \"|\" +str(self.successor[1]) \n\t\tself.send_message(self.predecessor,msg)\n\t\tmsg = str(self.hash_id) + \"|leaving_update_predecessor|\" + self.predecessor[0] + \"|\" +str(self.predecessor[1]) \n\t\tself.send_message(self.successor,msg)\n\t\t\n\t\tsoc = socket.socket()\n\t\tsoc.connect(self.successor)\n\t\tmsg = str(self.hash_id) + \"|rehashing_to_you|\" + dumps(self.files)\n\t\tsoc.send(msg.encode(\"utf-8\"))\n\t\t#print(\"leave block\")\n\t\tsoc.recv(1024)\n\t\t#print(\"/leave block\")\n\t\t#print(\"length at send:\", len(self.files))\n\t\tfor file in self.files:\n\t\t\ttime.sleep(0.1)\n\t\t\tself.sendFile(soc,self.host + \"_\" + str(self.port) + \"/\" + file)\n\n\t\tfor file in self.backUpFiles:\n\t\t\ttime.sleep(0.05)\n\t\t\tself.backup_to_successor(file)\t\t\n\n\tdef sendFile(self, soc, fileName):\n\t\t''' \n\t\tUtility function to send a file over a socket\n\t\t\tArguments:\tsoc => a socket object\n\t\t\t\t\t\tfileName => file's name including its path e.g. NetCen/PA3/file.py\n\t\t'''\n\t\tfileSize = os.path.getsize(fileName)\n\t\tsoc.send(str(fileSize).encode('utf-8'))\n\t\t#print(\"send block\")\n\n\t\tsoc.recv(1024).decode('utf-8')\n\t\t#print(\"/send block\")\n\n\t\twith open(fileName, \"rb\") as file:\n\t\t\t#print(\"send block1\")\n\n\t\t\tcontentChunk = file.read(1024)\n\t\t\twhile contentChunk!=\"\".encode('utf-8'):\n\t\t\t\t#print(\"send block2\")\n\n\t\t\t\tsoc.send(contentChunk)\n\t\t\t\tcontentChunk = file.read(1024)\n\n\tdef recieveFile(self, soc, fileName):\n\t\t'''\n\t\tUtility function to recieve a file over a socket\n\t\t\tArguments:\tsoc => a socket object\n\t\t\t\t\t\tfileName => file's name including its path e.g. NetCen/PA3/file.py\n\t\t'''\n\t\t#print(\"recv block\")\n\t\tfileSize = int(soc.recv(1024).decode('utf-8'))\n\t\t#print(\"/recv block\")\n\t\tsoc.send(\"ok\".encode('utf-8'))\t\t\n\n\t\tcontentRecieved = 0\n\t\tfile = open(fileName, \"wb\")\n\t\twhile contentRecieved < fileSize:\n\t\t\t#print(\"recv block1\")\n\n\t\t\tcontentChunk = soc.recv(1024)\n\t\t\t#print(\"/recv block1\")\n\t\t\tcontentRecieved += len(contentChunk)\n\t\t\tfile.write(contentChunk)\n\t\tfile.close()\n\n\tdef kill(self):\n\t\t# DO NOT EDIT THIS, used for code testing\n\t\tself.stop = True\n\n\t\t\n","sub_path":"DHT.py","file_name":"DHT.py","file_ext":"py","file_size_in_byte":14530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"484425739","text":"# This script reads each line of a file and counts the number of\n# characters in each line. It keeps track of the total number of \n# characters read up to 1,000.\n\nfilename = 'test_file.txt'\nf = open(filename,'r') # open file read only\nall_lines = f.read().splitlines() # read all lines of the file, remove '\\n'\nf.close() # close file\n\n# initialize variables\nlengths = []\ntotal_length = 0\n\nfor single_line in all_lines: # loop through each line and count chars\n if total_length >= 1000: # stop once total is 1000\n break\n else:\n lengths.append(len(single_line)) # add each line count to vector\n total_length = total_length + len(single_line) # tally total count\n \n# print the char length vector of all lines and total char count\nprint('number of characters for each line: ',lengths) \nprint('total characters in file, without comments: ', total_length)\n","sub_path":"scraping_sorting/countcharsall.py","file_name":"countcharsall.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"635453817","text":"from __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom pyramid.config import Configurator\nfrom pyramid.settings import asbool\nfrom pyramid.authentication import AuthTktAuthenticationPolicy\nfrom pyramid.authorization import ACLAuthorizationPolicy\nfrom sqlalchemy import engine_from_config\n\nfrom lwp.db import DBSession, Base\nfrom lwp.security import groupfinder, RootFactory, BaseRequest\n\n\ndef main(global_config, **settings):\n \"\"\"\n This function returns a WSGI application.\n \"\"\"\n # load custom settings from the ini file, provide defaults if missing\n debug = asbool(settings.get('lwp.debug', 'false'))\n static_dir = settings.get('lwp.static_dir', '/var/www/lwp/static')\n\n # write modified settings back to settings dict for use in the app\n settings['lwp.debug'] = debug\n settings['lwp.static_dir'] = static_dir\n settings['buckets.enabled'] = asbool(settings.get('buckets.enabled', 'false'))\n settings['storage_repos'] = [(key[8:], value) for key, value in settings.items() if key.startswith('storage.')]\n\n # initialise SQLAlchemy\n engine = engine_from_config(settings, 'sqlalchemy.')\n DBSession.configure(bind=engine)\n Base.metadata.bind = engine\n\n # setup security policies\n authn_policy = AuthTktAuthenticationPolicy(\n settings['session.secret'],\n http_only=True,\n callback=groupfinder,\n hashalg='sha512'\n )\n authz_policy = ACLAuthorizationPolicy()\n\n # setup the Configurator\n config = Configurator(\n settings=settings,\n authentication_policy=authn_policy,\n authorization_policy=authz_policy,\n root_factory=RootFactory,\n )\n\n # static routes\n config.add_static_view('static', static_dir, cache_max_age=3600)\n\n # This works in Pyramid 1.5, but not in 1.4 (though the docs say it should)\n # config.add_request_method(get_current_user, 'user', reify=True)\n\n # This method works fine with Pyramid 1.4\n config.set_request_factory(BaseRequest)\n\n # routing table\n config.add_route('home', '/')\n config.add_route('about', '/about')\n config.add_route('edit', '/container/{container}/edit')\n config.add_route('start-container', '/container/{container}/start')\n config.add_route('stop-container', '/container/{container}/stop')\n config.add_route('freeze-container', '/container/{container}/freeze')\n config.add_route('unfreeze-container', '/container/{container}/unfreeze')\n config.add_route('destroy-container', '/container/{container}/destroy')\n config.add_route('push-container', '/container/{container}/push')\n config.add_route('reboot-container', '/container/{container}/reboot')\n config.add_route('create-container', '/container/create')\n config.add_route('clone-container', '/container/clone')\n config.add_route('backup-container', '/container/backup')\n config.add_route('lxc-net', '/settings/lxc-net')\n config.add_route('api-tokens', '/lwp/tokens')\n config.add_route('users', '/lwp/users')\n config.add_route('checkconfig', '/checkconfig')\n config.add_route('login', '/login')\n config.add_route('logout', '/logout')\n config.add_route('refresh-host-info', '/_refresh_host_info')\n config.add_route('refresh-memory', '/_refresh_memory_{name}')\n config.add_route('check-version', '/_check_version')\n config.add_route('api-container', '/api/v1/container')\n config.add_route('api-container-detail', '/api/v1/container/{container}')\n config.add_route('api-token', '/api/v1/token')\n config.add_route('api-token-detail', '/api/v1/token/{token}')\n config.scan()\n\n # start app\n return config.make_wsgi_app()\n","sub_path":"lwp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"154203765","text":"import matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport time\nimport numpy as np\nimport alsaaudio, time, audioop\nimport scipy\n\ndef update_line(num, data, line):\n data = soundRecord()\n line.set_data(data[...,:num])\n #print (data)\n return line,\n\ndef soundRecord():\n # Open the device in nonblocking capture mode. The last argument could\n # just as well have been zero for blocking mode. Then we could have\n # left out the sleep call in the bottom of the loop\n inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NONBLOCK)\n \n # Set attributes: Mono, 8000 Hz, 16 bit little endian samples\n inp.setchannels(1)\n inp.setrate(8000)\n inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)\n \n # The period size controls the internal number of frames per period.\n # The significance of this parameter is documented in the ALSA api.\n # For our purposes, it is suficcient to know that reads from the device\n # will return this many frames. Each frame being 2 bytes long.\n # This means that the reads below will return either 320 bytes of data\n # or 0 bytes of data. The latter is possible because we are in nonblocking\n # mode.\n inp.setperiodsize(160)\n x = []\n y = []\n i=0\n while i<4:\n # Read data from device\n l,data = inp.read()\n if l:\n \t# Return the maximum of the absolute value of all samples in a fragment.\n #print (l)\n x.append(audioop.rms(data,2))\n y.append(i)\n #print audioop.max(data, 2)\n i+=1\n time.sleep(.001)\n x=np.array((y,x))\n freq = scipy.fft(x[:,1])\n Xdb = 20*scipy.log10(scipy.absolute(freq))\n \n \n print (y,frequencies)\n #print x\n return x\n\nfig1 = plt.figure()\n\n\nl, = plt.plot([], [], 'r--')\nplt.xlim(0, 3)\nplt.ylim(0, 2000)\nplt.xlabel('x')\nplt.title('Power')\n\ndata = np.array((0,0))\nline_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l), interval=5, blit=True)\n#line_ani.save('lines.mp4')\n\n\nplt.show()\n","sub_path":"recordSoundFunction.py","file_name":"recordSoundFunction.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"442385861","text":"# pylint: disable=R0201, C0103\n\nfrom . import utils, color\n\nINIT = utils.test_init\nEND = utils.test_end\nAST = utils.my_ast\n\nprintc = utils.printc\n\n\nclass TestScalarDimension(utils.TestCase):\n\n def setUp(self):\n self.DV = AST.DimensionVisitor()\n\n def test_name(self):\n INIT(self, 'a')\n\n node = AST.parse('a')\n self.DV.visit(node)\n self.assertDimEqual(self.DV.result[node], AST.Token())\n END()\n\n def test_int(self):\n INIT(self, '3')\n\n node = AST.parse('3')\n self.DV.visit(node)\n self.assertDimEqual(self.DV.result[node], AST.Token())\n END()\n\n def test_float(self):\n INIT(self, '3.')\n\n node = AST.parse('3.')\n self.DV.visit(node)\n self.assertDimEqual(self.DV.result[node], AST.Token())\n END()\n\n def test_name_predefined(self):\n INIT(self, 'a (predefined)')\n\n self.DV.predefined['a'] = AST.Token((1, 2))\n node = AST.parse('a')\n self.DV.visit(node)\n self.assertDimEqual(self.DV.result[node], AST.Token((1, 2)))\n\n END()\n","sub_path":"server/tests/test_scalar.py","file_name":"test_scalar.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"84957124","text":"\"\"\"\nWritten by: Ben Antonellis\nGithub: https://github.com/Linnydude3347\nImport Statements\n\"\"\"\nimport os\nimport random\nimport re\nimport string\nfrom typing import List\n\nUNCOMPRESSED_FILE = \"code/python/compression/uncompressed.txt\"\nCOMPRESSED_FILE = \"code/python/compression/compressed.txt\"\nDECOMPRESSED_FILE = \"code/python/compression/decompressed.txt\"\n\ndef get_random_letter(previous_letter: str) -> str:\n \"\"\"\n Gets a letter that isn't the previous letter\n\n :param str previous_letter: Previous letter used so no duplication\n\n :return str: Randomly chosen letter\n \"\"\"\n letter = random.choice(string.ascii_lowercase)\n return letter if letter != previous_letter else get_random_letter(previous_letter)\n\ndef generate_file() -> None:\n \"\"\"\n Generates file to be compressed\n\n :return: None\n \"\"\"\n min_file_size, max_file_size = 10000, 100000\n previous_letter = \"A\"\n with open(UNCOMPRESSED_FILE, \"w\") as file:\n for _ in range(random.randint(min_file_size, max_file_size)):\n letter = get_random_letter(previous_letter)\n min_letter_amount, max_letter_amount = 5, 9\n file.write(\n letter for _ in range(\n random.randint(min_letter_amount, max_letter_amount)\n )\n )\n previous_letter = letter\n\ndef compress_file(file_to_be_compressed: str) -> None:\n \"\"\"\n Creates a new compressed file from the past file\n\n :param str file_to_be_compressed: Path to file to compress\n\n :return: None\n \"\"\"\n compressed_string = \"\"\n characters = file_to_list(file_to_be_compressed)\n count = 0\n for index, value in enumerate(characters):\n try:\n if value == characters[index + 1]:\n count += 1\n else:\n compressed_string += f\"{value}{count + 1}\"\n count = 0\n except IndexError:\n if characters[len(characters) - 1] == characters[len(characters) - 2]:\n count += 1\n compressed_string += f\"{value}{count}\"\n else:\n quit(\"Something went wrong...\")\n\n with open(COMPRESSED_FILE, \"w\") as compressed_file:\n compressed_file.write(compressed_string)\n\ndef decompress_file(file_to_be_decompressed: str) -> None:\n \"\"\"\n Decompresses passed file\n\n :param str file_to_be_decompressed: Path to file to decompress\n\n :return: None\n \"\"\"\n compressed_content = file_to_one_line(file_to_be_decompressed)\n decompressed_content = re.findall(\"..\", compressed_content)\n with open(DECOMPRESSED_FILE, \"w\") as decompressed_file:\n for pair in decompressed_content:\n decompressed_file.write(f\"{pair[0] * int(pair[1])}\")\n\ndef get_file_size(filepath: str) -> int:\n \"\"\"\n Returns the file size, in bytes\n\n :param str filepath: File to determine size of\n\n :return int: Size of file\n \"\"\"\n return os.path.getsize(filepath)\n\ndef file_to_one_line(filepath: str) -> str:\n \"\"\"\n Concats all lines in file to one line and returns line\n\n :param str filepath: Path to file to analyze\n\n :return str: All lines combined to one line\n \"\"\"\n with open(filepath, \"r\") as file_to_read:\n return ''.join(line for line in file_to_read)\n\ndef file_to_list(filepath: str) -> List[str]:\n \"\"\"\n Converts all the lines into a list of characters and returns list\n\n :param str filepath: Path to file to analyze\n\n :return List[str]: A list of characters in the file\n \"\"\"\n with open(filepath, \"r\") as file_to_read:\n lines = ''.join(line for line in file_to_read)\n return list(map(str, lines))\n\n\nif __name__ == '__main__':\n generate_file()\n print(f\"\"\"\n File size before compression: \n {get_file_size(UNCOMPRESSED_FILE)} bytes\n {get_file_size(UNCOMPRESSED_FILE) / 1024} kilobytes\n {(get_file_size(UNCOMPRESSED_FILE) / 1024) / 1024} megabytes\n \"\"\")\n compress_file(UNCOMPRESSED_FILE)\n print(f\"\"\"\n File size after compression: \n {get_file_size(COMPRESSED_FILE)} bytes\n {get_file_size(COMPRESSED_FILE) / 1024} kilobytes\n {(get_file_size(COMPRESSED_FILE) / 1024) / 1024} megabytes\n \"\"\")\n decompress_file(COMPRESSED_FILE)\n print(f\"\"\"\n File size after decompression: \n {get_file_size(DECOMPRESSED_FILE)} bytes\n {get_file_size(DECOMPRESSED_FILE) / 1024} kilobytes\n {(get_file_size(DECOMPRESSED_FILE) / 1024) / 1024} megabytes\n \"\"\")\n","sub_path":"Python/Compression/compress.py","file_name":"compress.py","file_ext":"py","file_size_in_byte":4511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"184077175","text":"from mikatools import *\nfrom natas.normalize import call_onmt\n\n\ndef _chunks(l, n):\n\tn = max(1, n)\n\treturn [l[i:i+n] for i in range(0, len(l), n)]\n\ndef _dechunk(l):\n\tc = [x[0] for x in l]\n\tc = \" _ \".join(c)\n\tc = c.replace(\" \", \"\")\n\tc = c.replace(\"_\",\" \")\n\treturn c\n\ndef normalize_sentences(tokenized_sentences, wnut19_model=False):\n\tchunks = []\n\tsentence_map = []\n\tfor i, tokenized_sentence in enumerate(tokenized_sentences):\n\t\tif isinstance(tokenized_sentence, str):\n\t\t\ttokenized_sentence = tokenized_sentence.split(\" \")\n\t\tchunks_l = _chunks([\" \".join(x) for x in tokenized_sentence],3)\n\t\tsent_chunks = [\" _ \".join(x) for x in chunks_l]\n\t\tfor c in sent_chunks:\n\t\t\tchunks.append(c)\n\t\t\tsentence_map.append(i)\n\tres = _normalize_chunks(chunks, wnut19_model=wnut19_model)\n\tnormalized_sentences = []\n\tcur =0\n\tnorm = []\n\tfor i,s in enumerate(res):\n\t\tsent_i = sentence_map[i]\n\t\tif sent_i != cur:\n\t\t\tcur = sent_i\n\t\t\tnormalized_sentences.append(norm)\n\t\t\tnorm = []\n\t\tif sent_i == cur:\n\t\t\tnorm.append(s)\n\tnormalized_sentences.append(norm)\n\tr = [_dechunk(x) for x in normalized_sentences]\n\treturn r\n\n\n\n\ndef normalize_sentence(tokens, wnut19_model=False):\n\tif isinstance(tokens, str):\n\t\ttokens = tokens.split(\" \")\n\tchunks_l = _chunks([\" \".join(x) for x in tokens],3)\n\tchunks = [\" _ \".join(x) for x in chunks_l]\n\tres = _normalize_chunks(chunks, wnut19_model=wnut19_model)\n\treturn _dechunk(res)\n\ndef _normalize_chunks(chunks, wnut19_model=False):\n\tif wnut19_model:\n\t\t#New default model, might not work on some systems\n\t\tmodel_name = \"murre_norm_paper.pt\"\n\telse:\n\t\t#Same model trained on MacOS, slightly higher character error rate\n\t\tmodel_name = \"murre_norm_default.pt\"\n\tmodel_name = script_path(\"models/\" + model_name)\n\n\tres = call_onmt(chunks, model_name, n_best=1)\n\treturn res","sub_path":"murre/normalizer.py","file_name":"normalizer.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"190819800","text":"\n\n#calss header\nclass _PULSE():\n\tdef __init__(self,): \n\t\tself.name = \"PULSE\"\n\t\tself.definitions = [u'the regular beating of the heart, especially when it is felt at the wrist or side of the neck: ', u\"to hold someone's wrist and count how many times the heart beats in one minute\", u'a short period of energy that is repeated regularly, such as a short, loud sound or a short flash of light: ', u'seeds such as beans or peas that are cooked and eaten: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_pulse.py","file_name":"_pulse.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"394371730","text":"import logging\nfrom datetime import datetime\n\nimport discord\nfrom discord.ext import commands\nfrom django.conf import settings\nfrom django.utils.translation import gettext as _\n\nfrom .cogs import Miscellaneous, Roleplay\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass OilAndRopeBot(commands.Bot):\n \"\"\"\n Custom class to control the behavior of the bot by environment variables.\n \"\"\"\n\n def __init__(self, **options):\n self.command_prefix = settings.BOT_COMMAND_PREFIX\n self.description = settings.BOT_DESCRIPTION\n self.token = settings.BOT_TOKEN\n if 'intents' not in options:\n intents = discord.Intents.default()\n intents.members = True\n options['intents'] = intents\n super().__init__(command_prefix=self.command_prefix, description=self.description, **options)\n self.load_commands()\n\n def load_commands(self):\n \"\"\"\n Reads all the commands from `bot.commands` and adds them to the bot command list.\n \"\"\"\n\n print('\\nLoading commands ', end='')\n\n # List of categories\n cogs = [Miscellaneous, Roleplay]\n new_commands = []\n\n for cog in cogs:\n cog = cog(self)\n self.add_cog(cog)\n new_commands.extend(cog.get_commands())\n [print('.', end='') for _ in new_commands]\n\n # Linebreak to clean up\n print('\\n')\n\n async def on_ready(self):\n init_message = '{bot} is ready!\\nID: {id}\\nAt {time}'.format(\n bot=self.user.name,\n id=self.user.id,\n time=datetime.now().strftime('%d/%m/%Y %H:%M')\n )\n print(init_message)\n LOGGER.info(init_message)\n\n presence = f'awesome sessions! Type \\'{settings.BOT_COMMAND_PREFIX}help\\' for help.'\n activity = discord.Game(name=presence)\n status = discord.Status.online\n await self.change_presence(activity=activity, status=status)\n\n async def first_join_message(self, channel):\n greetings_msg = _('hello!').capitalize()\n info_msg = _('you are about to experience a brand-new way to manage sessions and play!').capitalize()\n msg = f'{greetings_msg} {info_msg}'\n await channel.send(f'{msg}')\n\n async def on_guild_join(self, guild):\n # Say hello in System's messages channel or first in list\n greet_channel = guild.system_channel or guild.text_channels[0]\n async with greet_channel.typing():\n await self.first_join_message(greet_channel)\n\n async def on_message(self, message: discord.Message):\n if not message.author.bot and message.content.startswith(self.command_prefix):\n author = message.author.name\n author_id = message.author.id\n message_content = message.content\n log_message = f'{author} ({author_id}): {message_content}'\n print(log_message)\n LOGGER.info(log_message)\n await super().on_message(message)\n\n def run(self, *args, **kwargs): # pragma: no cover\n super().run(self.token, *args, **kwargs)\n","sub_path":"bot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"556850918","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport urllib\nimport re\n\nresult = urllib.urlopen(\"http://www.douban.com/people/ahbei/\")\nhtml = result.read()\npattern = re.compile(r'http://([^\"]+jpg)')\nphoto = re.findall(pattern, html)\nprint(photo)\nfor url in photo:\n filename = url.split('/')[-1]\n url = \"http://\"+ url\n urllib.urlretrieve(url, filename)\n","sub_path":"03/yangxiangyu/getphoto.py","file_name":"getphoto.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"561013986","text":"import argparse\nimport importlib\nimport importlib.resources\nimport os\nimport random\nfrom shutil import copyfile\nimport time\n\n# Plotman libraries\nfrom plotman import analyzer, archive, configuration, interactive, manager, plot_util, reporting\nfrom plotman import resources as plotman_resources\nfrom plotman.job import Job\n\n\nclass PlotmanArgParser:\n def add_idprefix_arg(self, subparser):\n subparser.add_argument(\n 'idprefix',\n type=str,\n nargs='+',\n help='disambiguating prefix of plot ID')\n\n def parse_args(self):\n parser = argparse.ArgumentParser(description='Chia plotting manager.')\n sp = parser.add_subparsers(dest='cmd')\n\n sp.add_parser('version', help='print the version')\n\n sp.add_parser('status', help='show current plotting status')\n \n sp.add_parser('dirs', help='show directories info')\n\n sp.add_parser('interactive', help='run interactive control/monitoring mode')\n\n sp.add_parser('dsched', help='print destination dir schedule')\n\n sp.add_parser('plot', help='run plotting loop')\n\n sp.add_parser('archive', help='move completed plots to farming location')\n\n p_config = sp.add_parser('config', help='display or generate plotman.yaml configuration')\n sp_config = p_config.add_subparsers(dest='config_subcommand')\n sp_config.add_parser('generate', help='generate a default plotman.yaml file and print path')\n sp_config.add_parser('path', help='show path to current plotman.yaml file')\n\n p_details = sp.add_parser('details', help='show details for job')\n self.add_idprefix_arg(p_details)\n\n p_files = sp.add_parser('files', help='show temp files associated with job')\n self.add_idprefix_arg(p_files)\n\n p_kill = sp.add_parser('kill', help='kill job (and cleanup temp files)')\n self.add_idprefix_arg(p_kill)\n\n p_suspend = sp.add_parser('suspend', help='suspend job')\n self.add_idprefix_arg(p_suspend)\n\n p_resume = sp.add_parser('resume', help='resume suspended job')\n self.add_idprefix_arg(p_resume)\n\n p_analyze = sp.add_parser('analyze', help='analyze timing stats of completed jobs')\n\n p_analyze.add_argument('--clipterminals',\n action='store_true',\n help='Ignore first and last plot in a logfile, useful for '\n 'focusing on the steady-state in a staggered parallel '\n 'plotting test (requires plotting with -n>2)')\n p_analyze.add_argument('--bytmp',\n action='store_true',\n help='slice by tmp dirs')\n p_analyze.add_argument('--bybitfield',\n action='store_true',\n help='slice by bitfield/non-bitfield sorting')\n p_analyze.add_argument('logfile', type=str, nargs='+',\n help='logfile(s) to analyze')\n\n args = parser.parse_args()\n return args\n\ndef get_term_width():\n columns = 0\n try:\n (rows, columns) = os.popen('stty size', 'r').read().split()\n columns = int(columns)\n except:\n columns = 120 # 80 is typically too narrow. TODO: make a command line arg.\n return columns\n\ndef main():\n random.seed()\n\n pm_parser = PlotmanArgParser()\n args = pm_parser.parse_args()\n\n if args.cmd == 'version':\n import pkg_resources\n print(pkg_resources.get_distribution('plotman'))\n return\n\n elif args.cmd == 'config':\n config_file_path = configuration.get_path()\n if args.config_subcommand == 'path':\n if os.path.isfile(config_file_path):\n print(config_file_path)\n return\n print(f\"No 'plotman.yaml' file exists at expected location: '{config_file_path}'\")\n print(f\"To generate a default config file, run: 'plotman config generate'\")\n return 1\n if args.config_subcommand == 'generate':\n if os.path.isfile(config_file_path):\n overwrite = None\n while overwrite not in {\"y\", \"n\"}:\n overwrite = input(\n f\"A 'plotman.yaml' file already exists at the default location: '{config_file_path}' \\n\\n\"\n \"\\tInput 'y' to overwrite existing file, or 'n' to exit without overwrite.\"\n ).lower()\n if overwrite == 'n':\n print(\"\\nExited without overrwriting file\")\n return\n\n # Copy the default plotman.yaml (packaged in plotman/resources/) to the user's config file path,\n # creating the parent plotman file/directory if it does not yet exist\n with importlib.resources.path(plotman_resources, \"plotman.yaml\") as default_config:\n config_dir = os.path.dirname(config_file_path)\n\n os.makedirs(config_dir, exist_ok=True)\n copyfile(default_config, config_file_path)\n print(f\"\\nWrote default plotman.yaml to: {config_file_path}\")\n return\n\n if not args.config_subcommand:\n print(\"No action requested, add 'generate' or 'path'.\")\n return\n\n config_path = configuration.get_path()\n config_text = configuration.read_configuration_text(config_path)\n cfg = configuration.get_validated_configs(config_text, config_path)\n\n #\n # Stay alive, spawning plot jobs\n #\n if args.cmd == 'plot':\n print('...starting plot loop')\n while True:\n wait_reason = manager.maybe_start_new_plot(cfg.directories, cfg.scheduling, cfg.plotting)\n\n # TODO: report this via a channel that can be polled on demand, so we don't spam the console\n if wait_reason:\n print('...sleeping %d s: %s' % (cfg.scheduling.polling_time_s, wait_reason))\n\n time.sleep(cfg.scheduling.polling_time_s)\n\n #\n # Analysis of completed jobs\n #\n elif args.cmd == 'analyze':\n\n analyzer.analyze(args.logfile, args.clipterminals,\n args.bytmp, args.bybitfield)\n\n else:\n jobs = Job.get_running_jobs(cfg.directories.log)\n\n # Status report\n if args.cmd == 'status':\n print(reporting.status_report(jobs, get_term_width()))\n\n # Directories report\n elif args.cmd == 'dirs':\n print(reporting.dirs_report(jobs, cfg.directories, cfg.scheduling, get_term_width()))\n\n elif args.cmd == 'interactive':\n interactive.run_interactive()\n\n # Start running archival\n elif args.cmd == 'archive':\n print('...starting archive loop')\n firstit = True\n while True:\n if not firstit:\n print('Sleeping 60s until next iteration...')\n time.sleep(60)\n jobs = Job.get_running_jobs(cfg.directories.log)\n firstit = False\n\n archiving_status, log_message = archive.spawn_archive_process(cfg.directories, jobs)\n if log_message:\n print(log_message)\n\n\n # Debugging: show the destination drive usage schedule\n elif args.cmd == 'dsched':\n for (d, ph) in manager.dstdirs_to_furthest_phase(jobs).items():\n print(' %s : %s' % (d, str(ph)))\n \n #\n # Job control commands\n #\n elif args.cmd in [ 'details', 'files', 'kill', 'suspend', 'resume' ]:\n print(args)\n\n selected = []\n\n # TODO: clean up treatment of wildcard\n if args.idprefix[0] == 'all':\n selected = jobs\n else:\n # TODO: allow multiple idprefixes, not just take the first\n selected = manager.select_jobs_by_partial_id(jobs, args.idprefix[0])\n if (len(selected) == 0):\n print('Error: %s matched no jobs.' % args.idprefix[0])\n elif len(selected) > 1:\n print('Error: \"%s\" matched multiple jobs:' % args.idprefix[0])\n for j in selected:\n print(' %s' % j.plot_id)\n selected = []\n\n for job in selected:\n if args.cmd == 'details':\n print(job.status_str_long())\n\n elif args.cmd == 'files':\n temp_files = job.get_temp_files()\n for f in temp_files:\n print(' %s' % f)\n\n elif args.cmd == 'kill':\n # First suspend so job doesn't create new files\n print('Pausing PID %d, plot id %s' % (job.proc.pid, job.plot_id))\n job.suspend()\n\n temp_files = job.get_temp_files()\n print('Will kill pid %d, plot id %s' % (job.proc.pid, job.plot_id))\n print('Will delete %d temp files' % len(temp_files))\n conf = input('Are you sure? (\"y\" to confirm): ')\n if (conf != 'y'):\n print('canceled. If you wish to resume the job, do so manually.')\n else:\n print('killing...')\n job.cancel()\n print('cleaing up temp files...')\n for f in temp_files:\n os.remove(f)\n\n elif args.cmd == 'suspend':\n print('Suspending ' + job.plot_id)\n job.suspend()\n elif args.cmd == 'resume':\n print('Resuming ' + job.plot_id)\n job.resume()\n","sub_path":"src/plotman/plotman.py","file_name":"plotman.py","file_ext":"py","file_size_in_byte":9660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"1188369","text":"##################################\n#\n# These functions populate the logged in control pages\n#\n##################################\n\nfrom datetime import datetime, timedelta\n\nfrom skipole import FailPage, GoTo, ValidateError, ServerError\n\nfrom .. import sun, database_ops, redis_ops, send_mqtt\n\nfrom .sessions import doorsession\n\n\ndef create_index(skicall):\n \"Fills in the remscope index page, also used to refresh the page by JSON\"\n\n # door is one of UNKNOWN, STOPPED, OPEN, CLOSED, OPENING, CLOSING\n door = redis_ops.get_door(skicall.proj_data.get(\"rconn_0\"))\n skicall.page_data['door_status', 'para_text'] = \"Door : \" + door\n if (door == 'UNKNOWN') or (door == 'CLOSED') or (door == 'STOPPED'):\n skicall.page_data['door', 'button_text'] = 'Open Door'\n skicall.page_data['door', 'action'] = 'open'\n elif (door == 'OPENING') or (door == 'CLOSING'):\n skicall.page_data['door', 'button_text'] = 'Halt Door'\n skicall.page_data['door', 'action'] = 'halt'\n else:\n skicall.page_data['door', 'button_text'] = 'Close Door'\n skicall.page_data['door', 'action'] = 'close'\n\n skicall.page_data['utc', 'para_text'] = datetime.utcnow().strftime(\"UTC Time : %H:%M\")\n\n user_id = skicall.call_data['user_id']\n\n booked = database_ops.get_users_next_session(datetime.utcnow(), user_id)\n\n # does this user own the current session\n if user_id == skicall.call_data[\"booked_user_id\"]:\n # the current slot has been booked by the current logged in user,\n skicall.page_data['booked', 'para_text'] = \"Your session is live. You now have control.\"\n elif booked:\n skicall.page_data['booked', 'para_text'] = \"Your next booked session starts at UTC : \" + booked.strftime(\"%Y-%m-%d %H:%M\")\n else:\n skicall.page_data['booked', 'para_text'] = \"You do not have any sessions booked.\"\n\n\n if skicall.call_data[\"test_mode\"]:\n skicall.page_data['test_warning', 'para_text'] = \"\"\"WARNING: You are operating in Test Mode - Telescope commands will be sent regardless of the door status, or daylight situation. This could be damaging, please ensure you are in control of the test environment.\nNote: A time slot booked by a user will override Test Mode, to avoid this you should operate within time slots which you have previously disabled.\"\"\"\n elif skicall.call_data[\"role\"] == 'ADMIN':\n skicall.page_data['test_warning', 'para_text'] = \"\"\"The robotic telescope can be controlled by members during their valid booked session, or by Administrators who have enabled 'Test' mode.\nTest Mode can be set by following the 'Admin' link on the left navigation panel.\nOnly one Admin user can enable Test Mode at a time.\nNote: A time slot booked by a user will override Test Mode, to avoid this you should operate within time slots which you have previously disabled.\"\"\"\n else:\n skicall.page_data['test_warning', 'para_text'] = \"\"\n\n\n@doorsession\ndef door_control(skicall):\n \"A door control is requested, sends command and fills in the template page\"\n\n call_data = skicall.call_data\n page_data = skicall.page_data\n\n if ('door', 'action') not in call_data:\n return\n\n if call_data['door', 'action'] == 'open':\n send_mqtt.request_door_open()\n page_data['door_status', 'para_text'] = \"An Open door command has been sent.\"\n elif call_data['door', 'action'] == 'halt':\n send_mqtt.request_door_halt()\n page_data['door_status', 'para_text'] = \"An Halt door command has been sent.\"\n else:\n send_mqtt.request_door_close()\n page_data['door_status', 'para_text'] = \"A Close door command has been sent.\"\n\n page_data['door', 'button_text'] = 'Waiting'\n skicall.page_data['door', 'action'] = 'noaction'\n\n if skicall.call_data[\"test_mode\"]:\n skicall.page_data['test_warning', 'para_text'] = \"\"\"WARNING: You are operating in Test Mode - Telescope commands will be sent regardless of the door status, or daylight situation. This could be damaging, please ensure you are in control of the test environment.\nNote: A time slot booked by a user will override Test Mode, to avoid this you should operate within time slots which you have previously disabled.\"\"\"\n else:\n skicall.page_data['test_warning', 'para_text'] = \"\"\n\n\n\n\n\n","sub_path":"projectfiles/astro/code/astro_packages/members/remscope.py","file_name":"remscope.py","file_ext":"py","file_size_in_byte":4282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"504682315","text":"import sys\n\ndef main():\n\tw, h, startX, startY, m = readMap(sys.argv[1]);\n\tpath = findPath(startX, startY, m);\n\tif path != \"no luck!\":\n\t\tprint(str(path[0]) + \" \" + str(path[1]));\n\t\tprint(\"Blocks: \" + str(len(path[2])));\n\telse:\n\t\tprint(path)\n\n\ndef readMap(filename):\n\tf = open(filename, 'r');\n\tw, h, startX, startY = [int(x) for x in f.next().split()]\n\tm = [];\n\tfor line in f:\n\t\tm += [[c for c in line]];\n\treturn (w, h, startX, startY, m);\n\ndef findPath(sX, sY, m):\n\tfrnt = [];\n\thist = {};\n\tcX = sX;\n\tcY = sY;\n\twhile m[cY][cX] != '*':\n\t\tneighbors = getNeighbors(cX, cY, m);\n\t\tfor n in neighbors:\n\t\t\tif n not in hist:\n\t\t\t\thist[n] = (cX, cY);\n\t\t\t\tfrnt.insert(0, n);\n\t\tif len(frnt) <= 0:\n\t\t\tbreak;\n\t\tcX, cY = frnt.pop();\n\n\tif m[cY][cX] == '*':\n\t\tpath = [(cX, cY)]\n\t\twhile path[0] != (sX, sY):\n\t\t\tpath.insert(0, hist[path[0]])\n\t\treturn (cX, cY, path[1:]);\n\telse:\n\t\treturn \"no luck!\";\n\ndef getNeighbors(cx, cy, m):\n\tcheck = lambda x, y: y >= 0 and y < len(m) and x >= 0 and x < len(m[y]) and m[y][x] != 's' and m[y][x] != 'O';\n\tadd = lambda x, y, dx, dy: (x+dx, y+dy);\n\tneighbors = [];\n\tfor coor in [(0, -1), (0, 1), (-1, 0), (1, 0)]:\n\t\tpos = add(cx, cy, *coor);\n\t\tif check(*pos):\n\t\t\tneighbors.append(pos);\n\treturn neighbors;\n\n\n\nif __name__ == '__main__':\n\tif len(sys.argv) != 2:\n\t\tprint(\"Invalid ussage: python \" + sys.argv[0] + \" \")\n\telse:\n\t\tmain();\n\n","sub_path":"crafting-mines/craftingMines.py","file_name":"craftingMines.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"573850385","text":"def unikati(s):\n vrnjenSeznam = []\n for element in s:\n if element not in vrnjenSeznam:\n vrnjenSeznam.append(element)\n return vrnjenSeznam\n\ndef avtor(tvit):\n ime, besedilo = tvit.split(\":\",1)\n return ime\n\ndef vsi_avtorji(tviti):\n seznamAvtorjev = []\n for tvit in tviti:\n seznamAvtorjev.append(avtor(tvit))\n return unikati(seznamAvtorjev)\n\ndef izloci_besedo(beseda):\n for i in range(0,len(beseda)-1):\n if beseda[i].isalnum() == True:\n for j in range(len(beseda),i,-1):\n if beseda[j-1].isalnum() == True:\n beseda = beseda[i:j]\n break\n break\n return beseda\n\ndef se_zacne_z(tvit, c):\n seznam = tvit.split()\n seznamSeZacne = []\n for element in seznam:\n if element[0] == c:\n seznamSeZacne.append(izloci_besedo(element))\n return seznamSeZacne\n\ndef zberi_se_zacne_z(tviti, c):\n seznam = []\n for tvit in tviti:\n seznam += se_zacne_z(tvit,c)\n return unikati(seznam)\n\ndef vse_afne(tviti):\n return zberi_se_zacne_z(tviti, \"@\")\n\ndef vsi_hashtagi(tviti):\n return zberi_se_zacne_z(tviti, \"#\")\n\ndef vse_osebe(tviti):\n osebe = []\n osebe += vsi_avtorji(tviti) + vse_afne(tviti)\n return sorted(unikati(osebe))\n\ndef custva(tviti, hashtagi):\n osebe = []\n for tvit in tviti:\n if any(i in hashtagi for i in se_zacne_z(tvit,\"#\")):\n osebe.append(avtor(tvit))\n return sorted(unikati(osebe))\n\ndef se_poznata(tviti, oseba1, oseba2):\n for tvit in tviti:\n if avtor(tvit) == oseba1:\n if oseba2 in se_zacne_z(tvit, \"@\"):\n return True\n elif avtor(tvit) == oseba2:\n if oseba1 in se_zacne_z(tvit, \"@\"):\n return True\n return False\n\n","sub_path":"code/batch-1/vse-naloge-brez-testov/DN5-M-77.py","file_name":"DN5-M-77.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"305090761","text":"import unittest\nimport argparse\nimport numpy as np\nimport torch as th\nimport torch.distributed as dist\nimport torch.nn.functional as F\n\nfrom guided_diffusion.script_util import (\n NUM_CLASSES,\n model_and_diffusion_defaults,\n classifier_defaults,\n create_model_and_diffusion,\n create_classifier,\n add_dict_to_argparser,\n args_to_dict,\n)\n\ndef create_argparser(args):\n defaults = dict(\n clip_denoised=True,\n num_samples=1,\n batch_size=1,\n use_ddim=False,\n model_path=\"\",\n classifier_path=\"\",\n classifier_scale=1.0,\n )\n defaults.update(model_and_diffusion_defaults())\n defaults.update(classifier_defaults())\n parser = argparse.ArgumentParser(args.split())\n add_dict_to_argparser(parser, defaults)\n return parser\n\nclass ModelTestCase(unittest.TestCase):\n def test_valid_model(self):\n args1 = '--batch_size 4 --num_samples 100 --timestep_respacing 250 --attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --image_size 128 --learn_sigma True --noise_schedule linear --num_channels 256 --num_heads 4 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True'\n\n args = create_argparser(args1).parse_args()\n args_dict = args_to_dict(args, model_and_diffusion_defaults().keys())\n model, diffusion = create_model_and_diffusion(**args_dict)\n self.assertEqual(args_dict['image_size'], model.image_size)\n self.assertEqual(args_dict['num_channels'], model.model_channels)\n self.assertEqual(args_dict['num_heads'], model.num_heads)\n self.assertEqual(args_dict['num_res_blocks'], model.num_res_blocks)\n self.assertEqual(tuple(args_dict['image_size']//int(res) for res in args_dict['attention_resolutions'].split(\",\")), model.attention_resolutions)\n\n def test_valid_result(self):\n\n args1 = '--batch_size 4 --num_samples 100 --timestep_respacing 250 --attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --image_size 128 --learn_sigma True --noise_schedule linear --num_channels 256 --num_heads 4 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True'\n\n args = create_argparser(args1).parse_args()\n args_dict = args_to_dict(args, model_and_diffusion_defaults().keys())\n model, diffusion = create_model_and_diffusion(**args_dict)\n\n model.load_state_dict(\n dist_util.load_state_dict(args.model_path, map_location=\"cpu\")\n )\n model.eval()\n\n\n classifier = create_classifier(**args_to_dict(args1, classifier_defaults().keys()))\n classifier.load_state_dict(\n dist_util.load_state_dict(args.classifier_path, map_location=\"cpu\")\n )\n classifier.eval()\n\n\n def cond_fn(x, t, y=None):\n assert y is not None\n with th.enable_grad():\n x_in = x.detach().requires_grad_(True)\n logits = classifier(x_in, t)\n log_probs = F.log_softmax(logits, dim=-1)\n selected = log_probs[range(len(logits)), y.view(-1)]\n return th.autograd.grad(selected.sum(), x_in)[0] * args.classifier_scale\n\n def model_fn(x, t, y=None):\n assert y is not None\n return model(x, t, y if args.class_cond else None)\n\n model_kwargs = {}\n classes = th.randint(\n low=0, high=NUM_CLASSES, size=(args.batch_size,), device=dist_util.dev()\n )\n model_kwargs[\"y\"] = classes\n\n sample_fn = diffusion.p_sample_loop\n \n sample = sample_fn(\n model_fn,\n (1, 3, 128, 128),\n model_kwargs=model_kwargs,\n cond_fn=cond_fn,\n device=None,\n )\n sample = ((sample + 1) * 127.5).clamp(0, 255).to(th.uint8)\n sample = sample.permute(0, 2, 3, 1)\n sample = sample.contiguous()\n\n self.assertEqual(128, sample.shape[1])\n\n def test_boundary(self):\n im_size = 513\n args1 = '--batch_size 4 --num_samples 100 --timestep_respacing 250 --attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --image_size 128 --learn_sigma True --noise_schedule linear --num_channels 256 --num_heads 4 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True'\n\n args = create_argparser(args1).parse_args()\n args_dict = args_to_dict(args, model_and_diffusion_defaults().keys())\n args_dict.pop('image_size', None)\n with self.assertRaises(ValueError):\n create_model_and_diffusion(im_size, **args_dict)\n im_size = 63\n with self.assertRaises(ValueError):\n create_model_and_diffusion(im_size, **args_dict)\n\n\n \n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_sampling.py","file_name":"test_sampling.py","file_ext":"py","file_size_in_byte":4790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"535307054","text":"import sys\nimport random\nfrom PyQt5.QtWidgets import QPushButton\n\nfrom matplotlib.backends.qt_compat import QtCore, QtWidgets\nif QtCore.qVersion() >= \"5.\":\n from matplotlib.backends.backend_qt5agg import (\n FigureCanvas, NavigationToolbar2QT as NavigationToolbar)\nelse:\n from matplotlib.backends.backend_qt4agg import (\n FigureCanvas, NavigationToolbar2QT as NavigationToolbar)\nfrom matplotlib.figure import Figure\n\nclass ApplicationWindow(QtWidgets.QMainWindow):\n def __init__(self):\n super().__init__()\n self._main = QtWidgets.QWidget()\n self.setCentralWidget(self._main)\n layout = QtWidgets.QVBoxLayout(self._main)\n\n static_canvas = FigureCanvas(Figure(figsize=(5, 3)))\n layout.addWidget(static_canvas)\n self.addToolBar(NavigationToolbar(static_canvas, self)) \n\n # plot the vertices\n self._static_ax = static_canvas.figure.subplots()\n self._static_ax.plot(0, 0, \".\", color=\"black\")\n self._static_ax.plot(10, 0, \".\", color=\"black\")\n self._static_ax.plot(5, 5, \".\", color=\"black\")\n\n # plot the starting point, doesn't really matter where\n self.points = self._static_ax.plot(4, 3, \".\", color=\"green\")\n self.x = 4.0\n self.y = 3.0\n\n # buttons and connections for plotting points\n button1 = QPushButton(\"Plot point\")\n button2 = QPushButton(\"Plot 100 points\")\n button1.clicked.connect(self.plot_point)\n button2.clicked.connect(self.plot_one_hundred_points)\n layout.addWidget(button1)\n layout.addWidget(button2)\n \n # connect event for moving trace point\n self._static_ax.figure.canvas.mpl_connect('button_press_event', self.button_press_event)\n\n # calculates the midpoint from tracepoint to another point\n def find_midpoint(self, x2, y2) -> tuple[float, float]:\n x = (self.x+x2)/2\n y = (self.y+y2)/2\n return x, y\n\n # event for moving tracepoint\n def button_press_event(self, event):\n self.x = event.xdata\n self.y = event.ydata\n self.points[0].remove()\n self.points = self._static_ax.plot(self.x, self.y, \".\", color=\"green\")\n self._static_ax.figure.canvas.draw()\n \n # event for plotting point\n @QtCore.Slot()\n def plot_point(self):\n print(f\"start: ({self.x}, {self.y})\")\n r = random.randint(0, 2)\n if r == 0:\n print(\"vertice (0,0)\")\n self.x, self.y = self.find_midpoint(0.0, 0.0)\n elif r == 1:\n print(\"vertice (5, 5)\")\n self.x, self.y = self.find_midpoint(5.0, 5.0)\n else:\n print(\"vertice (10, 0)\")\n self.x, self.y = self.find_midpoint(10.0, 0.0)\n self.points[0].set_color(\"red\")\n self.points = self._static_ax.plot(self.x, self.y, \".\", color=\"green\")\n self._static_ax.figure.canvas.draw()\n print(self.x, self.y)\n\n # event for plotting 100 points \n @QtCore.Slot()\n def plot_one_hundred_points(self):\n for i in range(100):\n self.plot_point()\n\n\nif __name__ == \"__main__\":\n # Check whether there is already a running QApplication (e.g., if running\n # from an IDE).\n qapp = QtWidgets.QApplication.instance()\n if not qapp:\n qapp = QtWidgets.QApplication(sys.argv)\n\n app = ApplicationWindow()\n app.show()\n app.activateWindow()\n app.raise_()\n qapp.exec_()","sub_path":"triangles.py","file_name":"triangles.py","file_ext":"py","file_size_in_byte":3420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"104610652","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\n# se importa la clase(s) del \n# archivo genera_tablas\nfrom genera_tabla import Establecimiento, Parroquia, Canton, Provincia\n\n\n# se importa información del archivo configuracion\nfrom configuracion import cadena_base_datos\n# se genera enlace al gestor de base de\n# datos\n# para el ejemplo se usa la base de datos\n# sqlite\nengine = create_engine(cadena_base_datos)\n\n# Este objeto de sesión es nuestro manejador de base de datos\nSession = sessionmaker(bind=engine)\n# Se crea un objeto session de tipo Session, mismo que va apermitir \n# guardar, eliminar, actualizar, generar consultas en la base de datosrespecto a las entidades creadas.\nsession = Session()\n\n# Para proceder a realizar la siguiente consulta se hace un select de la tabla a analizar con session.query(),\n# un join de las tablas a las cuales se deseea acceder y un filtrado por el nombre de la provincia que sea = \"Loja\"\nestablecimiento_prov = session.query(Establecimiento).join(Parroquia, Canton, Provincia).filter(Provincia.nombre_provincia == \"LOJA\").all()\n \nprint(\"Todos los establecimientos de la provincia de Loja\")\nfor i in establecimiento_prov:\n print(\"%s\" % (i))\nprint(\"--------------------------------------\")\n\n# Para proceder a realizar la siguiente consulta se hace un select de la tabla a analizar con session.query(),\n# un join de las tablas a las cuales se deseea acceder y un filtrado por el nombre del cantón que sea = \"Loja\"\nestablecimiento_canton = session.query(Establecimiento).join(Parroquia, Canton).filter(Canton.nombre_canton == \"LOJA\").all()\n \nprint(\"Todos los establecimientos del cantón de Loja\")\nfor i in establecimiento_canton:\n print(\"%s\" % (i))\nprint(\"--------------------------------------\")\n\n\n","sub_path":"Proyecto/consulta1.py","file_name":"consulta1.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"619572637","text":"from menu import Menu\nfrom menuitem import MenuItem\n\nmenuItem1 = MenuItem('Chicken Popcorn', 98, 4.1)\nmenuItem2 = MenuItem('Zinger Burger', 258, 4.6)\nmenuItem3 = MenuItem('Chicken Pizza', 298, 4.0)\nmenuItem4 = MenuItem('Lime Krusher', 75, 4.3)\nmenuItem5 = MenuItem('Chicken Popcorn', 60, 4.1)\nmenuItem6 = MenuItem('Chicken Popcorn', 60, 4.1)\n\nprint(menuItem1)\nprint(menuItem1 == menuItem5)\nprint(menuItem5 == menuItem6)\n\nmenu = Menu([menuItem1, menuItem2, menuItem3, menuItem4, menuItem5, menuItem6])\n\nprint(len(menu))\n\nprint(menu)\nlist.sort(menu.menuitems, reverse=True)\nprint(menu)\n","sub_path":"Outlab 4- Python Advanced/kfctest1.py","file_name":"kfctest1.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"550414629","text":"from django.shortcuts import render\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.http import HttpResponse\nfrom django.http import HttpResponseRedirect\nfrom django.template import RequestContext\nfrom django.views.generic import ListView, DetailView\nfrom django.template.loader import render_to_string\nfrom sito.models import *\nfrom django.core.mail import send_mail\n\nfrom sito.gallery_revolution import *\n\n# Create your views here.\n\n\ndef HomePage(request):\n\tslider_list = Slider.objects.filter(active = '1').order_by('id')\n\ttestimonial_list = Testimonial.objects.all()[:2]\n\tevents_list = Events.objects.all()[:2]\n\tpage_list = Page.objects.filter(active = '1')\n\tpeople_list = People.objects.all()\n\tdocumenti_list = Documenti.objects.all().order_by('-pub_date')[:4]\n\tcontext = {'slider_list': slider_list,\n\t\t\t\t'testimonial_list': testimonial_list,\n\t\t\t\t'events_list': events_list,\n\t\t\t\t'page_list': page_list,\n\t\t\t\t'people_list': people_list,\n\t\t\t\t'documenti_list': documenti_list}\n\treturn render_to_response('index.html', context, context_instance=RequestContext(request))\n\t#return render_to_response('index.html', context, context_instance=RequestContext(request))\n\t#return render(request, 'index.html', context) '''\n\n\n\n\ndef PageView(request, post_id):\n page = Page.objects.get(pk=post_id)\n context = {'page': page}\n return render_to_response('page.html', context, context_instance=RequestContext(request))\n\n\ndef events(request):\n\tevents_list = Events.objects.all().order_by('-inizio')\n\teventi_slider = Eventigallery.objects.filter(active = '1')\n\tcontext = {'events_list': events_list,\n\t\t\t\t'eventi_slider': eventi_slider}\n\treturn render(request, 'news.html', context)\n\n\ndef eventsdettaglio(request, post_id):\n news = Events.objects.get(pk=post_id)\n context = {'news': news}\n return render_to_response('newsdettaglio.html', context, context_instance=RequestContext(request))\n\ndef PeopleDetail(request, post_id):\n\tpeople = People.objects.get(pk=post_id)\n\tcontext = {'people': people}\n\treturn render_to_response('people.html', context, context_instance=RequestContext(request))\n\ndef StatutoView(request):\n return render_to_response('statuto.html', context_instance=RequestContext(request))\n\ndef DocumentiView(request):\n\tdocumenti_list = Documenti.objects.all().order_by('-pub_date')\n\tdoc_slider = Docugallery.objects.filter(active = '1')\n\tcontext = {'documenti_list': documenti_list,\n\t\t\t\t'doc_slider': doc_slider}\n\treturn render(request, 'documenti.html', context)\n\ndef DocumentiDetail(request, post_id):\n\tdocumenti = Documenti.objects.get(pk=post_id)\n\tdoc_slider = Docugallery.objects.filter(active = '1')\n\tcontext = {'documenti': documenti,\n\t\t\t 'doc_slider': doc_slider}\n\treturn render_to_response('documenti_dettaglio.html', context, context_instance=RequestContext(request))\n\ndef DomandeView(request):\n\tdomande_list = Questions.objects.all()\n\tfaq_slider = Faqgallery.objects.filter(active = '1')\n\tcontext = {'domande_list': domande_list,\n\t\t\t\t'faq_slider': faq_slider}\n\treturn render(request, 'domande.html', context)\n\ndef contact(request):\n\tcontatti_slider = Contattigallery.objects.filter(active = '1')\n\tcontext = {'contatti_slider': contatti_slider}\n\treturn render_to_response('contact.html', context, context_instance=RequestContext(request))\n\n\ndef BlogView(request):\n\tpost_list = Post.objects.filter(active = '1').order_by('-pub_date')\n\tcontext = {'post_list': post_list}\n\treturn render(request, 'blog.html', context)\n\n\ndef BlogDettaglio(request, post_id):\n\tpost = Post.objects.get(pk=post_id)\n\tpost_list = Post.objects.filter(active = '1').order_by('-pub_date')\n\tcontext = {'post': post,\n\t\t\t\t'post_list': post_list}\n\treturn render_to_response('post.html', context, context_instance=RequestContext(request))\n\n\n## session en/it\n\n### setting language session\ndef language(request, language='it'):\n\tresponse = HttpResponse(\"setting language to %s\" % language)\n\tresponse.set_cookie('lang', language)\n\trequest.session['lang'] = language\n\treturn HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n\n","sub_path":"sito/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"575163138","text":"from importlib import reload\nimport context\nreload(context)\nfrom context import dipoletester\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nplt.ion()\n\nfig,ax = plt.subplots(2,3, figsize=(15,9))\nax = list(ax.flatten())\n\nmu_b = 9.274e-24 # [A m^2]\nmu_b = mu_b * 1e6 * 1e6\n\nsample = dipoletester.Sample( (0,0,0), (100,80,1), (3,), [1, 1, 1])\nsample.threezones( (+0*mu_b,+0*mu_b,+200*mu_b), \n (-0*mu_b,+0*mu_b,-200*mu_b))\nsample.plot(ax[0])\nax[0].set_title('Dipole Arangement')\n\nmeas = dipoletester.ScanBiotSavart(probe=None, sample=sample)\n\nscan = dipoletester.Coordinates( (10,10,.1), (80,60,1), (3,), [1,1,1])\ntotalb = meas.calc_b_full(scan.pos)\nscan.canvas = totalb\nscan.plot(ax[1])\nax[1].set_title('B field .1 above sample')\n\nsquid = dipoletester.Squid( (0,0,0), (40,40,1), (3,), \n [.025, .025, .025])\nsquid.circle(radius=.5)\nsquid.plot(ax[2])\nax[2].set_title('Squid point spread function')\n\n[interpx, interpy, interpz] = meas.interpolate_bfield_2D(scan.pos, \n scan.canvas)\ninterp = dipoletester.Coordinates( (0,0,0), (1000,900,1), (3,), [.1,.1,.1])\ninterp.plot_interpolate(ax[3], interpx, interpy, interpz, skip=50)\nax[3].set_title('Interpolated b field')\n\n\nxs = np.arange(0,100,.025)\nys = np.arange(0,100,.025)\nzs = np.array([.1])\npos = dipoletester.Coordinates.newpos((0,0,0), xs, ys, zs)\n\nconvol = meas.__class__.convolute_bfield_2D(squid.canvas[:,:,0,2], pos,\n interpz)\ndipoletester.Coordinates.plot_colormap(ax[4], convol, \n extent=(xs[0], xs[-1], \n ys[0], ys[-1])\n )\nax[4].set_title('B field convoluted with squid (flux detected)')\n\n\nfig.tight_layout()\n","sub_path":"2018/06/isaiah_magneticdipole/tests/test_visible1.py","file_name":"test_visible1.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"287242395","text":"'''\nScript to collect information from Receiver Functions\n'''\n#Importing modules\n\nimport numpy as np\nfrom obspy import UTCDateTime\nimport os\nimport json\nimport obspy\nimport shutil\n\nfrom parameters_py.config import (\n\t\t\t\t\tDIR_SAC,OUTPUT_JSON_FILE_DIR,GAUSSIAN_FILTER,RADIAL_EXT,TRANSVERSAL_EXT,RF_PERCENT,CODA_TRACE_CHECK_AMP_MIN,CODA_TRACE_CHECK_AMP_MAX,\n\t\t\t\t\tEV_GCARC_MIN,EV_GCARC_MAX,EV_MAGNITUDE_MB,CUT_BEFORE_P,CUT_AFTER_P,SAMPLING_RATE,CODA_TRACE_CHECK,DIR_SEL_SAC,ZERO_AMP_MIN,ZERO_AMP_MAX,\n\t\t\t\t\tCODA_TRACE_CHECK_MULT\n\t\t\t\t )\n\n\n\nprint('Get RF Parameters')\nprint('\\n')\n\n\n#### Radial ####\n\ndatalist = []\ndatalistS = []\nfor root, dirs, files in os.walk(DIR_SAC):\n for datafile in files:\n if datafile.endswith(RADIAL_EXT):\n datalist.append(os.path.join(root, datafile))\n\ndatalistS = sorted(datalist)\n\n#### Transversal ####\n\ndatalistT = []\ndatalistST = []\nfor root, dirs, files in os.walk(DIR_SAC):\n for datafile in files:\n if datafile.endswith(TRANSVERSAL_EXT):\n datalistT.append(os.path.join(root, datafile))\n\ndatalistST = sorted(datalistT)\n\n\ndic_RF = {\n\t\t'dataR':[],\n\t\t'dataR_time':[],\n\t\t'dataT':[],\n\t\t'npts':[],\n\t\t'kstnm':[],\n\t\t'nzyear':[],\n\t\t'nzjday':[],\n\t\t'nzhour':[],\n\t\t'nzmin':[],\n\t\t'nzmsec':[],\n\t\t'evla':[],\n\t\t'evlo':[],\n\t\t'evdp':[],\n\t\t'mag':[],\n\t\t'stla':[],\n\t\t'stlo':[],\n\t\t'user0':[],\n\t\t'user5':[],\n\t\t'user8':[],\n\t\t'dist':[],\n\t\t'az':[],\n\t\t'baz':[],\n\t\t'gcarc':[],\n\t\t'b':[],\n\t\t'e':[]\n}\n\nfor i,j in enumerate(datalistS):\n\n\n\tdata_RF = obspy.read(j)\n\tdata_RF_T = obspy.read(datalistST[i])\t\n\n\tdata_name = j.split('/')[-1]\n\n\tif len(data_RF[0].data) > CUT_AFTER_P*SAMPLING_RATE and data_RF[0].stats.sac.mag > EV_MAGNITUDE_MB:\n\n\t\tprint('Station: '+data_RF[0].stats.sac.kstnm+'/ Event lat = '+str(data_RF[0].stats.sac.evla)+'/ Event lon = '+str(data_RF[0].stats.sac.evlo))\n\n\t\t#RF P-arrival amplitudes check\n\t\tP_arrival_start = round((CUT_BEFORE_P*SAMPLING_RATE)-SAMPLING_RATE)\n\t\tP_arrival_mid = round(CUT_BEFORE_P*SAMPLING_RATE)\n\t\tP_arrival_end = round((CUT_BEFORE_P*SAMPLING_RATE)+SAMPLING_RATE)\n\t\t\n\t\tamp_mid = data_RF[0].data[P_arrival_mid]\n\t\t\n\t\t#RF Coda amplitudes check\n\t\tamp_Coda = data_RF[0].data[int((CODA_TRACE_CHECK+CUT_BEFORE_P)*SAMPLING_RATE):int(CUT_AFTER_P*SAMPLING_RATE)]\n\n\t\tamp_Coda_mask = np.ma.masked_outside(amp_Coda,CODA_TRACE_CHECK_AMP_MIN,CODA_TRACE_CHECK_AMP_MAX)\n\n\t\tmean_amp_Coda = np.mean(amp_Coda_mask)\n\t\tstd_amp_Coda = abs(np.std(amp_Coda_mask))\n\n\t\tif (\n\t\t\t#Gaussian Filter\n\t\t\tdata_RF[0].stats.sac.user0 == GAUSSIAN_FILTER and\n\n\t\t\t#Reconstruction value \n\t\t\tdata_RF[0].stats.sac.user5 >= RF_PERCENT and\n\n\t\t\t#Minimum data amplitude threshold \n\t \t\tdata_RF[0].data.min() >= -ZERO_AMP_MIN and\n\n\t \t\t#Maximum data amplitude threshold \n\t \t\tdata_RF[0].data.max() <= ZERO_AMP_MAX and\n\n\t\t\t#Maximum coda amplitude threshold \n\t \t\tamp_Coda.max() <= mean_amp_Coda + CODA_TRACE_CHECK_MULT*std_amp_Coda and\n\n\t\t\t#Minimum coda amplitude threshold \n\t\t\tamp_Coda.min() >= mean_amp_Coda - CODA_TRACE_CHECK_MULT*std_amp_Coda and\n\n\t\t\t#Origin amplitude larger than zero\n\t\t\tZERO_AMP_MIN <= amp_mid <= ZERO_AMP_MAX and all(elem > 0 for elem in data_RF[0].data[P_arrival_start:P_arrival_end])\n\t\t\t):\n\t\t\t\t\n\t\t\t\tRF_directory = DIR_SEL_SAC+str(GAUSSIAN_FILTER)+'/'+data_RF[0].stats.sac.kstnm+'/'\n\t\t\t\tos.makedirs(RF_directory,exist_ok=True)\n\t\t\t\tshutil.copy2(j,RF_directory+data_name)\n\n\t\t\t\tdic_RF['dataR'].append(data_RF[0].data[:int(CUT_AFTER_P*SAMPLING_RATE)].tolist())\n\t\t\t\tdic_RF['dataR_time'].append(np.linspace(-CUT_BEFORE_P, CUT_AFTER_P,len(data_RF[0].data[:int(CUT_AFTER_P*SAMPLING_RATE)])).tolist())\n\t\t\t\tdic_RF['dataT'].append(data_RF_T[0].data[:int(CUT_AFTER_P*SAMPLING_RATE)].tolist())\n\t\t\t\tdic_RF['npts'].append(float(data_RF[0].stats.sac.npts))\n\t\t\t\tdic_RF['kstnm'].append(data_RF[0].stats.sac.kstnm)\n\t\t\t\tdic_RF['nzyear'].append(float(data_RF[0].stats.sac.nzyear))\n\t\t\t\tdic_RF['nzjday'].append(float(data_RF[0].stats.sac.nzjday))\n\t\t\t\tdic_RF['nzhour'].append(float(data_RF[0].stats.sac.nzhour))\n\t\t\t\tdic_RF['nzmin'].append(float(data_RF[0].stats.sac.nzmin))\n\t\t\t\tdic_RF['nzmsec'].append(float(data_RF[0].stats.sac.nzmsec))\n\t\t\t\tdic_RF['evla'].append(float(data_RF[0].stats.sac.evla))\n\t\t\t\tdic_RF['evlo'].append(float(data_RF[0].stats.sac.evlo))\n\t\t\t\tdic_RF['evdp'].append(float(data_RF[0].stats.sac.evdp))\n\t\t\t\tdic_RF['mag'].append(float(data_RF[0].stats.sac.mag))\n\t\t\t\tdic_RF['stla'].append(float(data_RF[0].stats.sac.stla))\n\t\t\t\tdic_RF['stlo'].append(float(data_RF[0].stats.sac.stlo))\n\t\t\t\tdic_RF['user0'].append(float(data_RF[0].stats.sac.user0))\n\t\t\t\tdic_RF['user5'].append(float(data_RF[0].stats.sac.user5))\n\t\t\t\tdic_RF['user8'].append(float(data_RF[0].stats.sac.user8))\n\t\t\t\tdic_RF['dist'].append(float(data_RF[0].stats.sac.dist))\n\t\t\t\tdic_RF['az'].append(float(data_RF[0].stats.sac.az))\n\t\t\t\tdic_RF['baz'].append(float(data_RF[0].stats.sac.baz))\n\t\t\t\tdic_RF['gcarc'].append(float(data_RF[0].stats.sac.gcarc))\n\t\t\t\tdic_RF['b'].append(float(data_RF[0].stats.sac.b))\n\t\t\t\tdic_RF['e'].append(float(data_RF[0].stats.sac.e))\n\n\nprint('Saving Event Parameters in JSON file')\nprint('\\n')\n\nos.makedirs(OUTPUT_JSON_FILE_DIR,exist_ok=True)\n\nJSON_FILE = 'RF_dic_'+str(GAUSSIAN_FILTER)\n\nJSON_FILE_NAME = JSON_FILE.replace(\".\", \"_\")\n\n\nwith open(OUTPUT_JSON_FILE_DIR+JSON_FILE_NAME+'.json', 'w') as fp:\n\tjson.dump(dic_RF, fp)\n","sub_path":"coruja_buraqueira_receiver_function_toolkit/get_information_py/get_RF_information.py","file_name":"get_RF_information.py","file_ext":"py","file_size_in_byte":5242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"523460658","text":"import melon_utils as mu \nimport codecs\nimport csv\nimport datetime\n\nnow = datetime.datetime.now()\nn = now.strftime('%Y%m%d')\ndb = \"melondb\"\n\nfile_location = \"./results/melon_top_100_list({}).csv\".format(n)\n\n\nsql2 = 'insert into SongRank(songId, rank, likecnt, rankDate) values(%s, %s, %s, date_format(now(), \"%%Y%%m%%d\"))'\n# sql2 = 'insert into SongRank(songId, rank, likecnt, rankDate) values(%s, %s, %s, \"20190125\")'\n\ncsvFile2 = codecs.open(file_location, 'r', 'utf-8')\nreader2 = csv.reader(csvFile2, delimiter=',', quotechar='\"')\n\nfor row in reader2:\n lst = (row[1], row[0], row[4])\n mu.insert_data_to_db(db, sql2, lst)\n\nprint(\"=============== SongRank Insert Completed! =================\")","sub_path":"scraping/project_melon/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"136445997","text":"import pygame\nfrom pygame.sprite import Sprite\n\nclass Alien(Sprite):\n def __init__(self,screen,settings):\n super().__init__()\n self.screen=screen\n self.settings=settings\n \n self.image=pygame.image.load('D:/python project/python编程--从入门到实践练习/游戏项目/图片资源/alien.bmp')\n self.rect=self.image.get_rect()\n\n self.rect.right=self.screen.get_rect().right\n self.rect.top=self.screen.get_rect().top\n\n self.y=float(self.rect.y)\n \"\"\"更新外星人位置\"\"\"\n def update(self):\n self.y-=(self.settings.alien_right_speed*self.settings.alien_dir)\n self.rect.y=self.y\n \"\"\"判断是否触及边界\"\"\"\n def check_edges(self):\n if self.rect.bottom>=self.screen.get_rect().bottom:\n return True\n elif self.rect.top<=0:\n return True\n\n \"\"\"放置外星人\"\"\"\n def blime(self):\n self.screen.blit(self.image,self.rect)","sub_path":"pythonproject/python编程--从入门到实践练习/游戏项目/练习代码/练习14.3/alien.py","file_name":"alien.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"403337747","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom ptti.seirct_ode import SEIRCTODEMem\nfrom ptti.model import runModel\nfrom ptti.data import uk_mortality\n\nt0, tmax, steps = -34, 150, 150 # Day 0 is 21st Jan 2020 according to uk_mortality.csv\n\nifr = 0.008\noffset = 0 ## date offset for uk case data\n\ninitial = {\n \"N\": 67886011,\n \"IU\": 2,\n}\n\nparams = {\n \"beta\": 0.030,\n \"c\": 13,\n \"alpha\": 0.2,\n \"gamma\": 0.1429,\n \"theta\": 0.0,\n}\n\ninterventions = [\n { \"time\": 89, \"parameters\": { \"c\": 10 } },\n { \"time\": 96, \"parameters\": { \"c\": 4 } }\n]\n\nmodel = SEIRCTODEMem\nt, traj = runModel(model, t0, tmax, steps, params, initial, interventions)\nRU = traj[:, model.colindex(\"RU\")]\nRD = traj[:, model.colindex(\"RD\")]\nt += offset\ncases = RU + RD\ndeaths = ifr * cases\n\nukm = uk_mortality()\nukt = ukm[:,0]\nukcases = ukm[:,1]\nukdeaths = ukm[:,2]*1.6\n\nfig, (ax1, ax2) = plt.subplots(2, 1)\n\nax1.set_xlabel(\"Days since outbreak start\")\nax1.set_ylabel(\"Cases\")\nax1.set_xlim(t0, tmax)\nax1.set_yscale(\"log\")\nax1.plot(t, cases, label=\"Simulated\")\nax1.plot(ukt, ukcases, label=\"UK data\")\nax1.legend()\n\nax2.set_xlabel(\"Days since outbreak start\")\nax2.set_ylabel(\"Deaths\")\nax2.set_xlim(t0, tmax)\nax2.set_yscale(\"log\")\nax2.plot(t, deaths, label=\"Simulated\")\nax2.plot(ukt, ukdeaths, label=\"UK data\")\nax2.legend()\n\nfig.show()\n\ninput()\n","sub_path":"examples/ukfitting.py","file_name":"ukfitting.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"264973924","text":"from experimentInnovation.models import ExpBuyerModel, \\\n ExpParametersModel, ExpStateModel, ExpPayoffModel, ExpProcessModel, ExpPowerModel, ExpRndModel, ExpCapitalModel, \\\n ExpInnovationModel, ExpTotalProfit\nfrom survey.models import Profile, SurveyData\nfrom django.contrib.auth.models import User\n\ntrial = \"1\"\nbuyers = ExpBuyerModel.objects.filter(isActive=True)\nwith open(\"scripts/personal.txt\", \"a+\") as textstorage:\n for i in buyers:\n profile = Profile.objects.get(user=i.user)\n if SurveyData.objects.filter(user=i.user).exists():\n survey = SurveyData.objects.get(user=i.user)\n else:\n survey = SurveyData(user=i.user,risk='5',learn='5',confidence='5',compete='5')\n textstorage.write(i.user.username+\",\"+i.user.first_name+\",\"+ i.user.last_name+ \",\"+i.user.email+\",\"+\n profile.date_of_birth.strftime('%m/%d/%Y') + \",\" +profile.sex +\",\" +profile.department +\",\" +profile.year +\",\" +\n str(profile.gpa) +\",\" +survey.risk +\",\" + survey.learn +\",\" + survey.confidence +\",\" +\n survey.compete+\",\"+trial+\"\\n\")\n\nperiods = ExpStateModel.objects.all()\nwith open(\"scripts/periods.txt\", \"a+\") as textstorage:\n for i in periods:\n for j in buyers:\n cap = ExpCapitalModel.objects.get(buyer=j,state=i).val\n power = ExpPowerModel.objects.get(buyer=j,state=i).val\n rnd = ExpRndModel.objects.get(buyer=j,state=i).val\n profit = ExpPayoffModel.objects.get(buyer=j,state=i).profit\n if i!=periods[0]:\n inv_rnd = ExpRndModel.objects.get(buyer=j,state=i).val - ExpRndModel.objects.get(buyer=j,state=k).val\n inv_cap = ExpCapitalModel.objects.get(buyer=j,state=i).val - ExpCapitalModel.objects.get(buyer=j,state=k).val\n else:\n inv_rnd = 0\n inv_cap = 0\n textstorage.write(trial+\",\"+ j.user.username +\",\"+str(i.period) +\",\" + str(round(cap,1))+\",\"+str(round(power,1))+\",\"+str(\n round(rnd,1))+\",\"+str(round(profit,1))+\",\"+str(round(max(inv_rnd,0),1))+\",\"+str(round(max(inv_cap,0),1))+\"\\n\")\n k = i\n\nwith open(\"scripts/periods_total.txt\", \"a+\") as textstorage:\n for i in periods:\n inno = ExpInnovationModel.objects.get(state=i).val\n textstorage.write(trial+\",\"+ str(i.period) + \",\" +str(round(inno,1))+ \"\\n\")\n\n","sub_path":"scripts/pull_data.py","file_name":"pull_data.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"586892018","text":"# Tutaj napisze clase która mi dziedziczy po clasie wbudowanej w python modul calandar , to mi stworzy html calanedarz\n\nimport calendar\nfrom calendar import HTMLCalendar\nfrom datetime import date, timedelta\n\nfrom .models import *\nfrom django.contrib.auth.models import User\n\nimport locale\n\n# locale.setlocale(locale.LC_TIME, 'pl_PL.utf8')\nlocale.setlocale(locale.LC_TIME, 'en_US.utf8')\n\n\n\nclass Calendar(HTMLCalendar):\n def __init__(self, year=None, month=None, free_day=None, workers=None):\n self.year = int(year)\n self.month = month\n self.free_day = free_day\n self.workers= workers\n super(Calendar, self).__init__()\n\n def formatday(self, day, workday, workers=0):\n\n employee_that_day = workday.filter(date_day__day=day, date_free=False)\n\n holiday = workday.filter(date_day__day=day, date_free=True)\n d = ''\n\n\n for worker in employee_that_day:\n d += f\"
  • {worker.employee}:{worker.time_start.strftime('%H:%M')}-{worker.time_end.strftime('%H:%M')}
  • \"\n workers = workday.filter(date_day__day=day, date_free=False).count()\n for worker in holiday:\n d += f'
  • {worker.employee}:Holiday
  • '\n\n if day != 0:\n return f\"{day}
    \"\n return ''\n\n # formats a week as a t\n def formatweek(self, theweek, workday):\n week = ''\n for d, weekday in theweek:\n week += self.formatday(d, workday)\n return f' {week} '\n\n # formats a month as a table\n # filter events by year and month\n def formatweekday(self, day):\n \"\"\"\n Return a weekday name as a table header.\n \"\"\"\n return '%s' % (self.cssclasses[day], calendar.day_abbr[day])\n\n def formatweekheader(self):\n \"\"\"\n Return a header for a week as a table row.\n \"\"\"\n s = ''.join(self.formatweekday(i) for i in self.iterweekdays())\n return '%s' % s\n\n def formatmonthname(self, theyear, themonth, withyear=True):\n \"\"\"\n Return a month name as a table row.\n \"\"\"\n if withyear:\n s = '%s %s' % (calendar.month_name[themonth], theyear)\n else:\n s = '%s' % calendar.month_name[themonth]\n return '%s' % s\n\n def formatmonth(self, withyear=True):\n workdays = WorkDay.objects.filter(date_day__year=self.year, date_day__month=self.month)\n\n cal = f\"\\n\"\n cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\\n'\n cal += f'{self.formatweekheader()}\\n'\n for week in self.monthdays2calendar(self.year, self.month):\n cal += f'{self.formatweek(week, workdays)}\\n'\n\n return cal\n\n\nclass CalendarForUser(Calendar):\n def __init__(self, year=None, month=None, user=None):\n self.user = user\n super().__init__(year, month)\n\n def formatday(self, day, workday):\n\n employee_that_day = workday.filter(date_day__day=day, employee=self.user, date_free=False)\n holiday = workday.filter(date_day__day=day,employee=self.user, date_free=True)\n d = ''\n for worker in employee_that_day:\n d += f\" {worker.employee}:{worker.time_start.strftime('%H:%M')}-{worker.time_end.strftime('%H:%M')}
    \"\n for worker in holiday:\n d += f' {worker.employee}:holiday
    '\n\n if day != 0:\n return f\"\"\n return ''\n","sub_path":"WorkShedule/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"263372714","text":"from gi.repository import GObject, Gst\n\n\ndef main():\n Gst.init(None)\n\n pipespec = \"\"\"\n uvch264src device=/dev/video1 name=src auto-start=true\n\n src.vidsrc\n ! queue\n ! video/x-h264,width=1920,height=1080,framerate=30/1\n ! h264parse\n ! avdec_h264\n ! autovideosink sync=false\n \"\"\"\n pipeline = Gst.parse_launch(pipespec)\n pipeline.set_state(Gst.State.PLAYING)\n\n loop = GObject.MainLoop()\n loop.run()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"78927748","text":"from keras.models import Model\nfrom keras.layers import Input, Dense, Conv2D, MaxPooling2D, Dropout, Flatten, Lambda, BatchNormalization, Embedding, Conv1D, GlobalMaxPooling1D\nfrom keras import backend as K\nfrom keras import regularizers\nfrom keras.preprocessing import sequence\nfrom keras.preprocessing.text import Tokenizer\n\nimport random\nimport heapq\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport numpy as np\nfrom collections import defaultdict\n\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import StratifiedKFold\nimport SelfbackUtil as inn\nimport read as SelfBACK\n\nrandom.seed = 1337\nnp.random.seed = 1337\n\n### k-NN Functions ###\ndef cos_knn(k, test_data, test_target, stored_data, stored_target):\n \"\"\"k: number of neighbors to use for voting\n test_data: a set of unobserved images to classify\n test_target: the labels for the test_data (for calculating accuracy)\n stored_data: the images already observed and available to the model\n stored_target: labels for stored_data\n \"\"\"\n \n # find cosine similarity for every point in test_data between every other point in stored_data\n cosim = cosine_similarity(test_data, stored_data)\n \n # get top k indices of images in stored_data that are most similar to any given test_data point\n top = [(heapq.nlargest((k), range(len(i)), i.take)) for i in cosim]\n # convert indices to numbers using stored target values\n top = [[stored_target[j] for j in i[:k]] for i in top]\n \n # vote, and return prediction for every image in test_data\n pred = [max(set(i), key=i.count) for i in top]\n pred = np.array(pred)\n \n # print table giving classifier accuracy using test_target\n return pred\n\ndef get_neighbours(instance, dataset, n):\n return np.argsort(np.linalg.norm(dataset - instance, axis=1))[:n]\n\ndef get_accuracy(test_labels, predictions):\n correct = 0\n for j in range(len(test_labels)):\n if test_labels[j] == predictions[j]:\n correct += 1\n return (correct/float(len(test_labels))) * 100.0\n\n### Triplet Functions ###\ndef get_triples_minibatch_indices_me(dictionary):\n triples_indices = []\n for k in dictionary.keys():\n for value in dictionary[k]:\n anchor = value\n positive = random.choice(dictionary[k])\n negative_labels = np.arange(9)\n negative_label = random.choice(np.delete(negative_labels, np.argwhere(negative_labels==k)))\n negative = random.choice(dictionary[negative_label])\n triples_indices.append([anchor, positive, negative])\n \n return np.asarray(triples_indices)\n\ndef get_triples_minibatch_data_u(x, dictionary):\n indices = get_triples_minibatch_indices_me(dictionary)\n return x[indices[:,0]], x[indices[:,1]], x[indices[:,2]]\n\ndef triplet_generator_minibatch(x, y, no_minibatch):\n grouped = defaultdict(list)\n dict_list = []\n \n for i, label in enumerate(y):\n grouped[label].append(i)\n \n for k in range(len(grouped)):\n random.shuffle(grouped[k])\n \n for j in range(no_minibatch):\n dictionary = {}\n \n for k in range(len(grouped)):\n ran_sam = random.sample(grouped[k], 3)\n dictionary[k] = ran_sam\n \n dict_list.append(dictionary)\n \n i = 0\n \n while 1: \n x_anchor, x_positive, x_negative = get_triples_minibatch_data_u(x, dict_list[i])\n \n if i == (no_minibatch - 1):\n i = 0\n else:\n i += 1\n\n yield ({'anchor_input': x_anchor,\n 'positive_input': x_positive,\n 'negative_input': x_negative},\n None)\n \n### Triplet Loss ###\ndef triplet_loss(inputs, dist='sqeuclidean', margin='maxplus'):\n anchor, positive, negative = inputs\n positive_distance = K.square(anchor - positive)\n negative_distance = K.square(anchor - negative)\n if dist == 'euclidean':\n positive_distance = K.sqrt(K.sum(positive_distance, axis=-1, keepdims=True))\n negative_distance = K.sqrt(K.sum(negative_distance, axis=-1, keepdims=True))\n elif dist == 'sqeuclidean':\n positive_distance = K.mean(positive_distance, axis=-1, keepdims=True)\n negative_distance = K.mean(negative_distance, axis=-1, keepdims=True)\n loss = positive_distance - negative_distance\n if margin == 'maxplus':\n loss = K.maximum(0.0, 1 + loss)\n elif margin == 'softplus':\n loss = K.log(1 + K.exp(loss))\n return K.mean(loss)\n\n### Embedding Functions ###\ndef build_mlp_model(input_shape):\n\n base_input = Input(input_shape)\n x = Dense(1200, activation='relu')(base_input)\n embedding_model = Model(base_input, x, name='embedding')\n \n anchor_input = Input(input_shape, name='anchor_input')\n positive_input = Input(input_shape, name='positive_input')\n negative_input = Input(input_shape, name='negative_input')\n \n anchor_embedding = embedding_model(anchor_input)\n positive_embedding = embedding_model(positive_input)\n negative_embedding = embedding_model(negative_input)\n \n inputs = [anchor_input, positive_input, negative_input]\n outputs = [anchor_embedding, positive_embedding, negative_embedding]\n \n triplet_model = Model(inputs, outputs)\n triplet_model.add_loss(K.mean(triplet_loss(outputs)))\n triplet_model.compile(loss=None, optimizer='adam') #loss should be None\n \n return embedding_model, triplet_model\n\ndef build_cnn_model(input_shape):\n\n base_input = Input(input_shape)\n x = Dense(128, activation='relu')(base_input)\n embedding_model = Model(base_input, x, name='embedding')\n \n anchor_input = Input(input_shape, name='anchor_input')\n positive_input = Input(input_shape, name='positive_input')\n negative_input = Input(input_shape, name='negative_input')\n \n anchor_embedding = embedding_model(anchor_input)\n positive_embedding = embedding_model(positive_input)\n negative_embedding = embedding_model(negative_input)\n \n inputs = [anchor_input, positive_input, negative_input]\n outputs = [anchor_embedding, positive_embedding, negative_embedding]\n \n triplet_model = Model(inputs, outputs)\n triplet_model.add_loss(K.mean(triplet_loss(outputs)))\n triplet_model.compile(loss=None, optimizer='adam') #loss should be None\n \n return embedding_model, triplet_model\n\n### Dataset Functions ###\ndef read_full_dataset(indice_keys = None):\n data = SelfBACK.read()\n return data\n\ndef loov(data, test_person):\n x_train = []\n y_train = []\n x_test = []\n y_test = []\n \n test_data = data[test_person]\n for label in test_data.keys():\n for example in test_data[label]:\n x_test += [example]\n y_test += [label]\n \n copy = data.copy()\n copy.pop(test_person, None)\n \n for people in copy.keys():\n person = copy[people]\n for label in person.keys():\n for example in person[label]:\n x_train += [example]\n y_train += [label]\n \n return np.array(x_train), np.array(y_train), np.array(x_test), np.array(y_test)\n\n### Main code ###\n\ndata = read_full_dataset()\nwritepath = \"Results/SelfBACK_Triplet_Results.txt\"\nloov_scores = []\n\nfor person in data.keys():\n \n x_train, y_train, x_test, y_test = loov(data, person)\n print(len(x_train))\n print(set(y_train))\n \n no_minibatch = 200\n batch_size = 128\n steps_per_epoch = no_minibatch\n \n embedding_model, triplet_model = build_mlp_model((360,))\n \n history = triplet_model.fit_generator(triplet_generator_minibatch(x_train, y_train, no_minibatch),\n steps_per_epoch=steps_per_epoch,\n epochs=20,\n verbose=1)\n\n x_pred = embedding_model.predict(x_train)\n x_t = embedding_model.predict(x_test)\n \n predictions = []\n k = 3\n \n predictions = cos_knn(k, x_t, y_test, x_pred, y_train)\n \n print(len(predictions))\n acc = get_accuracy(y_test, predictions)\n \n inn.write_data(writepath, str(acc))\n print(\"Accuracy: \", acc)\n loov_scores += [acc]\n\nprint(loov_scores)\nloov_scores = np.array(loov_scores)\nprint(\"Average accuracy: \" + str(np.mean(loov_scores)))","sub_path":"SelfBACK/triplet.py","file_name":"triplet.py","file_ext":"py","file_size_in_byte":8321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"113951015","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\nimport json, httplib, urllib, os, sys\nimport subprocess, re\n\nNacosHostIP = os.environ.get('NacosHostIP', '192.168.24.22')\nNacosHostPort = os.environ.get('NacosHostPort', 59494)\nNacosUserName = os.environ.get('NacosUserName', 'nacos')\nNacosUserPassword = os.environ.get('NacosUserPassword', 'nacos')\nRetryInterval=int(os.environ.get('RetryInterval', 5))\nRetryTimes=int(os.environ.get('RetryTimes', 10))\nConnectionTimeOut=int(os.environ.get('ConnectionTimeOut', 10))\nDataDIR=os.environ.get('DataDIR', 'DATA/')\n\n\n\nheaders = {\n \"Content-type\": \"application/x-www-form-urlencoded\",\n}\n\ndef checkConnection(func):\n def wrapper(*args, **kwargs):\n canConnect=False\n for itime in range(RetryTimes):\n try:\n TmpHttpObj=httplib.HTTPConnection(NacosHostIP, NacosHostPort ,timeout=ConnectionTimeOut)\n TmpHttpObj.request(url='nacos', method='GET')\n canConnect = True\n break\n except Exception as e:\n pass\n\n if not canConnect:\n return {\n \"ret_code\": 1,\n 'result': u'无法连接: %s:%s'%(str(NacosHostIP), str(NacosHostPort))\n }\n return func(*args, **kwargs)\n return wrapper\n\n\n\ndef sendHttpRequest(host='127.0.0.1', port=9200, url='/', method='GET', body={}, header={}, timeout=5):\n try:\n tmpBody = urllib.urlencode(body) if body else ''\n HttpObj = httplib.HTTPConnection(host, port, timeout=timeout)\n # HttpObj.request(url=url,method=method,body=tmpBody,headers=header)\n\n if method.upper() == 'GET':\n TmpURL = url + '/?' + tmpBody if tmpBody else url\n HttpObj.request(url=TmpURL, method=method)\n else:\n HttpObj.request(url=url, method=method, body=tmpBody, headers=header)\n\n response = HttpObj.getresponse()\n data = response.read()\n return {\n 'ret_code': 0,\n \"result\": data\n }\n\n except Exception as e:\n return {\n 'ret_code': 1,\n \"result\": str(e)\n }\n\n@checkConnection\ndef get_namespaces():\n return sendHttpRequest(host=NacosHostIP, port=NacosHostPort, url='/nacos/v1/console/namespaces')\n\n@checkConnection\ndef get_namespace(namespace=None):\n if not namespace:\n return {\n \"ret_code\": 1,\n 'result': u'参数不合法',\n }\n\n TmpResult = get_namespaces()\n if TmpResult['ret_code'] != 0:\n return TmpResult\n\n TmpList = json.loads(TmpResult['result'])['data']\n\n for item in TmpList:\n if item['namespaceShowName'] == namespace:\n return {\n 'ret_code': 0,\n 'result': item\n }\n return {'ret_code': 0, 'result': None}\n\n@checkConnection\ndef create_namespace(namespace=None, namespaceID='6c0b3e50-8629-411a-a0ed-a270f327e8cd'):\n if not namespace or not isinstance(namespace, str):\n return {\n 'ret_code': 1,\n \"result\": u\"namespace 参数不合法:%s\" % (str(namespace, ))\n }\n\n TmpResult = get_namespaces()\n if TmpResult['ret_code'] != 0:\n return TmpResult\n\n TmpList = json.loads(TmpResult['result'])['data']\n TmpCurrentNamespace = [x['namespaceShowName'] for x in TmpList]\n\n if namespace in TmpCurrentNamespace:\n return {\n \"ret_code\": 0,\n 'result': \"namespace %s already exists\" % (namespace,)\n }\n\n TmpDict = {\n 'username': NacosUserName,\n 'password': NacosUserPassword,\n 'namespaceName': namespace,\n 'customNamespaceId': namespaceID,\n 'namespaceDesc': namespaceID,\n }\n\n return sendHttpRequest(host=NacosHostIP, port=NacosHostPort, method='POST', url='/nacos/v1/console/namespaces',\n body=TmpDict, header=headers)\n\n@checkConnection\ndef publish_config(tenant='wcm', dataid=None, group='DEFAULT_GROUP', content='', type='text'):\n if not dataid:\n return {\n 'ret_code': 1,\n 'result': u\"dataid 参数不合法\",\n }\n\n TmpNamespaceInfo = get_namespace(tenant)\n if TmpNamespaceInfo['result'] is None:\n RawCreateNamespace = create_namespace(tenant)\n if RawCreateNamespace['ret_code'] != 0 or RawCreateNamespace['result'] is None:\n return {'ret_code': 1, 'result': u\"名空间 %s 不存在,且创建失败\" % (tenant,)}\n TmpNamespaceInfo = get_namespace(tenant)\n\n TmpDict = {\n 'username': NacosUserName,\n 'password': NacosUserPassword,\n 'tenant': TmpNamespaceInfo['result']['namespace'],\n 'dataId': dataid,\n 'content': content,\n 'type': 'text',\n 'group': group,\n }\n\n TmpResult = sendHttpRequest(host=NacosHostIP, port=NacosHostPort, url='/nacos/v1/cs/configs', method='POST',\n body=TmpDict, header=headers)\n return TmpResult\n\n@checkConnection\ndef get_config(tenant='wcm', dataid=None, group='DEFAULT_GROUP'):\n if not dataid:\n return {\n 'ret_code': 1,\n 'result': u\"dataid 参数不合法\",\n }\n\n TmpNamespaceInfo = get_namespace(tenant)\n if TmpNamespaceInfo['result'] is None:\n return {\"ret_code\": 0, \"result\": None}\n\n TmpDict = {\n 'username': NacosUserName,\n 'password': NacosUserPassword,\n 'dataId': dataid,\n 'tenant': TmpNamespaceInfo['result']['namespace'],\n 'group': group,\n }\n\n TmpResult = sendHttpRequest(host=NacosHostIP, port=NacosHostPort, url='/nacos/v1/cs/configs', method='GET',\n body=TmpDict)\n return TmpResult\n\n\nif __name__ == \"__main__\":\n if not os.path.isfile(os.path.join(DataDIR, 'namespace.txt')):\n print ('ERROR; namespace file not exits: '+str(os.path.join(DataDIR, 'namespace.txt')))\n exit(1)\n with open(os.path.join(DataDIR, 'namespace.txt'),mode='r') as f:\n for line in f:\n line = line.strip()\n TmpList = line.split()\n if len(TmpList) != 2:\n continue\n\n TmpNamespace = TmpList[0]\n TmpID = TmpList[1]\n create_namespace(namespace=TmpNamespace, namespaceID=TmpID)\n\n TmpDataDIR = os.path.normpath(DataDIR) + os.sep\n if not os.path.isdir(DataDIR):\n print ('ERROR; namespace file not exits: ' + str(DataDIR))\n exit(1)\n\n RawInfo = subprocess.Popen(\"find %s -mindepth 3 -maxdepth 3 -type f\"%(TmpDataDIR,),shell=True,\n stdout=subprocess.PIPE).communicate()[0]\n for filepath in re.findall(r'(.*?)\\n', RawInfo, flags=re.MULTILINE|re.DOTALL|re.UNICODE):\n TmpFileExtension = filepath.split('.')[1]\n if TmpFileExtension not in ['yaml', 'yml', 'properties']:\n print ('Skipping: %s'%(filepath,))\n continue\n TmpFilename = filepath.lstrip(TmpDataDIR)\n if TmpFilename.count(os.sep) == 1:\n TmpGroupName = TmpFilename.split(os.sep)[0]\n print ('filename: '+str(filepath))\n print ('group name: '+str(TmpGroupName))\n with open(filepath) as f:\n print (u'导入 %s' % (filepath,))\n TmpResult = publish_config(dataid=filepath.split('/')[-1], content=f.read(), tenant=TmpGroupName)\n print (TmpResult)\n if TmpResult['ret_code'] != 0:\n print (str(TmpResult))\n sys.exit(1)\n elif TmpFilename.count(os.sep) == 2:\n TmpTenantName = TmpFilename.split(os.sep)[0]\n TmpFilename = TmpFilename.lstrip(TmpTenantName+'/')\n TmpGroupName = TmpFilename.split(os.sep)[0]\n\n print ('filename: '+str(filepath))\n print ('tenant name: %s'%(TmpTenantName,))\n print ('group name: '+str(TmpGroupName))\n with open(filepath) as f:\n print (u'load %s' % (filepath,))\n TmpResult = publish_config(dataid=filepath.split('/')[-1], content=f.read(), tenant=TmpTenantName, group=TmpGroupName)\n print (TmpResult)\n if TmpResult['ret_code'] != 0:\n print (str(TmpResult))\n sys.exit(1)\n\n\n","sub_path":"import_nacos_config.py","file_name":"import_nacos_config.py","file_ext":"py","file_size_in_byte":8216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"451022099","text":"import dropbox\r\nclass TransferData:\r\n def __init__ (self, access_token):\r\n self.access_token=access_token\r\n def upload_file (self, file_from, file_to):\r\n dbx=dropbox.Dropbox(self.access_token)\r\n f=open(file_from,\"rb\")\r\n dbx.files_upload(f.read(),file_to)\r\ndef main():\r\n access_token=\"sl.AwYF5fAk-Y15fuKtwxtewCgkdb1vsM9daNzbuPDgPONrJgOEQ09ta7k5gLWyFQzqAxFTraod-KNDFLOxMYxeTiqH6P_SmZf-ZcAAgC2A5u9JpG1WA_Y-JQyPk3U34_u7sqku-8s\"\r\n transferData=TransferData(access_token)\r\n file_from=input(\"Enter the path of the file to transfer\")\r\n file_to=\"/RomirArya/test.jpeg\"\r\n transferData.upload_file(file_from, file_to)\r\n print(\"File has been moved\")\r\nmain()\r\n","sub_path":"class - cloud storage/cloudstorage.py","file_name":"cloudstorage.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"257235428","text":"##\nimport sys\nimport warnings\nfrom soup.classic import *\nfrom skimage.exposure import equalize_adapthist as clahe\nfrom skimage.feature import blob_dog\nfrom skimage.transform import hough_circle, hough_circle_peaks\nfrom skimage.feature import canny\nfrom skimage.filters import gaussian\nfrom sklearn.cluster import AffinityPropagation, MeanShift\nfrom matplotlib.widgets import Slider\n \ndef yxr2mask(y,x,r,shape):\n \"\"\"Given y,x coords and radius of a blob, generate a binary mask for it\n\n Parameters\n ----------\n y,x : int\n center coordinates\n r : int\n radius\n shape : tuple\n (y,x) shape of mask array\n\n Returns\n -------\n mask : np.ndarray, mask array\n \"\"\"\n h,w = shape\n\n iy,ix = np.ogrid[-y:h-y, -x:w-x]\n return ix*ix + iy*iy <= r*r\n\ndef compute_clusterness(img_path, visualize=False, interactive=False):\n \n # read image and basic preprocessing\n im = imread(img_path).astype(np.uint16)\n im = np.squeeze(im).sum(axis=-1)\n im = clahe(im)\n im_disp = im.copy()\n im_prefilt = im.copy()\n im = gaussian(im, 3) \n\n return np.array([np.std(im[im>0.05])])\n\n if visualize:\n fig,axs = pl.subplots(2,2,sharex=True,sharey=True)\n axs = axs.ravel()\n [ax.axis('off') for ax in axs]\n axs[0].imshow(im_disp)\n \n def compute_pts(upper=0.007):\n # hough transform to find circles\n lower = 1e-5\n sigma_canny = 3.\n edges = canny(im, sigma=sigma_canny, low_threshold=lower, high_threshold=upper)\n\n hough_radii = np.arange(15, 40, 2) # strictly for size constraints on cells\n hough_res = hough_circle(edges, hough_radii)\n accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, threshold=.4*np.max(hough_res), min_xdistance=25, min_ydistance=25)\n\n pts = np.array([cy,cx]).T\n return pts,radii\n\n if interactive:\n def end_pause(*args):\n global paused\n paused = False\n\n def update_pts(*args):\n upper = slider.val\n pts,radii = compute_pts(upper)\n global _pts\n if _pts is not None:\n _pts.remove()\n _pts = axi.scatter(*pts.T[::-1], color='red')\n\n fig,(axi,ax_sl) = pl.subplots(2,1,num='Interactive window',gridspec_kw=dict(height_ratios=[10,1]))\n global _pts, paused\n _pts = None\n update_pts()\n slider = Slider(ax_sl, '', 0.0001, 0.1, valinit=0.005, valfmt='%0.5f')\n slider.on_changed(update_pts)\n fig.canvas.mpl_connect('close_event', end_pause)\n #fig.canvas.mpl_connect('button_press_event', self.on_press)\n axi.imshow(im)\n axi.axis('off')\n paused = True\n\n else:\n pts,radii = compute_pts()\n\n # merge bundles of hough results to converge on single cells\n ms = MeanShift(bandwidth=35)\n ms.fit(pts)\n c = ms.cluster_centers_\n labs = ms.labels_\n r = np.array([np.mean(radii[labs==ci]) for ci in np.arange(len(c))])\n circs = np.concatenate([c,r[:,None]], axis=1)\n\n if visualize:\n axs[1].imshow(im_disp)\n for cy,cx,ri in circs:\n circ = pl.Circle((cx,cy), ri, facecolor='none', edgecolor='k', lw=.5)\n axs[1].add_patch(circ)\n\n # characterize the contents of each cell\n masks = np.array([yxr2mask(*c,shape=im.shape) for c in circs])\n clusteriness = np.array([np.std(im_prefilt[m]) for m in masks])\n\n if visualize:\n disp = np.zeros_like(im)\n for v,m in zip(clusteriness,masks):\n disp[m] = v\n axs[2].imshow(disp)\n\n ret = clusteriness\n if visualize:\n ret = (ret, fig)\n return ret\n\n##\nif __name__ == '__main__':\n # how to use:\n # give the data path to a folder that contains one folder per condition\n # then just run this main, and it will save the images and values out to outputs\n\n #data_path = '111214_asyn/'\n data_path = sys.argv[1]\n\n out_path = os.path.join('outputs',data_path)\n if not os.path.exists(out_path):\n os.mkdir(out_path)\n\n conditions = [i for i in os.listdir(data_path) if i[0]!='.']\n\n results = []\n\n for cond in conditions:\n print(cond)\n cpath = os.path.join(data_path, cond)\n tfiles = [t for t in os.listdir(cpath) if t.endswith('.tif')]\n tpaths = [os.path.join(cpath,t) for t in tfiles]\n\n for tpath in tpaths:\n print('\\t',tpath)\n t_name = os.path.splitext(os.path.split(tpath)[-1])[0]\n result = compute_clusterness(tpath, visualize=False)\n #result,fig = compute_clusterness(tpath, visualize=True)\n #figpath = os.path.join(out_path, '{}-{}'.format(cond,t_name))\n #fig.savefig(figpath)\n #pl.close(fig)\n \n for r in result:\n results.append(dict( cond=cond,\n path=tpath,\n filename=t_name,\n value=r,\n ))\n results = pd.DataFrame(results)\n out = os.path.join(out_path, 'all_results.csv')\n results.to_csv(out)\n##\n","sub_path":"project3/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":5125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"449008126","text":"#!/usr/bin/env python3\r\nimport cgi\r\nimport html\r\nimport sys\r\nimport codecs\r\nimport requests\r\n\r\nDICT_WITH_LANGS = {'Русский': 'ru', 'Испанский': 'es', 'Английский': 'en',\r\n 'Итальянский': 'it', 'Французский': 'fr', 'Немецкий': 'de',\r\n 'Нидерландский': 'nl', 'Украинский': 'uk',\r\n 'Словенский': 'sl', 'Норвежский': 'no', 'Литовский': 'lt',\r\n 'Латинский': 'la', 'Белорусский': 'be'}\r\nURL = 'https://translate.yandex.net/api/v1.5/tr.json/translate?'\r\na = 'trnsl.1.1.20160119T035517Z.50c6906978ef1961'\r\nb = '.08d0c5ada49017ed764c042723895ffab867be7a'\r\nKEY = a + b\r\n\r\nsys.stdout = codecs.getwriter(\"utf-8\")(sys.stdout.detach())\r\n\r\nform = cgi.FieldStorage()\r\ntext = form.getfirst(\"TEXT_1\", \"не задано\")\r\ntext = html.escape(text)\r\nLANGUAGE1 = form.getfirst(\"LANGUAGE1\")\r\nLANGUAGE2 = form.getfirst(\"LANGUAGE2\")\r\nerr = 0\r\nif LANGUAGE1 is None:\r\n LANGUAGE1 = 'Русский'\r\n err = 1\r\nif LANGUAGE2 is None:\r\n LANGUAGE2 = 'Русский'\r\n err = 1\r\nif LANGUAGE1 == 'Язык исходного текста':\r\n LANGUAGE1 = 'Русский'\r\n err = 1\r\nif LANGUAGE2 == 'Язык перевода':\r\n LANGUAGE2 = 'Русский'\r\n err = 1\r\n\r\nprint(\"Content-type: text/html\\n\")\r\nprint(\"\"\"\r\n \r\n \r\n \r\n Перевод\r\n \r\n \r\n \r\n
    \r\n

    ----------------TextEngine by ev1n----------------

    \"\"\")\r\n\r\nLANGUAGE1 = DICT_WITH_LANGS[LANGUAGE1]\r\nLANGUAGE2 = DICT_WITH_LANGS[LANGUAGE2]\r\nlang = LANGUAGE1 + '-' + LANGUAGE2\r\nif err == 0:\r\n r = requests.post(URL, data={'key': KEY, 'text': text, 'lang': lang})\r\n data = r.text[r.text.find('['):-1][2:-2]\r\n print(\"

    Перевод введённого текста: {}

    \".format(data))\r\nelse:\r\n print(\"

    Не выбран язык

    \")\r\n\r\nprint(\"\"\"\r\n \"\"\")\r\n","sub_path":"cgi-bin/translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"226441658","text":"from __future__ import print_function\n\nimport argparse\nfrom os.path import join, realpath, dirname\n\nfrom dt_shell import DTCommandAbs\nfrom dt_shell.env_checks import check_docker_environment\nfrom past.builtins import raw_input\n\nfrom utils.cli_utils import start_command_in_subprocess\nfrom utils.docker_utils import bind_duckiebot_data_dir, attach_terminal\nfrom utils.networking_utils import get_duckiebot_ip\n\n\nclass DTCommand(DTCommandAbs):\n\n @staticmethod\n def command(shell, args):\n script_file = join(dirname(realpath(__file__)), 'calibrate_wheels.sh')\n\n prog = 'dts duckiebot calibrate_wheels DUCKIEBOT_NAME'\n usage = \"\"\"\nCalibrate: \n\n %(prog)s\n\"\"\"\n\n from utils.networking_utils import get_duckiebot_ip\n\n parser = argparse.ArgumentParser(prog=prog, usage=usage)\n parser.add_argument('hostname', default=None, help='Name of the Duckiebot to calibrate')\n parsed_args = parser.parse_args(args)\n\n duckiebot_ip = get_duckiebot_ip(parsed_args.hostname)\n # shell.calibrate(duckiebot_name=args[0], duckiebot_ip=duckiebot_ip)\n script_cmd = '/bin/bash %s %s %s' % (script_file, parsed_args.hostname, duckiebot_ip)\n\n start_command_in_subprocess(script_cmd)\n\n\ndef calibrate(hostname):\n duckiebot_ip = get_duckiebot_ip(hostname)\n import docker\n local_client = check_docker_environment()\n\n from utils.docker_utils import RPI_DUCKIEBOT_CALIBRATION\n duckiebot_client = docker.DockerClient('tcp://' + duckiebot_ip + ':2375')\n\n local_client.images.pull(RPI_DUCKIEBOT_CALIBRATION)\n raw_input(\"\"\"{}\\nTo perform the wheel calibration, follow the steps described in the Duckiebook.\n http://docs.duckietown.org/DT18/opmanual_duckiebot/out/wheel_calibration.html\n You will now be given a container running on the Duckiebot for wheel calibration.\"\"\".format('*' * 20))\n\n wheel_calibration_container = duckiebot_client.containers.run(image=RPI_DUCKIEBOT_CALIBRATION,\n privileged=True,\n network_mode='host',\n tty=True,\n datavol=bind_duckiebot_data_dir(),\n command='/bin/bash')\n\n attach_terminal(wheel_calibration_container.name, hostname)\n","sub_path":"duckiebot/calibrate_wheels/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"466580413","text":"import urllib, imghdr, os\r\n\r\n\r\ndef download(url, local_dest):\r\n \"\"\"\r\n Downloads a file from any URL path\r\n\r\n :param url: where in the file is stored on another machine\r\n :param local_dest: Where the file should be saved to e.g. ~/SaturnServer/images/map__20.10.2016_20.32.45.jpg\r\n \"\"\"\r\n try:\r\n urllib.urlretrieve(url, local_dest)\r\n except IOError as ex:\r\n raise DownloadException(url, local_dest, exception=ex)\r\n\r\n if not was_image_found(local_dest):\r\n os.remove(local_dest)\r\n raise DownloadException(url, local_dest,\r\n message='There was no file at the location: %s \\n'\r\n 'Deleting the file at %s' % (url, local_dest))\r\n\r\n\r\ndef was_image_found(local_dest):\r\n \"\"\"\r\n Determines if the file at the path is an image\r\n\r\n :param local_dest: The location of the file under question\r\n\r\n :return true if the download was an image\r\n \"\"\"\r\n # This function returns null if the file is not an image or returns a string if it is\r\n return not not imghdr.what(local_dest)\r\n\r\nclass DownloadException(Exception):\r\n def __init__(self, url, local_dest, message=None, exception=None):\r\n extra = ''\r\n if message:\r\n extra =\"\\n\\tMessage: {}\".format(message)\r\n\r\n super(DownloadException, self).__init__(\r\n \"DownloadException: Cannot download \\'{}\\' and store it in \\'{}\\'\".format(url,local_dest,message)+extra)\r\n\r\n self.url = url\r\n self.local_dest = local_dest\r\n self.exception = exception\r\n","sub_path":"service/tools/downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"399828350","text":"from setuptools import setup\nfrom licensetree import __version__\n\n__version__ = list(map(str, __version__))\n\nsetup(name='licensetree',\n version='.'.join(__version__),\n description='License Tree Generator for Python Projects',\n url='http://github.com/theSage21/licensetree',\n author='Arjoonn Sharma',\n author_email='arjoonn.94@gmail.com',\n packages=['licensetree'],\n entry_points={'console_scripts': ['licensetree=licensetree.cli:main']},\n keywords=['licensetree', 'license', 'mapping', 'dependeicies'],\n zip_safe=False)\n","sub_path":"pypi_install_script/licensetree-0.0.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"365969194","text":"#!/usr/bin/env python3\n\nimport glob\nimport logging\nimport numpy as np\nimport os\nimport random\nimport torch\nimport torch.utils.data\nimport pdb\nimport imageio\nimport time\nimport random\nimport imageio\n\nfrom lib.utils import *\n\n\ndef get_instance_filenames(data_source, split):\n npzfiles = []\n for dataset in split:\n for class_name in split[dataset]:\n for instance_name in split[dataset][class_name]:\n instance_filename = os.path.join(\n dataset, class_name, instance_name + \".npz\"\n )\n if not os.path.isfile(\n os.path.join(data_source, instance_filename)\n ):\n logging.warning(\n \"Requested non-existent file '{}'\".format(instance_filename)\n )\n npzfiles += [instance_filename]\n return npzfiles\n\n\ndef remove_nans(tensor):\n tensor_nan = torch.isnan(tensor[:, 3])\n return tensor[~tensor_nan, :]\n\n\ndef unpack_sdf_samples(filename, subsample=None):\n\n npz = np.load(filename)\n if subsample is None:\n return npz\n\n pos_tensor = remove_nans(torch.from_numpy(npz[\"pos\"].astype(float)))\n neg_tensor = remove_nans(torch.from_numpy(npz[\"neg\"].astype(float)))\n\n # split the sample into half\n half = int(subsample / 2)\n\n random_pos = (torch.rand(half).cpu() * pos_tensor.shape[0]).long()\n random_neg = (torch.rand(half).cpu() * neg_tensor.shape[0]).long()\n\n sample_pos = torch.index_select(pos_tensor, 0, random_pos)\n sample_neg = torch.index_select(neg_tensor, 0, random_neg)\n\n samples = torch.cat([sample_pos, sample_neg], 0).float()\n\n return samples\n\n\nclass SDFSamples(torch.utils.data.Dataset):\n def __init__(\n self,\n data_source,\n split,\n subsample\n ):\n self.subsample = subsample\n self.data_source = data_source\n self.npyfiles = get_instance_filenames(data_source, split)\n\n\n def __len__(self):\n return len(self.npyfiles)\n\n def __getitem__(self, idx):\n filename = os.path.join(\n self.data_source, self.npyfiles[idx]\n )\n return unpack_sdf_samples(filename, self.subsample), idx, self.npyfiles[idx]\n","sub_path":"lib/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"171888315","text":"import visa\n\nclass LSCI332S:\t\n\tdef __init__(self, GPIB_ADDR):\n\t\tself.GPIB_ADDR = GPIB_ADDR\n\t\tself.measurements = []\n\t\tself.rm = visa.ResourceManager()\n\t\tself.instr = self.rm.get_instrument('GPIB0::' + str(self.GPIB_ADDR) + '::INSTR')\n\t\t\n\tdef IDN(self):\n\t\treturn self.instr.ask('*IDN?')\n\t\t\n\tdef tempGet(self,channel):\n\t\tcontrol = 2\n\t\tif control == 0:\n\t\t\tchannel = 'A'\n\t\tif control == 1:\n\t\t\tchannel = 'B'\n\t\treturn self.instr.ask('KRDG? '+channel)\n\t\t\t","sub_path":"PNA/Backup/LSCI332S.py","file_name":"LSCI332S.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"573682803","text":"from turtle import Turtle \nfrom random import randint\n\nlaura = Turtle()\n\nlaura.color(\"red\")\nlaura.shape(\"turtle\")\n\nlaura.penup()\nlaura.goto(-160, 100)\nlaura.pendown()\n\njohn = Turtle()\n\njohn.color(\"black\")\njohn.shape(\"turtle\")\n\njohn.penup()\njohn.goto(-160, 70)\njohn.pendown()\n\nalica = Turtle()\n\nalica.color(\"blue\")\nalica.shape(\"turtle\")\n\nalica.penup()\nalica.goto(-160, 40)\nalica.pendown()\n\nmasik = Turtle()\n\nmasik.color(\"green\")\nmasik.shape(\"turtle\")\n\nmasik.penup()\nmasik.goto(-160, 10)\nmasik.pendown()\n\nfor movement in range(100):\n alica.forward(randint(1,5))\n masik.forward(randint(1,5))\n john.forward(randint(1,5))\n laura.forward(randint(1,5))","sub_path":"futurelearn_python/week1/turtle_race.py","file_name":"turtle_race.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"137527331","text":"import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom abc import ABC\nfrom dataset import NotMNIST2, NotMNIST10, FaceScrub\n\n\nclass LinearOptimizer(ABC):\n def __init__(self, NUM_CLASSES):\n self.ITERATIONS = 5000\n self.LEARNING_RATES = [0.005, 0.001, 0.0001]\n self.MINI_BATCH_SIZES = [500, 1500, 3500]\n self.WEIGHT_DECAYS = [0., 0.001, 0.1, 1.]\n self.NUM_CLASSES_TO_DATASETS = {\n 1: NotMNIST2,\n 2: NotMNIST2,\n 6: FaceScrub,\n 10: NotMNIST10,\n }\n self.data = self.NUM_CLASSES_TO_DATASETS[NUM_CLASSES]()\n\n self.x = tf.placeholder(tf.float32)\n self.x_plus_bias = tf.concat([tf.ones([tf.shape(self.x)[0], 1]), self.x], 1)\n self.y_ = tf.placeholder(tf.float32)\n\n self.b = tf.Variable(tf.zeros([NUM_CLASSES]))\n self.w = tf.Variable(tf.zeros([self.data.trainData.shape[1], NUM_CLASSES]))\n\n self.y = tf.matmul(self.x, self.w) + self.b\n\n self.sess = tf.InteractiveSession()\n\n def __optimize(self, mini_batch_size, error, train_step):\n tf.global_variables_initializer().run()\n\n losses = {\n 'training': [],\n 'validation': [],\n 'test': []\n }\n accuracies = {\n 'training': [],\n 'validation': [],\n 'test': []\n }\n\n for i in range(self.ITERATIONS):\n mini_batch_indices = np.random.randint(0, self.data.trainData.shape[0], size=mini_batch_size)\n batch_x = self.data.trainData[mini_batch_indices]\n batch_y = self.data.trainTarget[mini_batch_indices]\n self.sess.run(train_step, feed_dict={self.x: batch_x, self.y_: batch_y})\n\n if ((i + 1) * mini_batch_size) % self.data.trainData.shape[0] <= i * mini_batch_size % self.data.trainData.shape[0]:\n losses['training'].append(self.sess.run(error, feed_dict={self.x: self.data.trainData, self.y_: self.data.trainTarget})[0][0])\n losses['validation'].append(self.sess.run(error, feed_dict={self.x: self.data.validData, self.y_: self.data.validTarget})[0][0])\n losses['test'].append(self.sess.run(error, feed_dict={self.x: self.data.testData, self.y_: self.data.testTarget})[0][0])\n\n accuracies['training'].append(self.sess.run(self.accuracy, feed_dict={self.x: self.data.trainData, self.y_: self.data.trainTarget}))\n accuracies['validation'].append(self.sess.run(self.accuracy, feed_dict={self.x: self.data.validData, self.y_: self.data.validTarget}))\n accuracies['test'].append(self.sess.run(self.accuracy, feed_dict={self.x: self.data.testData, self.y_: self.data.testTarget}))\n\n return losses, accuracies\n\n def sgd(self, lr, mini_batch_size, weight_decay):\n error = self.loss_fcn + weight_decay/2*tf.matmul(tf.transpose(self.w), self.w)\n train_step = tf.train.GradientDescentOptimizer(lr).minimize(error)\n return self.__optimize(mini_batch_size, error, train_step)\n\n def adam(self, lr, mini_batch_size, weight_decay):\n error = self.loss_fcn + weight_decay/2*tf.matmul(tf.transpose(self.w), self.w)\n train_step = tf.train.AdamOptimizer(lr).minimize(error)\n return self.__optimize(mini_batch_size, error, train_step)\n\n\nclass LinearRegression(LinearOptimizer):\n def __init__(self):\n self.NUM_CLASSES = 1\n super().__init__(self.NUM_CLASSES)\n\n trainDataWithBias = tf.cast(np.concatenate((np.ones((self.data.trainData.shape[0], 1)), self.data.trainData), axis=1), tf.float32)\n self.normal_w = tf.matmul(tf.matrix_inverse(tf.matmul(tf.transpose(trainDataWithBias), trainDataWithBias)), tf.matmul(tf.transpose(trainDataWithBias), tf.cast(self.data.trainTarget, tf.float32)))\n self.normal_y = tf.matmul(self.x_plus_bias, self.normal_w)\n\n self.normal_mse = tf.reduce_mean(tf.square(self.y_ - self.normal_y))/2\n self.loss_fcn = tf.reduce_mean(tf.square(self.y_ - self.y))/2\n\n # this value is overriden in the case of normal equations\n self.correct_prediction = tf.equal(self.y_, tf.round(self.y))\n self.accuracy = tf.reduce_mean(tf.cast(self.correct_prediction, tf.float32))\n\n def get_normal_accuracies(self):\n self.correct_prediction = tf.equal(self.y_, tf.round(self.normal_y))\n\n accuracies = {\n 'training': self.sess.run(self.accuracy, feed_dict={self.x: self.data.trainData, self.y_: self.data.trainTarget}),\n 'validation': self.sess.run(self.accuracy, feed_dict={self.x: self.data.validData, self.y_: self.data.validTarget}),\n 'test': self.sess.run(self.accuracy, feed_dict={self.x: self.data.testData, self.y_: self.data.testTarget}),\n }\n return accuracies\n\n def get_normal_losses(self):\n losses = {\n 'training': self.sess.run(self.normal_mse, feed_dict={self.x: self.data.trainData, self.y_: self.data.trainTarget}),\n 'validation': self.sess.run(self.normal_mse, feed_dict={self.x: self.data.validData, self.y_: self.data.validTarget}),\n 'test': self.sess.run(self.normal_mse, feed_dict={self.x: self.data.testData, self.y_: self.data.testTarget}),\n }\n return losses\n\n\nclass LogisticRegression(LinearOptimizer):\n def __init__(self, NUM_CLASSES):\n super().__init__(NUM_CLASSES)\n\n self.predictions = tf.argmax(tf.sigmoid(self.y), 1)\n self.correct_prediction = tf.equal(tf.squeeze(tf.cast(self.y_, dtype=tf.int64)), self.predictions)\n self.accuracy = tf.reduce_mean(tf.cast(self.correct_prediction, tf.float32))\n self.loss_fcn = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=tf.one_hot(tf.cast(self.y_, dtype=tf.int32), NUM_CLASSES), logits=self.y))\n\n\nclass LogisticRegression2(LogisticRegression):\n def __init__(self):\n self.NUM_CLASSES = 2\n super().__init__(self.NUM_CLASSES)\n\n\nclass LogisticRegression10(LogisticRegression):\n def __init__(self):\n self.NUM_CLASSES = 10\n super().__init__(self.NUM_CLASSES)\n\n\nclass LogisticRegressionFaceScrub(LogisticRegression):\n def __init__(self):\n self.NUM_CLASSES = 6\n super().__init__(self.NUM_CLASSES)\n\n self.w = tf.Variable(tf.zeros([self.data.trainData.shape[1], self.NUM_CLASSES]))\n self.y = tf.matmul(self.x, self.w) + self.b\n\n\ndef plot_losses_over_epochs(epochs, losses, title):\n for lr in losses.keys():\n plt.plot(epochs, losses[lr], label='lr=' + str(lr))\n plt.legend()\n plt.title(title)\n plt.ylabel(\"Losses\")\n plt.xlabel(\"Epochs\")\n plt.show()\n\ndef plot_metrics_over_epochs(epochs, metrics, title):\n for key in metrics.keys():\n plt.plot(epochs, metrics[key], label=str(key))\n plt.legend()\n plt.title(title)\n plt.ylabel(\"Losses/Accuracies\")\n plt.xlabel(\"Epochs\")\n plt.show()\n","sub_path":"ECE521_Inference_Algorithms_and_Machine_Learning/assignment2/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":6885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"634506466","text":"#!/usr/bin/env python\n\n\nimport sys\nimport glob\n\nimport pandas as pd\n\n\n\ndef read_file(f):\n\n\tindel_df = pd.read_csv(f,sep=\"\\t\",header=None)\n\ttotal = indel_df[8].sum()\n\tindel_reads = indel_df[6].sum()\n\tindel = float(indel_reads)/total\n\tout = [total,indel_reads,indel]\n\tout = pd.DataFrame(out).T\n\tout.columns = ['Total reads','indel reads','indel frequency']\n\tout.index = [f.split(\"/\")[0]]\n\treturn out\n\n\nfiles = glob.glob(\"*/*.tsv\")\nprint (files)\ndf_list = [read_file(f) for f in files]\ndf = pd.concat(df_list)\n\n\n\n# for g34 indel types\ndef read_group_file(x,file_list):\n\ttry:\n\t\tdf_list = [pd.read_csv(f,index_col=0) for f in file_list]\n\t\tdf = pd.concat(df_list,axis=1)\n\t\tdf = df.fillna(0)\n\t\tdf = pd.DataFrame(df.sum(axis=1).astype(int).sort_values(ascending=False))\n\t\treturn [x]+df.head(n=10).reset_index().values.flatten().tolist()\n\texcept:\n\t\treturn [x]\n\n\n\nfiles = glob.glob(\"*/*indel_spectrum.sum.csv\")\nfile_group = {}\nfor f in files:\n\tg = f.split(\"/\")[0]\n\tif g in file_group:\n\t\tfile_group[g].append(f)\n\telse:\n\t\tfile_group[g]=[f]\nout = [read_group_file(x,file_group[x]) for x in file_group]\nout = pd.DataFrame(out)\nout = out.set_index(0)\n# out.to_csv(\"test.csv\")\nn=int(out.shape[1]/2)\ncols = [[\"Top indels %s\"%(i),\"Top indels %s Frequency\"%(i)] for i in range(1,n+1)]\nprint (out)\nprint (cols)\nout.columns = [j for sub in cols for j in sub]\ndf = pd.concat([df,out],axis=1)\nfor c in df.columns:\n\tif \"Frequency\" in c:\n\t\tdf[c] = df[c]/df['Total reads']\ndf.to_csv(\"summary.csv\")\n\n\n\n","sub_path":"bin/count_indel_summary.py","file_name":"count_indel_summary.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"160479371","text":"from django.shortcuts import render\nfrom django.db.models import Q\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nimport requests\nimport json\nfrom .models import Tinder\n\n\ndef get_default_attributes(data):\n return {\n 'id': data.id,\n 'user_id': data.user_id,\n 'content': data.content,\n 'status': data.status,\n }\n\n\n@csrf_exempt\ndef tinder_list(request):\n print(request, request.META, request.GET)\n status = 'active'\n if 'status' in request.GET:\n status = request.GET['status']\n content_regex = ''\n if 'q' in request.GET:\n content_regex = request.GET['q']\n tinders = Tinder.objects.filter(\n Q(content__regex=r'{0}'.format(content_regex)) & Q(status=status))\n result = []\n for tinder in tinders:\n if len(result) < 100:\n result.append(get_default_attributes(tinder))\n return JsonResponse({'results': result, 'length': len(tinders)})\n\n\n@csrf_exempt\ndef tinder_create(request):\n if request.method == 'POST':\n tinder = Tinder()\n body = json.loads(request.body.decode('utf-8'))\n if not 'user_id' in body:\n return JsonResponse({'data': 'Invalid data'})\n tinder.user_id = body['user_id']\n if not 'content' in body:\n return JsonResponse({'data': 'Invalid data'})\n tinder.content = body['content']\n tinder.save()\n if not tinder.id:\n return JsonResponse({'data': 'Created failed'})\n return JsonResponse({'data': 'Created successfully', 'tinder': get_default_attributes(tinder)})\n return JsonResponse({'data': 'Invalid request'})\n\n\n@csrf_exempt\ndef tinder_detail(request, pk):\n return JsonResponse({'data': 'detail'})\n\n\n@csrf_exempt\ndef tinder_update(request):\n if request.method == 'POST':\n body = json.loads(request.body.decode('utf-8'))\n if not 'id' in body:\n return JsonResponse({'data': 'Invalid data'})\n search_id = body['id']\n search_tinders = Tinder.objects.filter(id=search_id)\n print(search_tinders)\n if len(search_tinders) == 1:\n tinder = search_tinders[0]\n if 'status' in body:\n tinder.status = body['status']\n tinder.save()\n return JsonResponse({'data': 'Updated successfully', 'tinder': get_default_attributes(tinder)})\n return JsonResponse({'data': 'Item not found'})\n return JsonResponse({'data': 'Invalid request'})\n\n\n@csrf_exempt\ndef tinder_delete(request, pk):\n if request.method == 'POST':\n body = json.loads(request.body.decode('utf-8'))\n if not 'id' in body:\n return JsonResponse({'data': 'Invalid data'})\n search_id = body['id']\n tinders = tinder.objects.filter(id=search_id).delete()\n if tinders[0] == 1:\n return JsonResponse({'data': 'Deleted successfully'})\n else:\n return JsonResponse({'data': 'Deleted failed'})\n\n\n@csrf_exempt\ndef tinder_delete_all(request):\n if request.method == 'POST':\n Tinder.objects.all().delete()\n return JsonResponse({'data': 'Deleted all tinders successfully'})\n return JsonResponse({'data': 'Deteled all tinders failed'})\n\n\n@csrf_exempt\ndef get_quick_filtered_tinders(request):\n filtered_tinders = tinder.objects.filter(Q(Volume__gt=10000) & Q(\n RSI_14__gt=60) & Q(RSI_14__lt=70) & Q(RSI_14_diff__gt=0) & Q(ROE__gt=17) & Q(EPS__gt=3000))\n result = []\n for tinder in filtered_tinders:\n result.append(get_default_attributes(tinder))\n return JsonResponse({'tinders': result})\n\n\n@csrf_exempt\ndef tinder_filter(request):\n if request.method == 'POST':\n body = json.loads(request.body.decode('utf-8'))\n result = []\n if 'watching_tinders' in body:\n watching_tinders = body['watching_tinders']\n filtered_tinders = tinder.objects.filter(\n Symbol__in=watching_tinders)\n for tinder in filtered_tinders:\n result.append(get_default_attributes(tinder))\n return JsonResponse({'tinders': result})\n Volume_min = 0\n RSI_14_max = 1000000\n RSI_14_min = -99999999\n RSI_14_diff_min = -99999999\n ROE_min = -99999999\n EPS_min = -99999999\n today_capitalization_min = 0\n percentage_change_in_price_min = -99999999\n Symbol_search = ''\n if 'Symbol_search' in body:\n Symbol_search = body['Symbol_search']\n if 'Volume_min' in body:\n Volume_min = body['Volume_min']\n if 'RSI_14_max' in body:\n RSI_14_max = body['RSI_14_max']\n if 'RSI_14_min' in body:\n RSI_14_min = body['RSI_14_min']\n if 'RSI_14_diff_min' in body:\n RSI_14_diff_min = body['RSI_14_diff_min']\n if 'ROE_min' in body:\n ROE_min = body['ROE_min']\n if 'EPS_min' in body:\n EPS_min = body['EPS_min']\n if 'today_capitalization_min' in body:\n today_capitalization_min = body['today_capitalization_min']\n if 'percentage_change_in_price_min' in body:\n percentage_change_in_price_min = body['percentage_change_in_price_min']\n filtered_tinders = tinder.objects.filter(Q(Volume__gt=Volume_min) & Q(RSI_14__gt=RSI_14_min) & Q(RSI_14__lt=RSI_14_max) & Q(RSI_14_diff__gt=RSI_14_diff_min) & Q(ROE__gt=ROE_min) & Q(EPS__gt=EPS_min) & Q(\n today_capitalization__gt=today_capitalization_min) & Q(percentage_change_in_price__gt=percentage_change_in_price_min) & Q(Symbol__regex=r'{0}'.format(Symbol_search))).order_by('-today_capitalization')\n for tinder in filtered_tinders:\n result.append(get_default_attributes(tinder))\n return JsonResponse({'tinders': result})\n return JsonResponse({'data': 'Invalid request'})\n\n\n@csrf_exempt\ndef analyze(request):\n results = []\n for i in range(1980, 2005):\n regex = 'birth_date\\\":\\\"' + str(i)\n count = len(Tinder.objects.filter(content__regex=r'{0}'.format(regex)))\n key = str(i)\n item = {\n 'name': key,\n 'value': count\n }\n results.append(item)\n print(results)\n return JsonResponse({\n 'data': {\n 'count': results \n }\n })\n","sub_path":"tinder/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"289561185","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 3 12:28:09 2020\n\n@author: belen\n\"\"\"\n\nimport os\nimport pandas as pd\nimport numpy as np\n\n#NLTK\nimport nltk\nnltk.download('punkt')\nnltk.download('wordnet')\nnltk.download('stopwords')\nfrom nltk import word_tokenize\n\nimport gensim\nfrom gensim.utils import simple_preprocess\n\nimport pyLDAvis\nimport pyLDAvis.sklearn\n\nimport spacy\nimport en_core_web_sm\n\nfrom sklearn.decomposition import LatentDirichletAllocation\n\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\n\nos.chdir('C:\\\\Users\\\\Inteligencia 1\\\\Documents\\\\Inteligencia')\n\ndf = pd.read_excel(\".\\\\Clas_auto_manual_v2.xlsx\")\n\ndf['year'] = df.coverDate.astype(str).str[:4]\n\n\n#- tokenización\n\ndf['tok_text'] = df['text'].apply(word_tokenize)\n\n\ndf_geo = df[(df['earth_topic']>=0)|(df['tsu_topic']>=0)|(df['vol_topic']>=0)]\ndf_geo = df_geo[(df_geo['Ame1']=='Terremoto')|(df_geo['Ame1']=='Multi')|(df_geo['Ame1']=='Tsunami')|(df_geo['Ame1']=='Volcanismo')]\n\n#- Solo terremoto\n\ndf_earth = df[df['earth_topic']>=0]\ndf_earth = df_earth[(df_earth['Ame1']=='Terremoto')|(df_earth['Ame1']=='Multi')|(df_earth['Ame2']=='Terremoto')|(df_earth['Ame3']=='Terremoto')]\n\n#- Solo tsunami\n\ndf_tsu = df[df['tsu_topic']>=0]\ndf_tsu = df_tsu[(df_tsu['Ame1']=='Tsunami')|(df_tsu['Ame1']=='Multi')|(df_tsu['Ame2']=='Tsunami')|(df_tsu['Ame3']=='Tsunami')]\n\n#- Solo volcán\n\ndf_vol = df[df['vol_topic']>=0]\ndf_vol = df_vol[(df_vol['Ame1']=='Volcanismo')|(df_vol['Ame1']=='Multi')|(df_vol['Ame2']=='Volcanismo')|(df_vol['Ame3']=='Volcanismo')]\n\n\n#Seleccionar amenaza\ndf= df_vol\ndf = df.reset_index()\ndel df['index']\n\n# Crear BIGRAMAS Y TRIGRAMAS\ndata_words = df.tok_text.values.tolist()\nbigram = gensim.models.Phrases(data_words, min_count=5, threshold=100) # higher threshold fewer phrases.\nbigram_mod = gensim.models.phrases.Phraser(bigram)\n\n\ndef make_bigrams(texts):\n return [bigram_mod[doc] for doc in texts]\n\ndef lemmatization(texts, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']):\n \"\"\"https://spacy.io/api/annotation\"\"\"\n texts_out = []\n for sent in texts:\n doc = nlp(\" \".join(sent)) \n texts_out.append([token.lemma_ for token in doc if token.pos_ in allowed_postags])\n return texts_out\n\n# Form Bigrams\ndata_words_bigrams = make_bigrams(data_words)\n\n# Initialize spacy 'en' model, keeping only tagger component (for efficiency)\nnlp = en_core_web_sm.load()\n# Do lemmatization keeping only noun, adj, vb, adv\ndata_lemmatized = lemmatization(data_words_bigrams, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV'])\n\ndata_lemmatized = lemmatization(data_words, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV'])\n\ncorpus = list(map(' '.join, data_lemmatized))\n\n#LDA - Sklearn\n\n# 1. Create the Document-Word matrix\n\n#lemmatizer = nltk.stem.WordNetLemmatizer()\n#df['lem_text'] = df['tok_text'].apply(lambda x: [lemmatizer.lemmatize(y) for y in x])\n#df['lem_text']=[\" \".join(words) for words in df['lem_text'].values]\n#corpus = df.lem_text.values.tolist()\n\n\nTOKENS_BASIC = '\\\\S+(?=\\\\s+)'\n\nvectorizer = CountVectorizer(analyzer='word', \n min_df=10, # n° mínimo de ocurrencias por palabra\n stop_words='english', # remover stop words\n token_pattern=TOKENS_BASIC)\n\ndata_vectorized = vectorizer.fit_transform(corpus)\n\nlda_model = LatentDirichletAllocation(n_components=4, # Número de tópicos\n learning_method='online',\n random_state=0, \n n_jobs = -1 # Usar todas las CPUs disponibles\n )\n\nlda_output = lda_model.fit_transform(data_vectorized)\n\n#pyLDAvis.enable_notebook()\n#panel =pyLDAvis.sklearn.prepare(lda_model, data_vectorized, vectorizer, mds='tsne')\n#pyLDAvis.show(panel)\n\n\n# Show top 20 keywords for each topic\ndef show_topics(vectorizer=vectorizer, lda_model=lda_model, n_words=20):\n keywords = np.array(vectorizer.get_feature_names())\n topic_keywords = []\n for topic_weights in lda_model.components_:\n top_keyword_locs = (-topic_weights).argsort()[:n_words]\n topic_keywords.append(keywords.take(top_keyword_locs))\n return topic_keywords\n\ntopic_keywords = show_topics(vectorizer=vectorizer, lda_model=lda_model, n_words=20) \n\n# Topic - Keywords Dataframe\ndf_topic_keywords = pd.DataFrame(topic_keywords)\ndf_topic_keywords.columns = ['Word '+str(i) for i in range(df_topic_keywords.shape[1])]\ndf_topic_keywords.index = ['Topic '+str(i) for i in range(df_topic_keywords.shape[0])]\n\n# Asignar tópico dominante a cada documento\n \n #### Document-topic matrix\n \n # column names\ntopicnames = ['Topic' + str(i) for i in range(lda_model.n_components)]\n# index names\ndocnames = [str(i) for i in range(len(df))]\n# Make the pandas dataframe\ndf_document_topic = pd.DataFrame(np.round(lda_output, 2), columns=topicnames, index=docnames)\n# Get dominant topic for each document\ndominant_topic = np.argmax(df_document_topic.values, axis=1)\n\ndf_document_topic['dominant_topic'] = dominant_topic\n#df_document_topic['x_1_topic_probability'] = dominant_topic\n\ndf_document_topic['x_1_topic_probability'] = df_document_topic.max(axis=1)\n\n#cruce con df\ndf_document_topic = df_document_topic.reset_index()\ndel df_document_topic['index']\ndf_cruce = df.filter(['eid','title','description', 'text'], axis=1)\n\n#df = pd.concat([df_cruce, df_document_topic], axis=1)\ndf = df_cruce.merge(df_document_topic, left_index=True, right_index=True)\n\ndf.to_excel('.\\\\tsunami4topicos.xlsx', index=False) \n\n\n########################\n# Reducción de dimensionalidad \n\nfrom sklearn.manifold import TSNE\ntsne_model = TSNE(n_components=2, verbose=1, random_state=7, angle=.99, init='pca')\n# 13-D -> 2-D\ntsne_lda = tsne_model.fit_transform(lda_output) # doc_topic is document-topic matrix from LDA or GuidedLDA\n\ndf_document_topic['x_tsne'] = tsne_lda[:,0]\ndf_document_topic['y_tsne'] = tsne_lda[:,1]\n\ndf_document_topic.to_excel('.\\\\document_topic_tsu.xlsx', index=False) \n\n\n########################\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"02_Analisis_texto/10_Topicos_nota_tecnica.py","file_name":"10_Topicos_nota_tecnica.py","file_ext":"py","file_size_in_byte":6119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"464547507","text":"import cv2 as cv\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom numba import jit, cuda\n# from numba import jit\nimport random\nimport math\nimport copy\n\n\ndef LoadImage(name):\n imgMat = cv.imread(name,0)\n h_img, w_img = imgMat.shape[:2]\n return w_img, h_img, imgMat\n\ndef generate_matrix(w,h):\n m = [[random.randint(0,100) for i in range(w)] for j in range(h)]\n return m\n\ndef print_matrix(m,w):\n for i in range(len(m)):\n if( i % w == 0 and i !=0):\n print(\"\\n\")\n print(\"{} \".format(m[i]), end=\"\")\n print(\"\\n\")\n\n@jit('void(float64[:,:])')\ndef NormalizeValues(array):\n minv = np.amin(array)\n maxv = np.amax(array)\n for i in range(len(array)):\n for j in range(len(array[0])):\n # print(array[i][j])\n array[i][j] = round(((array[i][j] - minv)*(255))/(maxv-minv))\n\n\n@jit('void(uint8[:,:],uint8[:,:],int64, int64, int64 ,int64,float64[:,:])')\ndef template_matching(img,tmpl,w_img,h_img,w_tmpl,h_tmpl,tmp):\n wr , hr = int(w_tmpl/2), int(h_tmpl/2)\n # sumArray = []\n for i in range(h_img):\n for j in range(w_img):\n for it in range(-hr,hr):\n # idx = 0\n for wt in range(-wr,wr):\n y, x = i + it , j + wt\n # print(\"(y,x) = ({},{})\".format(y,x))\n if((0<=y and y\n \n {2}\n
    \n \n \"\"\".format(name, _(name).capitalize(), super(DictWidget, self).render(name, value, attrs))\n\n return mark_safe(html)\n\n\nclass ColorWidget(TextInput):\n\n def render(self, name, value, attrs=None):\n html = u\"\"\"\n
    \n
    \n \n
    \n {}\n
    \n \"\"\".format(value or \"#00c0ef\", super(ColorWidget, self).render(name, value, attrs))\n\n return mark_safe(html)\n\n\nclass TagBaseForm(BaseForm):\n def clean_params(self):\n data = self.cleaned_data['params']\n try:\n data = json.loads(data)\n except ValueError:\n raise forms.ValidationError(_(u\"Must be a dict\"))\n return data\n\n\nclass TagForm(TagBaseForm):\n def __init__(self, *args, **kwargs):\n super(TagForm, self).__init__(*args, **kwargs)\n self.lab_pk = self.initial.pop('lab_pk')\n self.fields['parent'].queryset = Tag.objects.filter(lab__pk=self.lab_pk)\n if kwargs.get('instance'):\n self.fields['parent'].queryset = self.fields['parent'].queryset.exclude(\n pk__in=[child.pk for child in kwargs.get('instance').get_descendants()])\n # self.fields['params'].initial = {\"\": \"\"}\n # self.fields['params'].label = _(u'params')\n\n class Meta:\n model = Tag\n widgets = {\n 'details': Textarea(attrs={'rows': 1}),\n # 'params': DictWidget(),\n 'color': ColorWidget()\n }\n # fields = ('details', 'parent', 'color', 'params',)\n fields = ('details', 'parent', )\n\n def clean(self):\n data = super(TagBaseForm, self).clean()\n color = data.get('color')\n parent = data.get('parent')\n if not color:\n data['color'] = parent.color if parent else '#000000'\n if data.get('details') and self.lab_pk:\n # Check on unique details, lab and parent, don't work as unique_with with parent.required=false\n tags = Tag.objects.filter(details=data.get('details'), lab=self.lab_pk, parent=parent)\n if tags and (self.instance and not filter(lambda tag: tag.pk == self.instance.pk, tags)):\n self.errors['details'] = [_(u'Must be unique inside lab and parent')]\n return data\n\n\nclass TagAdminForm(TagBaseForm):\n class Meta:\n exclude = ('pk', )\n model = Tag\n","sub_path":"apps/tags/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"569730420","text":"# exploring module cImage (a Tkinter wrapper)\n# from:\n# http://www.cs.luther.edu/~pythonworks/PythonContext/cImage.py\n \nimport cImage\n \n# this actually creates a canvas ready for drawing\n#win = cImage.ImageWin(\"My Canvas\", 500, 400)\n \n# let's draw a red line on the canvas object\n# from coordinate points x1=10, y1=100 to x2=400, y2=50\n#win.create_line(10, 100, 400, 50, fill=\"red\")\n\n#win.create_oval( 50,50,200,100,fill='blue')\n\n#win.create_rectangle(0,0,250,250,fill='green')\n\ndef triangulo(p1,p2,p3, win):\n win.create_line(p1[0], p1[1],p2[0],p2[1], fill=\"red\")\n win.create_line(p2[0], p2[1],p3[0],p3[1], fill=\"red\")\n win.create_line(p3[0], p3[1],p1[0],p1[1], fill=\"red\")\ndef main():\n win=cImage.ImageWin('Janela',600,400)\n triangulo((20,30),(40,80), (30,50),win)\n win.exitOnClick()\n# needed\n#win.exitOnClick()\n\nif __name__ =='__main__':\n main()","sub_path":"visoes_2/programas/Ficha 7/programas/create_line.py","file_name":"create_line.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"500297643","text":"from selenium import webdriver\n\nwd = webdriver.Chrome(r'D:\\chromedriver.exe')\n\n# 这个页面有一个iframe,即相当于嵌入的另一个HTML,我们的许多元素在这个iframe里面,所以我们需要切换到iframe\nwd.get('http://f.python3.vip/webauto/sample2.html')\n\n# 可以通过id或者name属性,切换到iframe\nwd.switch_to.frame('frame1') # 根据id切换到iframe\n#wd.switch_to.frame('innerFrame') # 根据name切换到iframe\n#wd.switch_to.frame(wd.find_element_by_tag_name(\"iframe\")) # 也可以找到该iframe元素切换\n\n# 切换到iframe之后,就可以选取iframe里面的内容\nanimals = wd.find_elements_by_class_name('animal')\nfor animal in animals:\n print(animal.text)\n\nprint('===================== 华丽的分割线 =======================')\n\n# 通过switch_to.default_content() 切换回原来的主HTML\nwd.switch_to.default_content()\n\n# 获取主HTML里面的button,并点击\nwd.find_element_by_id('outerbutton').click()","sub_path":"4iframe切换/1.切换iframe.py","file_name":"1.切换iframe.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"319432468","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# usage: genome_length.py [-h] -di path [-do DIR_OUT] [-sd SUB_DIR]\n# [-e EXTENSION]\n# genome_length.py: error: the following arguments are required: -di/--dir_in\nimport os\nimport sys\nimport glob\nfrom time import time\nfrom termcolor import colored\nfrom collections import defaultdict\nimport argparse\nimport numpy as np\nimport pandas as pd\nfrom system_utils import make_me_a_folder\nfrom fasta_parser import parse_fasta\n\n\ndef get_genome_length(filenames):\n gen_len = defaultdict(dict)\n\n for filename in filenames:\n genus = filename.split('/')[2]\n length = 0\n for name, seq in parse_fasta(filename):\n length += len(seq)\n gen_len[genus][name] = len(seq)\n\n return gen_len\n\n\ndef get_mean_genome_lengths(data_dict):\n mean_dict = defaultdict(int, [(name, 0) for name in data_dict.keys()])\n for genus in mean_dict:\n mean_dict[genus] = int(np.array(list(data_dict[genus].values())).mean())\n return mean_dict\n\n\ndef parse_arguments():\n \"\"\"Parse the command line arguments to the genome_length script.\n Sets up the argparse command-line parser and calls it. These args can be accessed\n using args.args.\n The resulting results are csv files from each genome contained in the genus directory\n with a list of all kmers generated from these genomes (chromosomes and plasmids).\n \"\"\"\n parser = argparse.ArgumentParser(description=\"\"\"A script to count all bases and GC content\n from bacterial genomes/plasmids in the fasta files.\"\"\",\n formatter_class=argparse.RawTextHelpFormatter)\n\n parser.add_argument('-di',\n '--dir_in',\n metavar='path',\n type=str,\n required=True,\n dest='dir_in',\n help='Directory root. In my case the name is conjugated with a subdir')\n\n parser.add_argument('-do',\n '--dir_out',\n type=str,\n dest='dir_out',\n help='directory name for output files.')\n\n parser.add_argument('-sd',\n '--sub_dir',\n type=str,\n dest='sub_dir',\n help='Name for a subdirectory, ex., Chromosomes.')\n\n parser.add_argument('-e',\n '--extension',\n type=str,\n dest='extension',\n help='Name representing the type file. Ex., gz')\n return parser.parse_args()\n\n\ndef main():\n # starting count the staring time of the script\n start = time()\n # checking the current directory and printing it\n cwd = os.getcwd()\n print(colored(f'\\nThe working directory: {cwd}\\n',\n 'green',\n attrs=['bold']))\n # passing the arguments to the script\n args = parse_arguments()\n # name of the input directory, ex. Data/Genomes_splitted\n dir_in = args.dir_in\n # name of the sub directory to save the final result\n # Chromosomes/Plasmids\n sub_dir = args.sub_dir\n # name of the root directory to save the final result\n dir_out = args.dir_out\n # name of the root directory to save the final result\n extension = args.extension\n # get the fasta files\n filenames = glob.glob(f'{dir_in}/*/{sub_dir}/*.{extension}')\n print(f\"The number of files is {len(filenames)}\")\n print(f'{filenames[0]}')\n # check if the output directory exist other wise create it\n if os.path.exists(dir_out):\n print(colored('The directory to save the files already exists!',\n 'red',\n attrs=['bold']))\n pass\n else:\n make_me_a_folder(dir_out)\n data_len = get_genome_length(filenames)\n print('Calculating the genome mean')\n data = get_mean_genome_lengths(data_len)\n df = pd.DataFrame(data.items(), columns=['Name', 'Length'])\n file_name = f'All_{sub_dir}_length'\n full_path = os.path.join('Results', 'Length')\n if not os.path.exists(full_path):\n os.makedirs(full_path)\n df.to_csv(f'{full_path}/{file_name}.csv', index=False)\n # the final time\n end = time()\n # print some info\n print(colored(f\"Total number of genus/species analyzed: {len(data)}\\n.\",\n attrs=['bold']))\n print(colored(f'Total time for the script finishes: {round(end - start, 2)}.',\n 'red',\n attrs=['bold']))\n print(colored('Done!',\n 'green',\n attrs=['bold']))\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"genome_length.py","file_name":"genome_length.py","file_ext":"py","file_size_in_byte":4704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"369469017","text":"# %%\n#######################################\ndef encode_punycode(string: str):\n \"\"\"Encodes the string using Punycode.\n\n Example:\n >>> encode_punycode('hello')\\n\n b'hello-'\n\n >>> decode_punycode(b'hello-')\\n\n 'hello'\n \"\"\"\n import codecs\n\n if isinstance(string, str):\n temp_obj = string\n\n result = codecs.encode(temp_obj, \"punycode\")\n return result\n\n","sub_path":"conversion_encoding_bytes_chr_funcs/encode_punycode.py","file_name":"encode_punycode.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"502291430","text":"\"\"\"\nDiagram notification\n\nDefines class used to periodically send graph data via websocket.\nTemporary implementation.\n\"\"\"\nimport time\nfrom kujira.websocket.lib.notification_thread import NotificationThread\n\n\nclass GraphNotificationThread(NotificationThread):\n \"\"\"Stoppable thread for diagram notification via websocket\"\"\"\n\n def __init__(self, socket, room_information):\n \"\"\"\n Initialize object\n\n :param socket: instance of SocketIO class\n :param room_information: dictionary with room and event names\n \"\"\"\n NotificationThread.__init__(self, socket, room_information)\n # Temporary implementation\n self.count = 0\n\n def get_data(self):\n \"\"\"\n Collect data from Redis, and return message dictionary\n\n :returns: message dictionary\n \"\"\"\n # Temporary implementation\n time.sleep(2)\n self.count += 1\n data = {\"x\": self.count, \"y\": self.count}\n message = {\"type\": \"DATA\",\n \"name\": self.room_name,\n \"message\": \"Data chunk\",\n \"data\": data}\n return message\n\n\n def check_connection(self):\n \"\"\"\n Check connection to Redis\n\n :returns: connection status\n \"\"\"\n return True\n ","sub_path":"kujira/websocket/lib/graph_notification.py","file_name":"graph_notification.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"391358948","text":"# def input_int_value():\n# while True:\n# try:\n# value = int(input(\"Enter int value\"))\n# break\n# except:\n# print(\"Not int, try again\")\n# return value\n#\n# def get_matrix_from_console():\n# matrix = []\n# print(\"Enter number row\")\n# mrow = input_int_value()\n# print(\"Enter number collumn\")\n# ncol = input_int_value()\n# for i in range(mrow):\n# matrix.append([])\n# for j in range(ncol):\n# print(\"Enter matrix[\", i,\"][\",j,\"]=\")\n# matrix[i].append(input_int_value())\n# print(matrix)\n# return matrix\n#\n#\n# get_matrix_from_console()\n\n\na1 = []\nfor j in range(5):\n a2 = []\n i = 1\n i *= 10\n for i in range(1,3):\n a2.append(i)\n\n a1.append(a2)\nprint(a1)","sub_path":"univer/lesson03/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"518765568","text":"import logging\nimport os\nimport wget\nimport shutil\nimport copy\nimport typing\nimport tempfile\nfrom typing import Text, Optional, Dict, Any\nfrom unicodedata import normalize as nl\n\nfrom rasa.nlu.components import Component\nfrom rasa.nlu.config import RasaNLUModelConfig\nfrom rasa.nlu.classifiers.classifier import IntentClassifier\nfrom rasa.nlu.extractors.extractor import EntityExtractor\nfrom rasa.shared.nlu.training_data.training_data import TrainingData, Message\n\nfrom denver.data import DenverDataSource\nfrom denver.learners import OnenetLearner\nfrom denver.trainers.trainer import ModelTrainer\n\nfrom salebot_nlu.utils import convert_to_denver_format, check_url_exists, cnormalize\n\nif typing.TYPE_CHECKING:\n from rasa.nlu.model import Metadata\n\nlogging.getLogger('allennlp.training.util').disabled = True\nlogging.getLogger('allennlp.common.params').disabled = True\nlogging.getLogger('allennlp.training.trainer').disabled = True\nlogging.getLogger('allennlp.training.tensorboard_writer').disabled = True\nlogging.getLogger('allennlp.nn.initializers').disabled = True\nlogging.getLogger('allennlp.common.from_params').disabled = True\nlogging.getLogger('allennlp.training.checkpointer').disabled = True\nlogging.getLogger('allennlp.common.checks').disabled = True\nlogging.getLogger('allennlp.modules.token_embedders.embedding').disabled = True\nlogging.getLogger('allennlp.data.vocabulary').disabled = True\nlogging.getLogger('allennlp.training.optimizers').disabled = True\nlogging.getLogger('allennlp.data.iterators.data_iterator').disabled = True\n\nlogger = logging.getLogger(__name__)\n\nclass OneNetNLU(IntentClassifier, EntityExtractor):\n name = \"OneNetNLU\"\n\n provides = [\"intent\", \"intent_ranking\", \"entities\"]\n requires = []\n defaults = {\n \"use_pretrain\": False,\n \"model_repo\": \"http://tool.dev.ftech.ai:30001/models/onenet_nlu\",\n \"model_version\": \"latest\",\n \"rnn_type\": \"lstm\", \n \"hidden_size\": 200,\n \"bidirectional\": True, \n \"word_embedding_dim\": 50, \n \"word_pretrained_embedding\": \"vi-glove-50d\", \n \"dropout\": 0.5, \n \"char_encoder_type\": \"cnn\",\n \"char_embedding_dim\": 30,\n \"num_filters\": 128,\n \"batch_size\": 64, \n \"learning_rate\": 0.001, \n \"num_epochs\": 150\n }\n\n def __init__(self, component_config=None, learner=None) -> None:\n super(OneNetNLU, self).__init__(component_config)\n\n self.learner = learner\n self.tempdir = tempfile.mkdtemp()\n self.MODEL_FILE_NAME = f\"{__class__.__name__}.tar.gz\"\n\n @classmethod\n def load(\n cls,\n meta: Dict[Text, Any],\n model_dir: Optional[Text] = None,\n model_metadata: Optional[\"Metadata\"] = None,\n cached_component: Optional[\"Component\"] = None,\n **kwargs: Any,\n ) -> \"Component\":\n \"\"\"\n load model from file path\n \"\"\"\n file_name = meta.get(\"file\")\n\n if not file_name:\n logger.debug(\n f\"Failed to load model for {__class__.__name__}. \"\n f\"Maybe you did not provide enough training data and no model was \"\n f\"trained or the path '{os.path.abspath(model_dir)}' doesn't exist?\"\n )\n return cls(component_config=meta)\n\n model_file = os.path.join(model_dir, file_name)\n\n if os.path.exists(model_file):\n learner = OnenetLearner(mode=\"inference\", model_path=model_file)\n return cls(meta, learner)\n else:\n logger.debug(\n f\"Failed to load model for tag '{file_name}' for {__class__.__name__}. \"\n f\"Maybe you did not provide enough training data and no model was \"\n f\"trained or the path '{os.path.abspath(model_file)}' doesn't \"\n f\"exist?\"\n )\n\n return cls(meta)\n\n def train(\n self, training_data: TrainingData, cfg: RasaNLUModelConfig, **kwargs: Any\n ) -> None:\n\n if self.component_config[\"use_pretrain\"]:\n logger.debug(f\"Use pretrained model for {__class__.__name__}\")\n\n else:\n train_df = convert_to_denver_format(training_data)\n data_source = DenverDataSource.from_df(train_df=train_df,\n text_cols='text',\n intent_cols='intent',\n tag_cols='tags',\n lowercase=True)\n self.learner = OnenetLearner(\n mode='training', \n data_source=data_source, \n rnn_type=self.component_config[\"rnn_type\"], \n dropout=self.component_config[\"dropout\"], \n bidirectional=self.component_config[\"bidirectional\"], \n hidden_size=self.component_config[\"hidden_size\"], \n word_embedding_dim=self.component_config[\"word_embedding_dim\"], \n word_pretrained_embedding=self.component_config[\"word_pretrained_embedding\"],\n char_embedding_dim=self.component_config[\"char_embedding_dim\"], \n char_encoder_type=self.component_config[\"char_encoder_type\"], \n num_filters=self.component_config[\"num_filters\"])\n\n trainer = ModelTrainer(learn=self.learner)\n trainer.train(base_path=self.tempdir, \n model_file=self.MODEL_FILE_NAME, \n batch_size=self.component_config[\"batch_size\"], \n learning_rate=self.component_config[\"learning_rate\"], \n num_epochs=self.component_config[\"num_epochs\"])\n\n def process(self, message: Message, **kwargs: Any) -> None:\n \"\"\"\n predict intent & entities from a text message\n :return: rasa nlu output format\n \"\"\"\n if self.learner:\n text = message.data.get('text')\n output = {}\n if text:\n # if payload == Get started\n if 'get started' in text.lower():\n intent = {\n 'name': 'start_conversation',\n 'confidence': 1.0\n }\n message.set(\"intent\", intent, add_to_output=True)\n message.set(\"entities\", [], add_to_output=True)\n return \n\n elif check_url_exists(text):\n intent = {\n \"name\": \"inform\", \n \"confidence\": 1.0\n }\n intent_ranking = [intent]\n \n elif text.isdigit() and len(text) >= 9:\n intent = {\n \"name\": \"handoff\", \n \"confidence\": 1.0\n }\n intent_ranking = [intent]\n\n else:\n\n utterance = cnormalize(text)\n sample = copy.deepcopy(utterance)\n\n output = self.learner.process(sample=sample, lowercase=True)\n\n intent = output.get(\"intent\")\n intent_ranking = [intent]\n \n message.set(\"intent\", intent, add_to_output=True)\n message.set(\"intent_ranking\", intent_ranking, add_to_output=True)\n\n old_entities = message.data.get(\"entities\")\n entities = output.get(\"entities\", [])\n for entity in entities:\n entity.update({'extractor': 'OneNetNLU'})\n old_entities.append(entity)\n\n message.set(\"entities\", old_entities, add_to_output=True)\n\n message.set(\"text\", output.get('text', text))\n\n else:\n logger.debug(f'Have no {__class__.__name__} to process message {message.data.get(\"text\")}')\n\n def persist(self, file_name: Text, model_dir: Text) -> Optional[Dict[Text, Any]]:\n \"\"\"\n Persist this model into the passed directory.\n Returns the metadata necessary to load the model again.\n\n customize: move trained model from temp_dir to persisting location\n \"\"\"\n file_name = file_name + \".tar.gz\"\n model_file_path = os.path.join(model_dir, file_name)\n\n if self.component_config[\"use_pretrain\"]:\n self._fetch_model(model_file_path)\n else:\n temp_path = os.path.join(self.tempdir, self.MODEL_FILE_NAME)\n shutil.move(temp_path, model_file_path)\n\n return {\"file\": file_name}\n\n def _fetch_model(self, model_file):\n try:\n model_name = self.name\n model_version = self.component_config[\"model_version\"]\n model_repo = self.component_config[\"model_repo\"]\n model_download_path = model_repo + \"/\" + model_name + \"_\" + model_version + \".tar.gz\"\n\n if os.path.exists(model_file):\n os.remove(model_file)\n\n logger.info(\"Download file: %s into %s\", model_download_path, model_file)\n wget.download(model_download_path, model_file)\n\n except Exception as e:\n logger.exception(\"Download model exception: {}\".format(e))\n\n return\n","sub_path":"build/lib/salebot_nlu/joint/onenetnlu.py","file_name":"onenetnlu.py","file_ext":"py","file_size_in_byte":9236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"349988242","text":"\"\"\" Fonctions pour l'exploitation des frequences obtenues \"\"\"\nimport math\nfrom matplotlib.pyplot import *\nimport csv\nimport FFT\nimport listeOperation as lo\nimport sqlite3\n\n\n\"\"\" Fonction calculant la moyenne frequentielle ponderee par les amplitudes \ndes frequences.\nparam : spectre -> amplitudes des frequences \n freq -> frequences du spectre, rangees dans le meme ordre que les \n amplitudes\n n -> nombre de donnees dans spectre (= nb data dans freq)\n\"\"\"\n\ndef pondMoy(freq,spectre,n):\n moyf = 0\n nf = 0\n\n for i in range(n):\n moyf = moyf + spectre[i]*freq[i]\n nf = nf + spectre[i]\n moyf = moyf/nf\n return moyf\n\n\n\n\n\n\"\"\" Fonction qui renvoie l'écart-type autour de la moyenne ponderee.\nparam : freq -> frequences du spectre\n pondMoy -> la moyenne ponderee\n n -> nombre de donnees dans spectre (= nb data dans freq)\n\"\"\"\n\ndef pondVar(freq,pondMoy,n):\n sum = 0\n for i in range(n):\n sum = sum + (pondMoy - freq[i])**2\n return (((math.sqrt(sum/n))*100)//1)/100\n\n\n\n\n\n\"\"\" Fonction arrondissant un floatant à l'entier supérieur \"\"\"\n\ndef arrondirSup(x):\n reste = x%(x//1)\n if (reste == 0):\n return x\n else:\n return (x//1)+1\n\n\n\n\n\n\"\"\" Fonction calculant diverses données concernant les quartiles.\nparam : n -> nombre de frequences (=nombre d'amplitudes)\nreturn : q1 -> premier quartile\n q2 -> deuxième quartile\n q3 -> troisième quartile\n inter -> ecart interquartile\n\"\"\"\n\ndef quartiles(n):\n q1 = int(arrondirSup(n/4))\n q2 = int(arrondirSup(n/2))\n q3 = int(arrondirSup(3*n/4))\n inter = q3 - q1\n return q1, q2, q3, inter\n\n\n\n\n\n\n#print(arrDeleteDouble([2.354,2.648,78.2452,2.47,78.364,78.0],6))\n\n\n\"\"\"Fonction qui effectue le prétraitement d'un donnee z : normalisation et reduction\nparam : z -> variable a traiter\"\"\"\n\ndef pretraitement(z):\n n = len(z)\n moy = 0\n for i in range(len(z)):\n moy = moy + z[i]\n moy = moy/n\n sigma = 0\n for i in range(len(z)):\n sigma = sigma + (z[i] - moy)**2\n sigma = math.sqrt(sigma/(n-1))\n res = lo.sous(z,[moy for i in range(n)])\n res = lo.div(res,[sigma for i in range(n)])\n #On ne conserve que 5 chiffres après la virgule\n for i in range(len(res)):\n res[i] = ((res[i]*100000)//1)/100000\n return res\n\n\n\n\n\n\n\n\"\"\" Fonction calculant la répartition des fréquences dans le spectre. \nparam : spectre -> amplitudes dans le spectre\n n -> nombre de frequences \n nbParts -> nombre de sections de densites que l'on veut \nretour : f1, f2, ...,f(nbParts-1) de sorte que [qi:q(i+1)] contient 10% \ndes frequences du spectre\"\"\"\n\ndef densite(spectre,n,nbParts):\n #Calcul de la somme totale des frequences\n sumAmp = 0\n for i in range(n):\n sumAmp = sumAmp + spectre[i]\n\n #Calcul des pourcentages correspondants\n pourcentages = [sumAmp*(i/nbParts) for i in range(1,nbParts)]\n\n\n #Calcul des rangs correspondants\n rangs = []\n i = 0\n pourc = 0\n suiv = 0\n while ((i < n) & (suiv < (nbParts-1))):\n if (pourc > pourcentages[suiv]):\n i = i - 1\n rangs.append(i)\n suiv += 1\n else:\n pourc = pourc + spectre[i]\n i = i + 1\n return rangs\n\n\n\n\n\n\"\"\" Fonction traçant le spectre, avec les différentes données statistiques : \nquartiles, moyenne ponderee, variance par rapport à cette moyenne.\nparam : freq -> frequences dans le spectre \n spectre -> amplitudes des frequences \n couleur -> couleur utilisée pour tracer le spectre \n \"\"\"\ndef tracerSpectre(freq,spectre,couleur,nbParts):\n\n spectre = spectre/max(spectre)\n n = len(spectre)\n\n #Calcul de donnees statistiques\n moyf = pondMoy(freq,spectre,n)\n varf = pondVar(freq,moyf,n)\n rangs = densite(spectre,n)\n figure(figsize=(9,4))\n\n #Tracer du spectre\n vlines(freq,[0],spectre,couleur)\n #Tracer de la moyenne\n vlines([moyf],[0],[1],'lime')\n #Tracer les repartitions des densites\n vlines(rangs,[0],[1 for i in range(nbParts)],'m')\n xlabel('f (Hz)')\n ylabel('A' + \" sigma = \" + str(varf))\n #axis([0,0.5*rate,0,1])\n axis([freq[0],freq[n-1],0,1])\n show()\n return rangs\n\n\n\n\n\ndef affichageSpectres(freqMin,freqMax,nbParts):\n with open(\"/media/ray974/common-voice/cv-valid-dev.csv\", 'rt') as f:\n reader = csv.reader(f)\n nbRow = 0\n compteurH = 0\n compteurF = 0\n rangsF = [0 for i in range(nbParts-1)]\n rangsH = [0 for i in range(nbParts-1)]\n for col in reader:\n if (nbRow >= 50):\n break\n ind = \"\"\n for i in range(6-len(str(nbRow))):\n if (ind == \"\"):\n ind = \"0\"\n else:\n ind = ind + \"0\"\n if (col[5]==\"male\"):\n freq,spectre = FFT.fftFreq(\"/media/ray974/common-voice/cv-valid-dev/wav/sample-\" + ind + str(nbRow) + \".wav\", freqMin, freqMax)\n r = tracerSpectre(freq,spectre,'r',freqMax)\n rangsH = lo.add(r,rangsH)\n compteurH += 1\n elif (col[5]==\"female\"):\n freq,spectre = FFT.fftFreq(\"/media/ray974/common-voice/cv-valid-dev/wav/sample-\" + ind + str(nbRow) + \".wav\",freqMin,freqMax)\n r = tracerSpectre(freq,spectre,'b',freqMax)\n rangsF = lo.add(r,rangsF)\n compteurF += 1\n else:\n unknown = 1\n nbRow += 1\n\n #Moyenne sur les densités des amplitudes\n rangsF = lo.div(rangsF,[compteurF for i in range(len(rangsF))])\n for i in range(len(rangsF)):\n rangsF[i] = ((rangsF[i]*10)//1)/10\n rangsH = lo.div(rangsH,[compteurH for i in range(len(rangsH))])\n for i in range(len(rangsH)):\n rangsH[i] = ((rangsH[i]*10)//1)/10\n print(\"Moyennes hommes :\" + str(rangsH))\n print(\"Moyennes femmes :\" + str(rangsF))\n\n\n\"\"\" Fonction récupérant les donnees dans l'espace des observations pour la selection de variables. \nparam : chemin -> chemin vers la base de donnée depuis le répertoire de travail \"\"\"\n\ndef getDataVar(chemin):\n conn = sqlite3.connect(chemin)\n cursor = conn.cursor()\n\n Z = []\n y = []\n creation = True\n nbDesc = 0\n\n cursor.execute(\"\"\"SELECT moyenne_freq_ponderee, densites FROM male\"\"\")\n for row in cursor:\n ex = row[1].split(\"<->\")\n n = len(ex)\n for j in range(n):\n if (creation):\n Z.append([])\n nbDesc = len(ex)+1 #+1 car on a juste moyenne_freq_pronderee en plus des densites\n Z[j].append(float(ex[j]))\n if (creation):\n Z.append([])\n Z[n].append(float(row[0]))\n y.append(1)\n creation = False\n\n cursor.execute(\"\"\"SELECT moyenne_freq_ponderee, densites FROM female\"\"\")\n for row in cursor:\n ex = row[1].split(\"<->\")\n n = len(ex)\n for j in range(n):\n Z[j].append(float(ex[j]))\n Z[n].append(float(row[0]))\n y.append(-1)\n\n return y,Z, nbDesc\n\n\n#recupererData(\"bdd_dev.db\",10)\n\n\n\"\"\" Fonction récupérant les donnees dans l'espace de représentation pour l'algo de retropropagation.\nparam : chemin -> chemin vers la base de données depuis le répertoire de travail \nRemarque : **** CODE NE TENANT PAS COMPTE DU RESULTAT DE LA SELECTION DE VARIABLES **** \"\"\"\n\ndef getDataEx(chemin):\n conn = sqlite3.connect(chemin)\n cursor = conn.cursor()\n\n Z = []\n y = []\n\n cursor.execute(\"\"\"SELECT moyenne_freq_ponderee, densites FROM male\"\"\")\n for row in cursor:\n ex = row[1].split(\"<->\")\n for i in range(len(ex)):\n ex[i] = float(ex[i])\n ex.append(float(row[0]))\n #Ajout du biais\n ex = [1]@ex\n Z.append(ex)\n y.append(1)\n\n cursor.execute(\"\"\"SELECT moyenne_freq_ponderee, densites FROM female\"\"\")\n for row in cursor:\n ex = row[1].split(\"<->\")\n for i in range(len(ex)):\n ex[i] = float(ex[i])\n ex.append(float(row[0]))\n #Ajout du biais\n ex = [1]@ex\n Z.append(ex)\n y.append(-1)\n\n return y,Z, len(Z[0])\n\n\n\n\n\n\n\"\"\" Fonction qui supprime toutes les variables créées de la mémoire. \"\"\"\ndef clearall():\n all = [var for var in globals() if var[0] != \"_\"]\n for var in all:\n del globals()[var]\n\n\n\n\n\n\"\"\" Fonction qui supprime de la mémoire toutes les variables de la liste var. \"\"\"\ndef clear(var):\n for v in var:\n del v\n","sub_path":"exploitation.py","file_name":"exploitation.py","file_ext":"py","file_size_in_byte":8454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"542548923","text":"import argparse\nfrom scrap import KyoboScraper\n\ndef parse_command_line_args():\n parser = argparse.ArgumentParser(description=\"\"\"\n parse yes24 search parameters\n \"\"\")\n\n parser.add_argument('--key', type=str, required=True, help=\"\"\"\n enter the key-link you want to search for\n \"\"\")\n\n parser.add_argument('--pages', type=int, required=True, help=\"\"\"\n enter the pages of you want to search for\n \"\"\")\n\n parser.add_argument('--name', type=str, required=True, help=\"\"\"\n enter the name of you want to save for\n \"\"\")\n return vars(parser.parse_args())\n\nif __name__ == \"__main__\":\n\n search_keys = parse_command_line_args()\n\n Scraper = KyoboScraper(**search_keys)\n links = Scraper.scrap_links()\n Scraper.scrap_books(links)\n\n\n","sub_path":"Kyobo/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"264279983","text":"\n\nfrom xai.brain.wordbase.nouns._collector import _COLLECTOR\n\n#calss header\nclass _COLLECTORS(_COLLECTOR, ):\n\tdef __init__(self,): \n\t\t_COLLECTOR.__init__(self)\n\t\tself.name = \"COLLECTORS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"collector\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_collectors.py","file_name":"_collectors.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"603234025","text":"import numpy as np\r\nimport matplotlib.pyplot as plot\r\nfrom numpy.fft import fft, ifft\r\n\r\nnx = 64 # grid points / sampling points\r\ndx = 2.0*np.pi/nx # step size\r\ndt = 0.01 # time step\r\nNt = 5000; # # of time steps\r\n# grid points where function is evaluated\r\nx = np.linspace(0, 2 * np.pi - dx, nx - 1)\r\nprint(\"x = \\n\", x) \r\n\r\nnu = 0.1; # diffusivity\r\n\r\n# define the initial condition\r\ninit = np.exp(-(x-np.pi)**2)\r\n# take its FFT\r\nfftinit = fft(init)\r\n# take the iFFT of FFT of the function\r\n# ifftinit = ifft(fftinit)\r\n\r\n# construct the array of wavenumbers\r\nk1 = np.arange(0, nx/2)\r\nk2 = np.arange(-nx/2 + 1, 0)\r\nk = np.concatenate((k1, k2))\r\n# print(\"k = \\n\", k) \r\nfftsol = np.zeros(nx-1)\r\n\r\nfor n in range(0, Nt):\r\n fftsol = fftinit - nu * dt * np.multiply(k**2 , fftinit) \r\n # fftsol = fftinit - nu*(dt * k**2 * fftinit );\r\n \r\n sol = ifft(fftsol)\r\n\r\n # if(n%5 == 0):\r\n # plot.plot(x, sol.real, 'r', x, init.real, 'b')\r\n \r\n # update \r\n fftinit = fftsol\r\n\r\n \r\n \r\n\r\n\r\n\r\n# plot the initial and final solutions\r\nplot.plot(x, sol.real, 'r', x, init.real, 'b')\r\nplot.xlabel(\"domain (x)\")\r\nplot.ylabel(\"function (f(x))\")\r\nplot.title(\"Heat equation\")\r\nplot.grid(True)\r\n\r\nplot.tight_layout()\r\nplot.show()\r\n","sub_path":"test_files_fourier/heat_eq2.py","file_name":"heat_eq2.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"381342508","text":"from datetime import datetime\n\nimport discord\nfrom discord.ext import commands, tasks\n\nfrom models.db_ops import DBOperation\nfrom models.utils import guild_id, channels, roles\n\n\nclass Tasks(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n self.muted_users = []\n\n @tasks.loop(minutes=1)\n async def mute_timer(self):\n guild = self.bot.get_guild(guild_id)\n if self.muted_users and self.muted_users is not None:\n for muted_user in self.muted_users:\n if muted_user.get(\"muted\"):\n member = guild.get_member(muted_user.get(\"user_id\"))\n if datetime.now() >= muted_user.get(\"mute_end\"):\n await self.remove_mute(muted_user, guild)\n try:\n await member.send(\"Your mute has ended.\")\n except Exception as e:\n pass\n channel = guild.get_channel(channels[\"discord_staff_room\"])\n await channel.send(f\"{member.mention}'s mute has ended.\")\n else:\n self.muted_users.remove(muted_user)\n\n @mute_timer.before_loop\n async def load_mutes(self):\n db = await DBOperation.new()\n try:\n self.muted_users.extend(await db.get_mutes())\n finally:\n await db.close()\n\n async def remove_mute(self, user, guild):\n db = await DBOperation.new()\n try:\n await db.remove_mute(user.get(\"user_id\"))\n self.muted_users.remove(user)\n muted_role = guild.get_role(roles[\"muted\"])\n member = guild.get_member(user.get(\"user_id\"))\n if muted_role is not None and member is not None and muted_role in member.roles:\n await member.remove_roles(muted_role, reason=\"Mute ended\")\n finally:\n await db.close()\n\n\ndef setup(bot):\n bot.add_cog(Tasks(bot))\n","sub_path":"cogs/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"275724156","text":"import os\nimport sys\nimport requests\nimport json\nfrom bs4 import BeautifulSoup\nfrom logger import logger\nfrom datetime import datetime\nfrom tqdm import tqdm\nimport random\nimport time\n\nfrom html_anchors import (\n PLAYER_NAME_CLASS,\n GAME_FINISHED_CLASS,\n GAME_DURATION_CLASS,\n TOTAL_POINTS_CLASS,\n FOUR_PLAYERS_CLASS\n)\nfrom urls import(\n URL_GAME_REPLAY,\n URL_GAME_INFO\n)\n\nPROJ_FOLDER = os.path.dirname(os.path.abspath(__file__))\nLOGGER = logger('crawler')\nHEADERS = {'User-Agent': 'Mozilla/5.0'}\nCONFIG_PATH = PROJ_FOLDER + '/assets/config.json'\nwith open(CONFIG_PATH, 'r') as f:\n CONFIG = json.load(f)\n\n\ndef get_html_content(url: str, id: int, session) -> str:\n # returns html text form given url, game id and session\n res = session.get(\n f'{url}?id={id}',\n headers=HEADERS\n\n )\n\n return res.text\n\n\ndef get_game_replay_data(text: str) -> dict:\n # returns replay related game data like\n # moves and scores\n tag = 'parseJSON'\n labels = ('game', 'score')\n data = {}\n ix_from, ix_to = 0, 0\n\n for i in range(2):\n ix_from = text.find(tag, ix_from + 1)\n if ix_from < 0:\n return data\n ix_to = text.find(\");\", ix_from)\n json_text = text[ix_from: ix_to]\n json_text = json_text[len(tag) + 2: -1]\n data[labels[i]] = json.loads(json_text)\n\n return data\n\n\ndef get_game_info_data(text: str) -> dict:\n # returns info related game data like\n # game date, duration and points\n data = {}\n\n # getting game date\n bs = BeautifulSoup(text, \"html.parser\")\n tags = bs.find_all(attrs={'class': GAME_FINISHED_CLASS})\n try:\n data['game_date'] = tags[0].find('b').getText()\n except Exception as e:\n LOGGER.error('Exception caught: ')\n LOGGER.error(str(e))\n with open('data/error.html', 'w') as html_file:\n html_file.write(text)\n LOGGER.error('saved html file to data/error.html')\n sys.exit(1)\n # getting game winner\n winner_text = tags[1].getText().replace('\\n', '')\n # winner = winner[25:]\n # winner = winner[:winner.find(' după ')]\n data['winner_text'] = winner_text\n\n # getting game duration\n tags = bs.find_all(attrs={'class': GAME_DURATION_CLASS})\n data['game_duration'] = tags[0].find('b').getText()\n\n # getting player names\n names = []\n tags = bs.find_all(attrs={'class': PLAYER_NAME_CLASS})\n for tag in tags[1:]: # first one is logged in user\n names.append(tag.getText())\n data['players'] = names\n\n # get all players points\n points = []\n if len(names) == 4: # special case when there are 4 players\n tags = bs.find_all(attrs={'class': FOUR_PLAYERS_CLASS})\n for tag in tags:\n inner_tags = tag.find_all('b')\n for inner_tag in inner_tags:\n points.append(inner_tag.getText())\n\n else:\n tags = bs.find_all(attrs={'class': TOTAL_POINTS_CLASS})\n for tag in tags: # first one is logged in user\n points.append(tag.getText())\n points = [point.split()[0] for point in points]\n data['points'] = points\n\n return data\n\n\ndef get_game_data(id: int, session) -> dict:\n # returns information for game with id=id\n # LOGGER.info(f'getting data for game {id}')\n\n # getting data form game replay page\n html_content = get_html_content(\n URL_GAME_REPLAY,\n id,\n session\n )\n\n data = {'id': id}\n\n # getting score and moves from game replay\n data.update(get_game_replay_data(html_content))\n\n # getting data from game info page\n html_content = get_html_content(\n URL_GAME_INFO,\n id,\n session\n )\n\n data.update(get_game_info_data(html_content))\n\n # setting datetime when data was obtained\n # data['date_crawled'] = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n return data\n\n\ndef get_session(config: dict = CONFIG):\n # returns a request session object\n payload = {'action': 'login'}\n payload['login'] = config.get('login', '')\n payload['pass'] = config.get('pass', '')\n\n session = requests.Session()\n session.post(\n 'https://belot.md/action.php',\n headers=HEADERS,\n data=payload\n )\n\n return session\n\n\ndef save_batch_data(data):\n id_start = data[0]['id']\n id_end = data[-1]['id']\n filename = f\"{PROJ_FOLDER}/data/{id_start}_{id_end}.json\"\n with open(filename, 'w') as f:\n json.dump(data, f)\n LOGGER.info(f'saved data in {filename}')\n\n\ndef update_config(data):\n with open(CONFIG_PATH, 'r') as f:\n config = json.load(f)\n config.update(data)\n with open(CONFIG_PATH, 'w') as f:\n json.dump(config, f)\n\n\ndef crawl_batch(id_start: int, batch_size: int = 5) -> bool:\n # runs crawler for ids between from id_start to + batch_size\n # returns False if no data is crawled, True otherwise\n LOGGER.info(f\"crawler batch for {id_start} started\")\n data = []\n session = get_session()\n for i in tqdm(range(id_start, id_start + batch_size)):\n data.append(get_game_data(i, session))\n # a very lame imitation of user behavior\n # trying to be \"polite\" to server actually\n time.sleep(random.randint(100, 300) / 1000)\n\n # safe check\n if len(data) == 0 or 'players' not in data[0]:\n LOGGER.info(f'No data received in crawl_batch for id = {id_start}')\n return False\n\n # saving data\n save_batch_data(data)\n\n # updating last processed game id in config file\n\n update_data = {\"last_processed_game_id\": data[-1]['id']}\n update_config(update_data)\n\n return True\n\n\ndef run_crawler(n_iterations: int, batch_size: int = 1000):\n # runs crawl_batch n_iterations times\n ix = CONFIG['last_processed_game_id']\n LOGGER.info(f'starting crawler with id_start = {ix}')\n for i in range(n_iterations):\n LOGGER.info(f'running crawler iteration # {i + 1}/{n_iterations}')\n crawl_batch(ix, batch_size=batch_size)\n ix += batch_size\n # sleeping for 3-5 seconds, trying to be polite\n time.sleep(random.randint(300, 500) / 1000)\n\n LOGGER.info('crawler successfully finished')\n\n\nif __name__ == \"__main__\":\n run_crawler(200, batch_size=1000)\n","sub_path":"collect_data.py","file_name":"collect_data.py","file_ext":"py","file_size_in_byte":6197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"173228238","text":"import psycopg2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport errno\n# import pickle\n\nfrom sklearn.svm import SVR\nfrom sklearn.model_selection import ShuffleSplit\nfrom sklearn.preprocessing import MaxAbsScaler\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import mean_squared_error\n\ndef split_list(list, indexes):\n result = []\n for index in indexes:\n result.append(list[index])\n return result\n\ndef rain_type(value):\n if (value < 2.5):\n return \"fraca\"\n elif (value >= 2.5 and value <= 12.5):\n return \"moderada\"\n elif (value > 12.5 and value <= 25):\n return \"forte\"\n elif (value > 25):\n return \"muito forte\"\n\n# connect to the PostgreSQL server\nconn = psycopg2.connect(host=\"localhost\",database=\"tcc_development\", user=\"postgres\", password=\"postgres\")\n# create a cursor\ncur = conn.cursor()\n\ncur.execute('SELECT id from gauges')\ngauges_ids = [id[0] for id in cur.fetchall()]\n\nattribs = [ [\"year\",\"month\",\"day\",\"hour\",\"minute\",\"tweets\",\"related\",\"rainfall (mm/30min)\",\"precision\",\"recall\"],\n [\"hour\",\"minute\",\"tweets\",\"related\",\"rainfall (mm/30min)\",\"precision\",\"recall\"],\n [\"tweets\",\"related\",\"rainfall (mm/30min)\",\"precision\",\"recall\"],\n [\"year\",\"month\",\"day\",\"hour\",\"minute\",\"tweets\",\"related\",\"rainfall (mm/30min)\"],\n [\"hour\",\"minute\",\"tweets\",\"related\",\"rainfall (mm/30min)\"],\n [\"tweets\",\"related\",\"rainfall (mm/30min)\"]]\n\nresults_paths = [\"./SVR_cv_notn/ymdhmtrrpr/\",\n \"./SVR_cv_notn/hmtrrpr/\",\n \"./SVR_cv_notn/trrpr/\",\n \"./SVR_cv_notn/ymdhmtrr/\",\n \"./SVR_cv_notn/hmtrr/\",\n \"./SVR_cv_notn/trr/\"]\n\nfor attribs_index in range(6):\n if not os.path.exists(os.path.dirname(results_paths[attribs_index])):\n try:\n os.makedirs(os.path.dirname(results_paths[attribs_index]))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n\n rs = ShuffleSplit(n_splits=10, test_size=.1, random_state=42)\n\n with open(\"%ssvr_scores.csv\" %(results_paths[attribs_index]), \"w\") as scores_file:\n scores_file.write(\"Sensor;Split;Mean Squared Error;Accuracy;F1;Recall;Precision\\n\")\n for gauge_id in gauges_ids:\n cur.execute('SELECT * from infos_in_half_hours where gauge_id = %s', [gauge_id])\n infos_in_half_hours = cur.fetchall()\n\n if (results_paths[attribs_index] == results_paths[0]):\n X = [[int(row[2].strftime(\"%Y\")), int(row[2].strftime(\"%m\")), int(row[2].strftime(\"%d\")), int(row[2].strftime(\"%H\")), int(row[2].strftime(\"%M\")), row[3], row[4], row[5], (float(row[4])/241314.0), (float(row[4])/620.0)] for row in infos_in_half_hours[:-1]]\n elif (results_paths[attribs_index] == results_paths[1]):\n X = [[int(row[2].strftime(\"%H\")), int(row[2].strftime(\"%M\")), row[3], row[4], row[5], (float(row[4])/241314.0), (float(row[4])/620.0)] for row in infos_in_half_hours[:-1]]\n elif (results_paths[attribs_index] == results_paths[2]):\n X = [[row[3], row[4], row[5], (float(row[4])/241314.0), (float(row[4])/620.0)] for row in infos_in_half_hours[:-1]]\n elif (results_paths[attribs_index] == results_paths[3]):\n X = [[int(row[2].strftime(\"%Y\")), int(row[2].strftime(\"%m\")), int(row[2].strftime(\"%d\")), int(row[2].strftime(\"%H\")), int(row[2].strftime(\"%M\")), row[3], row[4], row[5]] for row in infos_in_half_hours[:-1]]\n elif (results_paths[attribs_index] == results_paths[4]):\n X = [[int(row[2].strftime(\"%H\")), int(row[2].strftime(\"%M\")), row[3], row[4], row[5]] for row in infos_in_half_hours[:-1]]\n elif (results_paths[attribs_index] == results_paths[5]):\n X = [[row[3], row[4], row[5]] for row in infos_in_half_hours[:-1]]\n\n Y = [measure[5] for measure in infos_in_half_hours[1:]]\n\n regr = SVR(kernel='rbf', C=10, gamma=0.001)\n\n split_index = 0\n for train_index, test_index in rs.split(X):\n X_train, X_test, y_train, y_test = split_list(X,train_index), split_list(X,test_index), split_list(Y,train_index), split_list(Y,test_index)\n\n regr.fit(X_train, y_train)\n\n y_pred = regr.predict(X_test)\n\n y_train_classified = [rain_type(measure) for measure in y_train]\n y_test_classified = [rain_type(measure) for measure in y_test]\n y_pred_classified = [rain_type(measure) for measure in y_pred]\n\n # metrics\n mse = mean_squared_error(y_test, y_pred)\n accuracy = accuracy_score(y_test_classified, y_pred_classified)\n f1 = f1_score(y_test_classified, y_pred_classified, average='micro')\n recall = recall_score(y_test_classified, y_pred_classified, average='micro')\n precision = precision_score(y_test_classified, y_pred_classified, average='micro')\n\n split_index = split_index + 1\n\n with open(\"%sgauge%s_split%s_train.csv\" %(results_paths[attribs_index], str(gauge_id), split_index), \"w\") as f:\n # print header\n for attrib in attribs[attribs_index]:\n f.write(\"%s;\" %(attrib))\n f.write(\"Next batch rainfall (mm/30min);Next batch rainfall class\\n\")\n # print data\n for i in range(len(X_train)):\n for column in range(len(X_train[i])):\n f.write(\"%s;\" %(X_train[i][column]))\n f.write(\"%s;%s\\n\" %(y_train[i], y_train_classified[i]))\n\n with open(\"%sgauge%s_split%s_test.csv\" %(results_paths[attribs_index], str(gauge_id), split_index), \"w\") as f:\n # print header\n for attrib in attribs[attribs_index]:\n f.write(\"%s;\" %(attrib))\n f.write(\"Next batch rainfall (mm/30min);Predicted next batch rainfall (mm/30min);Next batch rainfall class;Predicted next batch rainfall class\\n\")\n # print data\n for i in range(len(X_test)):\n for column in range(len(X_test[i])):\n f.write(\"%s;\" %(X_test[i][column]))\n f.write(\"%s;%s;%s;%s\\n\" %(y_test[i],y_pred[i],y_test_classified[i],y_pred_classified[i]))\n\n scores_file.write(\"%s;%s;%s;%s;%s;%s;%s\\n\" %(gauge_id, split_index, mse, accuracy, f1, recall, precision))\n\n# end connection\ncur.close()\nconn.close()\n","sub_path":"python/individual_SVR_cv_notn.py","file_name":"individual_SVR_cv_notn.py","file_ext":"py","file_size_in_byte":6797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"496864095","text":"#!/usr/bin/env python \n# encoding: utf-8 \n#@author: nick\n#@software: PyCharm\n#@file: logging_handler_2.py\n#@time: 2020/8/5 18:24\nimport logging\n\nclass LoggerHandler(logging.Logger):\n\n def __init__(self,\n name = 'root',\n level ='DEBUG',\n file =None,\n format = '%(filename)s-%(lineno)d-%(name)s-%(levelname)s-%(message)s-%(asctime)s'\n ):\n super().__init__(name)\n\n # 设置级别\n self.setLevel(level)\n\n fmt = logging.Formatter(format)\n # 初始化处理器\n if file:\n file_handler = logging.FileHandler(file)\n file_handler.setLevel(level)\n file_handler.setFormatter(fmt)\n self.addHandler(file_handler)\n\n steam_handler = logging.StreamHandler()\n\n # 设置handler级别\n steam_handler.setLevel(level)\n steam_handler.setFormatter(fmt)\n self.addHandler(steam_handler)\n\n\n\nif __name__ == '__main__':\n # yaml_data = read_yaml(config.yaml_config_path)\n # print(yaml_data)\n # logger = LoggerHandler(name=yaml_data['logger']['name'], level=yaml_data['logger']['level'],\n # file=yaml_data['logger']['file'])\n logger = LoggerHandler('')\n logger.error('hellow')\n\n","sub_path":"UiTest_SKB/Common/logging_handler.py","file_name":"logging_handler.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"114583160","text":"from src.views.base import ValidatableView\nfrom src.errors import InvalidEntityFormat\nfrom src.constants.status_codes import NOT_FOUND_CODE, OK_CODE\n\n\nclass CategoryDetailView(ValidatableView):\n def __init__(self, validator, service, serializer_cls):\n super().__init__(validator)\n self._service = service\n self._serializer_cls = serializer_cls\n\n def get(self, request, category_id):\n try:\n category = self._service.get_one(category_id)\n should_get_raw_intl_field = request.args.get('raw_intl') == '1'\n serialized_category = (\n self\n ._serializer_cls(category)\n .in_language(None if should_get_raw_intl_field else request.language)\n .serialize()\n )\n return {'data': serialized_category}, OK_CODE\n except self._service.CategoryNotFound:\n return {}, NOT_FOUND_CODE\n\n def put(self, request, category_id):\n try:\n data = request.get_json()\n self._validate(data)\n category = \\\n self._service.update(category_id, data, user=request.user)\n should_get_raw_intl_field = request.args.get('raw_intl') == '1'\n serialized_category = (\n self\n ._serializer_cls(category)\n .in_language(None if should_get_raw_intl_field else request.language)\n .serialize()\n )\n return {'data': serialized_category}, OK_CODE\n except self._service.CategoryNotFound:\n return {}, NOT_FOUND_CODE\n except self._service.CircularCategoryConnection:\n raise InvalidEntityFormat(\n {'parent_category_id': 'errors.circularConnection'}\n )\n\n def delete(self, request, category_id):\n try:\n self._service.delete(category_id)\n return {}, OK_CODE\n except self._service.CategoryNotFound:\n return {}, NOT_FOUND_CODE\n\n def head(self, request, category_id):\n try:\n self._service.get_one(category_id)\n return {}, OK_CODE\n except self._service.CategoryNotFound:\n return {}, NOT_FOUND_CODE\n","sub_path":"backend/src/views/category/detail.py","file_name":"detail.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"359630781","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\ndef waytospeak(class_names, distance,classnum=1, position=0, *args, **kwargs):\n word_class_names = {'cat': '猫', 'dog':'狗','car': '车', 'person': '人', 'motobike': '摩托车', 'bike': \"自信车\"}\n class_names = word_class_names[class_names]\n if classnum >= 3:\n classnum = 3\n word_classnum = {1: '只', 2: '个', 3: '许多'}\n classnum = word_classnum[classnum]\n if position >= 3:\n position = 3\n\n position_classnum = {0: \"前方\", -1: \"左前方\", 1: \"右前方\"}\n position = position_classnum[position]\n\n word_templete = position + str(distance) + '米' + '有' + classnum + class_names\n return word_templete.decode('utf-8')\n","sub_path":"send/speak/word_st.py","file_name":"word_st.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"189737678","text":"\"\"\"\nScript to verify the states distribution\n\"\"\"\nimport json\nimport os\nimport argparse\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport torch as th\nfrom tqdm import tqdm\nfrom multiprocessing import Pool\nfrom functools import partial\nfrom ipdb import set_trace as tt\n\n\n\nfrom state_representation.models import loadSRLModel, getSRLDim\nfrom srl_zoo.utils import loadData\nfrom srl_zoo.preprocessing.data_loader import SupervisedDataLoader, DataLoader\n\nsns.set()\n\n#os.chdir('/home/tete/Robotics-branches/robotics-rl-srl-two/logs/teacher_policies_for_evaluation/sc/OmnirobotEnv-v0/srl_combination/ppo2/19-06-19_01h10_00')\n\nBATCH_SIZE = 256\nN_WORKERS = 8\nDEVICE = th.device(\"cuda\" if th.cuda.is_available() else \"cpu\")\nVALIDATION_SIZE = 0.2 # 20% of training data for validation\n\ndef PCA(data, dim=2):\n # preprocess the data\n X = th.from_numpy(data).to(DEVICE)\n X_mean = th.mean(X,0)\n X = X - X_mean.expand_as(X)\n\n # svd\n U,S,V = th.svd(th.t(X))\n C = th.mm(X,U[:,:dim]).to('cpu').numpy()\n return C\n\ndef dataSrlLoad(data_folder, srl_model_path=None, pca_mode=True, normalized=True, threshold=0.01):\n \"\"\"\n\n :param data_folder: (str) the path to the dataset we want to sample\n :param srl_model_path: (str)\n :return: the dataset after the srl evaluation and a pca preprocessd,\n it self, a random sampled training set, validation set\n \"\"\"\n\n state_dim = getSRLDim(srl_model_path)\n srl_model = loadSRLModel(srl_model_path, th.cuda.is_available(), state_dim, env_object=None)\n\n #load images and other data\n print('Loading data for separation ')\n training_data, ground_truth, true_states, _ = loadData(data_folder, absolute_path=True)\n rewards, episode_starts = training_data['rewards'], training_data['episode_starts']\n images_path = ground_truth['images_path']\n actions = training_data['actions']\n actions_proba = training_data['actions_proba']\n ground_turht_states_dim = true_states.shape[1]\n\n\n\n # we change the path to the local path at the toolbox level\n images_path_copy = [\"srl_zoo/data/\" + images_path[k] for k in range(images_path.shape[0])]\n images_path = np.array(images_path_copy)\n\n num_samples = images_path.shape[0] # number of samples\n\n # indices for all time steps where the episode continues\n indices = np.array([i for i in range(num_samples-1) if not episode_starts[i + 1]], dtype='int64')\n\n minibatchlist = [np.array(sorted(indices[start_idx:start_idx + BATCH_SIZE]))\n for start_idx in range(0, len(indices) - BATCH_SIZE + 1, BATCH_SIZE)]\n\n data_loader = DataLoader(minibatchlist, images_path, n_workers=N_WORKERS, multi_view=False,\n use_triplets=False, is_training=True, absolute_path=True)\n\n srl_data = []\n #we only use the srl model to deduct the states\n srl_model.model = srl_model.model.eval()\n pbar = tqdm(total=len(data_loader))\n for minibatch_num, (minibatch_idx, obs, _, _, _) in enumerate(data_loader):\n obs = obs.to(DEVICE)\n state = srl_model.model.getStates(obs).to('cpu').detach().numpy()\n srl_data.append(state)\n pbar.update(1)\n\n # concatenate into one numpy array\n srl_data = np.concatenate(srl_data,axis=0)\n # PCA for the v\n if pca_mode:\n pca_srl_data = PCA(srl_data, dim=ground_turht_states_dim)\n else:\n pca_srl_data = srl_data\n if normalized: # Normilized into -0.5 to +0.5\n for k in range(pca_srl_data.shape[1]):\n pca_srl_data[:, k] = (pca_srl_data[:, k] - np.min(pca_srl_data[:, k])) / (\n np.max(pca_srl_data[:, k]) - np.min(pca_srl_data[:, k])) - 0.5\n\n training_indices = np.concatenate(minibatchlist)\n\n val_num = int(len(training_indices) * VALIDATION_SIZE)\n\n #return the index that we dont need to save anymore\n index_del = dataSelection(0.01,pca_srl_data)\n\n index_save = [i for i in range(len(index_del)) if not index_del[i]]\n\n return\n\ndef plotDistribution(pca_srl_data, val_num):\n fig, ax = plt.subplots(nrows=1, ncols=3, figsize=[24, 8])\n x_min, x_max = pca_srl_data[:, 0].min(), pca_srl_data[:, 0].max()\n y_min, y_max = pca_srl_data[:, 1].min(), pca_srl_data[:, 1].max()\n ax[0].scatter(pca_srl_data[val_num:, 0], pca_srl_data[val_num:, 1], s=5, c='b', label='Training')\n ax[0].scatter(pca_srl_data[:val_num, 0], pca_srl_data[:val_num, 1], s=5, c='r', label='Validation')\n ax[0].legend()\n ax[0].title.set_text('Sample')\n # plt.show()\n ax[1].hist2d(pca_srl_data[:val_num, 0], pca_srl_data[:val_num, 1],\n bins=100, range=[[x_min, x_max], [y_min, y_max]])\n ax[1].title.set_text('Validation distribution')\n ax[2].hist2d(pca_srl_data[val_num:, 0], pca_srl_data[val_num:, 1],\n bins=100, range=[[x_min, x_max], [y_min, y_max]])\n ax[2].title.set_text('Training distribution')\n plt.show()\n\n\ndef _del_val(p_val, train_set, threshold):\n \"\"\"\n if the points are too close to each other, we will delete it from the dataset.\n :param p_val: (np.array) the data points of validation set\n :param train_set: (np.array) the training set\n :param threshold: (float)\n :return:\n \"\"\"\n for p_train in train_set:\n if (np.linalg.norm(p_val - p_train) < threshold):\n # we will delete the data point\n return True\n else:\n return False\n\ndef dataSelection(threshold, train_set, val_set=None):\n \"\"\"\n\n :param val_set: the validation set that we want to resimpling\n :param train_set:\n :param threshold:\n :return:\n \"\"\"\n #if we dont precise the validation set, the suppression will be on the whole dataset (training set)\n if val_set == None:\n val_set = train_set\n # multiprocessing\n pool = Pool()\n # if index[i] is ture, then we will delete it from the dataset\n index_to_del = pool.map(partial(_del_val, train_set=train_set, threshold=threshold), val_set)\n\n return index_to_del\n\n\ndef loadKwargs(log_dir):\n with open(os.path.join(log_dir, 'args.json')) as data:\n rl_kwargs = json.load(data)\n with open(os.path.join(log_dir, 'env_globals.json')) as data:\n env_kwargs = json.load(data)\n return rl_kwargs, env_kwargs\n\nif __name__ == '__main__':\n\n\n parser = argparse.ArgumentParser(description=\"Train script for RL algorithms\")\n parser.add_argument('--log-dir', type=str, default='logs/teacher_policies_for_evaluation/sc/OmnirobotEnv-v0/srl_combination/ppo2/19-06-19_01h10_00')\n parser.add_argument('--data-path', type=str, default='data/test_dataset/')\n args, unknown = parser.parse_known_args()\n\n rl_kwargs, env_kwargs = loadKwargs(args.log_dir)\n srl_model_path = env_kwargs['srl_model_path']\n tt()\n #srl_model_path = 'srl_zoo/logs/test_dataset/19-06-26_23h44_20_custom_cnn_ST_DIM200_inverse_autoencoder/srl_model.pth'\n\n\n dataSrlLoad(data_folder=args.data_path, srl_model_path=srl_model_path)\n print(\"OK\")\n","sub_path":"environments/data_separator.py","file_name":"data_separator.py","file_ext":"py","file_size_in_byte":6957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"173028264","text":"import datetime\n\nfrom bag.settings import BAG_STATUS, BAG_STATUSES\nfrom bag.app_settings import BAG_TYPE_CHOICES\nfrom bag.models import Bag\nfrom bag.validators import validate_bag_seal\nfrom bag.app_settings import BAGMATRIX_FILE_UPLOAD_EXTENSIONS,\\\n BAG_TYPE_TUPLES_FOR_BAG_GUIDE, MOT_CHOICES, STATUS_CHOICES,\\\n BAG_MATRIX_EDIT_METHOD, BAG_MATRIX_BAG_TYPE_NOTATION, BAG_MATRIX_MOT_NOTATION\nfrom bag.cache import get_bag_guide_center_cache\n\nfrom deliverycenters.models import *\n\nfrom django import forms\n\nfrom django_mongokit.forms import DocumentForm\n\nfrom dvutils.widgets import DateRangePicker, MultiSelectWidget\nfrom dvutils.widgets import Html5DateInput\nfrom deliverycenters.cache import get_center_cache, get_child_centers\nfrom dvutils.utils import enforce_file_extension\n\n\nclass BagForm(DocumentForm):\n '''\n Form to create/modify instances of bag model\n '''\n\n class Meta:\n document = Bag\n exclude = ['s', 'cs', 'dd', 'inc', 'cd', 'ud', 'u', 'oc', 'cn', 'cm']\n\n\nclass BaseUpdateBagForm(BagForm):\n '''\n Form to update/modify instances of bag model\n '''\n\n gm = forms.FloatField(label='Weight (gm):', widget=forms.TextInput(attrs={\n 'style': 'width: 60px;',\n 'placeholder': 'Weight of bag in grams'}), required=False)\n vl = forms.FloatField(label='Length (cm):', widget=forms.TextInput(attrs={\n 'style': 'width: 60px;',\n 'placeholder': 'Length of bag in centimeters'}), required=False)\n vb = forms.FloatField(label='Breadth (cm):', widget=forms.TextInput(attrs={\n 'style': 'width: 60px;',\n 'placeholder': 'Breadth of bag in centimeters'}), required=False)\n vh = forms.FloatField(label='Height (cm):', widget=forms.TextInput(attrs={\n 'style': 'width: 60px;',\n 'placeholder': 'Height of bag in centimeters'}), required=False)\n\n class Meta:\n document = Bag\n fields = ['gm', 'vl', 'vb', 'vh']\n\n\nclass UpdateBagForm(BaseUpdateBagForm):\n '''\n Form to update/modify instances of bag model\n '''\n\n bs = forms.CharField(\n label='Bag Seal:', validators=[validate_bag_seal],\n widget=forms.TextInput(attrs={\n 'style': 'width: 90px;',\n 'placeholder': 'Bag Seal',\n 'autofocus': 'autofocus',}))\n\n class Meta:\n document = Bag\n fields = ['bs', 'gm', 'vl', 'vb', 'vh']\n\n\nclass BulkUpdateBagForm(UpdateBagForm):\n '''\n Form to update/modify instances of bag model\n '''\n\n bs = forms.CharField(\n label='Bag Seal:',\n widget=forms.TextInput(attrs={\n 'style': 'width: 90px;',\n 'placeholder': 'Bag Seal'}))\n\n class Meta:\n document = Bag\n fields = ['gm', 'vl', 'vb', 'vh', 'bs']\n\n\nclass UpdateBagWeightForm(BaseUpdateBagForm):\n '''\n Form to allow updating/modifying weights and dimensions of bag.\n '''\n\n def __init__(self, *args, **kwargs):\n super(UpdateBagWeightForm, self).__init__(*args, **kwargs)\n\n\nclass BagCreationForm(BagForm):\n '''\n Form to create a new bag\n '''\n\n cn = forms.ChoiceField(\n label='Destination Center', choices=((None, 'None'),), required=True)\n\n class Meta:\n document = Bag\n fields = ['cn']\n\n def __init__(self, origin, *args, **kwargs):\n super(BagCreationForm, self).__init__(*args, **kwargs)\n destinations = origin.prealert_centers()\n self.fields['cn'].choices = [(cn.pk, cn.name) for cn in destinations]\n\n\nclass CreateBagForm(forms.Form):\n '''\n Form to create a bag\n '''\n def __init__(self, *args, **kwargs):\n if kwargs.get('center', None):\n center = kwargs['center']\n kwargs.pop('center')\n else:\n center = None\n can_add_bag_type = kwargs.pop('add_bag_type', False)\n super(CreateBagForm, self).__init__(*args, **kwargs)\n self.fields['destination_center'].choices = \\\n [('', 'None')] + get_child_centers(center) + \\\n get_center_cache('unicode_bag')\n self.fields['bag_type'].choices = [('', 'None')] + \\\n BAG_TYPE_CHOICES\n self._process_permission(can_add_bag_type)\n\n def _process_permission(self, permitted):\n if not permitted:\n del self.fields['bag_type']\n\n bag_type = forms.ChoiceField(choices=[('', 'None')], required=False)\n destination_center = forms.ChoiceField(choices=[('', 'None')], required=False)\n\n\nclass EditBagForm(forms.Form):\n '''\n Form to modify bag attributes\n '''\n\n destination_center = forms.ChoiceField(choices=[('', 'None')])\n\n def __init__(self, *args, **kwargs):\n\n if kwargs.get('old_cn', None):\n old_cn = kwargs['old_cn']\n kwargs.pop('old_cn')\n else:\n old_cn = None\n oc = None\n if kwargs.get('bag_oc', None):\n bag_oc = kwargs['bag_oc']\n oc = bag_oc\n kwargs.pop('bag_oc')\n\n super(EditBagForm, self).__init__(*args, **kwargs)\n self.fields['destination_center'].choices = [\n ('', 'None')] + get_child_centers(oc) + \\\n get_center_cache('unicode_bag')\n self.fields['destination_center'].required = True\n if old_cn:\n self.fields['destination_center'].initial = old_cn\n\n\nclass SealBagForm(forms.Form):\n '''\n Form to take bag attributes on sealing bag\n '''\n\n confirm_seal = forms.BooleanField(required=False)\n seal_num = forms.CharField(label='Bag Seal Number', required=False)\n bag_weight = forms.FloatField(label='Weight', required=True)\n bag_length = forms.FloatField(label='Length (cm)', required=True)\n bag_breadth = forms.FloatField(label='Breadth (cm)', required=True)\n bag_height = forms.FloatField(label='Height (cm)', required=True)\n auto_seal = forms.BooleanField(required=False)\n # bag_v_weight = forms.FloatField(label='Vol. Weight', required=True)\n\n def cleaning(self):\n \"\"\"\n Enforce manual entry of seal_num if confirm seal is on,\n auto seal is off, and the seal_num is not specified\n \"\"\"\n\n cleaned_data = self.cleaned_data\n confirm_seal = cleaned_data.get('confirm_seal', None)\n seal_num = cleaned_data.get('seal_num', None)\n auto_seal = cleaned_data.get('auto_seal', None)\n\n if confirm_seal and not auto_seal:\n raise forms.ValidationError(\"Please specify the bag seal no.\")\n\n return cleaned_data\n\n\nclass BagSearchForm(forms.Form):\n '''\n Search Dispatches\n '''\n\n def __init__(self, *args, **kwargs):\n '''\n Initialize variable/db dependent\n '''\n\n super(BagSearchForm, self).__init__(*args, **kwargs)\n center_choices = [\n ('NSZ', 'NSZ'), ('', 'None')] + get_center_cache('unicode_name')\n status_choices = [(v, v) for v in BAG_STATUSES]\n\n #center_qs =list(DeliveryCenter.objects.all())\n self.fields['cs_ss'].choices = status_choices\n self.fields['oc'].choices = center_choices\n self.fields['cn'].choices = center_choices\n self.fields['cs_sl'].choices = center_choices\n\n\n error_css_class = 'error'\n\n\n today = datetime.datetime.today()\n earliest = today - datetime.timedelta(days=30)\n latest = today + datetime.timedelta(days=1)\n bs = forms.CharField(required=False, label=\"Bag Seal #\")\n wbn = forms.CharField(required=False, label=\"Waybills\")\n cs_ss = forms.MultipleChoiceField(\n label='Status', choices=[('', 'None'), ], required=False,\n widget=MultiSelectWidget())\n date_filter = forms.ChoiceField(\n choices=[\n ('', 'Select Date'),\n ('cs.sd', 'Last Scan Date'),\n ('_id', 'Creation Date'), ], required=False)\n date_range = forms.CharField(\n initial=today.strftime('%d/%m/%y'), required=False,\n widget=DateRangePicker(options={\n 'dateFormat': 'dd/mm/y',\n 'earliestDate': earliest.strftime('%d/%m/%y'),\n 'latestDate': latest.strftime('%d/%m/%y')}))\n oc = forms.ChoiceField(\n label='Origin Center', choices=[('', 'None')],\n required=False)\n cn = forms.ChoiceField(\n label=\"Destination Center\", choices=[('', 'None'), ], required=False)\n cs_sl = forms.ChoiceField(\n label=\"Last Scan Location\", choices=[('', 'None'), ], required=False)\n\n def clean_date_range(self):\n date_range = self.cleaned_data['date_range']\n if date_range:\n dates = date_range.split('-')\n try:\n sd = datetime.datetime.strptime(dates[0].strip(), '%d/%m/%y')\n\n # -1 will take care of single selected date\n ed = datetime.datetime.strptime(dates[-1].strip(), '%d/%m/%y')\n ed = ed + datetime.timedelta(days=1)\n except ValueError:\n raise forms.ValidationError(\"Invalid date selected\")\n return sd, ed\n\n\nclass SaveIncomingForm(forms.Form):\n '''Form to save incoming'''\n\n save_incoming = forms.BooleanField(\n label='All packages/bags that were received have been scanned',\n required=False)\n\n create_missing_ist = forms.BooleanField(\n label='Create a new IST for the missing packages',\n widget=forms.CheckboxInput(attrs={'checked': 'checked'}),\n required=False)\n\n otp = forms.CharField(required=False, label='OTP', help_text=(\n 'To proceed either scan all missing waybills or provide the OTP.'))\n\n\nclass CustodyScanForm(forms.Form):\n '''Form for custody scan '''\n bag = forms.CharField(required=True, widget=forms.TextInput(\n attrs={'placeholder': 'Enter bags',\n 'name': 'ref_ids',\n 'id': 'ref_id_input',\n 'class': 'span-12 prepend-top append-bottom',\n 'required': 'required'}))\n\n\nclass BagGuideUploadForm(forms.Form):\n \"\"\"\n Form for uploading bag matrix\n \"\"\"\n upload_file = forms.FileField(label=\"Bag guide matrix\",\n required=True, help_text=\n (\"CSV file to be processed, \"\n \"keep it < 2.5MB for best \"\n \"performance\"))\n\n def clean_upload_file(self):\n \"\"\"\n Enforce file type\n :return:\n \"\"\"\n curr_file = self.cleaned_data['upload_file']\n\n if not enforce_file_extension(curr_file.name,\n BAGMATRIX_FILE_UPLOAD_EXTENSIONS):\n raise forms.ValidationError('Invalid file format. '\n 'Can only upload file types {}'.\\\n format(' '.join(BAGMATRIX_FILE_UPLOAD_EXTENSIONS)))\n\n\nclass StateSelectionForm(forms.Form):\n \"\"\"\n Form for selecting state\n \"\"\"\n state = forms.ChoiceField(label='State', widget=forms.Select(attrs={'class': 'state'}))\n\n def __init__(self, states):\n super(StateSelectionForm, self).__init__()\n self.fields['state'].choices = states\n\n\nclass BagGuideUpdateForm(forms.Form):\n \"\"\"\n Form to update bag matrix entry\n query fields: ['bt', 'bd', 'bi', 'cn',\n 'sl', 'mot', 'pc', 'st']\n update fields: ['nbt', 'nbd', 'nbi', 'ncn',\n 'nsl', 'nmot', 'npc', 'nst']\n \"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"\n Initialize variables/fields\n \"\"\"\n sl = kwargs.pop('sl', '')\n super(BagGuideUpdateForm, self).__init__(*args, **kwargs)\n fields_choices = get_bag_guide_center_cache(sl)\n query_bd_choices = [('', 'None')] + fields_choices.get('bd')\n query_cn_choices = [('', 'None')] + fields_choices.get('cn')\n query_bag_type_choices = [('', 'None')] + fields_choices.get('bt')\n query_mot_choices = [('', 'None')] + fields_choices.get('mot')\n center_choices = [('', 'None')] + get_center_cache('code_unicode')\n bag_type_choices = [('', 'None')] + BAG_MATRIX_BAG_TYPE_NOTATION\n mot_choices = [('', 'None')] + BAG_MATRIX_MOT_NOTATION\n query_bi_choices = [('', 'None')] + fields_choices.get('bi')\n\n self.fields['bt'].choices = query_bag_type_choices\n self.fields['nbt'].choices = bag_type_choices\n self.fields['bi'].choices = query_bi_choices\n self.fields['bd'].choices = query_bd_choices\n self.fields['nbd'].choices = center_choices\n self.fields['cn'].choices = query_cn_choices\n self.fields['ncn'].choices = center_choices\n self.fields['mot'].choices = query_mot_choices\n self.fields['nmot'].choices = mot_choices\n self.fields['st'].choices = STATUS_CHOICES\n self.fields['nst'].choices = STATUS_CHOICES\n bt = forms.ChoiceField(\n label=\"Bag Type\", choices=[('', 'None')])\n nbt = forms.ChoiceField(\n label=\"New Bag Type\", choices=[('', 'None')])\n bi = forms.ChoiceField(label=\"Bag Identifier\", choices=[('', 'None'), ])\n nbi = forms.CharField(label=\"New Bag Identifier\")\n bd = forms.ChoiceField(\n label='Bag Destination', choices=[('', 'None'), ])\n nbd = forms.ChoiceField(\n label='New Bag Destination', choices=[('', 'None'), ])\n cn = forms.ChoiceField(\n label=\"Destination Center\", choices=[('', 'None'), ])\n ncn = forms.ChoiceField(\n label=\"New Destination Center\", choices=[('', 'None'), ])\n mot = forms.ChoiceField(\n label=\"MOT\", choices=[('', 'None'), ])\n nmot = forms.ChoiceField(\n label=\"New MOT\", choices=[('', 'None'), ])\n pc = forms.CharField(label=\"Product Type\", required=False)\n npc = forms.CharField(label=\"New Product Type\", required=False)\n st = forms.MultipleChoiceField(\n label='Status Type',\n widget=forms.CheckboxSelectMultiple)\n nst = forms.MultipleChoiceField(\n label='New Status Type',\n widget=forms.CheckboxSelectMultiple)\n\n\nclass BagGuideDeleteForm(forms.Form):\n \"\"\"\n Form to delete bag matrix entry\n query fields: ['bt', 'bd', 'bi', 'cn',\n 'sl', 'mot', 'pc', 'st']\n \"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"\n Initialize variables/fields\n \"\"\"\n sl = kwargs.pop('sl', '')\n super(BagGuideDeleteForm, self).__init__(*args, **kwargs)\n fields_choices = get_bag_guide_center_cache(sl)\n query_bd_choices = [('', 'None')] + fields_choices.get('bd')\n query_cn_choices = [('', 'None')] + fields_choices.get('cn')\n query_bag_type_choices = [('', 'None')] + fields_choices.get('bt')\n query_mot_choices = [('', 'None')] + fields_choices.get('mot')\n query_bi_choices = [('', 'None')] + fields_choices.get('bi')\n\n self.fields['bt'].choices = query_bag_type_choices\n self.fields['bi'].choices = query_bi_choices\n self.fields['bd'].choices = query_bd_choices\n self.fields['cn'].choices = query_cn_choices\n self.fields['mot'].choices = query_mot_choices\n self.fields['st'].choices = STATUS_CHOICES\n\n bt = forms.ChoiceField(\n label=\"Bag Type\", choices=[('', 'None')])\n bi = forms.ChoiceField(label=\"Bag Identifier\", choices=[('', 'None'), ])\n bd = forms.ChoiceField(\n label='Bag Destination', choices=[('', 'None'), ])\n cn = forms.ChoiceField(\n label=\"Destination Center\", choices=[('', 'None'), ])\n mot = forms.ChoiceField(\n label=\"MOT\", choices=[('', 'None'), ])\n pc = forms.CharField(label=\"Product Type\", required=False)\n st = forms.MultipleChoiceField(\n label='Status Type',\n widget=forms.CheckboxSelectMultiple)\n\n\nclass BagGuideEditMethod(forms.Form):\n \"\"\"\n Form to find edit method for bag matrix\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(BagGuideEditMethod, self).__init__(*args, **kwargs)\n method_choices = [('', 'None')] + BAG_MATRIX_EDIT_METHOD\n self.fields['method'].choices = method_choices\n method = forms.ChoiceField(\n label=\"Edit Method (Update/Delete)\", choices=[('', 'None'), ])\n","sub_path":"bag/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":16003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"467884394","text":"import streamlit as st\nfrom st_utils import texts\nfrom covid19 import data\n\nimport st_app_r0\nimport st_app_seir\nimport st_app_queue\n\nfrom datetime import datetime\n\nfrom covid19.regressions import spline_poisson\nimport under_report as ur\n\ndef create_basic_sidebar(): \n\n MIN_DATA_BRAZIL = '2020-03-26'\n DEFAULT_CITY = 'São Paulo/SP'\n DEFAULT_STATE = 'SP'\n MIN_CASES_TH = 10\n\n def format_local(key):\n return {\n 'state': 'Estado',\n 'city': 'Município'\n }.get(key, key)\n\n def format_date(date):\n return (datetime\n .strptime(date, \"%Y-%m-%d\")\n .strftime(\"%d/%m/%Y\"))\n @st.cache(show_spinner=False)\n def make_place_options(cases_df, population_df):\n return (cases_df\n .swaplevel(0,1, axis=1)\n ['totalCases']\n .pipe(lambda df: df >= MIN_CASES_TH)\n .any()\n .pipe(lambda s: s[s & s.index.isin(population_df.index)])\n .index)\n\n @st.cache(show_spinner=False)\n def make_date_options(cases_df, place):\n return (cases_df\n [place]\n ['totalCases']\n .pipe(lambda s: s[s >= MIN_CASES_TH])\n [MIN_DATA_BRAZIL:]\n .index\n .strftime('%Y-%m-%d'))\n\n st.sidebar.markdown(texts.INTRODUCTION_SIDEBAR)\n\n w_r0_model = st.sidebar.checkbox(texts.R0_MODEL_DESC)\n w_seir_model = st.sidebar.checkbox(texts.SEIR_MODEL_DESC)\n w_queue_model = st.sidebar.checkbox(texts.QUEUE_MODEL_DESC)\n \n st.sidebar.markdown(texts.BASE_PARAMETERS_DESCRIPTION)\n\n st.sidebar.markdown(\"**Parâmetro de UF/Município**\")\n \n w_location_granularity = st.sidebar.radio(\n \"Unidade\",\n options=(\"state\", \"city\"),\n index=1,\n format_func=format_local)\n\n cases_df = data.load_cases(w_location_granularity)\n \n\n if w_location_granularity == 'city':\n\n population_df = data.load_population(w_location_granularity)\n options_place = make_place_options(cases_df, population_df)\n\n index = options_place.get_loc(DEFAULT_CITY)\n\n w_location = st.sidebar.selectbox(\n 'Município',\n options=options_place,\n index=index)\n\n elif w_location_granularity == \"state\":\n\n population_df = data.load_population(w_location_granularity)\n options_place = make_place_options(cases_df, population_df)\n \n index = options_place.get_loc(DEFAULT_STATE)\n\n w_location = st.sidebar.selectbox(\n 'Estado',\n options=options_place,\n index=index)\n\n options_date = make_date_options(cases_df, w_location)\n w_date = st.sidebar.selectbox('Data',\n options=options_date,\n index=len(options_date)-1,\n format_func=format_date)\n\n real_cases = ur.estimate_subnotification(w_location,w_date,w_location_granularity,period=True)\n \n return {\"location_granularity\": w_location_granularity,\n \"date\": w_date,\n \"location\": w_location,\n \"cases\": cases_df,\n \"real_cases\": real_cases,\n \"population\": population_df,\n \"r0_model\": w_r0_model,\n \"seir_model\": w_seir_model,\n \"queue_model\": w_queue_model}\n\nif __name__ == '__main__':\n\n my_placeholder = st.empty()\n my_placeholder.markdown(texts.new_INTRODUCTION)\n\n base_parameters = create_basic_sidebar()\n\n if base_parameters['r0_model']:\n my_placeholder.markdown(\"\")\n\n r0_samples, place = st_app_r0.build_r0(base_parameters['date'],\n base_parameters[\"location\"],\n base_parameters[\"cases\"],\n base_parameters[\"real_cases\"])\n \n if base_parameters['seir_model']:\n my_placeholder.markdown(\"\")\n\n if not base_parameters['r0_model']:\n r0_samples, _ = st_app_r0.estimate_r0(base_parameters['date'],\n base_parameters[\"location\"],\n base_parameters[\"cases\"],\n base_parameters['real_cases'])\n \n seir_output, reported_rate = st_app_seir.build_seir(base_parameters['date'],\n base_parameters[\"location\"],\n base_parameters[\"cases\"],\n base_parameters[\"real_cases\"],\n base_parameters[\"population\"],\n base_parameters[\"location_granularity\"],\n r0_samples)\n \n if base_parameters['queue_model']:\n my_placeholder.markdown(\"\")\n\n if not base_parameters['seir_model']:\n \n r0_samples, _ = st_app_r0.estimate_r0(base_parameters['date'],\n base_parameters[\"location\"],\n base_parameters[\"cases\"],\n base_parameters['real_cases'])\n r0_dist = r0_samples[:, -1]\n seir_output, reported_rate, _ = st_app_seir.run_seir(base_parameters['date'],\n base_parameters[\"location\"],\n base_parameters[\"cases\"],\n base_parameters[\"population\"],\n base_parameters[\"location_granularity\"],\n r0_dist,\n w_params=st_app_seir.DEFAULT_PARAMS,\n sample_size=st_app_seir.SAMPLE_SIZE,\n reported_rate=None,\n NEIR0=None)\n \n st_app_queue.build_queue_simulator(base_parameters['date'],\n base_parameters[\"location\"],\n base_parameters[\"cases\"],\n base_parameters[\"location_granularity\"],\n base_parameters['real_cases'],\n seir_output,\n reported_rate)\n st.markdown(texts.DATA_SOURCES)","sub_path":"simulator/st_app.py","file_name":"st_app.py","file_ext":"py","file_size_in_byte":6916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"110055717","text":"import sys\nimport argparse\nimport subprocess\nimport multiprocessing\nfrom multiprocessing import Pool\nfrom contextlib import closing\nimport time\nimport os\n\nnproc = 3\n\nmodules = [\n\t'-m sitting_time_sensor.sitting_time_system',\n\t'bot_run.py',\n\t'scheduler_WBGT.py',\n ]\n\ndef proc(argument):\n start = time.time()\n p = subprocess.Popen(['python', argument],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n res = p.communicate()\n end = time.time()\n with open('run_HeatStroke_Sitting.log', 'w') as ofs:\n ofs.write(str(end - start))\n ofs.write('\\n' + '-'*30 + '\\n')\n ofs.write(str(res))\n return None\n\nif __name__ == '__main__':\n with closing(Pool(nproc)) as p:\n res = p.map(proc, modules)\n p.terminate()\n","sub_path":"src/run_HeatStroke_Sitting.py","file_name":"run_HeatStroke_Sitting.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"390909844","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, BatchNormalization\nfrom keras.layers import Activation, Dropout, Flatten, Dense\nfrom keras.losses import categorical_crossentropy\nfrom keras import backend as K\nfrom keras.optimizers import Adam\nfrom keras.regularizers import l2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# dimensions of our images.\nwidth, height = 182, 182\n\ntrain_data_dir = 'data/train'\nvalidation_data_dir = 'data/validation'\nnb_train_samples = 3000\nnb_validation_samples = 1200\nnum_features = 64\nepochs = 200\nbatch_size = 16\noutput_n = 10\n\nif K.image_data_format() == 'channels_first':\n input_shape = (3, width, height)\nelse:\n input_shape = (width, height, 3)\n\n#desinging the CNN\nmodel = Sequential()\n\nmodel.add(Conv2D(num_features, kernel_size=(3, 3), activation='relu', input_shape=input_shape, data_format='channels_last', kernel_regularizer=l2(0.01)))\nmodel.add(Conv2D(num_features, kernel_size=(3, 3), activation='relu', padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\nmodel.add(Dropout(0.5))\n\nmodel.add(Conv2D(2*num_features, kernel_size=(3, 3), activation='relu', padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(2*num_features, kernel_size=(3, 3), activation='relu', padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\nmodel.add(Dropout(0.5))\n\nmodel.add(Conv2D(2*2*num_features, kernel_size=(3, 3), activation='relu', padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(2*2*num_features, kernel_size=(3, 3), activation='relu', padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\nmodel.add(Dropout(0.5))\n\nmodel.add(Conv2D(2*2*2*num_features, kernel_size=(3, 3), activation='relu', padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(2*2*2*num_features, kernel_size=(3, 3), activation='relu', padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\nmodel.add(Dropout(0.5))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.4))\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.4))\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(output_n, activation='softmax'))\nmodel.summary()\nmodel.compile(loss=categorical_crossentropy,\n optimizer=Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-7),\n metrics=['accuracy'])\ntrain_datagen = ImageDataGenerator(\n rescale=1. / 255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True)\n\n# this is the augmentation configuration we will use for testing:\n# only rescaling\n\ntest_datagen = ImageDataGenerator(rescale=1. / 255)\n\ntrain_generator = train_datagen.flow_from_directory(\n train_data_dir,\n target_size=(width, height),\n batch_size=batch_size,\n class_mode='categorical',\n seed=123\n)\n\nprint(train_generator)\n\nvalidation_generator = test_datagen.flow_from_directory(\n validation_data_dir,\n target_size=(width, height),\n batch_size=batch_size,\n class_mode='categorical',\n seed=123\n)\n\nmodel.fit_generator(\n train_generator,\n steps_per_epoch=nb_train_samples // batch_size,\n epochs=epochs,\n verbose=1,\n validation_data=validation_generator,\n validation_steps=nb_validation_samples // batch_size,\n shuffle=True\n)\n\n# fig = plt.figure()\n# plt.plot(np.arange(0, epochs), H.history['loss'], label='training loss')\n# plt.plot(np.arange(0, epochs), H.history['val_loss'], label='validation loss')\n# plt.plot(np.arange(0, epochs), H.history['accuracy'], label='accuracy')\n# plt.plot(np.arange(0, epochs), H.history['val_accuracy'], label='validation accuracy')\n# plt.title('Accuracy and Loss')\n# plt.xlabel('Epoch')\n# plt.ylabel('Loss|Accuracy')\n# plt.show()\nmodel.save('model.h5')\n","sub_path":"Pretrain_model.py","file_name":"Pretrain_model.py","file_ext":"py","file_size_in_byte":4025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"241881573","text":"\nMODE_NM = 200 # default mode numbers to calculate\n\nPLOT_EIGEN_NUM = 50 # number of eigenvalues to plot\n\nTMP = 300 # temperature\n\nUnits_k_B = 1.3806513e-23 * 6.0221367e23 / 1.0e3 \n\n\n# target secondary structures (helix and β-sheet) for fluctuation plots\nTAR_SS_B = ['E'] # β-sheet, min: 2 res \nTAR_SS_H = ['G','H','I'] # helixes, min: 3 res\nTAR_SS = TAR_SS_B + TAR_SS_H\n\n\n# Correlation\nDIS_MIN = 8. # 8Å, minimum distance threshold\n\n# result dir template\nDIR_DEFAULT_NAME = 'WEBnma_analyses_results'\nDIRS_S = ('deformation',\n 'displacement',\n 'visualization',\n 'correlation',\n 'overlap')\nDIRS_C = ('profile', 'covariance')\n\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"155498748","text":"\nimport re\n\nOPT_WHITESPACE = \"[\\s]*\"\nVAL_IN_BRACKETS = \"\\([\\s]*([0-9]*)[\\s]*\\)\"\n\n\nNUMBER = \"[\\s]*([0-9]*)[\\s]*\"\nCAPT_NUMBER = NUMBER\nVAL2_IN_BRACKETS = \"\\(\" \\\n +OPT_WHITESPACE+CAPT_NUMBER+OPT_WHITESPACE+\",\"\\\n +OPT_WHITESPACE+CAPT_NUMBER +OPT_WHITESPACE\\\n +\"\\)\"+OPT_WHITESPACE+\"$\"\n\n\n\nclass Val2Wrapper(object):\n \"\"\" just allow functions to change parameter values\n \"\"\"\n def __init__(self, val1=None, val2=None):\n self._val1 = val1\n self._val2 = val2\n self._strval = None\n\n @property\n def strval(self):\n return self._strval\n\n @strval.setter\n def strval(self, val):\n self._strval = val\n\n @property\n def val1(self):\n return self._val1\n\n @val1.setter\n def val1(self, val):\n self._val1 = val\n\n @property\n def val2(self):\n return self._val2\n\n @val2.setter\n def val2(self, val):\n self._val2 = val\n\n\ndef cap_grp(s, is_optional):\n tmp = \"({})\".format(s)\n if is_optional:\n tmp += \"?\"\n return tmp\n\n\ndef pref_cap_grp(s, is_optional):\n\n if is_optional:\n tmp = \"(?:_({}))?\".format(s)\n else:\n tmp = \"_({})\".format(s)\n return tmp\n\n\ndef non_cap_grp(s, is_optional):\n tmp = \"(?:{})\".format(s)\n if is_optional:\n tmp += \"?\"\n return tmp\n\n\ndef matches_dbtype_with_1size(root_word, str_to_check, valwrapper):\n \"\"\" checks if it matches xxx(N) and retusn\n (True/False, N)\n \"\"\"\n ptrn = root_word+\"\\([\\s]*([0-9]*)[\\s]*\\)\"\n captured_groups = re.findall(ptrn,str_to_check)\n if captured_groups is not None and len(captured_groups) == 1:\n valwrapper.val1 = int(captured_groups[0])\n valwrapper.strval = root_word\n return True\n else:\n return False\n\n\ndef matches_dbtypes_with_1size(pattern_stems, str_to_check, valwrapper):\n \"\"\" checks if one of the patterns is matched xxx(N) and retusn\n (True/False, N)\n \"\"\"\n\n for pattern_stem in pattern_stems:\n if matches_dbtype_with_1size(pattern_stem, str_to_check, valwrapper):\n return True\n\n return False\n\n\n\ndef matches_dbtype_with_2size(root_word, str_to_check, val2_wrapper):\n \"\"\" checks if it matches xxx(N) and retusn\n (True/False, N)\n \"\"\"\n ptrn = root_word+VAL2_IN_BRACKETS\n captured_groups = re.findall(ptrn,str_to_check)\n if captured_groups is not None and len(captured_groups) >= 1:\n matched_vals = []\n for tmp in captured_groups:\n if isinstance(tmp,tuple):\n for t in tmp:\n matched_vals.append(t)\n else:\n matched_vals.append(tmp)\n val2_wrapper.val1 = int(matched_vals [0])\n val2_wrapper.val2= int(matched_vals[1])\n val2_wrapper.strval = root_word\n return True\n else:\n return False\n\n\ndef matches_dbtypes_with_2size(pattern_stems, str_to_check, valwrapper):\n \"\"\" checks if one of the patterns is matched xxx(N) and retusn\n (True/False, N)\n \"\"\"\n\n for pattern_stem in pattern_stems:\n if matches_dbtype_with_2size(pattern_stem, str_to_check, valwrapper):\n return True\n\n return False\n","sub_path":"slim_docs_verify/utils_regex_tiny.py","file_name":"utils_regex_tiny.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"210623555","text":"import math\n\ndef area(radius):\n '''\n (float) -> float\n\n Return circle's area\n Precondition: radius can't be negative, return zero\n\n print(area(5))\n >>> 78.54\n '''\n\n try:\n if radius >= 0:\n S = math.pi * radius ** 2\n return S\n else:\n return 0\n except TypeError:\n return 0\n\ndef sector_area_len(radius, length):\n '''\n (float, float) -> float\n\n Return area of a circle's sector using arc's length\n Precondition: radius and length can't be negative, return 0\n\n print(sector_area_len(5, 5))\n >>>12.5\n '''\n try:\n if 0 <= length <= circumference(radius) and radius >= 0:\n S = (length * radius) / 2\n return S\n else:\n return 0\n except TypeError:\n return 0\n\ndef sector_area_angle(radius, angle):\n '''\n (float, float) -> float\n\n Return area of a circle's sector using angle\n Precondition: angle can't be smaller than 0 and more than 360, return 0;\n radius can't be negative, return 0\n\n print(sector_area_angle(5, 90))\n >>>19.635\n '''\n try:\n if 0 <= angle <= 360 and radius >= 0:\n S = (area(radius) * angle) / 360\n return S\n else:\n return 0\n except TypeError:\n return 0\n\ndef circumference(radius):\n '''\n (float) -> float\n\n Return length of circle\n Precondition: radius can't be negative, return 0\n\n print(circumference(5))\n >>>31.416\n '''\n try:\n if radius >= 0:\n P = 2 * math.pi * radius\n return P\n else:\n return 0\n except TypeError:\n return 0\n\ndef volume(radius, height):\n '''\n (float, float) -> float\n\n Return cylinder's volume\n Precondition: radius and height can't be negative\n\n print(volume(5, 5))\n >>>392.699\n '''\n try:\n if radius >= 0 and height >= 0:\n V = height * area(radius)\n return V\n else:\n return 0\n except TypeError:\n return 0\n","sub_path":"circle.py","file_name":"circle.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"336449498","text":"'''\nCreated on 15-Apr-2021\n\n@author: riteshagarwal\n'''\nimport json\nimport random\nfrom threading import Thread\nimport threading\nimport time\n\nfrom sdk_client3 import SDKClient\nfrom com.couchbase.client.java.analytics import AnalyticsOptions,\\\n AnalyticsScanConsistency, AnalyticsStatus\nfrom com.couchbase.client.core.deps.io.netty.handler.timeout import TimeoutException\nfrom com.couchbase.client.core.error import RequestCanceledException,\\\n CouchbaseException\n\n\nclass DoctorCBAS():\n\n def __init__(self, cluster, bucket_util,\n num_idx=10, server_port=8095,\n querycount=100, batch_size=50):\n self.port = server_port\n self.failed_count = 0\n self.success_count = 0\n self.rejected_count = 0\n self.error_count = 0\n self.cancel_count = 0\n self.timeout_count = 0\n self.total_query_count = 0\n self.concurrent_batch_size = batch_size\n self.total_count = querycount\n self.cluster = cluster\n\n self.sdkClient = SDKClient(self.cluster.cbas_nodes, None)\n self.cluster_conn = self.sdkClient.cluster\n self.stop_run = False\n self.queries = list()\n self.num_indexes = num_idx\n i = 0\n while i < self.num_indexes:\n for bucket in self.cluster.buckets:\n for scope in bucket_util.get_active_scopes(bucket, only_names=True):\n for collection in sorted(bucket_util.get_active_collections(bucket, scope, only_names=True)):\n self.initial_idx = \"ds\"\n self.initial_idx_q = \"CREATE DATASET %s%s on `%s`.`%s`.`%s`;\" % (\n self.initial_idx, i, bucket.name,\n scope, collection)\n self.execute_statement_on_cbas_util(self.initial_idx_q)\n self.queries.append(\"select body from %s%s limit 1;\" % (self.initial_idx, i))\n i += 1\n th = threading.Thread(target=self._run_concurrent_queries,\n kwargs=dict(num_queries=self.num_indexes))\n th.start()\n\n def discharge_CBAS(self):\n self.stop_run = True\n\n def _run_concurrent_queries(self, num_queries):\n threads = []\n total_query_count = 0\n query_count = 0\n for i in range(0, num_queries):\n total_query_count += 1\n threads.append(Thread(\n target=self._run_query,\n name=\"query_thread_{0}\".format(total_query_count),\n args=(random.choice(self.queries), False, 0)))\n\n i = 0\n for thread in threads:\n i += 1\n if i % self.concurrent_batch_size == 0:\n time.sleep(5)\n thread.start()\n self.total_query_count += 1\n query_count += 1\n\n i = 0\n while not self.stop_run:\n threads = []\n new_queries_to_run = num_queries - self.total_count\n for i in range(0, new_queries_to_run):\n total_query_count += 1\n threads.append(Thread(\n target=self._run_query,\n name=\"query_thread_{0}\".format(total_query_count),\n args=(random.choice(self.queries), False, 0)))\n i = 0\n self.total_count += new_queries_to_run\n for thread in threads:\n i += 1\n thread.start()\n\n time.sleep(2)\n if self.failed_count + self.error_count != 0:\n raise Exception(\"Queries Failed:%s , Queries Error Out:%s\" %\n (self.failed_count, self.error_count))\n\n def _run_query(self, query, validate_item_count=False, expected_count=0):\n name = threading.currentThread().getName()\n client_context_id = name\n try:\n status, _, _, results, _ = self.execute_statement_on_cbas_util(\n query, client_context_id=client_context_id)\n if status == AnalyticsStatus.SUCCESS:\n if validate_item_count:\n if results[0]['$1'] != expected_count:\n self.failed_count += 1\n self.total_count -= 1\n else:\n self.success_count += 1\n self.total_count -= 1\n else:\n self.success_count += 1\n self.total_count -= 1\n else:\n self.failed_count += 1\n self.total_count -= 1\n except Exception as e:\n if e == TimeoutException:\n self.timeout_count += 1\n self.total_count -= 1\n elif e == RequestCanceledException:\n self.cancel_count += 1\n self.total_count -= 1\n elif e == CouchbaseException:\n self.rejected_count += 1\n self.total_count -= 1\n else:\n self.error_count += 1\n self.total_count -= 1\n\n def execute_statement_on_cbas_util(self, statement,\n client_context_id=None):\n \"\"\"\n Executes a statement on CBAS using the REST API using REST Client\n \"\"\"\n try:\n response = self.execute_statement_on_cbas(\n statement, False, client_context_id)\n\n if type(response) == str:\n response = json.loads(response)\n if \"errors\" in response:\n errors = response[\"errors\"]\n else:\n errors = None\n\n if \"results\" in response:\n results = response[\"results\"]\n else:\n results = None\n\n if \"handle\" in response:\n handle = response[\"handle\"]\n else:\n handle = None\n\n if \"metrics\" in response:\n metrics = response[\"metrics\"]\n else:\n metrics = None\n return response[\"status\"], metrics, errors, results, handle\n\n except Exception as e:\n raise Exception(str(e))\n\n def execute_statement_on_cbas(self, statement, readonly=False,\n client_context_id=None):\n options = AnalyticsOptions.analyticsOptions()\n options.scanConsistency(AnalyticsScanConsistency.NOT_BOUNDED)\n options.readonly(readonly)\n if client_context_id:\n options.clientContextId(client_context_id)\n\n output = {}\n try:\n result = self.cluster_conn.analyticsQuery(statement)\n\n output[\"status\"] = result.metaData().status()\n output[\"metrics\"] = result.metaData().metrics()\n\n try:\n output[\"results\"] = result.rowsAsObject()\n except:\n output[\"results\"] = None\n\n if str(output['status']) == AnalyticsStatus.FATAL:\n msg = output['errors'][0]['msg']\n if \"Job requirement\" in msg and \"exceeds capacity\" in msg:\n raise Exception(\"Capacity cannot meet job requirement\")\n elif output['status'] == AnalyticsStatus.SUCCESS:\n output[\"errors\"] = None\n else:\n raise Exception(\"Analytics Service API failed\")\n\n except TimeoutException as e:\n raise Exception(e)\n except RequestCanceledException as e:\n raise Exception(e)\n except CouchbaseException as e:\n raise Exception(e)\n return output\n\n def monitor_query_status(self, duration=0, print_duration=600):\n st_time = time.time()\n update_time = time.time()\n if duration == 0:\n while True:\n if st_time + print_duration < time.time():\n print(\"%s queries submitted, %s failed, \\\n %s passed, %s rejected, \\\n %s cancelled, %s timeout\" % (\n self.total_query_count, self.failed_count,\n self.success_count, self.rejected_count,\n self.cancel_count, self.timeout_count))\n st_time = time.time()\n else:\n while st_time + duration > time.time():\n if update_time + print_duration < time.time():\n print(\"%s queries submitted, %s failed, \\\n %s passed, %s rejected, \\\n %s cancelled, %s timeout\" % (\n self.total_query_count, self.failed_count,\n self.success_count, self.rejected_count,\n self.cancel_count, self.timeout_count))\n update_time = time.time()\n","sub_path":"pytests/aGoodDoctor/cbas.py","file_name":"cbas.py","file_ext":"py","file_size_in_byte":8719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"345947215","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom enum import Enum\n\n\nclass ManagedServiceIdentityType(str, Enum):\n\n user_assigned = \"UserAssigned\"\n\n\nclass CreatedByType(str, Enum):\n\n user = \"User\"\n application = \"Application\"\n managed_identity = \"ManagedIdentity\"\n key = \"Key\"\n\n\nclass CleanupOptions(str, Enum):\n\n always = \"Always\"\n on_success = \"OnSuccess\"\n on_expiration = \"OnExpiration\"\n\n\nclass ScriptProvisioningState(str, Enum):\n\n creating = \"Creating\"\n provisioning_resources = \"ProvisioningResources\"\n running = \"Running\"\n succeeded = \"Succeeded\"\n failed = \"Failed\"\n canceled = \"Canceled\"\n","sub_path":"sdk/resources/azure-mgmt-resource/azure/mgmt/resource/deploymentscripts/v2019_10_preview/models/_deployment_scripts_client_enums.py","file_name":"_deployment_scripts_client_enums.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"641308309","text":"from datetime import datetime\nimport pytz\n\ndef strformatdate(dateiso):\n iso = dateiso\n date = None\n try:\n date = datetime.strptime(iso[:-4], '%Y-%m-%dT%H:%M:%S.%f')\n date = pytz.utc.localize(date).astimezone(pytz.timezone(\"Asia/Tokyo\"))\n except ValueError:\n print(\"formaterror\", iso[:-4])\n\n return date\n","sub_path":"oanda_api/strformatdate.py","file_name":"strformatdate.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"272987080","text":"\"\"\"\nhttps://www.hackerrank.com/challenges/python-arithmetic-operators/\n\"\"\"\n\n\ndef arithmetic_operators(a, b):\n \"\"\"Read two integers from STDIN and print three lines where:\n\n The first line contains the sum of the two numbers.\n The second line contains the difference of the two numbers (first - second).\n The third line contains the product of the two numbers.\n :type a: int\n :type b: int\n :rtype: tuple[int, int, int]\n \"\"\"\n return a + b, a - b, a * b\n\n\nif __name__ == '__main__':\n a = int(input())\n b = int(input())\n\n print('\\n'.join(str(i) for i in arithmetic_operators(a, b)))\n","sub_path":"python-arithmetic-operators.py","file_name":"python-arithmetic-operators.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"1466801","text":"#!/usr/bin/env python3\nimport asyncio\nimport logging\nfrom typing import Literal, Optional\n\nimport discord\nfrom discord import Intents\nfrom discord.ext import commands\nfrom discord.ext.commands import Bot, Context, Greedy, check, when_mentioned_or\nfrom discord_simple_pretty_help import SimplePrettyHelp\n\nfrom config import CONFIG\nfrom utils.utils import done_react, is_compsoc_exec_in_guild, wait_react\n\nDESCRIPTION = \"\"\"\nApollo is the Discord bot for the University of Warwick Computing Society, designed to augment the server with a number of utilities and website services.\n\nApollo is open source and available at: https://github.com/UWCS/apollo. Pull requests are welcome!\n\"\"\"\n\n# The command extensions to be loaded by the bot\nEXTENSIONS = [\n \"cogs.commands.counting\",\n \"cogs.commands.chatgpt\",\n \"cogs.commands.chatgpt_custom\"\n \"cogs.commands.date\",\n \"cogs.commands.event_sync\",\n \"cogs.commands.flip\",\n \"cogs.commands.karma_admin\",\n \"cogs.commands.karma_blacklist\",\n \"cogs.commands.karma\",\n \"cogs.commands.lcalc\",\n \"cogs.commands.misc\",\n \"cogs.commands.quotes\",\n \"cogs.commands.rolemenu\",\n \"cogs.commands.reminders\",\n \"cogs.commands.announce\",\n \"cogs.commands.roll\",\n \"cogs.commands.roomsearch\",\n \"cogs.commands.say\",\n \"cogs.commands.tex\",\n \"cogs.commands.vote\",\n \"cogs.commands.widen\",\n \"cogs.channel_checker\",\n \"cogs.database\",\n \"cogs.irc\",\n \"cogs.parallelism\",\n \"cogs.welcome\",\n]\n\n\nintents = Intents.default()\nintents.members = True\nintents.message_content = True\n\nbot = Bot(\n command_prefix=when_mentioned_or(CONFIG.PREFIX),\n description=DESCRIPTION,\n intents=intents,\n help_command=SimplePrettyHelp(),\n)\n\n\n@bot.command()\n@check(is_compsoc_exec_in_guild)\nasync def reload_cogs(ctx: Context):\n for extension in EXTENSIONS:\n await bot.reload_extension(extension)\n await ctx.message.add_reaction(\"✅\")\n\n\n@bot.event\nasync def on_ready():\n logging.info(\"Logged in as\")\n logging.info(str(bot.user))\n logging.info(\"------\")\n\n\nasync def main():\n logging.basicConfig(\n level=logging.getLevelName(CONFIG.LOG_LEVEL),\n format=\"[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s\",\n handlers=[\n logging.FileHandler(\"apollo.log\"),\n logging.StreamHandler(),\n ],\n )\n\n async with bot:\n for extension in EXTENSIONS:\n try:\n logging.info(f\"Attempting to load extension {extension}\")\n await bot.load_extension(extension)\n except Exception as e:\n logging.exception(\"Failed to load extension {extension}\", exc_info=e)\n await bot.start(CONFIG.DISCORD_TOKEN)\n\n\n@bot.command()\n@commands.guild_only()\n@check(is_compsoc_exec_in_guild)\n@done_react\n@wait_react\nasync def sync(ctx: Context) -> None:\n \"\"\"\n Syncs slash commands to server\n \"\"\"\n synced = await ctx.bot.tree.sync()\n await ctx.send(f\"Synced {len(synced)} commands globally to the current guild.\")\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n","sub_path":"apollo.py","file_name":"apollo.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"446778753","text":"def init(ctx):\n print(\"[worker init]\")\n ctx.set(\"greeting\", \"Hello\")\n\n\nasync def handler(ctx, data):\n print(\"[worker handler]\")\n result = f\"{ctx.get('greeting')} {data['name']}!\"\n print(result)\n\n print(\"Saving some metrics...\")\n # Saves prediction metrics in MongoDB DB sending a message to the MongoWriter queue\n await ctx.prediction.save(date=\"2020-04-06T09:02:09.277853Z\", predicted_value=\"class_x\", true_value=\"class_y\")\n await ctx.prediction.save(error=ctx.prediction.ERR_MISSING_VALUES, date=\"2020-04-07T00:00:00.0Z\")\n await ctx.prediction.save(\n error=ctx.prediction.ERR_NEW_LABELS) # If the date is not set, the 'date' field value will be now\n\n print(\"Saving some data...\")\n # Saves data in MongoDB DB sending a message to the MongoWriter queue\n await ctx.db.save(\"test_data\", {\"random\": 123, \"dict\": {\"some\": True, \"value\": 0}})\n\n return {\"result\": result} # Must be a serializable JSON\n","sub_path":"runners/kre-py/test/myvol/src/node/node_handler.py","file_name":"node_handler.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"485613150","text":"import smtplib #simple mail transfer protocol\n\n\nfrom email.mime.multipart import MIMEMultipart##for attacjhment\n\nfrom email.mime.text import MIMEText#it covertd the attachment to string ...kuki sendmail fxn k ander only string me pass hota hai like binary form me\n\nimport random,string\nimport datetime as dt\n\ndef email(subject,mail,password,link):\n\n msg=MIMEMultipart()\n\n msg['From']= 'hospitalh525@gmail.com'\n msg['To']=mail\n msg['Subject'] = subject\n\n server =smtplib.SMTP(\"smtp.gmail.com\",587)#google server se connect krn ek lie yhi address,587 port no. mailing ka...\n #print(server)\n body = link\n\n msg.attach(MIMEText(body,\"plain\"))\n server.starttls()#it starts the transferlayer security for snnding mail\n try:\n\n server.login('hospitalh525@gmail.com','desire626')\n text = msg.as_string()\n server.sendmail(msg['From'],msg[\"To\"],text)\n print(\"email sent\")\n server.quit()\n return True\n\n except smtplib.SMTPException:\n print(\"email is not send\")\n\n return False\n\n\n\n\n\n\n\n\n\n\n","sub_path":"miscellaneous/staff_email.py","file_name":"staff_email.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"354954442","text":"\"\"\"\n253. Meeting Rooms II\n\n\nGiven an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.\n\nExample 1:\n\nInput: [[0, 30],[5, 10],[15, 20]]\nOutput: 2\nExample 2:\n\nInput: [[7,10],[2,4]]\nOutput: 1\n\n\n\"\"\"\n\n'''\n\nAlgorithm\n\nSort the given meetings by their start time.\nInitialize a new min-heap and add the first meeting's ending time to the heap. We simply need to keep track of the ending times as that tells us when a meeting room will get free.\nFor every meeting room check if the minimum element of the heap i.e. the room at the top of the heap is free or not.\nIf the room is free, then we extract the topmost element and add it back with the ending time of the current meeting we are processing.\nIf not, then we allocate a new room and add it to the heap.\nAfter processing all the meetings, the size of the heap will tell us the number of rooms allocated. This will be the minimum number of rooms needed to accommodate all the meetings.\n'''\n\n# Definition for an interval.\n# class Interval:\n# def __init__(self, s=0, e=0):\n# self.start = s\n# self.end = e\n\nclass Solution:\n def minMeetingRooms(self, intervals):\n \"\"\"\n :type intervals: List[Interval]\n :rtype: int\n \"\"\"\n if not intervals:\n return 0\n intervals. sort(key = lambda elem: elem.start)\n rooms = []\n heapq.heappush(rooms, intervals[0].end)\n for i in range(1, len(intervals)):\n if intervals[i].start >= rooms[0]:\n heapq.heappop(rooms)\n heapq.heappush(rooms, intervals[i].end)\n return len(rooms)\n\n# c++\n\n'''\n/**\n * Definition for an interval.\n * struct Interval {\n * int start;\n * int end;\n * Interval() : start(0), end(0) {}\n * Interval(int s, int e) : start(s), end(e) {}\n * };\n */\nclass Solution {\npublic:\n int minMeetingRooms(vector& intervals) {\n sort(intervals.begin(), intervals.end(), cmp);\n priority_queue, greater > rooms;\n for (auto time: intervals){\n if(!rooms.empty() && rooms.top() <= time.start) rooms.pop();\n rooms.push(time.end);\n }\n return rooms.size();\n \n }\n \n static bool cmp(Interval &a , Interval &b){\n return a.start < b.start;\n }\n};\n\n'''\n\n# 2021/02/15\n\n# Runtime: 76 ms, faster than 75.12% of Python3 online submissions for Meeting Rooms II.\n# Memory Usage: 17.4 MB, less than 67.59% of Python3 online submissions for Meeting Rooms II.\n\n\n# 最小堆的运用\n# 首先将所有的会议按照starting time 排序\n# 然后将会议的 ending time 一个一个的push到堆里面去\n# 每push一个room时,首先判断是否有available room。最小堆的堆顶是第一个available的room 的时间\n# 如果新的会议的starting time可以用堆顶的room,那么将堆顶pop出去,再push这个新的会议。相当于是\n# 重新利用了已有的room,并且更新了这个room 的available的时间\n# 如果新会议的start < 堆顶的room,那么当前没有可用的room。需要push一个新的room进入堆。\n# 最后这个堆的size就是所有需要用到的room。\n\n\nclass Solution:\n def minMeetingRooms(self, intervals: List[List[int]]) -> int:\n intervals.sort()\n heap = []\n for start, end in intervals:\n if not heap:\n heapq.heappush(heap, end)\n continue\n available = heap[0]\n if start >= available:\n heapq.heappop(heap)\n heapq.heappush(heap, end)\n return len(heap)\n\n# 2021/03/24\n# Runtime: 76 ms, faster than 73.05% of Python3 online submissions for Meeting Rooms II.\n# Memory Usage: 17.6 MB, less than 23.79% of Python3 online submissions for Meeting Rooms II.\n\n# 扫描线算法。\n# 一个会议开始时, count++; 一个会议结束时,count--; 如果两个会议开始和结束在同一时刻,可以认为会议先结束,也就是说这个room是可以用的。\n# 我们只需要知道每个时刻需要房间的数量,并不关心具体是哪个会议开始了,又是哪个会议结束了。\n\n\nclass Solution:\n def minMeetingRooms(self, intervals: List[List[int]]) -> int:\n events = [(s, 1) for s,_ in intervals] + [(e, -1) for _,e in intervals]\n events.sort()\n ans, curr = 0, 0\n for t, state in events:\n curr += state\n ans = max(ans, curr)\n return ans\n\n# 2021/03/24\n# Runtime: 76 ms, faster than 73.05% of Python3 online submissions for Meeting Rooms II.\n# Memory Usage: 17.5 MB, less than 23.79% of Python3 online submissions for Meeting Rooms II.\n\n# 最小堆的另一种解法。\n# 将时间表按照起点时间排序后。将起点依次插到堆中。\n# 插入元素时,判断这个会议的开始时间是否>=堆顶,如果是的话,就表明堆顶的room可用,将堆顶pop出去。可以通过while循环来持续这种操作,直到\n# 堆顶时间 > 当前会议的开始时间。由于是最小堆,这意味着这个目前堆中所有的房间都不可用。此时需要一个新房间才能开始这个会议,即将这个会议\n# 的结束时间插入堆中。\n# 堆的size是当前所需要的房间的总数。通过track堆的size就能够得到所需要房间的最大值。\n\nclass Solution:\n def minMeetingRooms(self, intervals: List[List[int]]) -> int:\n intervals.sort()\n heap, ans = [], 0\n for s, e in intervals:\n while heap and s >= heap[0]:\n heapq.heappop(heap)\n heapq.heappush(heap, e)\n ans = max(ans, len(heap))\n return ans","sub_path":"0253. Meeting Rooms II.py","file_name":"0253. Meeting Rooms II.py","file_ext":"py","file_size_in_byte":5707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"39016494","text":"import glob\nimport numpy as np\nimport pandas as pd\nimport re\nimport sys\n\n\ndef extract_from_nested_invocation_map(invocation_map):\n invocation_map_to_list = invocation_map.split(\"}, \")\n print(\"Found nested invocations\", len(invocation_map_to_list))\n return invocation_map_to_list\n\n\ndef get_class_name_from_invocation_string(invocation):\n class_name = re.sub(r\"(.+)(nestedInvocationDeclaringType=')(.+)(', nestedInvocationMethod.+)\", r\"\\3\", invocation)\n return class_name\n\n\ndef get_method_from_invocation_string(invocation):\n method = re.sub(r\"(.+nestedInvocationMethod=)('\\w+')(.+)\", r\"\\2\", invocation).replace(\"'\", \"\")\n return method\n\n\ndef get_parameters_from_invocation_string(invocation):\n args = re.sub(r\"(.+nestedInvocationParams='\\[)(.*)(\\]'.+)\", r\"\\2\", invocation).replace(\"\\s\", \"\")\n return args\n\n\ndef get_mode(invocation):\n mode = re.sub(r\"(.+nestedInvocationMode=)('\\w+')(.+)\", r\"\\2\", invocation).replace(\"'\", \"\")\n return mode\n\n\ndef sanitize_parameter_list(param_list):\n parameters = param_list.replace(\"(\", \"\").replace(\")\", \"\")\n parameters = re.sub(r\"([a-zA-Z0-9\\$\\.\\[\\]]+)\", \"\\\"\" + r\"\\1\" + \"\\\"\", parameters)\n parameters = re.sub(\"\\\"[EKNTV]\\\"\", \"\\\"java.lang.Object\\\"\", parameters)\n parameters = re.sub(\"\\\"[EKNTV]\\[\\]\\\"\", \"\\\"java.lang.Object[]\\\"\", parameters)\n return parameters\n\n\n# Generate aspect classes based on the CounterAspect0Nested0 template\ndef generate_mock_aspect_class(template_file_path, new_file_path, count, nested_count, nested_invocation,\n invocation_on_library_method):\n print(\"Generating aspect class\", new_file_path)\n class_name = get_class_name_from_invocation_string(nested_invocation)\n method_name = get_method_from_invocation_string(nested_invocation)\n param_list = get_parameters_from_invocation_string(nested_invocation)\n with open(template_file_path) as template:\n with open(new_file_path, \"w\") as f:\n for line in template:\n if (\"public class CounterAspect0Nested0\" in line):\n line = line.replace(\"Aspect0\", \"Aspect\" + str(count))\n line = line.replace(\"Nested0\", \"Nested\" + str(nested_count))\n if (\"@Pointcut(className =\" in line):\n line = re.sub(r\"=\\s\\\"(.+)\\\",\", \"= \\\"\" + class_name + \"\\\",\", line)\n if (\"methodName = \" in line):\n line = re.sub(r\"=\\s\\\"(.+)\\\",\", \"= \\\"\" + method_name + \"\\\",\", line)\n if (\"methodParameterTypes = \" in line):\n if (param_list == \"()\"):\n param_list = \"\"\n else:\n param_list = sanitize_parameter_list(param_list)\n line = re.sub(r\"=\\s{.*},\", \"= {\" + param_list + \"},\", line)\n if (\"timerName = \" in line):\n line = re.sub(r\"=\\s\\\".+\\\"\\)\", \"= \\\"\" + class_name + \"-\" + method_name + \"\\\")\", line)\n if (\"double COUNT = \" in line):\n line = re.sub(r\"=\\s\\d+;\", \"= \" + str(count) + \".\" + str(nested_count) + \";\", line)\n if (\"CounterAspect0.TargetMethodAdvice\" in line):\n line = line.replace(\"CounterAspect0\", \"CounterAspect\" + str(count))\n if (invocation_on_library_method and \"boolean invocationOnLibraryMethod\" in line):\n line = line.replace(\"false\", \"true\")\n f.write(line)\n\n\n# Generate aspect classes based on the CounterAspect0 template\ndef generate_aspect_class(template_file_path, new_file_path, count, row, df):\n print(\"Generating aspect class\", new_file_path)\n with open(template_file_path) as template:\n with open(new_file_path, \"w\") as f:\n for line in template:\n if (\"public class CounterAspect0\" in line):\n line = line.replace(\"0\", str(count))\n if (\"@Pointcut(className =\" in line):\n line = re.sub(r\"=\\s\\\"(.+)\\\",\", \"= \\\"\" + row['parent-FQN'] + \"\\\",\", line)\n if (\"methodName = \" in line):\n line = re.sub(r\"=\\s\\\"(.+)\\\",\", \"= \\\"\" + row['method-name'] + \"\\\",\", line)\n if (\"String rowInCSVFile\" in line):\n values = []\n for col in df.columns:\n col_value = str(row[col])\n if \",\" in col_value:\n col_value = \"\\\\\\\"\" + col_value.replace(\" \", \"\") + \"\\\\\\\"\"\n values.append(col_value)\n row_as_string = ','.join(values)\n line = re.sub(r\"\\\"\\\"\", \"\\\"\" + row_as_string + \"\\\"\", line)\n # Changes needed for void methods\n if row['return-type'] == \"void\":\n if \"boolean isReturnTypeVoid\" in line:\n line = line.replace(\"false\", \"true\")\n # if \"@OnReturn\" in line:\n if \"onReturn(@BindReturn Object returnedObject,\" in line:\n line = line.replace(\"@BindReturn Object returnedObject\", \"@BindReceiver Object receivingObjectPost\")\n if \"writeObjectXMLToFile(returnedObject, returnedObjectFilePath)\" in line:\n line = line.replace(\"returnedObject\", \"receivingObjectPost\")\n # if method has mockable invocations\n if row['has-mockable-invocations']:\n if \"boolean hasMockableInvocations\" in line:\n line = line.replace(\"false\", \"true\")\n if (\"methodParameterTypes = \" in line):\n if (pd.isnull(row['param-list'])):\n param_list = \"\"\n else:\n param_list = sanitize_parameter_list(row['param-list'])\n line = re.sub(r\"=\\s{.*},\", \"= {\" + param_list + \"},\", line)\n if (\"timerName = \" in line):\n line = re.sub(r\"=\\s\\\".+\\\"\\)\", \"= \\\"\" + row['parent-FQN'] + \"-\" + row['method-name'] + \"\\\")\", line)\n if (\"int COUNT = \" in line):\n line = re.sub(r\"=\\s\\d+;\", \"= \" + str(count) + \";\", line)\n f.write(line)\n\n\n# Generate aspect classes\ndef generate_aspects(df, cut):\n base_path = \"./src/main/java/se/kth/castor/pankti/instrument/plugins/CounterAspect\"\n found_aspects = sorted(glob.glob(base_path + \"*.java\"), key=lambda x: float(re.findall(\"(\\d+)\", x)[0]))\n original_count = int(re.search(r\"(\\d+)\", found_aspects[-1]).group())\n count = original_count\n aspects = []\n template_file_path = base_path + str(0) + \".java\"\n mock_template_file_path = base_path + \"0Nested0.java\"\n df.replace(np.nan, '', regex=True, inplace=True)\n for index, row in df.iterrows():\n # temporarily, instrument classes with mockable invocations\n # if row['visibility'] == \"public\":\n if row['has-mockable-invocations'] and (row['parent-FQN'] == cut if cut else True):\n count += 1\n aspects.append(str(count))\n new_file_path = base_path + str(count) + \".java\"\n if (row['param-list'].startswith('[') and row['param-list'].endswith(']')):\n row['param-list'] = re.sub(r\"^\\[\", \"\", row['param-list'])\n row['param-list'] = re.sub(r\"\\]$\", \"\", row['param-list'])\n generate_aspect_class(template_file_path, new_file_path, count, row, df)\n if (row['has-mockable-invocations']):\n nested_invocations = extract_from_nested_invocation_map(row['nested-invocations'])\n for i in range(len(nested_invocations)):\n invocation_on_library_method = get_mode(nested_invocations[i]) == 'LIBRARY'\n nested_count = i + 1\n new_file_path = base_path + str(count) + \"Nested\" + str(nested_count) + \".java\"\n aspects.append(str(count) + \".\" + str(nested_count))\n generate_mock_aspect_class(mock_template_file_path, new_file_path, count, nested_count,\n nested_invocations[i],\n invocation_on_library_method)\n if (original_count == count):\n print(\"No new aspect classes added in se.kth.castor.pankti.instrument.plugins - \"\n \"You may want to check the CUT again. Escape $ signs in the CUT name with a \\\\\")\n else:\n print(f'{count - original_count} new aspect classes added in se.kth.castor.pankti.instrument.plugins')\n return aspects\n\n\n# Update Glowroot plugin\ndef update_glowroot_plugin_json(aspects):\n aspect_path = \"se.kth.castor.pankti.instrument.plugins.CounterAspect\"\n plugin_json_path = \"./src/main/resources/META-INF/glowroot.plugin.json\"\n index = 0\n aspect_lines = \"\"\n has_existing_aspects = False\n last_existing_aspect = \"\"\n for i in range(len(aspects)):\n whole = re.sub(r\"(\\d+)(\\.*)(\\d*)\", r\"\\1\", str(aspects[i]))\n frac = re.sub(r\"(\\d+)(\\.*)(\\d*)\", r\"\\3\", str(aspects[i]))\n if frac == '':\n aspect_lines += \" \\\"\" + aspect_path + whole + \"\\\"\"\n else:\n aspect_lines += \" \\\"\" + aspect_path + whole + \"Nested\" + frac + \"\\\"\"\n if i < len(aspects) - 1:\n aspect_lines += \",\"\n aspect_lines += \"\\n\"\n with open(plugin_json_path, \"r+\") as json_file:\n for num, line in enumerate(json_file, 1):\n if \"aspects\" in line:\n index = num\n if re.search(r\"CounterAspect.+\\\"[^,]\", line):\n index = num - 1\n has_existing_aspects = True\n last_existing_aspect = line\n if has_existing_aspects:\n with open(plugin_json_path, \"r+\") as json_file:\n contents = json_file.readlines()\n json_file.seek(0)\n for line in contents:\n if line != last_existing_aspect:\n json_file.write(line)\n json_file.truncate()\n with open(plugin_json_path, \"r+\") as json_file:\n contents = json_file.readlines()\n if has_existing_aspects:\n aspect_lines = last_existing_aspect.replace(\"\\n\", \",\\n\") + aspect_lines\n contents.insert(index, aspect_lines)\n json_file.seek(0)\n json_file.writelines(contents)\n print(\"resources/META-INF/glowroot.plugin.json updated\")\n\n\ndef main(argv):\n try:\n cut = \"\"\n if len(argv) == 3:\n cut = argv[2]\n print(\"Attempting to generate aspects for target methods within\", cut)\n elif len(argv) == 2:\n print(\"CUT not provided, will generate aspects for all target methods\")\n df = pd.read_csv(argv[1])\n print(\"input (rows, columns): \", df.shape)\n aspects = generate_aspects(df, cut)\n if (len(aspects) > 0):\n update_glowroot_plugin_json(aspects)\n except Exception as e:\n print(\n \"USAGE: python instrument-mock.py .csv \")\n print(e)\n sys.exit()\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"pankti-instrument/counter.py","file_name":"counter.py","file_ext":"py","file_size_in_byte":9986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"499738553","text":"# -*- coding: utf-8 -*-\r\nfrom collections import Counter\r\nimport numpy as np\r\n\r\nn, k = list(map(int,input().split()))\r\ntable = np.zeros((2*k,2*k),dtype='int32')\r\nfor i in range(n):\r\n t = input().split()\r\n if(t[2]=='B'):\r\n table[int(t[0])%(2*k)][int(t[1])%(2*k)] += 1\r\n else:\r\n table[(int(t[0])+k)%(2*k)][int(t[1])%(2*k)] += 1\r\n \r\n#print(table)\r\n\r\nn_table = np.zeros((3*k+1,3*k+1),dtype='int32')\r\nn_table[1:2*k+1,1:2*k+1] = table\r\nn_table[2*k+1:3*k+1,1:2*k+1] = table[0:k,0:2*k]\r\nn_table[1:2*k+1,2*k+1:3*k+1] = table[0:2*k,0:k]\r\nn_table[2*k+1:3*k+1,2*k+1:3*k+1] = table[0:k,0:k]\r\n\r\nprint(n_table)\r\ni_table = np.zeros((3*k+1,3*k+1),dtype='int32')\r\n\r\nfor i in range(0,3*k+1):\r\n for j in range(1,3*k+1):\r\n i_table[i][j] += i_table[i][j-1] + n_table[i][j] \r\nfor i in range(1,3*k+1):\r\n for j in range(0,3*k+1):\r\n i_table[i][j] += i_table[i-1][j] \r\n\r\nprint(i_table)\r\nans = 0\r\nfor i in range(0,k):\r\n for j in range(0,k): \r\n hope1 = i_table[i+k][j+k] - i_table[i+k][j] - i_table[i][j+k] + i_table[i][j]\r\n hope2 = i_table[i+2*k][j+2*k] - i_table[i+2*k][j+k] - i_table[i+k][j+2*k] + i_table[i+k][j+k]\r\n ans = max(ans,hope1+hope2)\r\nprint(ans)","sub_path":"RegularContest/089D.py","file_name":"089D.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"277826013","text":"import random\nimport numpy as np\n\n\nclass Chromozom:\n MAX = 44\n\n def __init__(self, num_of_genes, empty):\n self.__genes = []\n self.__fitnes = 0\n if empty:\n return\n for i in range(0, num_of_genes): # creating unique genes in chromosome\n value = random.randint(1, self.MAX)\n while self.__genes.__contains__(value):\n value = random.randint(1, self.MAX)\n self.__genes.append(value)\n\n def get_genes(self):\n return self.__genes\n\n def set_fitnes(self, fitnes):\n self.__fitnes = fitnes\n\n def get_fitnes(self):\n return self.__fitnes\n\n def set_gene(self, i, value): # function, which replaces genes on position i\n self.__genes[i] = value\n\n def add_gene(self, value): # adding gene to the end of chromosome\n self.__genes.append(value)\n\n\nclass Population:\n def __init__(self, size_of_population, empty):\n self.__Chromozoms = []\n if empty:\n return\n for i in range(0, size_of_population):\n self.__Chromozoms.append([])\n self.__Chromozoms[i].append(Chromozom(14, False))\n\n def get_chromozoms(self):\n return self.__Chromozoms\n\n def add_chroms(self, c): # adding new chromosome to the population\n self.__Chromozoms.append([])\n self.__Chromozoms[self.__Chromozoms.__len__() - 1].append(c)\n\n\nclass Garden:\n def __init__(self, size_y, size_x): # creates garden defined in task\n self.out_of_matrix = True\n self.fitnes = 0\n self.step = 1\n self.matrix = np.zeros([size_y + 2, size_x + 2], dtype=int)\n # creates matrix with numbered starting positions of monk\n tmp = 0\n for i in range(1, size_y + 1):\n self.matrix[i][0] = i\n tmp = i\n tmp += 1\n for i in range(1, size_x + 1):\n self.matrix[size_y + 1][i] = tmp\n tmp += 1\n i = size_y\n while i >= 1:\n self.matrix[i][size_x + 1] = tmp\n tmp += 1\n i -= 1\n i = size_x\n while i >= 1:\n self.matrix[0][i] = tmp\n tmp += 1\n i -= 1\n\n # adding stones (obstacles)\n self.matrix[3][2] = -1\n self.matrix[5][3] = -1\n self.matrix[4][5] = -1\n self.matrix[2][6] = -1\n self.matrix[7][9] = -1\n self.matrix[7][10] = -1\n\n def test_it(self, chrom): # testing chromosome for solution\n genes = chrom.get_genes()\n for g in genes:\n if g < 11: # monk starts at the left side, can move only to the right\n if self.matrix[g + 1][1] != 0:\n continue\n if not self.right(g, 0):\n break\n elif g < 23: # monk starts at the bottom, can move only up\n if self.matrix[10][g - 10] != 0:\n continue\n if not self.up(11, g - 10):\n break\n elif g < 33: # monk starts at the right side, can move only to the left\n if self.matrix[33 - g][12] != 0:\n continue\n if not self.left(33 - g, 13):\n break\n elif g < 45: # monk starts at the top, can move only down\n if self.matrix[1][45 - g] != 0:\n continue\n if not self.down(0, 45 - g):\n break\n if self.out_of_matrix or self.fitnes != 114: # solution is correct only if monk doesn`t stand in the garden\n chrom.set_fitnes(self.fitnes)\n else:\n chrom.set_fitnes(self.fitnes - 1)\n\n def right(self, start_y, start_x): # movement to the right\n # print str(self.step) + \" right\"\n error = True\n for i in range(start_x + 1, 13):\n if self.matrix[start_y][i] == 0:\n self.out_of_matrix = False # monk steps to the garden\n self.fitnes += 1\n self.matrix[start_y][i] = self.step\n if i == 12:\n self.step += 1\n self.out_of_matrix = True # monk steps out of the garden\n error = False\n break\n else: # monk finds obstacle\n if self.matrix[start_y - 1][i - 1] == 0: # first checks upper side\n error = not self.up(start_y, i - 1)\n else:\n if self.matrix[start_y + 1, i - 1] == 0: # then checks bottom side\n error = not self.down(start_y, i - 1)\n else:\n if i == 13: # end of garden\n error = False\n self.fitnes += 1\n self.out_of_matrix = True\n break\n return not error\n\n def left(self, start_y, start_x): # movement to the left\n # print str(self.step) + \" left\"\n error = True\n for i in range(start_x - 1, 0, -1):\n if self.matrix[start_y][i] == 0:\n self.out_of_matrix = False # monk steps to the garden\n self.fitnes += 1\n self.matrix[start_y][i] = self.step\n if i == 1:\n self.step += 1\n self.out_of_matrix = True # monk steps out of the garden\n error = False\n break\n else: # monk finds obstacle\n if self.matrix[start_y - 1][i + 1] == 0: # first checks upper side\n error = not self.up(start_y, i + 1)\n else:\n if self.matrix[start_y + 1][i + 1] == 0: # then checks bottom side\n error = not self.down(start_y, i + 1)\n else:\n if i == 0: # end of garden\n error = False\n self.fitnes += 1\n self.out_of_matrix = True\n break\n return not error\n\n def up(self, start_y, start_x):\n # print str(self.step) + \" up\"\n error = True\n for i in range(start_y - 1, 0, -1):\n if self.matrix[i][start_x] == 0:\n self.out_of_matrix = False # monk steps to the garden\n self.fitnes += 1\n self.matrix[i][start_x] = self.step\n if i == 1:\n self.step += 1\n self.out_of_matrix = True # monk steps out of the garden\n error = False\n break\n else:\n if self.matrix[i + 1][start_x + 1] == 0:\n error = not self.right(i + 1, start_x)\n else:\n if self.matrix[i + 1][start_x - 1] == 0:\n error = not self.left(i + 1, start_x)\n else:\n if i == 0:\n error = False\n self.fitnes += 1\n self.out_of_matrix = True\n break\n return not error\n\n def down(self, start_y, start_x):\n # print str(self.step) + \" down\"\n error = True\n for i in range(start_y + 1, 11):\n if self.matrix[i][start_x] == 0:\n self.out_of_matrix = False\n self.fitnes += 1\n self.matrix[i][start_x] = self.step\n if i == 10:\n self.step += 1\n self.out_of_matrix = True\n error = False\n break\n else:\n if self.matrix[i - 1][start_x + 1] == 0:\n error = not self.right(i - 1, start_x)\n else:\n if self.matrix[i - 1][start_x - 1] == 0:\n error = not self.left(i - 1, start_x)\n else:\n if i == 11:\n error = False\n self.fitnes += 1\n self.out_of_matrix = True\n break\n return not error\n","sub_path":"z3/Objects.py","file_name":"Objects.py","file_ext":"py","file_size_in_byte":8109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"129821107","text":"import numpy as np\nimport Node\n\nclass DecisionTree(object):\n \"\"\" Really thin abstraction here \"\"\"\n\n def __init__(self, dataset):\n self.dataset = dataset\n\n self.classes = dataset.target_count\n self.cols = list(range(0, len(dataset.data[0])))\n\n self.tree = Node.Node(self.dataset.training_data, self.dataset.training_targets, self.cols, root=True)\n\n # pass in array, number of nodes for each layer\n def create_tree(self):\n self.tree.create_next_node()\n\n def predict_numeric(self):\n predicted_targets = []\n for row in self.dataset.test_data:\n predicted_targets.append(self.evaluate_numeric_node(row, self.tree))\n\n return predicted_targets\n\n def evaluate_numeric_node(self, row, node):\n if node.value:\n return node.value\n else:\n upper_bound = 0\n for i in reversed(self.dataset.rules[node.feature]):\n if row[node.feature] > i:\n break\n elif upper_bound == len(node.nodes) - 1:\n break\n upper_bound += 1\n return self.evaluate_numeric_node(row, node.nodes[len(node.nodes) - (1 + upper_bound)])\n\n def predict_nominal(self):\n predicted_targets = []\n for row in self.dataset.test_data:\n predicted_targets.append(self.evaluate_nominal_node(row, self.tree))\n\n return predicted_targets\n\n def evaluate_nominal_node(self, row, node):\n if node.value != None:\n return node.value\n else:\n value_set = np.unique(self.dataset.training_data[:, node.feature]).tolist()\n indexOfNode = value_set.index(row[node.feature])\n return self.evaluate_nominal_node(row, node.nodes[indexOfNode])\n\n def print_tree(self):\n print(\"root split on feature {}\".format(self.tree.feature))\n for node in self.tree.nodes:\n self.node_to_string(node)\n\n def node_to_string(self, node):\n \"\"\" This looks terrible but my brain hurts \"\"\"\n print(\" \", end='')\n if node.value is not None:\n print(\"|___{}\".format(node.value))\n else:\n print(\"Node split on feature {}\".format(node.feature))\n for node in node.nodes:\n self.node_to_string(node)\n\n","sub_path":"Decision Tree/DecisionTree.py","file_name":"DecisionTree.py","file_ext":"py","file_size_in_byte":2315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"220378396","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n Fabfile example file to deploy a standard simple webapp\n\"\"\"\n\nfrom os.path import join\n\nfrom fabric.api import env, execute, roles, task\nfrom pydiploy.prepare import build_env as pydiploy_build_env\nfrom pydiploy.prepare import tag as pydiploy_tag\nfrom pydiploy.simple import deploy_backend as pydiploy_deploy_backend\nfrom pydiploy.simple import post_install_backend as pydiploy_postinstall_backend\nfrom pydiploy.simple import pre_install_backend as pydiploy_preinstall_backend\nfrom pydiploy.simple import rollback as pydiploy_rollback\n\n# edit config here !\n\nenv.use_sudo = True # use sudo or not\n\nenv.remote_owner = 'myremoteuser'\nenv.remote_group = 'myremotegroup'\n\nenv.application_name = 'myapp'\nenv.root_package_name = 'myapp'\n\nenv.remote_home = '/home/myremoteuser' # remote home root\nenv.remote_python_version = 3.4 # python version\nenv.remote_virtualenv_root = join(env.remote_home, '.virtualenvs') # venv root\nenv.remote_virtualenv_dir = join(env.remote_virtualenv_root, env.application_name) # venv for webapp dir\n\nenv.remote_repo_url = 'git@git.net:myapp.git'\nenv.local_tmp_dir = '/tmp' # tmp dir\nenv.locale = 'fr_FR.UTF-8' # locale to use on remote\nenv.timezone = 'Europe/Paris' # timezone for remote\nenv.keep_releases = 2 # number of old releases to keep before cleaning\n\n# optional parameters\n\nenv.application_type = 'simple' # specify another type of application\n\n# env.remote_repo_specific_folder = '' # specify a subfolder for the remote repository\n# env.user = 'my_user' # user for ssh\n# env.dest_path = '' # if not set using env_local_tmp_dir\n# env.excluded_files = ['pron.jpg'] # file(s) that rsync should exclude when deploying app\n# env.extra_ppa_to_install = ['ppa:vincent-c/ponysay'] # extra ppa source(s) to use\n# env.extra_pkg_to_install = ['ponysay'] # extra debian/ubuntu package(s) to install on remote\n# env.extra_source_to_install = [['mongodb', 'http://downloads-distro.mongodb.org/repo/ubuntu-upstart', 'dist', '10gen'], ['deb-src', 'http://site.example.com/debian', 'distribution', 'component1', 'component2', 'component3']]\n# env.cfg_shared_files = ['config','/app/path/to/config/config_file'] # config files to be placed in shared config dir\n# env.extra_symlink_dirs = ['mydir','/app/mydir'] # dirs to be symlinked in shared directory\n# env.extra_goals = ['preprod'] # add extra goal(s) to defaults (test,dev,prod)\n# env.verbose = True # verbose display for pydiploy default value = True\nenv.req_pydiploy_version = '1.1.5.0' # required pydiploy version for this fabfile\n\n#  env.run_tests_command = 'tox'\n\n# fill and uncomment not to pass parameters in term (eg: fab tag:master test --set default_db_host='localhost',default_db_name='my_app_db' )\n# env.default_db_host = 'localhost'\n# env.default_db_name = 'myapp_db'\n# env.default_db_user = 'myapp_db_user'\n# env.default_db_password = 'S3CR3T'\n\n# env.no_tag_check = True # When your fabfile is not in your project git repository be sure to set this var\n\n\n@task\ndef test():\n \"\"\"Define test stage\"\"\"\n env.user = 'vagrant'\n env.roledefs = {'web': ['192.168.1.4']}\n env.goal = \"test\"\n # env.server_name = \"myapp.net\" # optional: if you want to use an url for the name of the remote app folder instead of the application name (manual bottle or flask app)\n env.map_settings = {\n # uncomment to use :\n #'ldap_user': \"DATABASES['ldap']['USER']\",\n #'ldap_password': \"DATABASES['ldap']['PASSWORD']\"\n }\n execute(build_env)\n\n\n@task\ndef prod():\n \"\"\"Define prod stage\"\"\"\n env.roledefs = {'web': ['myserver.net']}\n env.goal = \"prod\"\n # env.server_name = \"myapp.net\" # optional: if you want to use an url for the name of the remote app folder instead of the application name (manual bottle or flask app)\n env.map_settings = {\n # uncomment to use :\n #'ldap_user': \"DATABASES['ldap']['USER']\",\n #'ldap_password': \"DATABASES['ldap']['PASSWORD']\"\n }\n execute(build_env)\n\n\n# dont touch after that point if you don't know what you are doing !\n\n\n@task\ndef tag(version_string):\n \"\"\" Set the version to deploy to `version_number`. \"\"\"\n execute(pydiploy_tag, version=version_string)\n\n\n@task\ndef head_master():\n \"\"\" Set the version to deploy to the head of the master. \"\"\"\n execute(pydiploy_tag, version='master')\n\n\n@roles(['web'])\ndef build_env():\n \"\"\" Build the deployment environnement. \"\"\"\n execute(pydiploy_build_env)\n\n\n@task\ndef pre_install():\n \"\"\" Pre install of backend & frontend. \"\"\"\n execute(pre_install_backend)\n\n\n@roles('web')\n@task\ndef pre_install_backend():\n \"\"\" Setup server for backend. \"\"\"\n execute(pydiploy_preinstall_backend, commands='/usr/bin/rsync')\n\n\n@task\ndef deploy():\n \"\"\"Deploy code and sync static files\"\"\"\n execute(deploy_backend)\n\n\n@roles('web')\n@task\ndef deploy_backend(update_pkg=False):\n \"\"\"Deploy code on server\"\"\"\n execute(pydiploy_deploy_backend, update_pkg)\n\n\n@roles('web')\n@task\ndef rollback():\n \"\"\" Rollback code (current-1 release). \"\"\"\n execute(pydiploy_rollback)\n\n\n@task\ndef post_install():\n \"\"\" Post install for backend & frontend. \"\"\"\n execute(post_install_backend)\n\n\n@roles('web')\n@task\ndef post_install_backend():\n \"\"\" Post installation of backend. \"\"\"\n execute(pydiploy_postinstall_backend)\n","sub_path":"pydiploy/examples/simple_fabfile.py","file_name":"simple_fabfile.py","file_ext":"py","file_size_in_byte":5291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"400712966","text":"# coding=utf-8\nfrom pyspark.sql.types import *\nimport pandas as pd\n\n\ndef max_outlier_pnl_job(spark, df_EIA, df_uni, df_hos_city):\n df_panel_hos = df_uni.where(df_uni.PANEL == 1).select(\"HOSP_ID\").withColumnRenamed(\"HOSP_ID\", \"HOSP_ID1\")\n if(\"City\" in df_EIA.columns):\n df_EIA = df_EIA.drop(\"City\")\n df_pnl = df_EIA.join(df_hos_city, df_EIA.HOSP_ID == df_hos_city.Panel_ID, how=\"left\").\\\n join(df_panel_hos, df_EIA.HOSP_ID == df_panel_hos.HOSP_ID1, how=\"right\")\n # df_pnl.show()\n\n df_pnl = df_pnl.groupBy([\"City\", \"POI\"]).sum(\"Sales\").withColumnRenamed(\"sum(Sales)\", \"Sales\")\n df_pnl.persist()\n # pnl = df_pnl.toPandas()\n # pnl = pnl.set_index([\"City\", \"POI\"])\n # pnl = pnl.unstack(\"POI\").fillna(0).stack()\n #\n # pnl2= \\\n # pd.DataFrame(pnl.sum(level=\"City\")).reset_index() \\\n # .merge(pd.DataFrame(pnl).reset_index(),\n # on=\"City\",\n # how=\"right\",\n # suffixes=[\"_pnl_mkt\",\"_pnl\"])\n #\n # print pnl2\n\n df_pnl_tmp = df_pnl.withColumnRenamed(\"Sales\", \"Sales_pnl\")\n df_pnl_mkt = df_pnl.groupBy(\"City\").agg({\"Sales\": \"sum\"}) \\\n .withColumnRenamed(\"sum(Sales)\", \"Sales_pnl_mkt\")\n\n df_pnl = df_pnl_tmp.join(df_pnl_mkt, on=[\"City\"], how=\"left\")\n # print df_pnl.count()\n # df_pnl.where(df_pnl.City == \"上海市\").show()\n return df_pnl\n","sub_path":"outerlier/phpnljob.py","file_name":"phpnljob.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"41962130","text":"class Console:\n @staticmethod\n def text(text):\n print(text)\n\n @staticmethod\n def text_line(text):\n print(text)\n print()\n\n @staticmethod\n def line():\n print('------------------------------------------------------------')\n\n @staticmethod\n def header(text):\n len_text = len(text)\n space = int((58 - len_text) / 2)\n\n if space < 0:\n space = 0\n\n space_str = \"\"\n space_str_suffix = \"\"\n\n if len_text % 2 == 1:\n space_str_suffix += \" \"\n\n for i in range(space):\n space_str += \" \"\n space_str_suffix += \" \"\n\n print(\" \")\n print(\"############################################################\")\n print(\"#\" + space_str + text + space_str_suffix + \"#\")\n print('############################################################')\n\n @staticmethod\n def read(prompt):\n return input(prompt)\n\n @staticmethod\n def error(text):\n Console.text(\" \")\n Console.line()\n Console.text_line(\"ERROR!\")\n Console.text(text)\n Console.line()\n Console.text(\" \")\n","sub_path":"CLI.py","file_name":"CLI.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"151979233","text":"# -*- coding:utf-8 -*-\nimport json\nimport urllib2\n\ndef dialog(text_input):\n api_url = \"http://openapi.tuling123.com/openapi/api/v2\"\n\n req = {\n \"perception\":\n {\n \"inputText\":\n {\n \"text\": text_input\n },\n\n \"selfInfo\":\n {\n \"location\":\n {\n \"city\": \"上海\",\n \"province\": \"上海\",\n \"street\": \"文汇路\"\n }\n }\n },\n\n \"userInfo\": \n {\n \"apiKey\": \"7bd01dac044b40c3b3e40f1ae2419574\",\n \"userId\": \"18676661594\"\n }\n }\n # print(req)\n # 将字典格式的req编码为utf8\n req = json.dumps(req).encode('utf8')\n # print(req)\n\n http_post = urllib2.Request(api_url, data=req, headers={'content-type': 'application/json'})\n response = urllib2.urlopen(http_post)\n response_str = response.read().decode('utf8')\n # print(response_str)\n response_dic = json.loads(response_str)\n # print(response_dic)\n\n intent_code = response_dic['intent']['code']\n results_text = response_dic['results'][0]['values']['text']\n\n return intent_code,results_text\n","sub_path":"mybot_up/Dialog.py","file_name":"Dialog.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"245527667","text":"###############################################################################\n#\n# Copyright (c) 2006 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n###############################################################################\n\"\"\"\n$Id$\n\"\"\"\n__docformat__ = \"reStructuredText\"\n\nimport unittest\nfrom zope.testing import doctest\nfrom zope.app.testing import setup\nfrom zope.app.testing import placelesssetup\n\n\ndef siteSetUp(test):\n site = setup.placefulSetUp(site=True)\n test.globs['rootFolder'] = site\n\n\ndef siteTearDown(test):\n setup.placefulTearDown()\n\n\ndef test_suite():\n return unittest.TestSuite((\n doctest.DocFileSuite('README.txt',\n setUp=siteSetUp, tearDown=siteTearDown,\n optionflags=doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS),\n doctest.DocFileSuite('group.txt',\n setUp=siteSetUp, tearDown=siteTearDown,\n optionflags=doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS),\n doctest.DocTestSuite('z3c.authentication.simple.principal',\n setUp=placelesssetup.setUp, tearDown=placelesssetup.tearDown),\n doctest.DocTestSuite('z3c.authentication.simple.group',\n setUp=placelesssetup.setUp, tearDown=placelesssetup.tearDown),\n doctest.DocFileSuite('vocabulary.txt',\n setUp=placelesssetup.setUp, tearDown=placelesssetup.tearDown),\n ))\n\nif __name__ == '__main__':\n unittest.main(defaultTest='test_suite')\n","sub_path":"z3c.authentication/branches/darrylcousins/src/z3c/authentication/simple/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"124354648","text":"from test import showErrors\nnom=\"\"\nprenom=\"\"\nage=0\nwhile True:\n\tprint(\"Faites votre choix:\\n 1- Taper votre nom \\n 2- Taper vos prénoms\\n 3- Taper votre age\\n 4- Mes infos\\n 5- QUITTER\")\n\ta=int(input(\"taper un chiffre de 1 à 5 de votre choix: \")) #input considère l'élément entré comme étant une chaine de caractère\n\tif(a==5):\n\t\tprint(\"QUITTER\")\n\t\tbreak\n\telse:\n\t\tif(a==1):\n\t\t\tnom=input(\"entrer votre nom: \")\n\t\telif(a==2):\n\t\t\tprenom=input(\"entrer vos prenoms: \")\n\t\telif(a==3):\n\t\t\tage=int(input(\"entrer votre age: \"))\n\t\telif(a==4):\n\t\t\terreurs=[] #tableau vide\n\t\t\tif len(nom)==0:\n\t\t\t\terreurs.append('nom')\n\n\t\t\tif len(prenom)==0:\n\t\t\t\terreurs.append('prenom')\n\n\t\t\tif age==0:\n\t\t\t\terreurs.append('age')\n\n\t\t\tif (erreurs): #tester s'il y a klk choz a l'interieur du tableau\n\t\t\t\tprint(\"Les champs suivant doivent etre remplies:\")\n\t\t\t\tshowErrors(erreurs)\n\t\t\t\t#for i in erreurs:\n\t\t\t\t\t#print(\"- \",i)\n\t\t\telse:\n\t\t\t\tinfos={'nom:':nom, 'prenoms:':prenom, 'age:':age}\n\t\t\t\tprint(infos)\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"77927117","text":"from datetime import timedelta, datetime\n\nfrom organisations.models import (\n OrganisationDivisionSet\n)\n\n\ndef add_end_date_to_previous_div_sets(div_set):\n older_div_set = OrganisationDivisionSet.objects.filter(\n organisation=div_set.organisation,\n end_date=None,\n start_date__lt=div_set.start_date\n ).order_by('-start_date').first()\n if older_div_set:\n start_date = datetime.strptime(str(div_set.start_date), \"%Y-%m-%d\")\n older_div_set.end_date = start_date - timedelta(days=1)\n older_div_set.save()\n","sub_path":"every_election/apps/organisations/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"381962385","text":"import cv2\nimport numpy as np\n\n\nimage1 = cv2.imread(\"log_3.png\")\nimage2 = cv2.imread(\"log_4.png\")\n\n\nheight = np.size(image1, 0)\nwidth = np.size(image1, 1)\n\ndef logical_XOR(img1,img2,height,width):\n for i in range (width-1):\n for j in range (height-1):\n b,r,g = img1[j,i]\n temp1 = int((b+r+g)/3)\n x,y,z = img2[j,i]\n temp2 = int((x+y+z)/3)\n temp3 = bin(int(bin(temp1),2) ^ int(bin(temp2),2))\n img2[j,i] = int(temp3,2)\n cv2.imwrite('output_XOR.png',img2)\n\nif __name__ == \"__main__\":\n logical_XOR(image1,image2,height,width)","sub_path":"src/Logic operator/logical_xor.py","file_name":"logical_xor.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"345075601","text":"\"\"\"\nSendex eh um modulo criado para envio de arquivos.\nPor exemplo, para se enviar um video em HD para um cliente.\nNo final do upload dos arquivos, e-mails de notificao sao enviados pelo servidor. \nO remetente e o destinatario recebem as mensagens.\n\nOs diferentes meios de envio estendem a classe SendexSender.\n\n\"\"\"\nfrom pyramid.response import Response\nfrom pyramid.view import view_config\nfrom pts.login.views import jsonLogin\nfrom pts.vzSQL import mysql_db\nfrom pts.vzFile import vzPtsFile\nfrom pts.vzEmail import Email\nfrom pts.views import not_found\nfrom pts.vzGrid import convert_json\nfrom settings import SENDEX_FILE_TYPE_ID,VETORZERO_ID,SENDEX_FTP_FOLDER\nfrom urlparse import urlparse\nfrom ftplib import FTP\nimport json\nimport shutil\nimport os.path\n\nclass SendexSender(object):\n \"\"\"As classes usadas no envio de arquivos por sendex sao derivadas desta classe.\n O upload do arquivo esta incluso no metodo __init__ ,\n atributos:\n self.arquivo contem o arquivo File\n self.filename contem o nome do arquivo\n self.file_id contem o id no banco de dados do arquivo\n \"\"\"\n \n def __init__(self,file_id=None,new_file=None,filename=None):\n self.ptsfile = vzPtsFile()\n if file_id:\n self.ptsfile.open('r',file_id=file_id)\n self.arquivo= self.ptsfile.get_file()\n self.filename = self.ptsfile.db_file[1]\n if new_file and filename:\n self.filename = filename\n self.ptsfile.open('w',name=self.filename,filetype=SENDEX_FILE_TYPE_ID)\n new_file.seek(0)\n while 1:\n data = new_file.read(2<<16)\n if not data:\n break\n self.ptsfile.write(data)\n file_data = self.ptsfile.close()\n self.file_id = file_data[0][0]\n self.ptsfile.open('r',file_id=self.file_id)\n self.arquivo = self.ptsfile.get_file()\n\nclass FtpClient(SendexSender):\n \n def register_ftpclient(self,request):\n params = request.params.copy()\n if not (params.has_key('sendex_ftp-port') and params['sendex_ftp-port']):\n params['sendex_ftp-port']='21'\n x=mysql_db.execute(\"\"\"INSERT INTO ftp\n (entity_id,ftp_adress,ftp_port)\n values (%s,%s,%s) \"\"\",params['sendex_entity'],\n params['sendex_ftp-address'],\n params['sendex_ftp-port'])\n mysql_db.execute(\"\"\"INSERT into ftp_user\n (ftp_id,entity_id,ftp_user_login,ftp_user_password)\n values (%s,%s,%s,%s)\"\"\",x.lastrowid,\n request.session['session']['entity_id_company'],\n params['sendex_ftp-login'],\n params['sendex_ftp-password'])\n\n def send(self,request):\n send_dic = request.params\n ftp = FTP(send_dic[\"sendex_ftp-address\"])\n #anonymous. precisa mudar o formulario para tbm aceitar logins\n if send_dic.has_key(\"sendex_ftp-login\") and send_dic.has_key(\"sendex_ftp-password\"):\n try: \n ftp.login(user=send_dic[\"sendex_ftp-login\"],\n passwd=send_dic[\"sendex_ftp-password\"])\n except:\n return {\"error\":[\"Failed\",\"Error on FTP login\"]}\n else:\n try:\n ftp.login()\n except:\n return {\"error\":[\"Failed\",\"Error on FTP login\"]}\n try:\n ftp.storbinary('STOR %s'%self.filename,self.arquivo)\n except:\n return {\"error\":[\"Failed\",\"Error on FTP update\"]}\n self.arquivo.close()\n ftp.quit()\n try:\n address = [send_dic[\"sendex_email-receiver\"]] #precisa ser uma lista\n sender = send_dic[\"sendex_email-sender\"]\n except:\n return {\"error\":[\"Failed\",\"Missing arguments\"]}\n #cria uma mensagem padrao se nao tiver nenhuma outra\n if send_dic.has_key(\"sendex_message\") and send_dic[\"sendex_message\"]:\n message = send_dic[\"sendex_message\"]\n else:\n message = \"%s enviou um arquivo no ftp %s\"%(sender,send_dic[\"sendex_ftp-address\"])\n email = Email()\n #envia os e-mails atraves do e-mail definido no settings\n try:\n email.send_mail(message,address)\n except:\n return {\"error\":[\"Failed\",\"Error sending e-mail\"]}\n try:\n self.register_ftpclient(request)\n except:\n return {\"error\":[\"OK\",\"File send successfully\"]}\n return {\"error\":[\"OK\",\"File send successfully\"]}\n\nclass FtpLocal(SendexSender):\n \n def copy_file_to_ftp(self):\n f = open(os.path.join(SENDEX_FTP_FOLDER,self.filename),'wb')\n self.arquivo.seek(0)\n f.write(self.arquivo.read())\n f.close()\n\n\n def send(self,request):\n send_dic = request.params\n receiver_entity = send_dic[\"sendex_entity\"]\n teste = mysql_db.execute(\"\"\"SELECT * FROM ftp_user \n LEFT JOIN ftp ON ftp_user.ftp_id = ftp.ftp_id\n WHERE ftp_user.entity_id = %s AND ftp.entity_id = %s \"\"\",\n receiver_entity,request.session['session']['entity_id_company']).fetchall()\n if teste:\n self.copy_file_to_ftp()\n self.arquivo.close()\n else:\n self.arquivo.close()\n return {\"error\":[\"Failed\",\"Sorry, Could not find a ftp user for this entity\"]}\n return {\"error\":[\"OK\",\"File send successfully\"]}\n \n \nclass EmailFile(SendexSender):\n \n def send(self,request):\n send_dic = request.params\n try:\n address = [send_dic[\"sendex_email-receiver\"]] #precisa ser uma lista\n sender = send_dic[\"sendex_email-sender\"]\n except:\n return {\"error\":[\"Failed\",\"missing parameters\"]}\n #cria uma mensagem padrao se nao tiver nenhuma outra\n if send_dic.has_key(\"sendex_message\") and send_dic[\"sendex_message\"]:\n message = send_dic[\"sendex_message\"]\n else:\n message = \"%s te enviou um arquivo em anexo\"%sender\n email = Email()\n #envia os e-mails atraves do e-mail definido no settings\n try:\n email.send_mail(message,address,attachments=[[self.arquivo,self.filename]])\n except:\n return {\"error\":[\"Failed\",\"Error sending e-mail\"]}\n self.arquivo.close()\n return {\"error\":[\"OK\",\"File send successfully\"]}\n \nclass HttpFile(SendexSender):\n \n def send(self,request):\n send_dic = request.params\n try:\n address = [send_dic[\"sendex_email-receiver\"]] #precisa ser uma lista\n sender = send_dic[\"sendex_email-sender\"]\n except:\n return {\"error\":[\"Failed\",\"missing parameters\"]}\n o = urlparse(request.url)\n urlhost = o.scheme+'://'+o.netloc\n url = \"%s/json.sendex.download?id=%s\"%(urlhost,self.file_id)\n message = \" %s te enviou um arquivo, ele pode ser baixado em %s\"%(sender,url)\n email = Email()\n try:\n email.send_mail(message,address)\n except:\n return {\"error\":[\"Failed\",\"Error sending e-mail\"]}\n self.arquivo.close()\n return {\"error\":[\"OK\",\"File send successfully\"]}\n\n@view_config(route_name=\"sendex.download\")\n@jsonLogin\ndef download_sendex(request):\n file_id = request.params['id']\n f = vzPtsFile()\n f.open('r',file_id=file_id)\n dbfile = f.comp_file\n l = dbfile.select_unique_id(file_id)[0]\n tipo = dbfile.get_item_by_name(l,'type')\n if int(tipo) == SENDEX_FILE_TYPE_ID:\n server_file = f.get_file()\n file_name = f.db_file[1]\n response = Response(server_file.read(),content_type=f.get_mime_type(),\n content_disposition='attachment; filename=\"%s\"'%file_name)\n server_file.close()\n return response\n else:\n return not_found(request)\n\n\nsend_type_dict = {\n 'ftpclient':FtpClient,\n 'ftplocal':FtpLocal,\n 'email':EmailFile,\n 'http':HttpFile,\n }\n\n\n@view_config(route_name=\"sendex.send\",renderer=\"json\")\n@jsonLogin\ndef send_file(request):\n if not (request.params.has_key(\"file\") or request.params.has_key(\"file_id\")) and request.params.has_key(\"sendex_type\"):\n return {\"error\":[\"failed\",\"missing arguments %s\"%request.params.keys()]}\n if request.params['sendex_type'] in send_type_dict:\n send_type = request.params['sendex_type']\n if request.params.has_key(\"file_id\"):\n send_object = send_type_dict[send_type](request.params['file_id'])\n else:\n file_request = request.params['file']\n file_name = file_request.filename\n input_file = file_request.file\n send_object = send_type_dict[send_type](new_file = input_file,filename=file_name)\n result = send_object.send(request)\n return result\n else:\n return {\"error\":[\"failed\",\"type don't exist\"]}\n\n@view_config(route_name=\"sendex.form.header\",renderer=\"json\")\n@jsonLogin\ndef new_sendex_header(request):\n header = []\n if request.params.has_key(\"type\"):\n tipo = request.params['type']\n if tipo=='ftpclient':\n header=[\n [\"id\",\"hidden\",False,False],\n [\"entity\",\"select.search\",False,False],\n [\"email receiver\",\"text\",False,False],\n [\"email sender\",\"text\",False,False],\n [\"ftp address\",\"text\",False,False],\n [\"ftp login\",\"text\",False,False],\n [\"ftp password\",\"text\",False,False],\n [\"message\",\"textarea\",False,False]\n ]\n elif tipo=='email':\n header=[\n [\"id\",\"hidden\",False,False],\n [\"email receiver\",\"text\",False,False],\n [\"email sender\",\"text\",False,False],\n [\"message\",\"textarea\",False,False]\n ]\n elif tipo=='ftplocal':\n header = [\n [\"id\",\"hidden\",False,False],\n [\"entity\",\"select.search\",False,False],\n [\"email receiver\",\"text\",False,False],\n [\"email sendex\",\"text\",False,False],\n [\"message\",\"textarea\",False,False],\n ]\n elif tipo=='http':\n header=[\n [\"id\",\"hidden\",False,False],\n [\"email receiver\",\"text\",False,False],\n [\"email sender\",\"text\",False,False],\n [\"message\",\"textarea\",False,False]\n ]\n return {\n \"components\":[\n {\n \"body\":[],\n \"header\":header,\n \"type\":\"single\",\n \"name\":\"sendex\",\n }\n ]\n }\n\n@view_config(route_name=\"sendex.form.select\",renderer=\"json\")\n@jsonLogin\ndef new_sendex_select(request):\n total = []\n if request.params.has_key(\"sendex_type\"):\n itens = [{\"id\":i,\"name\":i} for i in send_type_dict.keys()]\n total.append({\"name\":\"sendex_type\", \"choices\":itens})\n return total\n\n@view_config(route_name=\"sendex.form.search\",renderer=\"json\")\n@jsonLogin\ndef new_sendex_search(request):\n fields = []\n if request.params.has_key(\"sendex_entity\") and request.params[\"sendex_entity\"]:\n keyword = request.params[\"sendex_entity\"]\n f = mysql_db.execute(\"\"\"SELECT entity_id,CONCAT(entity_first_name,' ',entity_last_name)\n FROM entity\n WHERE CONCAT(entity_first_name,' ',entity_last_name) LIKE %s\"\"\",'%%'+keyword+'%%').fetchall()\n if f:\n choices = []\n choices_raw = convert_json(f)\n for i in f:\n choices.append({'id':i[0],'name':i[1]})\n fields.append({\"name\":'sendex_entity', \"choices\": choices})\n return fields\n","sub_path":"sendex/sendex.py","file_name":"sendex.py","file_ext":"py","file_size_in_byte":11775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"470116271","text":"#!/usr/bin/env python\n\"\"\"Script to load project info from Lims into the project database in statusdb.\n\nMaya Brandi, Science for Life Laboratory, Stockholm, Sweden.\n\"\"\"\nfrom __future__ import print_function\nfrom genologics.config import BASEURI, USERNAME, PASSWORD\nfrom genologics.lims import Lims\nfrom argparse import ArgumentParser\nfrom LIMS2DB.utils import formatStack\nfrom statusdb.db.utils import load_couch_server\nfrom genologics_sql.queries import get_last_modified_projectids\nfrom genologics_sql.utils import get_session, get_configuration\nfrom genologics_sql.tables import Project as DBProject\nfrom LIMS2DB.classes import ProjectSQL\n\nimport yaml\nimport json\nimport logging\nimport logging.handlers\nimport multiprocessing as mp\nimport os\ntry:\n import queue as Queue\nexcept ImportError:\n import Queue\nimport sys\nimport time\nimport traceback\n\n\ndef main(options):\n conf = options.conf\n output_f = options.output_f\n couch = load_couch_server(conf)\n mainlims = Lims(BASEURI, USERNAME, PASSWORD)\n lims_db = get_session()\n\n mainlog = logging.getLogger('psullogger')\n mainlog.setLevel(level=logging.INFO)\n mfh = logging.handlers.RotatingFileHandler(options.logfile, maxBytes=209715200, backupCount=5)\n mft = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n mfh.setFormatter(mft)\n mainlog.addHandler(mfh)\n\n # try getting orderportal config\n oconf = None\n try:\n with open(options.oconf, 'r') as ocf:\n oconf = yaml.load(ocf, Loader=yaml.SafeLoader)['order_portal']\n except Exception as e:\n mainlog.warn(\"Loading orderportal config {} failed due to {}, so order information \"\n \"for project will not be updated\".format(options.oconf, e))\n\n if options.project_name:\n host = get_configuration()['url']\n pj_id = lims_db.query(DBProject.luid).filter(DBProject.name == options.project_name).scalar()\n if not pj_id:\n pj_id = options.project_name\n P = ProjectSQL(lims_db, mainlog, pj_id, host, couch, oconf)\n if options.upload:\n P.save(update_modification_time=not options.no_new_modification_time)\n else:\n if output_f is not None:\n with open(output_f, 'w') as f:\n f.write(json.dumps(P.obj))\n else:\n print(json.dumps(P.obj))\n\n else:\n projects = create_projects_list(options, lims_db, mainlims, mainlog)\n masterProcess(options, projects, mainlims, mainlog, oconf)\n lims_db.commit()\n lims_db.close()\n\n\ndef create_projects_list(options, db_session, lims, log):\n projects = []\n if options.all_projects:\n if options.hours:\n postgres_string = \"{} hours\".format(options.hours)\n project_ids = get_last_modified_projectids(db_session, postgres_string)\n valid_projects = db_session.query(DBProject).filter(DBProject.luid.in_(project_ids)).all()\n log.info(\"project list : {0}\".format(\" \".join([p.luid for p in valid_projects])))\n return valid_projects\n else:\n projects = db_session.query(DBProject).all()\n log.info(\"project list : {0}\".format(\" \".join([p.luid for p in projects])))\n return projects\n\n elif options.input:\n with open(options.input, \"r\") as input_file:\n for pname in input_file:\n try:\n projects.append(lims.get_projects(name=pname.rstrip())[0])\n except IndexError:\n pass\n\n return projects\n\n\ndef processPSUL(options, queue, logqueue, oconf=None):\n couch = load_couch_server(options.conf)\n db_session = get_session()\n work = True\n procName = mp.current_process().name\n proclog = logging.getLogger(procName)\n proclog.setLevel(level=logging.INFO)\n mfh = QueueHandler(logqueue)\n mft = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n mfh.setFormatter(mft)\n proclog.addHandler(mfh)\n # Not completely sure what this does, maybe trying to load balance?\n try:\n time.sleep(int(procName[8:]))\n except:\n time.sleep(1)\n\n while work:\n # grabs project from queue\n try:\n projname = queue.get(block=True, timeout=3)\n proclog.info(\"Starting work on {} \".format(projname))\n proclog.info(\"Approximately {} projects left in queue\".format(queue.qsize()))\n except Queue.Empty:\n work = False\n proclog.info(\"exiting gracefully\")\n break\n except NotImplementedError:\n # qsize failed, no big deal\n pass\n else:\n # locks the project : cannot be updated more than once.\n lockfile = os.path.join(options.lockdir, projname)\n if not os.path.exists(lockfile):\n try:\n open(lockfile, 'w').close()\n except:\n proclog.error(\"cannot create lockfile {}\".format(lockfile))\n try:\n pj_id = db_session.query(DBProject.luid).filter(DBProject.name == projname).scalar()\n host = get_configuration()['url']\n P = ProjectSQL(db_session, proclog, pj_id, host, couch, oconf)\n P.save()\n except:\n error = sys.exc_info()\n stack = traceback.extract_tb(error[2])\n proclog.error(\"{0}:{1}\\n{2}\".format(error[0], error[1], formatStack(stack)))\n\n try:\n os.remove(lockfile)\n except:\n proclog.error(\"cannot remove lockfile {}\".format(lockfile))\n else:\n proclog.info(\"project {} is locked, skipping.\".format(projname))\n\n # signals to queue job is done\n queue.task_done()\n db_session.commit()\n db_session.close()\n\n\ndef masterProcess(options, projectList, mainlims, logger, oconf=None):\n projectsQueue = mp.JoinableQueue()\n logQueue = mp.Queue()\n childs = []\n # Initial step : order projects by sample number:\n logger.info(\"ordering the project list\")\n orderedprojectlist = sorted(projectList, key=lambda x: (mainlims.get_sample_number(projectname=x.name)), reverse=True)\n logger.info(\"done ordering the project list\")\n # spawn a pool of processes, and pass them queue instance\n for i in range(options.processes):\n p = mp.Process(target=processPSUL, args=(options, projectsQueue, logQueue, oconf))\n p.start()\n childs.append(p)\n # populate queue with data\n for proj in orderedprojectlist:\n projectsQueue.put(proj.name)\n\n # wait on the queue until everything has been processed\n notDone = True\n while notDone:\n try:\n log = logQueue.get(False)\n logger.handle(log)\n except Queue.Empty:\n if not stillRunning(childs):\n notDone = False\n break\n\n\ndef stillRunning(processList):\n ret = False\n for p in processList:\n if p.is_alive():\n ret = True\n\n return ret\n\n\nclass QueueHandler(logging.Handler):\n \"\"\"\n This handler sends events to a queue. Typically, it would be used together\n with a multiprocessing Queue to centralise logging to file in one process\n (in a multi-process application), so as to avoid file write contention\n between processes.\n\n This code is new in Python 3.2, but this class can be copy pasted into\n user code for use with earlier Python versions.\n \"\"\"\n\n def __init__(self, queue):\n \"\"\"\n Initialise an instance, using the passed queue.\n \"\"\"\n logging.Handler.__init__(self)\n self.queue = queue\n\n def enqueue(self, record):\n \"\"\"\n Enqueue a record.\n\n The base implementation uses put_nowait. You may want to override\n this method if you want to use blocking, timeouts or custom queue\n implementations.\n \"\"\"\n self.queue.put_nowait(record)\n\n def prepare(self, record):\n \"\"\"\n Prepares a record for queuing. The object returned by this method is\n enqueued.\n\n The base implementation formats the record to merge the message\n and arguments, and removes unpickleable items from the record\n in-place.\n\n You might want to override this method if you want to convert\n the record to a dict or JSON string, or send a modified copy\n of the record while leaving the original intact.\n \"\"\"\n # The format operation gets traceback text into record.exc_text\n # (if there's exception data), and also puts the message into\n # record.message. We can then use this to replace the original\n # msg + args, as these might be unpickleable. We also zap the\n # exc_info attribute, as it's no longer needed and, if not None,\n # will typically not be pickleable.\n self.format(record)\n record.msg = record.message\n record.args = None\n record.exc_info = None\n return record\n\n def emit(self, record):\n \"\"\"\n Emit a record.\n\n Writes the LogRecord to the queue, preparing it for pickling first.\n \"\"\"\n try:\n self.enqueue(self.prepare(record))\n except Exception:\n self.handleError(record)\n\n\nif __name__ == '__main__':\n usage = \"Usage: python project_summary_upload_LIMS.py [options]\"\n parser = ArgumentParser(usage=usage)\n\n parser.add_argument(\"-p\", \"--project\", dest=\"project_name\", default=None,\n help=\"eg: M.Uhlen_13_01. Dont use with -a flagg.\")\n\n parser.add_argument(\"-a\", \"--all_projects\", action=\"store_true\",\n default=False, help=(\"Upload all Lims projects into couchDB.\"\n \"Don't use together with -f flag.\"))\n parser.add_argument(\"-c\", \"--conf\", default=os.path.join(\n os.environ['HOME'], 'conf/LIMS2DB/post_process.yaml'),\n help=\"Config file. Default: ~/conf/LIMS2DB/post_process.yaml\")\n parser.add_argument(\"--oconf\", default=os.path.join(\n os.environ['HOME'], '.ngi_config/orderportal_cred.yaml'),\n help=\"Orderportal config file. Default: ~/.ngi_config/orderportal_cred.yaml\")\n parser.add_argument(\"--no_upload\", dest=\"upload\", default=True, action=\"store_false\",\n help=(\"Use this tag if project objects should not be uploaded,\"\n \" but printed to output_f, or to stdout. Only works with\"\n \" individual projects, not with -a.\"))\n parser.add_argument(\"--output_f\", default=None,\n help=\"Output file that will be used only if --no_upload tag is used\")\n parser.add_argument(\"-m\", \"--multiprocs\", type=int, dest=\"processes\", default=4,\n help=\"The number of processes that will be spawned. Will only work with -a\")\n parser.add_argument(\"-l\", \"--logfile\", default=os.path.expanduser(\"~/lims2db_projects.log\"),\n help=\"log file that will be used. Default is $HOME/lims2db_projects.log\")\n parser.add_argument(\"--lockdir\", default=os.path.expanduser(\"~/psul_locks\"),\n help=(\"Directory for handling the lock files to avoid multiple updates \"\n \"of one project. default is $HOME/psul_locks \"))\n parser.add_argument(\"-j\", \"--hours\", type=int, default=None,\n help=(\"only handle projects modified in the last X hours\"))\n parser.add_argument(\"-i\", \"--input\", default=None,\n help=\"path to the input file containing projects to update\")\n parser.add_argument(\"--no_new_modification_time\", action=\"store_true\",\n help=(\"This updates documents without changing the modification time. \"\n \"Slightly dangerous, but useful e.g. when all projects would be updated.\"))\n\n options = parser.parse_args()\n\n main(options)\n","sub_path":"scripts/project_summary_upload_LIMS.py","file_name":"project_summary_upload_LIMS.py","file_ext":"py","file_size_in_byte":12114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"278451161","text":"from socket import *\nimport numpy as np\nimport cv2\n\nHOST = '127.0.0.1'\nPORT = 56789\nBUFSIZ = 1024\nADDR = (HOST, PORT)\ntcpCliSock = socket(AF_INET, SOCK_STREAM)\nsoc = False\n\ndef send():\n tcpCliSock = socket(AF_INET, SOCK_STREAM)\n try:\n tcpCliSock.connect(ADDR)\n except Exception as e:\n print('서버(%s:%s)에 연결 할 수 없습니다.' % ADDR)\n return\n print('서버(%s:%s)에 연결 되었습니다.' % ADDR)\n ############################################################\n test = [123, 45, -2]\n angle = np.array(test)\n # angle = np.array(b\"%d\" % 50)\n stringData = angle.tostring()\n print(\"stringData: %s\" % stringData)\n tcpCliSock.send(stringData)\n # tcpCliSock.send(nptest)\n print(\"recv second data\", tcpCliSock.recv(100))\n\n # angle = np.array(b\"%d\" % 50)\n # stringData = angle.tostring()\n # tcpCliSock.send(stringData)\n # print(\"recv second data\", tcpCliSock.recv(100))\n\n encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]\n result, imgencode = cv2.imencode('.jpg', image_rgb, encode_param)\n data = np.array(imgencode)\n stringData = data.tostring()\n # tcpCliSock.send(stringData)\n # print(\"recv second data\", tcpCliSock.recv(100))\n\n\n tcpCliSock.close()\n\nif __name__ == '__main__':\n\n capture = cv2.VideoCapture(0)\n capture.set(3, 640)\n capture.set(4, 480)\n\n while True:\n ret, frame = capture.read()\n if not ret:\n print(\"비디오 읽기 오류\")\n break\n image_rgb = np.array(frame)\n\n cv2.namedWindow('webcam', cv2.WINDOW_AUTOSIZE)\n cv2.imshow('webcam', image_rgb)\n\n key = cv2.waitKey(1)\n if key == 27: # esc key\n break\n elif key == 73 or key == 105: # I or i key\n if soc:\n soc = False\n else:\n soc = True\n\n if soc:\n send()\n capture.release()\n\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"610067661","text":"from pony.orm import *\nfrom datetime import datetime\nfrom model.group import Group\nfrom model.address import Address\nfrom pymysql.converters import encoders, decoders, convert_mysql_timestamp\n\n\nclass ORMFixture:\n db = Database()\n\n # описываем группы\n class ORMGroup(db.Entity):\n _table_ = 'group_list'\n id = PrimaryKey(int, column=\"group_id\")\n name = Optional(str, column=\"group_name\")\n header = Optional(str, column=\"group_header\")\n footer = Optional(str, column=\"group_footer\")\n contacts = Set(lambda: ORMFixture.ORMContact, table=\"address_in_groups\", column=\"id\", reverse=\"groups\", lazy=True)\n\n # описываем адрес\n class ORMContact(db.Entity):\n _table_ = \"addressbook\"\n # описание контактов\n id = PrimaryKey(int, column=\"id\")\n firstname = Optional(str, column=\"firstname\")\n lastname = Optional(str, column=\"lastname\")\n deprecated = Optional(str, column=\"deprecated\")\n middlename = Optional(str, column=\"middlename\")\n nickname = Optional(str, column=\"nickname\")\n company = Optional(str, column=\"company\")\n title = Optional(str, column=\"title\")\n address = Optional(str, column=\"address\")\n home = Optional(str, column=\"home\")\n mobile = Optional(str, column=\"mobile\")\n work = Optional(str, column=\"work\")\n fax = Optional(str, column=\"fax\")\n email = Optional(str, column=\"email\")\n email2 = Optional(str, column=\"email2\")\n email3 = Optional(str, column=\"email3\")\n homepage = Optional(str, column=\"homepage\")\n bday = Optional(str, column=\"bday\")\n bmonth = Optional(str, column=\"bmonth\")\n byear = Optional(str, column=\"byear\")\n aday = Optional(str, column=\"aday\")\n amonth = Optional(str, column=\"amonth\")\n ayear = Optional(str, column=\"ayear\")\n address2 = Optional(str, column=\"address2\")\n phone2 = Optional(str, column=\"phone2\")\n notes = Optional(str, column=\"notes\")\n photo = Optional(str, column=\"photo\")\n groups = Set(lambda: ORMFixture.ORMGroup, table=\"address_in_groups\", column=\"group_id\", reverse=\"contacts\", lazy=True)\n\n\n def __init__(self, host, name, user, password):\n conv = encoders\n conv.update(decoders)\n conv[datetime] = convert_mysql_timestamp\n self.db.bind('mysql', host=host, database=name, user=user, password=password, conv=conv)\n self.db.generate_mapping()\n\n # конвертация после выборки\n def convert_groups_to_model(self, groups):\n def convert(group):\n return Group(index=str(group.id), name=group.name, header=group.header, footer=group.footer)\n return list(map(convert, groups))\n\n # конвертация после выборки\n def convert_contacts_to_model(self, contacts):\n def convert(contact):\n return Address(id=str(contact.id), first_name=contact.firstname, last_name=contact.lastname,\n middle_name=contact.middlename, nick_name=contact.nickname, company=contact.company,\n title=contact.title, adress=contact.address, home_number=contact.home,\n mobile_number=contact.mobile, bday_day=contact.bday, bday_month=contact.bmonth,\n bday_year=contact.byear, aday_day=contact.aday, aday_month=contact.amonth,\n aday_year=contact.ayear, address_2=contact.address2, home_phone_2=contact.phone2,\n notes_2=contact.notes, path_to_foto=contact.photo\n )\n return list(map(convert, contacts))\n\n # конвертация после выборки\n def convert_contacts_to_model_web(self, contacts):\n def convert(contact):\n return Address(id=str(contact.id), first_name=contact.firstname, last_name=contact.lastname,\n adress=contact.address,\n all_emails=contact.email + '\\n' + contact.email2 + '\\n' + contact.email3,\n all_phones_from_page=contact.home + '\\n' +contact.mobile+ '\\n' +\n contact.work+ '\\n' +contact.phone2\n )\n\n return list(map(convert, contacts))\n\n # список групп\n # декоратор нужен\n @db_session\n def get_group_list(self):\n return self.convert_groups_to_model((select(g for g in ORMFixture.ORMGroup)))\n\n # список контактов\n @db_session\n def get_contact_list(self):\n return self.convert_contacts_to_model((select(c for c in ORMFixture.ORMContact if c.deprecated is None)))\n\n # список контактов с главной страницы\n @db_session\n def get_contact_list_for_web(self):\n return self.convert_contacts_to_model_web((select(c for c in ORMFixture.ORMContact if c.deprecated is None)))\n\n @db_session\n def contacts_in_group(self, group):\n orm_group = self.return_group(group)\n return self.convert_contacts_to_model(orm_group.contacts)\n\n\n def return_group(self, group):\n return list(select(g for g in ORMFixture.ORMGroup if g.id == group.id))[0]\n\n @db_session\n def get_contact_not_in_group(self, group):\n orm_group = self.return_group(group)\n return self.convert_contacts_to_model(select(c for c in ORMFixture.ORMContact if c.deprecated is None\n and orm_group not in c.groups))\n\n def destroy(self):\n self.db.disconnect()\n\n\n","sub_path":"fixture/orm.py","file_name":"orm.py","file_ext":"py","file_size_in_byte":5664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"241427239","text":"# coding=utf-8\nimport os\nimport cv2\nimport numpy as np\n\nprePoint = (-1, -1)\n\n\ndef onMouse(event, x, y, flags, param):\n global prePoint, floodImg\n if event == cv2.EVENT_LBUTTONUP or not (flags & cv2.EVENT_FLAG_LBUTTON):\n prePoint = (-1, -1)\n elif event == cv2.EVENT_LBUTTONDOWN:\n prePoint = (x, y)\n elif event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON):\n point = (x, y)\n if prePoint[0] < 0:\n prePoint = point\n cv2.line(mask, prePoint, point, (0, 0, 0), 2, 8, 0)\n cv2.line(image, prePoint, point, (255, 255, 255), 2, 8, 0)\n prePoint = point\n cv2.imshow(\"dcmjpg\", img)\n if event == cv2.EVENT_RBUTTONUP:\n cv2.floodFill(image, mask, (x, y), (0, 0, 0))\n dstImg = mask.array(image, mask=mask)\n cv2.imshow(\"dst\", dstImg)\n\n\nimage = cv2.imread(\"dcm.jpg\")\ncv2.imshow(\"image\",image)\nmask = np.zeros((np.array(image.shape)+2), np.uint8)\n# mask = np.zeros((130, 130, 130), np.uint8)\ncv2.setMouseCallback(\"image\", onMouse)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n","sub_path":"grabcutTrash.py","file_name":"grabcutTrash.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"440956978","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 16 11:03:28 2019\n\n@author: User\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\nimport os.path\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mtick\nimport matplotlib as mpl\nimport pylab as plb\nimport matplotlib.mlab as mlab\nimport math\nfrom numpy.random import seed\nimport random\nfrom IPython.core.pylabtools import figsize\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport seaborn as sns\n\nfigsize(14,10)\n#sns.set(rc={'axes.facecolor':'white', 'figure.facecolor':'white'})\nsns.set_style('white') \n\n# standard global constants\nMIN_AT_BATS = 0\nSTART_YEAR = 1970\nEND_YEAR = 2018\nFSHZ = 17\nSTART_DATE = datetime.strptime(str(START_YEAR)+'-01-01','%Y-%m-%d')\nEND_DATE = datetime.strptime(str(END_YEAR)+'-12-31','%Y-%m-%d')\nLEGEND_PROPERTIES = {'weight':'bold'}\n\n# general save file function\ndef save_stats_file(path, fn, df):\n stf = path + fn\n df.to_csv(stf, index=None, header=True)\n return True\n\n# custom split into training and test sets where a player will belong to one and only one set (training or testing).\ndef split_players(df,pct):\n random.seed(63)\n players = np.array(df.playerID.drop_duplicates())\n plen = len(players)\n indlst = random.sample(range(0,plen), round(pct*plen))\n print('Number of Testing Players ' + str(round(plen*pct)))\n test_players = np.array(players[indlst])\n train_players = np.setdiff1d(players,test_players)\n return train_players, test_players\n\n# custom split into training and test sets\ndef split_df(df,pct):\n train_p, test_p = split_players(df,pct)\n df_train = df[df.playerID.isin(train_p)]\n df_test = df[df.playerID.isin(test_p)]\n return df_train, df_test\n\ndef nprojections(dfproj,yrs,pyrs):\n print('in nprojecttions')\n plst = np.array(dfproj.playerID.drop_duplicates())\n dfpred = pd.DataFrame()\n i = -1\n for p in plst:\n yrlst = np.array(dfproj[dfproj['playerID'] == p]['yearID'].sort_values())\n agelst = np.array(dfproj[dfproj['playerID'] == p]['age'].sort_values())\n print(p)\n# print(yrlst)\n #\n # lag1 prior year\n #\n i = i + 1\n dfpred.loc[i,'yearnum'] = yrs+1\n dfpred.loc[i,'yearID'] = yrlst[yrs]\n dfpred.loc[i,'playerID'] = p \n dfpred.loc[i,'age'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs] ) & ( dfproj['playerID'] == p )]['age'].values[0]\n dfpred.loc[i,'OPS'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs] ) & ( dfproj['playerID'] == p )]['OPS'].values[0]\n dfpred.loc[i,'cOPS'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs] ) & ( dfproj['playerID'] == p )]['cOPS'].values[0]\n \n dfpred.loc[i,'lag1_OPS'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs-1] ) & ( dfproj['playerID'] == p )]['OPS'].values[0]\n dfpred.loc[i,'lag1_OBP'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs-1] ) & ( dfproj['playerID'] == p )]['OBP'].values[0]\n dfpred.loc[i,'lag1_OBP_OB'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs-1] ) & ( dfproj['playerID'] == p )]['OBP_OB'].values[0]\n dfpred.loc[i,'lag1_OBP_PA'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs-1] ) & ( dfproj['playerID'] == p )]['OBP_PA'].values[0]\n dfpred.loc[i,'lag1_SLG'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs-1] ) & ( dfproj['playerID'] == p )]['SLG'].values[0]\n dfpred.loc[i,'lag1_TB'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs-1] ) & ( dfproj['playerID'] == p )]['TB'].values[0]\n dfpred.loc[i,'lag1_H'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs-1] ) & ( dfproj['playerID'] == p )]['H'].values[0]\n dfpred.loc[i,'lag1_HR'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs-1] ) & ( dfproj['playerID'] == p )]['HR'].values[0]\n dfpred.loc[i,'lag1_AB'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs-1] ) & ( dfproj['playerID'] == p )]['AB'].values[0]\n\n\n dfpred.loc[i,'lag1_cOPS'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs-1] ) & ( dfproj['playerID'] == p )]['cOPS'].values[0]\n dfpred.loc[i,'lag1_cOBP'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs-1] ) & ( dfproj['playerID'] == p )]['cOBP'].values[0]\n dfpred.loc[i,'lag1_cOBP_OB'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs-1] ) & ( dfproj['playerID'] == p )]['cOB'].values[0]\n dfpred.loc[i,'lag1_cOBP_PA'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs-1] ) & ( dfproj['playerID'] == p )]['cPA'].values[0]\n dfpred.loc[i,'lag1_cSLG'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs-1] ) & ( dfproj['playerID'] == p )]['cSLG'].values[0]\n dfpred.loc[i,'lag1_cTB'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs-1] ) & ( dfproj['playerID'] == p )]['cTB'].values[0]\n dfpred.loc[i,'lag1_cH'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs-1] ) & ( dfproj['playerID'] == p )]['cH'].values[0]\n dfpred.loc[i,'lag1_cHR'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs-1] ) & ( dfproj['playerID'] == p )]['cHR'].values[0]\n dfpred.loc[i,'lag1_cAB'] = dfproj[ ( dfproj['yearID'] == yrlst[yrs-1] ) & ( dfproj['playerID'] == p )]['cAB'].values[0]\n \n for idx in range(yrs+1, yrs + pyrs):\n i = i + 1\n dfpred.loc[i,'yearnum'] = idx + 1\n dfpred.loc[i,'yearID'] = yrlst[idx]\n dfpred.loc[i,'playerID'] = p\n dfpred.loc[i,'OPS'] = dfproj[ ( dfproj['yearID'] == yrlst[idx] ) & ( dfproj['playerID'] == p )]['OPS'].values[0]\n dfpred.loc[i,'cOPS'] = dfproj[ ( dfproj['yearID'] == yrlst[idx] ) & ( dfproj['playerID'] == p )]['cOPS'].values[0]\n dfpred.loc[i,'age'] = df[ ( df['yearID'] == yrlst[idx] ) & ( df['playerID'] == p )]['age'].values[0]\n #\n # lag1 prior\n #\n dfpred.loc[i,'lag1_OPS'] = dfpred[ ( dfpred['yearID'] == yrlst[idx-1] ) & ( dfpred['playerID'] == p )]['lag1_OPS'].values[0]\n dfpred.loc[i,'lag1_OBP'] = dfpred[ ( dfpred['yearID'] == yrlst[idx-1] ) & ( dfpred['playerID'] == p )]['lag1_OBP'].values[0] \n dfpred.loc[i,'lag1_OBP_OB'] = dfpred[ ( dfpred['yearID'] == yrlst[idx-1] ) & ( dfpred['playerID'] == p )]['lag1_OBP_OB'].values[0]\n dfpred.loc[i,'lag1_OBP_PA'] = dfpred[ ( dfpred['yearID'] == yrlst[idx-1] ) & ( dfpred['playerID'] == p )]['lag1_OBP_PA'].values[0]\n dfpred.loc[i,'lag1_SLG'] = dfpred[ ( dfpred['yearID'] == yrlst[idx-1] ) & ( dfpred['playerID'] == p )]['lag1_SLG'].values[0]\n dfpred.loc[i,'lag1_TB'] = dfpred[ ( dfpred['yearID'] == yrlst[idx-1] ) & ( dfpred['playerID'] == p )]['lag1_TB'].values[0] \n dfpred.loc[i,'lag1_H'] = dfpred[ ( dfpred['yearID'] == yrlst[idx-1] ) & ( dfpred['playerID'] == p )]['lag1_H'].values[0]\n dfpred.loc[i,'lag1_HR'] = dfpred[ ( dfpred['yearID'] == yrlst[idx-1] ) & ( dfpred['playerID'] == p )]['lag1_HR'].values[0] \n dfpred.loc[i,'lag1_AB'] = dfpred[ ( dfpred['yearID'] == yrlst[idx-1] ) & ( dfpred['playerID'] == p )]['lag1_AB'].values[0] \n \n\n dfpred.loc[i,'lag1_cOPS'] = dfpred[ ( dfpred['yearID'] == yrlst[idx-1] ) & ( dfpred['playerID'] == p )]['lag1_cOPS'].values[0] \n dfpred.loc[i,'lag1_cOBP'] = dfpred[ ( dfpred['yearID'] == yrlst[idx-1] ) & ( dfpred['playerID'] == p )]['lag1_cOBP'].values[0]\n dfpred.loc[i,'lag1_cOBP_OB'] = dfpred[ ( dfpred['yearID'] == yrlst[idx-1] ) & ( dfpred['playerID'] == p )]['lag1_cOBP_OB'].values[0] \n dfpred.loc[i,'lag1_cOBP_PA'] = dfpred[ ( dfpred['yearID'] == yrlst[idx-1] ) & ( dfpred['playerID'] == p )]['lag1_cOBP_PA'].values[0]\n dfpred.loc[i,'lag1_cSLG'] = dfpred[ ( dfpred['yearID'] == yrlst[idx-1] ) & ( dfpred['playerID'] == p )]['lag1_cSLG'].values[0]\n dfpred.loc[i,'lag1_cTB'] = dfpred[ ( dfpred['yearID'] == yrlst[idx-1] ) & ( dfpred['playerID'] == p )]['lag1_cTB'].values[0]\n dfpred.loc[i,'lag1_cH'] = dfpred[ ( dfpred['yearID'] == yrlst[idx-1] ) & ( dfpred['playerID'] == p )]['lag1_cH'].values[0] \n dfpred.loc[i,'lag1_cHR'] = dfpred[ ( dfpred['yearID'] == yrlst[idx-1] ) & ( dfpred['playerID'] == p )]['lag1_cHR'].values[0] \n dfpred.loc[i,'lag1_cAB'] = dfpred[ ( dfpred['yearID'] == yrlst[idx-1] ) & ( dfpred['playerID'] == p )]['lag1_cAB'].values[0] \n \n return dfpred\n \ndef calc_proj(df,dfaging):\n dfproj = df[['yearID','playerID','yearnum','age','OPS','OBP','SLG','H','HR','TB','AB','OBP_OB','OBP_PA']]\n return dfproj\n\ndef calc_aging(df):\n df = df[['yearID','age','OPS','OBP','SLG','H','HR','TB','AB','OBP_OB','OBP_PA']]\n dfpctchg_all = pd.DataFrame()\n for a in range(22,40,1):\n for y in range(1960,2019,1):\n dfcurr = df[ ( df['age'] == a ) & ( df['yearID'] < y ) & ( df['yearID'] >= y-5 ) ]\n dfcurr = dfcurr.groupby('age').mean()\n dfcurr = dfcurr.reset_index(drop=False)\n dfprev = df[ ( df['age'] == a-1 ) & ( df['yearID'] < y ) & ( df['yearID'] >= y-5 ) ]\n dfprev = dfprev.groupby('age').mean()\n dfprev = dfprev.reset_index(drop=False)\n dfpctchg = ( dfcurr - dfprev ) / dfprev\n dfpctchg['yearID'] = y \n dfpctchg['age'] = a\n dfpctchg_all = pd.concat([dfpctchg_all,dfpctchg])\n dfpctchg_all.columns =['age','yearID','OPSpctchg','OBPpctchg','SLGpctchg','Hpctchg','HRpctchg','TBpctchg','ABpctchg','OBP_OBpctchg','OBP_PApctchg']\n return dfpctchg_all\n \ndef assign_yearnum(df):\n plst = np.array(df.playerID.drop_duplicates()) \n for p in plst:\n yrIDlst = np.array(df[df['playerID'] == p]['yearID'])\n yrnum = 0\n for yrID in yrIDlst:\n yrnum += 1\n idx = df[ ( df['playerID'] == p ) & ( df['yearID'] == yrID ) ].index\n df.loc[idx,'yearnum'] = yrnum\n return df\n \ndef career_stats(df):\n playerlist = np.array(df.playerID.drop_duplicates())\n dfresults_all = pd.DataFrame()\n cnt = 0\n for p in playerlist:\n cnt += 1\n print(cnt,p)\n dfstats = df[ (df['playerID'] == p) ]\n yID_list = df[df['playerID'] == p]['yearID'].sort_values().values\n for i in range(0,len(yID_list)):\n dfresults = calc_career_stats(dfstats,yID_list[i])\n dfresults_all = dfresults_all.append(dfresults)\n return dfresults_all\n\ndef calc_career_stats(df,yr):\n dfkeep = [yr]\n dfcurr = df[df['yearID'] <= yr][['playerID','G','AB','H','1B','2B','3B','HR','SB','BB','SO','HBP','SF','RBI']]\n dfcurr = dfcurr.groupby('playerID').sum().reset_index(drop=False)\n dfcurr = calc_ops(dfcurr)\n dfcurr['yearID'] = dfkeep\n dfcurr = dfcurr.reset_index(drop=True)\n return dfcurr\n\ndef calc_ops(df): \n df['1B'] = df['H'] - ( df['2B'] + df['3B'] + df['HR'] ) \n df['TB'] = df['1B'] + (df['2B'] * 2) + (df['3B'] * 3) + (df['HR'] * 4) \n df['SLG'] = df['TB'] / df['AB']\n df['OBP_OB'] = ( df['H'] + df['BB'] + df['HBP'] )\n df['OBP_PA'] = ( df['AB'] + df['BB'] + df['SF'] + df['HBP'] ) \n df['OBP'] = df['OBP_OB'] / df['OBP_PA'] \n df['OPS'] = df['OBP'] + df['SLG'] \n df['AVG'] = df['H'] / df['AB']\n return df\n\n# set path for reading Lahman baseball statistics and read data from rttm dataset\npath = 'C:\\\\Users\\\\User\\\\Documents\\\\PAUL\\\\Springboard\\\\core\\\\'\nbattingf = path + 'dfbatting_player_stats_OPS_career.csv'\ndfbatting_player_stats = pd.read_csv(battingf)\n\nbattingf = path + 'dfbatting_player_stats_OPS.csv'\ndf_train = pd.read_csv(battingf)\n\ndf = dfbatting_player_stats\ndf = df.reset_index(drop=True)\ndf = df[df['yearID'] >= 1960 & ( df['AB'] >= 300 )]\n#\n#battingf = path + 'df_five_yr_train.csv'\n#df_train = pd.read_csv(battingf)\n#\n#battingf = path + 'df_five_yr_test.csv'\n#df_test = pd.read_csv(battingf)\n\npct = 0.20\n# custom train / test split on player boundaries. IE, a player will belong to one and only one set (training or test)\n# for a given run\n#df_train, df_test = split_df(df,pct)\ndf = df.drop('yearnum_x',axis=1)\ndf = df.rename(columns={'yearnum_y':'yearnum'})\ndf_yr = df[['playerID','yearID']]\ndf_yr = df_yr.groupby('playerID').count().reset_index(drop=False)\ndf_yr.columns = ['playerID','years_played']\ndf = df.drop(['years_played'],axis=1)\ndf = pd.merge(df,df_yr,on='playerID')\ndf_test = df[ ( df['years_played'] == 6 ) ]\n\n\n#save_stats_file(path,'df_ten_years.csv',df)\n#df = pd.read_csv(path + 'df_ten_years.csv')\n\n#df_test = df[ (df['yearnum'] >= 1) & (df['yearnum'] <= 5) ]\ndfvar = df_test[['playerID','OPS']]\ndfvar = dfvar.groupby('playerID').var().reset_index(drop=False)\ndfvar.columns = ['playerID','OPSvar']\ndftopvar = dfvar.sort_values('OPSvar',ascending=True).head(20)\nplst = np.array(dftopvar.playerID)\ndf_test = df_test[df_test['playerID'].isin(plst)]\ndf_train = df_train[~df_train['playerID'].isin(plst)]\nprint(df_test[df_test['playerID'].isin(plst)])\nprint(df_train[df_train['playerID'].isin(plst)])\nprint(df)\n\nsave_stats_file(path,'df_train_lowvar.csv',df_train)\nsave_stats_file(path,'df_test_lowvar.csv',df_test)\n\n# make a copy of df\ndf_copy = df.copy()\n\n#df_test_career = career_stats(df_test_copy)\n#df_test_career.columns = ['playerID','cG','cAB','cH','c1B','c2B','c3B','cHR','cSB','cBB','cSO','cHBP','cSF','cRBI','cTB','cSLG','cOBP_OB','cOBP_PA','cOBP','cOPS','cAVG','yearID']\n#df_test = pd.merge(df_test,df_test_career,on=['yearID','playerID'])\n#print(df_test)\n#print(df_test.info())\n\nyears=4\nprojectyears=2\n\n#dfaging = calc_aging(df)\n#save_stats_file(path, 'dfage_pctchg.csv', dfaging)\n#dfproj = calc_proj(df_test,dfaging)\n\ndfpred = nprojections(df_test,years,projectyears)\nsave_stats_file(path, 'df_projections_4_and_2_lv.csv', dfpred)\n\n\n\n\n\n\n\n","sub_path":"CapstoneP1/MachineLearning/BaseballConsistentvsNonConsistentPlayers.py","file_name":"BaseballConsistentvsNonConsistentPlayers.py","file_ext":"py","file_size_in_byte":13487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"443121543","text":"#EXERCISE 9.1\n#\n#\n#\n# EXAMPLE 1: The following program is an example from the lecture on how to use the\n# count.get(\"\", ) itiration for counting words.\n#\n#\n#counts = dict()\n#print(\"Enter a line of text: \")\n#line = input(\" \")\n#\n#words = line.split()\n#\n#print(\"Words: \", words)\n#\n#print(\"Counting....\")\n#for word in words:\n# counts[word] = counts.get(word, 0) + 1\n#print(\"Counts\", counts)\n#\n#\n# EXAMPLE 2: In this exmaple we are doing a for loop to show that it goes over\n# the keys in a dictionary and not the values. {\"key\" : value}\n#\n# Note: python can turn dictionaries into lists if you use the list(dict) on a\n# dictionary, and it will render the keys only, not the values; if you want the\n# to print out the values you can ask do so by uing the print(dict.values())\n# method; lastly you can use the print(dict.items()) to print out both the keys\n# and the vlues together as a list. Food for thought, what is a \"tuple\"?\n#\n#\n#counts = {\"chuck\" : 1, \"fred\" : 42, \"jan\" : 100}\n#for key in counts:\n# print(key, counts[key])\n#\n#\n# SOME DOPE SHIT THAT PYTHON DOES, IT CAN ITERATE OVER TWO ITERATION VARIABLES\n#\n#\n# The following is the code used in the last slide of 9.3, which should be\n# useful for the next assignment.\n#\n#\n#name = input(\"Enter file: \")\n#handle = open(name)\n\n#counts = dict()\n#for line in handle:\n# words = line.split()\n# for word in words:\n# counts[word] = counts.get(word,0) + 1\n\n#bigcount = None\n#bigword = None\n#for word,count in counts.items():\n# if bigcount is None or count > bigcount:\n# bigword = word\n# bigcount = count\n\n#print(bigword, bigcount)\n#\n#\n# Assignment 9.4 because i'm already late as fuck for this one.\n#\n# Write a program to read through the mbox-short.txt and figure out who has\n# sent the greatest number of mail messages. The program looks for \"From \"\n# lines and takes the second word of those lines as the person who sent the\n# mail. The program creates a Python dictionary that maps the sender's mail\n# address to a count of the number of times they appear in the file. After the\n# dictionary is produced, the program reads through the dictionary using a\n# maximum loop to find the most prolific committer.\n#\n#\nname = input(\"Enter file: \")\nfhand = open(name)\nwords = list()\n#count = 0\n\nfor line in fhand:\n if not line.startswith(\"From \"): continue\n line = line.split()\n words.append(line[1])\n# emails[words] = line[1]\n\ncounts = dict()\n\nfor word in words:\n counts[word] = counts.get(word, 0) + 1\n\nbigcount = None\nbigword = None\nfor email,counts in counts.items():\n if bigcount is None or counts > bigcount:\n bigword = email\n bigcount = counts\n\nprint(bigword, bigcount)\n# count = count + 1\n# print(words[1])\n#print(\"There were\", count, \"lines in the file with From as the first word\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#\n","sub_path":"Ex_9.py","file_name":"Ex_9.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"573125264","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport rospy\nfrom std_srvs.srv import Empty\nfrom gazebo_msgs.srv import GetModelState\nfrom sensor_msgs.msg import JointState\nfrom std_msgs.msg import Bool, Float64\nimport numpy as np\nfrom bd1_gazebo_env_interface.srv import Step, Reset, StepResponse, ResetResponse\nfrom tf.transformations import euler_from_quaternion\n\ndef unnorm(x, x_min, x_max): \n return ((x+1)/2)*(x_max-x_min) + x_min\n\nclass UniversalGazeboEnvironmentInterface(object):\n def __init__(self):\n \n rospy.init_node('simple_standup_gazebo_environment_interface')\n \n self.name = rospy.get_name()\n \n self.max_velocity_lim = 1.0\n \n # service clients\n rospy.wait_for_service('gazebo/reset_simulation')\n self.reset_sim_srv = rospy.ServiceProxy('gazebo/reset_simulation', Empty)\n \n rospy.wait_for_service('gazebo/get_model_state')\n self.get_model_state_srv = rospy.ServiceProxy('gazebo/get_model_state', GetModelState)\n \n # publishers\n self.head_pub = rospy.Publisher('head_servo_velocity_controller/command', Float64, queue_size = 1)\n \n self.neck_pub = rospy.Publisher('neck_servo_velocity_controller/command', Float64, queue_size = 1)\n \n self.up_r_pub = rospy.Publisher('leg_up_r_servo_velocity_controller/command', Float64, queue_size = 1)\n \n self.mid_r_pub = rospy.Publisher('leg_mid_r_servo_velocity_controller/command', Float64, queue_size = 1)\n \n self.feet_r_pub = rospy.Publisher('feet_r_servo_velocity_controller/command', Float64, queue_size = 1)\n \n self.up_l_pub = rospy.Publisher('leg_up_l_servo_velocity_controller/command', Float64, queue_size = 1)\n \n self.mid_l_pub = rospy.Publisher('leg_mid_l_servo_velocity_controller/command', Float64, queue_size = 1)\n \n self.feet_l_pub = rospy.Publisher('feet_l_servo_velocity_controller/command', Float64, queue_size = 1)\n \n # subscribers and data containers\n self.last_joint_states = None\n rospy.Subscriber(\"joint_states\", JointState, self.joint_states_cb)\n \n self.last_episode_fall = []\n rospy.Subscriber(\"fall_detector/fall\", Bool, self.fall_cb)\n \n # service servers\n rospy.Service(\"~reset\", Reset, self.reset_cb)\n rospy.Service(\"~step\", Step, self.step_cb)\n \n rospy.logwarn(\"[{}] ready!\".format(self.name))\n \n #\n # HIGH INTERFACE FUNCTIONS\n #\n def step_cb(self, req):\n # clear fall data \n self.last_episode_fall = []\n self.set_action(req.action)\n rospy.sleep(req.step_duration_sec)\n state = self.get_state()\n return StepResponse(state, self.get_reward(state), self.check_done())\n \n def reset_cb(self, req):\n self.pub_action(0., 0., 0.)\n self.reset_sim_srv() \n return ResetResponse(self.get_state())\n \n #\n # LOW INTERFACE FUNCTIONS\n # \n def set_action(self, action):\n feet_v = unnorm(action[0], -self.max_velocity_lim, self.max_velocity_lim) \n mid_v = unnorm(action[1], -self.max_velocity_lim, self.max_velocity_lim)\n up_v = unnorm(action[2], -self.max_velocity_lim, self.max_velocity_lim)\n self.pub_action(feet_v, mid_v, up_v)\n \n def pub_action(self, feet_v, mid_v, up_v):\n self.feet_l_pub.publish(feet_v)\n self.feet_r_pub.publish(feet_v)\n self.mid_l_pub.publish(mid_v)\n self.mid_r_pub.publish(mid_v)\n self.up_l_pub.publish(up_v)\n self.up_r_pub.publish(up_v) \n \n def check_done(self):\n return True in self.last_episode_fall\n \n def get_reward(self, state):\n return -(0.3 - state[2])**2 \n \n def get_state(self):\n \n state = []\n \n # Model State \n model_state = self.get_model_state_srv(\"bd1\",\"\")\n state.append(model_state.pose.position.x)\n state.append(model_state.pose.position.y)\n state.append(model_state.pose.position.z)\n \n rpy = euler_from_quaternion([model_state.pose.orientation.x, model_state.pose.orientation.y, model_state.pose.orientation.z, model_state.pose.orientation.w]) \n state += rpy\n \n # Joints Positions\n state.append( self.last_joint_states.position[0] )\n state.append( self.last_joint_states.position[3] )\n state.append( self.last_joint_states.position[6] )\n \n # Joint Velocities\n state.append( self.last_joint_states.velocity[0] )\n state.append( self.last_joint_states.velocity[3] )\n state.append( self.last_joint_states.velocity[6] ) \n \n return state \n \n #\n # DATA COLLECTING\n #\n def joint_states_cb(self, msg):\n self.last_joint_states = msg\n \n def fall_cb(self, msg):\n self.last_episode_fall.append(msg.data)\n \n def run(self):\n rospy.spin()\n \nif __name__ == '__main__' :\n ugei = UniversalGazeboEnvironmentInterface()\n ugei.run()\n","sub_path":"bd1_gazebo_env_interface/src/simple_standup_gazebo_environment_inteface.py","file_name":"simple_standup_gazebo_environment_inteface.py","file_ext":"py","file_size_in_byte":5151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"521028545","text":"from elo_functions import *\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom sklearn import linear_model\n\neta = 1500 ###starting elo\nbeta = 400 # +- on your opponents rating\nkappa = 90\n\nfor kappa in [95]: #rejected 60 and 30 as non improvements\n for z in [0.85,0.9,0.95]: #also discard 0.1,0.3,0.5\n ## imports\n matches = pd.read_csv('data/french_l1.csv',index_col='id')\n t1 = matches.home_team_api_id.unique()\n elo = [eta]*len(t1)\n elo_df = pd.DataFrame({'team_id':t1, 'elo':elo},index=t1)\n ### run\n hyp = [eta,kappa,beta,z]\n full_elo_run(matches,elo_df,*hyp)\n matches['elo_diff'] = np.subtract(matches.elo_home,matches.elo_away)\n ### learn\n X = matches[['elo_home','elo_away','elo_diff']]\n Y = matches['D'] + 2*matches['AW'] #0 for HW, 1 for draw, 2 for AW\n X,Y = X[kappa:],Y[kappa:] \n logreg = linear_model.LogisticRegression(C=1e5)\n logreg.fit(X, Y)\n print(logreg.score(X,Y))\n \n \n\"\"\" \nScores are \n0.481 and 0.486\n+ elo diff\n===> no change\n### changing lengths of chunks does create problems\n### so perhaps using 20 is the way? 0.47 and 0.48 seem to agree\n### bug fix goes 0.485 vs 0.484\n\"\"\"","sub_path":"hyper_searching_for_elo.py","file_name":"hyper_searching_for_elo.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"401737404","text":"\nimport unittest\n\nimport paramak\nimport pytest\n\n\nclass test_ToroidalFieldCoilTripleArc(unittest.TestCase):\n def test_ToroidalFieldCoilTripleArc_creation_with_inner_leg(self):\n \"\"\"creates a tf coil with inner leg using the ToroidalFieldCoilTripleArc\n parametric component and checks that a cadquery solid is created\"\"\"\n\n test_shape = paramak.ToroidalFieldCoilTripleArc(\n R1=100,\n h=100,\n radii=(100, 200),\n coverages=(10, 60),\n thickness=10,\n distance=50,\n number_of_coils=1,\n vertical_displacement=10,\n with_inner_leg=True\n )\n assert test_shape.solid is not None\n assert test_shape.volume > 1000\n assert test_shape.inner_leg_connection_points is not None\n\n test_inner_leg = paramak.ExtrudeStraightShape(\n points=test_shape.inner_leg_connection_points, distance=0.5\n )\n assert test_inner_leg.solid is not None\n\n def test_ToroidalFieldCoilTripleArc_creation_no_inner_leg(self):\n \"\"\"creates a tf coil with no inner leg using the ToroidalFieldCoilRectangle\n parametric component and checks that a cadquery solid is created\"\"\"\n\n test_shape_1 = paramak.ToroidalFieldCoilTripleArc(\n R1=100, h=100, radii=(100, 200), coverages=(10, 60), thickness=10,\n distance=50, number_of_coils=1, vertical_displacement=10,\n with_inner_leg=True\n )\n test_volume_1 = test_shape_1.volume\n\n test_inner_leg = paramak.ExtrudeStraightShape(\n points=test_shape_1.inner_leg_connection_points, distance=50\n )\n inner_leg_volume = test_inner_leg.volume\n\n test_shape_2 = paramak.ToroidalFieldCoilTripleArc(\n R1=100, h=100, radii=(100, 200), coverages=(10, 60), thickness=10,\n distance=50, number_of_coils=1, vertical_displacement=10,\n with_inner_leg=False\n )\n assert test_shape_2.solid is not None\n assert test_shape_2.volume == pytest.approx(\n test_volume_1 - inner_leg_volume, rel=0.01)\n\n def test_ToroidalFieldCoilTripleArc_relative_volume(self):\n \"\"\"creates tf coil shapes with different numbers of tf coils and checks that\n their relative volumes are correct\"\"\"\n\n test_shape_1 = paramak.ToroidalFieldCoilTripleArc(\n R1=100, h=100, radii=(100, 200), coverages=(10, 60), thickness=10,\n distance=50, number_of_coils=1, vertical_displacement=10,\n with_inner_leg=True\n )\n test_volume_1 = test_shape_1.volume\n\n test_shape_2 = paramak.ToroidalFieldCoilTripleArc(\n R1=100, h=100, radii=(100, 200), coverages=(10, 60), thickness=10,\n distance=50, number_of_coils=8, vertical_displacement=10,\n with_inner_leg=True\n )\n assert test_shape_2.volume == pytest.approx(\n test_volume_1 * 8, rel=0.01)\n\n def test_ToroidalFieldCoilTripleArc_rotation_angle(self):\n \"\"\"Creates tf coils with rotation_angles < 360 in different workplanes\n and checks that the correct cuts are performed and their volumes are\n correct.\"\"\"\n\n test_shape = paramak.ToroidalFieldCoilTripleArc(\n R1=150,\n h=200,\n radii=(50, 50),\n coverages=(70, 70),\n thickness=50,\n distance=50,\n number_of_coils=8,\n )\n\n test_shape.rotation_angle = 360\n test_shape.workplane = \"XZ\"\n test_volume = test_shape.volume\n test_shape.rotation_angle = 180\n assert test_shape.volume == pytest.approx(test_volume * 0.5, rel=0.01)\n\n test_shape.rotation_angle = 360\n test_shape.workplane = \"YZ\"\n test_volume = test_shape.volume\n test_shape.rotation_angle = 180\n assert test_shape.volume == pytest.approx(test_volume * 0.5, rel=0.01)\n\n # this test will remain commented until workplane issue #308 is resolved\n # currently causes terminal to crash due to large number of unions\n # test_shape.rotation_angle = 360\n # test_shape.workplane = \"XY\"\n # test_volume = test_shape.volume\n # test_shape.rotation_angle = 180\n # assert test_shape.volume == pytest.approx(test_volume * 0.5)\n","sub_path":"tests/test_parametric_components/test_ToroidalFieldCoilTripleArc.py","file_name":"test_ToroidalFieldCoilTripleArc.py","file_ext":"py","file_size_in_byte":4299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"566942042","text":"import torch\nimport torch.nn as nn\n\n\nclass _DCR_block(nn.Module):\n def __init__(self, channel_in):\n super(_DCR_block, self).__init__()\n\n self.conv1 = nn.Conv2d(in_channels=channel_in, out_channels=int(channel_in / 2.), kernel_size=3, stride=1,\n padding=1)\n self.relu1 = nn.PReLU()\n self.conv2 = nn.Conv2d(in_channels=int(channel_in * 3 / 2.), out_channels=int(channel_in / 2.), kernel_size=3,\n stride=1, padding=1)\n self.relu2 = nn.PReLU()\n self.conv3 = nn.Conv2d(in_channels=channel_in * 2, out_channels=channel_in, kernel_size=3,\n stride=1, padding=1)\n self.relu3 = nn.PReLU()\n\n def forward(self, x):\n\n out1 = self.relu1(self.conv1(x))\n\n out = self.relu2(self.conv2(torch.cat([x, out1], 1)))\n\n out = self.relu3(self.conv3(torch.cat([x, out1, out], 1)))\n\n out = torch.add(out, x)\n\n return out\n \n\nclass _down(nn.Module):\n def __init__(self, channel_in):\n super(_down, self).__init__()\n\n self.relu = nn.PReLU()\n self.maxpool = nn.MaxPool2d(2)\n self.conv = nn.Conv2d(in_channels=channel_in, out_channels=2 * channel_in, kernel_size=1, stride=1, padding=0)\n\n def forward(self, x):\n \n out = self.maxpool(x)\n\n out = self.relu(self.conv(out))\n\n return out\n\n\nclass _up(nn.Module):\n def __init__(self, channel_in):\n super(_up, self).__init__()\n\n self.relu = nn.PReLU()\n self.subpixel = nn.PixelShuffle(2)\n self.conv = nn.Conv2d(in_channels=channel_in, out_channels=channel_in, kernel_size=1, stride=1, padding=0)\n\n def forward(self, x):\n \n out = self.relu(self.conv(x))\n\n out = self.subpixel(out)\n\n return out\n\n\nclass DHDN(nn.Module):\n def __init__(self, inchannel, outchannel):\n super(DHDN, self).__init__()\n cn = 30\n self.conv_i = nn.Conv2d(in_channels=inchannel, out_channels=cn, kernel_size=1, stride=1, padding=0)\n self.relu1 = nn.PReLU()\n self.DCR_block11 = self.make_layer(_DCR_block, cn)\n self.down1 = self.make_layer(_down, cn)\n self.DCR_block21 = self.make_layer(_DCR_block, cn * 2)\n self.down2 = self.make_layer(_down, cn * 2)\n self.DCR_block31 = self.make_layer(_DCR_block, cn * 4)\n self.down3 = self.make_layer(_down, cn * 4)\n self.DCR_block41 = self.make_layer(_DCR_block, cn * 8)\n self.down4 = self.make_layer(_down, cn * 8)\n self.DCR_block51 = self.make_layer(_DCR_block, cn * 16)\n self.up4 = self.make_layer(_up, cn * 32)\n self.DCR_block42 = self.make_layer(_DCR_block, cn * 16)\n self.up3 = self.make_layer(_up, cn * 16)\n self.DCR_block32 = self.make_layer(_DCR_block, cn * 8)\n self.up2 = self.make_layer(_up, cn * 8)\n self.DCR_block22 = self.make_layer(_DCR_block, cn * 4)\n self.up1 = self.make_layer(_up, cn * 4)\n self.DCR_block12 = self.make_layer(_DCR_block, cn * 2)\n self.conv_r = nn.Conv2d(in_channels=cn * 2, out_channels=cn, kernel_size=1, stride=1, padding=0)\n self.relu2 = nn.PReLU()\n self.conv_f = nn.Conv2d(in_channels=cn, out_channels=outchannel, kernel_size=1, stride=1, padding=0)\n self.relu3 = nn.PReLU()\n\n def make_layer(self, block, channel_in):\n layers = []\n layers.append(block(channel_in))\n return nn.Sequential(*layers)\n\n def forward(self, x):\n\n residual = self.relu1(self.conv_i(x))\n\n conc1 = self.DCR_block11(residual)\n\n out = self.down1(conc1)\n\n conc2 = self.DCR_block21(out)\n\n out = self.down2(conc2)\n\n conc3 = self.DCR_block31(out)\n\n out = self.down3(conc3)\n\n conc4 = self.DCR_block41(out)\n\n conc5 = self.down4(conc4)\n\n out = self.DCR_block51(conc5)\n\n out = self.up4(torch.cat([conc5, out], 1))\n\n out = self.DCR_block42(torch.cat([conc4, out], 1))\n\n out = self.up3(out)\n\n out = self.DCR_block32(torch.cat([conc3, out], 1))\n\n out = self.up2(out)\n\n out = self.DCR_block22(torch.cat([conc2, out], 1))\n\n out = self.up1(out)\n\n out = self.DCR_block12(torch.cat([conc1, out], 1))\n\n out = self.relu2(self.conv_r(out))\n\n out = torch.add(residual, out)\n\n out = self.relu3(self.conv_f(out))\n\n return out\n","sub_path":"DHDN_12.py","file_name":"DHDN_12.py","file_ext":"py","file_size_in_byte":4398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"226359550","text":"import pandas as pd\nimport numpy as np\nimport csv\n\n# df = pd.read_csv('E:/work/myTensor/dataset2/DR-256-valid0-more/A/Property-A.csv')\n# print(df)\n\nwith open('test.csv', 'w') as f:\n writer = csv.writer(f, lineterminator='\\n')\n writer.writerow(['a', 'b', 'c'])\n writer.writerow([1,2,3])\n writer.writerow([4,5,6])\n writer.writerow([1,2,3])\n writer.writerow([1,2,3])\n\n# print(df['a'])\n\ndf = pd.read_csv('test.csv')\nprint(df)\nprint(df['a'].values)\nli = df['a'].values\nprint( 2 in li )\n# print(df['a'].values[-1])\n# a = np.average(np.array(df['a'].values))\n# print(a)\n# print(len(df.index))\n# print(len(df.columns))\n# print(df['a'].idxmax())\n\n# with open('test.csv', 'r') as f:\n","sub_path":"sub/pandas_test.py","file_name":"pandas_test.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"121498735","text":"from settings import DEVICE, reproducibility_setup, RANDOM_STATE\n\nreproducibility_setup()\n\nimport argparse\nimport os\nimport torch\n\nfrom processing import TokenClassificationModel, GazeTester, GazeDataLoader, Config, GazeDataset, \\\n create_tokenizer, load_json, LOGGER\n\n\ndef main(args):\n data_gaze_dir = args.data_gaze_dir\n results_gaze_dir = args.results_gaze_dir\n tasks = args.tasks\n\n cf = Config.load_json(os.path.join(results_gaze_dir, \"config.json\"))\n\n tokenizer = create_tokenizer(cf.model_pretrained)\n\n for task in tasks:\n\n if args.test_task is None:\n test_task = task\n else:\n test_task = args.test_task\n\n results_task_dir = os.path.join(results_gaze_dir, task)\n\n model_init_args = load_json(os.path.join(results_task_dir, \"model_init.json\"))\n model = TokenClassificationModel.init(cf, **model_init_args)\n if cf.finetune_on_gaze:\n # set finetune_on_gaze to False in the cf file loaded above to test the pretrained models without fine-tuning on eye-tracking data\n LOGGER.info(\"Fine-tuning on eye-tracking data!\")\n model.load_state_dict(torch.load(os.path.join(results_task_dir, \"model-\"+str(RANDOM_STATE)+\".pth\")))\n else:\n LOGGER.info(\"NOT fine-tuning on eye-tracking data!\")\n\n d = GazeDataset(cf, tokenizer, os.path.join(data_gaze_dir, test_task), test_task)\n d.read_pipeline()\n\n dl = GazeDataLoader(cf, d.numpy[\"test\"], d.target_pad, mode=\"test\")\n\n tester = GazeTester(model, dl, DEVICE, task)\n tester.evaluate()\n\n eval_dir = os.path.join(results_gaze_dir, task)\n tester.save_preds(os.path.join(eval_dir, \"preds-\"+str(RANDOM_STATE)+\"-\"+cf.model_pretrained.replace(\"/\",\"\")+\".csv\"))\n tester.save_logs(os.path.join(eval_dir, \"results.\"+str(RANDOM_STATE)+\"-\"+cf.model_pretrained.replace(\"/\",\"\")+\".log\"))\n LOGGER.info(f\"Testing completed, training on task {task}, testing on {test_task}\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-dg\", \"--data_gaze_dir\", type=str,\n default=\"../../data/gaze\")\n parser.add_argument(\"-rg\", \"--results_gaze_dir\", type=str,\n default=\"../../results/gaze\")\n parser.add_argument(\"-ts\", \"--tasks\", type=str, nargs=\"+\",\n default=[\"zuco\"])\n parser.add_argument(\"-tt\", \"--test_task\", type=str, default=None)\n args = parser.parse_args()\n main(args)\n","sub_path":"scripts/gaze/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"509410637","text":"#!/usr/bin/env python2\n\nimport os\nimport sys\ncurrent_dir = os.path.dirname( os.path.abspath( __file__ ) )\npystil_parent_path = os.path.abspath( current_dir + \"/..\" )\nif pystil_parent_path not in sys.path:\n sys.path.append( pystil_parent_path)\n\nimport pika\nimport pickle\nfrom pystil import config\n\nif __name__ == '__main__':\n # sys.stdout = open(os.devnull, \"w\")\n # sys.stderr = open(\"/var/log/pystil.err\", \"w\")\n\n config.freeze()\n connection = pika.BlockingConnection(\n pika.ConnectionParameters(host='localhost'))\n channel = connection.channel()\n channel.queue_declare(queue='pystil')\n channel_out = connection.channel()\n channel_out.queue_declare(queue='pystil_push')\n\n def callback(ch, method, properties, body):\n message = pickle.loads(body)\n visit = message.process()\n if visit:\n channel_out.basic_publish(\n exchange='', routing_key='pystil_push',\n body=pickle.dumps(visit))\n ch.basic_ack(delivery_tag=method.delivery_tag)\n\n channel.basic_consume(callback, queue='pystil')\n channel.start_consuming()\n","sub_path":"bin/datafeed.py","file_name":"datafeed.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"366107167","text":"'''Start with the list [8,9,10]. Do the following:\r\n(a) Set the second entry (index 1) to 17\r\n(b) Add 4, 5, and 6 to the end of the list\r\n(c) Remove the first entry from the list\r\n(d) Sort the list\r\n(e) Double the list\r\n(f) Insert 25 at index 3\r\nThe final list should equal [4,5,6,25,10,17,4,5,6,10,17]'''\r\n\r\nList=[8,9,10]\r\n\r\nList.insert(1,17)\r\nprint(\"The list after inserting 17..\",List,'\\n')\r\n\r\n\r\nList.append(4)\r\nList.append(5)\r\nList.append(6)\r\nprint(\"The list after appending 4,5,6 =\",List,'\\n')\r\n\r\nList.pop(1)\r\nprint(\"The list after remove first entry =\",List,'\\n')\r\n\r\nList.sort()\r\nprint(\"The sorted List=\",List,'\\n')\r\n\r\nList2=List\r\nList3=List+List2\r\nprint(\"The double the list=\",List3,'\\n')\r\n\r\nList3.insert(3,25)\r\n\r\nprint(\"The list after inserting 25..\",List3,'\\n')\r\n\r\n","sub_path":"list/asgn_list4.py","file_name":"asgn_list4.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"30749957","text":"\nimport json\nimport os\nimport pathlib\nimport shutil\nimport warnings\nfrom pathlib import Path\nfrom typing import List\n\nfrom paramak import get_neutronics_results_from_statepoint_file\n\ntry:\n import openmc\n from openmc.data import REACTION_NAME, REACTION_MT\nexcept ImportError:\n warnings.warn('OpenMC not found, NeutronicsModelFromReactor.simulate \\\n method not available', UserWarning)\n\ntry:\n import neutronics_material_maker as nmm\nexcept ImportError:\n warnings.warn(\"neutronics_material_maker not found, \\\n NeutronicsModelFromReactor.materials can't accept strings or \\\n neutronics_material_maker objects\", UserWarning)\n\n\nclass NeutronicsModel():\n \"\"\"Creates a neuronics model of the provided shape geometry with assigned\n materials, source and neutronics tallies. There are three methods\n available for producing the the DAGMC h5m file. The PyMoab option is able\n to produce non imprinted and non merged geometry so is more suited to\n individual components or reactors without touching surfaces. Trelis is\n the only method currently able to produce imprinted and merged DAGMC h5m\n geometry. PPP is a experimental route that has not been fully demonstrated\n yet but is partly intergrated to test this promising new method.\n make_watertight is also used to seal the DAGMC geoemtry produced by Trelis.\n Further details on imprinting and merging are available on the\n DAGMC homepage\n https://svalinn.github.io/DAGMC/usersguide/trelis_basics.html\n The Parallel-PreProcessor is an open-source tool available\n https://github.com/ukaea/parallel-preprocessor and can be used in\n conjunction with the OCC_faceter\n (https://github.com/makeclean/occ_faceter) to create imprinted and\n merged geometry while Trelis (also known as Cubit) is available from\n the CoreForm website https://www.coreform.com/ version 17.1 is the version\n of Trelis used when testing the Paramak code.\n\n Arguments:\n geometry (paramak.Shape, paramak.Rector): The geometry to convert to a\n neutronics model. e.g. geometry=paramak.RotateMixedShape() or\n reactor=paramak.BallReactor() .\n cell_tallies (list of string or int): the cell based tallies to calculate,\n options include TBR, heating, flux, MT numbers and OpenMC standard\n scores such as (n,Xa) which is helium production are also supported\n https://docs.openmc.org/en/latest/usersguide/tallies.html#scores\n materials (dict): Where the dictionary keys are the material tag\n and the dictionary values are either a string, openmc.Material,\n neutronics-material-maker.Material or\n neutronics-material-maker.MultiMaterial. All components within the\n geometry object must be accounted for. Material tags required\n for a Reactor or Shape can be obtained with .material_tags.\n mesh_tally_2d (list of str): the 2D mesh based tallies to calculate,\n options include heating and flux , MT numbers and OpenMC standard\n scores such as (n,Xa) which is helium production are also supported\n https://docs.openmc.org/en/latest/usersguide/tallies.html#scores\n mesh_tally_3d (list of str): the 3D mesh based tallies to calculate,\n options include heating and flux , MT numbers and OpenMC standard\n scores such as (n,Xa) which is helium production are also supported\n https://docs.openmc.org/en/latest/usersguide/tallies.html#scores\n fusion_power (float): the power in watts emitted by the fusion\n reaction recalling that each DT fusion reaction emitts 17.6 MeV or\n 2.819831e-12 Joules\n simulation_batches (int): the number of batch to simulate.\n simulation_particles_per_batch: (int): particles per batch.\n source (openmc.Source()): the particle source to use during the\n OpenMC simulation.\n merge_tolerance (float): the tolerance to use when merging surfaces.\n Defaults to 1e-4.\n faceting_tolerance (float): the tolerance to use when faceting surfaces.\n Defaults to 1e-1.\n mesh_2D_resolution (tuple of ints): The 3D mesh resolution in the height\n and width directions. The larger the resolution the finer the mesh\n and more computational intensity is required to converge each mesh\n element.\n mesh_3D_resolution (tuple of int): The 3D mesh resolution in the height,\n width and depth directions. The larger the resolution the finer the\n mesh and the more computational intensity is required to converge each\n mesh element.\n \"\"\"\n\n def __init__(\n self,\n geometry,\n source,\n materials,\n cell_tallies=None,\n mesh_tally_2d=None,\n mesh_tally_3d=None,\n simulation_batches: int = 100,\n simulation_particles_per_batch: int = 10000,\n max_lost_particles: int = 10,\n faceting_tolerance: float = 1e-1,\n merge_tolerance: float = 1e-4,\n mesh_2D_resolution: float = (400, 400),\n mesh_3D_resolution: float = (100, 100, 100),\n fusion_power: float = 1e9 # convert from watts to activity source_activity\n ):\n\n self.materials = materials\n self.geometry = geometry\n self.source = source\n self.cell_tallies = cell_tallies\n self.mesh_tally_2d = mesh_tally_2d\n self.mesh_tally_3d = mesh_tally_3d\n self.simulation_batches = simulation_batches\n self.simulation_particles_per_batch = simulation_particles_per_batch\n self.max_lost_particles = max_lost_particles\n self.faceting_tolerance = faceting_tolerance\n self.merge_tolerance = merge_tolerance\n self.mesh_2D_resolution = mesh_2D_resolution\n self.mesh_3D_resolution = mesh_3D_resolution\n self.fusion_power = fusion_power\n self.model = None\n self.results = None\n self.tallies = None\n self.output_filename = None\n self.statepoint_filename = None\n\n @property\n def faceting_tolerance(self):\n return self._faceting_tolerance\n\n @faceting_tolerance.setter\n def faceting_tolerance(self, value):\n if not isinstance(value, (int, float)):\n raise TypeError(\n \"NeutronicsModelFromReactor.faceting_tolerance should be a\\\n number (floats or ints are accepted)\")\n if value < 0:\n raise ValueError(\n \"NeutronicsModelFromReactor.faceting_tolerance should be a\\\n positive number\")\n self._faceting_tolerance = value\n\n @property\n def merge_tolerance(self):\n return self._merge_tolerance\n\n @merge_tolerance.setter\n def merge_tolerance(self, value):\n if not isinstance(value, (int, float)):\n raise TypeError(\n \"NeutronicsModelFromReactor.merge_tolerance should be a\\\n number (floats or ints are accepted)\")\n if value < 0:\n raise ValueError(\n \"NeutronicsModelFromReactor.merge_tolerance should be a\\\n positive number\")\n self._merge_tolerance = value\n\n @property\n def cell_tallies(self):\n return self._cell_tallies\n\n @cell_tallies.setter\n def cell_tallies(self, value):\n if value is not None:\n if not isinstance(value, list):\n raise TypeError(\n \"NeutronicsModelFromReactor.cell_tallies should be a\\\n list\")\n output_options = ['TBR', 'heating', 'flux', 'spectra'] + \\\n list(REACTION_MT.keys()) + list(REACTION_NAME.keys())\n for entry in value:\n if entry not in output_options:\n raise ValueError(\n \"NeutronicsModelFromReactor.cell_tallies argument\",\n entry,\n \"not allowed, the following options are supported\",\n output_options)\n self._cell_tallies = value\n\n @property\n def mesh_tally_2d(self):\n return self._mesh_tally_2d\n\n @mesh_tally_2d.setter\n def mesh_tally_2d(self, value):\n if value is not None:\n if not isinstance(value, list):\n raise TypeError(\n \"NeutronicsModelFromReactor.mesh_tally_2d should be a\\\n list\")\n output_options = ['heating', 'flux'] + \\\n list(REACTION_MT.keys()) + list(REACTION_NAME.keys())\n for entry in value:\n if entry not in output_options:\n raise ValueError(\n \"NeutronicsModelFromReactor.mesh_tally_2d argument\",\n entry,\n \"not allowed, the following options are supported\",\n output_options)\n self._mesh_tally_2d = value\n\n @property\n def mesh_tally_3d(self):\n return self._mesh_tally_3d\n\n @mesh_tally_3d.setter\n def mesh_tally_3d(self, value):\n if value is not None:\n if not isinstance(value, list):\n raise TypeError(\n \"NeutronicsModelFromReactor.mesh_tally_3d should be a\\\n list\")\n output_options = ['heating', 'flux'] + \\\n list(REACTION_MT.keys()) + list(REACTION_NAME.keys())\n for entry in value:\n if entry not in output_options:\n raise ValueError(\n \"NeutronicsModelFromReactor.mesh_tally_3d argument\",\n entry,\n \"not allowed, the following options are supported\",\n output_options)\n self._mesh_tally_3d = value\n\n @property\n def materials(self):\n return self._materials\n\n @materials.setter\n def materials(self, value):\n if not isinstance(value, dict):\n raise TypeError(\"NeutronicsModelFromReactor.materials should be a\\\n dictionary\")\n self._materials = value\n\n @property\n def simulation_batches(self):\n return self._simulation_batches\n\n @simulation_batches.setter\n def simulation_batches(self, value):\n if isinstance(value, float):\n value = int(value)\n if not isinstance(value, int):\n raise TypeError(\n \"NeutronicsModelFromReactor.simulation_batches should be an int\")\n if value < 2:\n raise ValueError(\n \"The minimum of setting for simulation_batches is 2\"\n )\n self._simulation_batches = value\n\n @property\n def simulation_particles_per_batch(self):\n return self._simulation_particles_per_batch\n\n @simulation_particles_per_batch.setter\n def simulation_particles_per_batch(self, value):\n if isinstance(value, float):\n value = int(value)\n if not isinstance(value, int):\n raise TypeError(\n \"NeutronicsModelFromReactor.simulation_particles_per_batch\\\n should be an int\")\n self._simulation_particles_per_batch = value\n\n def create_material(self, material_tag: str, material_entry):\n if isinstance(material_entry, str):\n openmc_material = nmm.Material(\n material_entry,\n material_tag=material_tag).openmc_material\n elif isinstance(material_entry, openmc.Material):\n # sets the material name in the event that it had not been set\n material_entry.name = material_tag\n openmc_material = material_entry\n elif isinstance(material_entry, (nmm.Material, nmm.MultiMaterial)):\n # sets the material tag in the event that it had not been set\n material_entry.material_tag = material_tag\n openmc_material = material_entry.openmc_material\n else:\n raise TypeError(\"materials must be either a str, \\\n openmc.Material, nmm.MultiMaterial or nmm.Material object \\\n not a \", type(material_entry), material_entry)\n return openmc_material\n\n def create_materials(self):\n # # checks all the required materials are present\n # for reactor_material in self.geometry.material_tags:\n # if reactor_material not in self.materials.keys():\n # raise ValueError(\n # \"material included by the reactor model has not \\\n # been added\", reactor_material)\n\n # # checks that no extra materials we added\n # for reactor_material in self.materials.keys():\n # if reactor_material not in self.geometry.material_tags:\n # raise ValueError(\n # \"material has been added that is not needed for this \\\n # reactor model\", reactor_material)\n\n openmc_materials = {}\n for material_tag, material_entry in self.materials.items():\n openmc_material = self.create_material(\n material_tag, material_entry)\n openmc_materials[material_tag] = openmc_material\n\n self.openmc_materials = openmc_materials\n\n self.mats = openmc.Materials(list(self.openmc_materials.values()))\n\n return self.mats\n\n def create_neutronics_geometry(self, method: str = None):\n \"\"\"Produces a dagmc.h5m neutronics file compatable with DAGMC\n simulations.\n\n Arguments:\n method: (str): The method to use when making the imprinted and\n merged geometry. Options are \"ppp\", \"trelis\", \"pymoab\" and\n None. Defaults to None.\n \"\"\"\n\n if method in ['ppp', 'trelis', 'pymoab']:\n os.system('rm dagmc_not_watertight.h5m')\n os.system('rm dagmc.h5m')\n elif method is None and Path('dagmc.h5m').is_file():\n print('Using previously made dagmc.h5m file')\n else:\n raise ValueError(\n \"the method using in create_neutronics_geometry \\\n should be either ppp, trelis, pymoab or None.\", method)\n\n if method == 'ppp':\n\n raise NotImplementedError(\n \"PPP + OCC Faceter / Gmesh option is under development and not \\\n ready to be implemented. Further details on the repositories \\\n https://github.com/makeclean/occ_faceter/ \\\n https://github.com/ukaea/parallel-preprocessor \")\n\n # TODO when the development is ready to test\n # self.geometry.export_stp()\n # self.geometry.export_neutronics_description()\n # # as the installer connects to the system python not the conda\n # # python this full path is needed for now\n # if os.system(\n # '/usr/bin/python3 /usr/bin/geomPipeline.py manifest.json') != 0:\n # raise ValueError(\n # \"geomPipeline.py failed, check PPP is installed\")\n\n # # TODO allow tolerance to be user controlled\n # if os.system(\n # 'occ_faceter manifest_processed/manifest_processed.brep') != 0:\n # raise ValueError(\n # \"occ_faceter failed, check occ_faceter is install and the \\\n # occ_faceter/bin folder is in the path directory\")\n # self._make_watertight()\n\n elif method == 'trelis':\n self.geometry.export_stp()\n self.geometry.export_neutronics_description()\n\n shutil.copy(\n src=pathlib.Path(__file__).parent.absolute() /\n 'make_faceteted_neutronics_model.py',\n dst=pathlib.Path().absolute())\n\n if not Path(\"make_faceteted_neutronics_model.py\").is_file():\n raise FileNotFoundError(\n \"The make_faceteted_neutronics_model.py was \\\n not found in the directory\")\n os.system(\"trelis -batch -nographics make_faceteted_neutronics_model.py \\\"faceting_tolerance='\" +\n str(self.faceting_tolerance) + \"'\\\" \\\"merge_tolerance='\" + str(self.merge_tolerance) + \"'\\\"\")\n\n if not Path(\"dagmc_not_watertight.h5m\").is_file():\n raise FileNotFoundError(\n \"The dagmc_not_watertight.h5m was not found \\\n in the directory, the Trelis stage has failed\")\n self._make_watertight()\n\n elif method == 'pymoab':\n\n self.geometry.export_h5m(\n filename='dagmc.h5m',\n tolerance=self.faceting_tolerance\n )\n return 'dagmc.h5m'\n\n def _make_watertight(self):\n \"\"\"Runs the DAGMC make_watertight script thatt seals the facetets of\n the geometry\"\"\"\n\n if not Path(\"dagmc_not_watertight.h5m\").is_file():\n raise ValueError(\n \"Failed to create a dagmc_not_watertight.h5m file\")\n\n if os.system(\n \"make_watertight dagmc_not_watertight.h5m -o dagmc.h5m\") != 0:\n raise ValueError(\n \"make_watertight failed, check DAGMC is install and the \\\n DAGMC/bin folder is in the path directory\")\n\n def create_neutronics_model(self, method: str = None):\n \"\"\"Uses OpenMC python API to make a neutronics model, including tallies\n (cell_tallies and mesh_tally_2d), simulation settings (batches,\n particles per batch).\n\n Arguments:\n method: (str): The method to use when making the imprinted and\n merged geometry. Options are \"ppp\", \"trelis\", \"pymoab\".\n Defaults to None.\n \"\"\"\n\n self.create_materials()\n\n self.create_neutronics_geometry(method=method)\n\n # this is the underlying geometry container that is filled with the\n # faceteted DGAMC CAD model\n self.universe = openmc.Universe()\n geom = openmc.Geometry(self.universe)\n\n # settings for the number of neutrons to simulate\n settings = openmc.Settings()\n settings.batches = self.simulation_batches\n settings.inactive = 0\n settings.particles = self.simulation_particles_per_batch\n settings.run_mode = \"fixed source\"\n settings.dagmc = True\n settings.photon_transport = True\n settings.source = self.source\n settings.max_lost_particles = self.max_lost_particles\n\n # details about what neutrons interactions to keep track of (tally)\n self.tallies = openmc.Tallies()\n\n if self.mesh_tally_3d is not None:\n mesh_xyz = openmc.RegularMesh(mesh_id=1, name='3d_mesh')\n mesh_xyz.dimension = self.mesh_3D_resolution\n mesh_xyz.lower_left = [\n -self.geometry.largest_dimension,\n -self.geometry.largest_dimension,\n -self.geometry.largest_dimension\n ]\n\n mesh_xyz.upper_right = [\n self.geometry.largest_dimension,\n self.geometry.largest_dimension,\n self.geometry.largest_dimension\n ]\n\n for standard_tally in self.mesh_tally_3d:\n score = standard_tally\n prefix = standard_tally\n mesh_filter = openmc.MeshFilter(mesh_xyz)\n tally = openmc.Tally(name=prefix + '_on_3D_mesh')\n tally.filters = [mesh_filter]\n tally.scores = [score]\n self.tallies.append(tally)\n\n if self.mesh_tally_2d is not None:\n\n # Create mesh which will be used for tally\n mesh_xz = openmc.RegularMesh(mesh_id=2, name='2d_mesh_xz')\n\n mesh_xz.dimension = [\n self.mesh_2D_resolution[1],\n 1,\n self.mesh_2D_resolution[0]\n ]\n\n mesh_xz.lower_left = [\n -self.geometry.largest_dimension,\n -1,\n -self.geometry.largest_dimension\n ]\n\n mesh_xz.upper_right = [\n self.geometry.largest_dimension,\n 1,\n self.geometry.largest_dimension\n ]\n\n mesh_xy = openmc.RegularMesh(mesh_id=3, name='2d_mesh_xy')\n mesh_xy.dimension = [\n self.mesh_2D_resolution[1],\n self.mesh_2D_resolution[0],\n 1\n ]\n\n mesh_xy.lower_left = [\n -self.geometry.largest_dimension,\n -self.geometry.largest_dimension,\n -1\n ]\n\n mesh_xy.upper_right = [\n self.geometry.largest_dimension,\n self.geometry.largest_dimension,\n 1\n ]\n\n mesh_yz = openmc.RegularMesh(mesh_id=4, name='2d_mesh_yz')\n mesh_yz.dimension = [\n 1,\n self.mesh_2D_resolution[1],\n self.mesh_2D_resolution[0]\n ]\n\n mesh_yz.lower_left = [\n -1,\n -self.geometry.largest_dimension,\n -self.geometry.largest_dimension\n ]\n\n mesh_yz.upper_right = [\n 1,\n self.geometry.largest_dimension,\n self.geometry.largest_dimension\n ]\n\n for standard_tally in self.mesh_tally_2d:\n score = standard_tally\n prefix = standard_tally\n\n for mesh_filter, plane in zip(\n [mesh_xz, mesh_xy, mesh_yz], ['xz', 'xy', 'yz']):\n mesh_filter = openmc.MeshFilter(mesh_filter)\n tally = openmc.Tally(name=prefix + '_on_2D_mesh_' + plane)\n tally.filters = [mesh_filter]\n tally.scores = [score]\n self.tallies.append(tally)\n\n if self.cell_tallies is not None:\n\n for standard_tally in self.cell_tallies:\n if standard_tally == 'TBR':\n score = '(n,Xt)' # where X is a wild card\n sufix = 'TBR'\n tally = openmc.Tally(name='TBR')\n tally.scores = [score]\n self.tallies.append(tally)\n self._add_tally_for_every_material(sufix, score)\n\n elif standard_tally == 'spectra':\n neutron_particle_filter = openmc.ParticleFilter([\n 'neutron'])\n photon_particle_filter = openmc.ParticleFilter(['photon'])\n energy_bins = openmc.mgxs.GROUP_STRUCTURES['CCFE-709']\n energy_filter = openmc.EnergyFilter(energy_bins)\n\n self._add_tally_for_every_material(\n 'neutron_spectra',\n 'flux',\n [neutron_particle_filter, energy_filter]\n )\n\n self._add_tally_for_every_material(\n 'photon_spectra',\n 'flux',\n [photon_particle_filter, energy_filter]\n )\n else:\n score = standard_tally\n sufix = standard_tally\n self._add_tally_for_every_material(sufix, score)\n\n # make the model from gemonetry, materials, settings and tallies\n self.model = openmc.model.Model(\n geom, self.mats, settings, self.tallies)\n\n def _add_tally_for_every_material(self, sufix: str, score: str,\n additional_filters: List = None) -> None:\n \"\"\"Adds a tally to self.tallies for every material.\n\n Arguments:\n sufix: the string to append to the end of the tally name to help\n identify the tally later.\n score: the openmc.Tally().scores value that contribute to the tally\n \"\"\"\n if additional_filters is None:\n additional_filters = []\n for key, value in self.openmc_materials.items():\n if key != 'DT_plasma':\n material_filter = openmc.MaterialFilter(value)\n tally = openmc.Tally(name=key + '_' + sufix)\n tally.filters = [material_filter] + additional_filters\n tally.scores = [score]\n self.tallies.append(tally)\n\n def simulate(self, verbose: bool = True, method: str = None,\n cell_tally_results_filename: str = 'results.json',\n threads: int = None):\n \"\"\"Run the OpenMC simulation. Deletes exisiting simulation output\n (summary.h5) if files exists.\n\n Arguments:\n verbose (Boolean, optional): Print the output from OpenMC (true)\n to the terminal and don't print the OpenMC output (false).\n Defaults to True.\n method (str): The method to use when making the imprinted and\n merged geometry. Options are \"ppp\", \"trelis\", \"pymoab\".\n Defaults to pymoab.\n threads (int, optional): Sets the number of OpenMP threads\n used for the simulation. None takes all available threads by\n default. Defaults to None.\n\n Returns:\n dict: the simulation output filename\n \"\"\"\n\n self.create_neutronics_model(method=method)\n\n # Deletes summary.h5m if it already exists.\n # This avoids permission problems when trying to overwrite the file\n os.system('rm summary.h5')\n os.system('rm statepoint.' + str(self.simulation_batches) + '.h5')\n\n # this removes any old file from previous simulations\n os.system('rm geometry.xml')\n os.system('rm materials.xml')\n os.system('rm settings.xml')\n os.system('rm tallies.xml')\n\n self.statepoint_filename = self.model.run(\n output=verbose, threads=threads\n )\n self.results = get_neutronics_results_from_statepoint_file(\n statepoint_filename=self.statepoint_filename,\n fusion_power=self.fusion_power\n )\n\n with open(cell_tally_results_filename, 'w') as outfile:\n json.dump(self.results, outfile, indent=4, sort_keys=True)\n\n return self.statepoint_filename\n","sub_path":"paramak/parametric_neutronics/neutronics_model.py","file_name":"neutronics_model.py","file_ext":"py","file_size_in_byte":26253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"597332719","text":"\n\nclass Board :\n '''\n The chess board is defied by ICCF numberic notation for ease of operation \n https://en.wikipedia.org/wiki/ICCF_numeric_notation\n the self.board attribute reutrns a dictionary with the ICCF number as the key to store the positions of all pieces currently on the board\n '''\n def __init__(self):\n self.build_board_squares()\n\n def build_board_squares(self):\n board_squares = {}\n i = 11 \n while i < 89:\n board_squares.update(self.build_column(i))\n i += 10\n self.board_positions = board_squares\n\n def build_column(self,column_index):\n column = {}\n index = column_index\n while index < column_index + 8:\n column[index] = 'EMPTY'\n index += 1 \n return column \n \n def pawn_start_positions(self,pawn):\n if pawn.colour == 'white' :\n pass\n\n\n\n\n \n","sub_path":"lib/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"488378549","text":"import boto3\nfrom airflow import DAG\nfrom airflow.contrib.operators.emr_create_job_flow_operator \\\n import EmrCreateJobFlowOperator\nfrom airflow.contrib.operators.emr_add_steps_operator \\\n import EmrAddStepsOperator\nfrom airflow.contrib.sensors.emr_step_sensor import EmrStepSensor\nfrom airflow.contrib.operators.emr_terminate_job_flow_operator \\\n import EmrTerminateJobFlowOperator\nfrom airflow.operators import PythonOperator\n\ndef clean_others_dag(\n parent_dag_name,\n task_id,\n aws_conn_id,\n emr_conn_id,\n config,\n *args, **kwargs):\n \"\"\"\n Returns a SubDAG which load data to all dimension tables\n Parameters:\n parent_dag_name (string): the parent DAG task id\n task_id (string): the SubDAG task_id\n redshift_conn_id (string): the redshift connection id\n Return:\n dag (DAG): the sub dag object \n \"\"\"\n\n dag = DAG(\n f\"{parent_dag_name}.{task_id}\",\n **kwargs\n )\n\n CLEAN_OTHER_JOB_FLOW_OVERRIDES = {\n 'Name': 'Clean_Other_Data_Cluster'\n }\n airport_clean_path = \"s3://{}/{}\".format(config['S3']['bucket_name'], config['CLEAN_DATA']['airport_key'])\n demo_clean_path = \"s3://{}/{}\".format(config['S3']['bucket_name'], config['CLEAN_DATA']['demo_key'])\n world_temp_clean_path = \"s3://{}/{}\".format(config['S3']['bucket_name'], config['CLEAN_DATA']['world_temp_key'])\n ports_clean_path = \"s3://{}/{}\".format(config['S3']['bucket_name'], config['CLEAN_DATA']['ports_key'])\n\n clean_airport_script_path = \"s3://{}/{}\".format(config['S3']['bucket_name'], config['SCRIPT']['clean_airport'])\n clean_demo_script_path=\"s3://{}/{}\".format(config['S3']['bucket_name'], config['SCRIPT']['clean_demo'])\n clean_world_temp_script_path=\"s3://{}/{}\".format(config['S3']['bucket_name'], config['SCRIPT']['clean_world_temp'])\n clean_ports_script_path=\"s3://{}/{}\".format(config['S3']['bucket_name'], config['SCRIPT']['clean_ports'])\n\n manifest_script_path = \"s3://{}/{}\".format(config[\"S3\"][\"bucket_name\"], config[\"SCRIPT\"][\"gen_manifest\"])\n\n CLEAN_DATA_STEPS = [\n {\n 'Name': 'clean_airport',\n 'ActionOnFailure': 'CONTINUE',\n 'HadoopJarStep': {\n 'Jar': 'command-runner.jar',\n 'Args': [\n 'spark-submit',\n clean_airport_script_path,\n config['SOURCE_DATA']['airport_path'],\n airport_clean_path\n ]\n }\n },\n {\n 'Name': 'clean_us_demo',\n 'ActionOnFailure': 'CONTINUE',\n 'HadoopJarStep': {\n 'Jar': 'command-runner.jar',\n 'Args': [\n 'spark-submit',\n clean_demo_script_path,\n config['SOURCE_DATA']['us_demo_path'],\n demo_clean_path\n ]\n }\n },\n {\n 'Name': 'clean_world_temp',\n 'ActionOnFailure': 'CONTINUE',\n 'HadoopJarStep': {\n 'Jar': 'command-runner.jar',\n 'Args': [\n 'spark-submit',\n clean_world_temp_script_path,\n config['SOURCE_DATA']['world_temp_path'],\n world_temp_clean_path\n ]\n }\n },\n {\n 'Name': 'clean_ports',\n 'ActionOnFailure': 'CONTINUE',\n 'HadoopJarStep': {\n 'Jar': 'command-runner.jar',\n 'Args': [\n 'spark-submit',\n clean_ports_script_path,\n config['SOURCE_DATA']['ports_path'],\n ports_clean_path\n ]\n }\n }\n ]\n\n create_clean_other_data_cluster = EmrCreateJobFlowOperator(\n task_id=\"create_clean_other_data_cluster\",\n job_flow_overrides=CLEAN_OTHER_JOB_FLOW_OVERRIDES,\n aws_conn_id=aws_conn_id,\n emr_conn_id=emr_conn_id,\n dag=dag\n )\n\n add_clean_other_data_step = EmrAddStepsOperator(\n task_id='add_clean_other_data_step',\n job_flow_id=\"{{ task_instance.xcom_pull('create_clean_other_data_cluster', key='return_value') }}\",\n aws_conn_id=aws_conn_id,\n steps=CLEAN_DATA_STEPS,\n dag=dag\n )\n\n # remove_clean_checker = EmrStepSensor(\n # task_id='check_step_remove',\n # job_flow_id=\"{{ task_instance.xcom_pull('create_clean_other_data_cluster', key='return_value') }}\",\n # step_id=\"{{ task_instance.xcom_pull('add_clean_other_data_step', key='return_value')[0] }}\",\n # aws_conn_id=aws_conn_id,\n # dag=dag\n # )\n\n clean_airport_checker = EmrStepSensor(\n task_id='check_step_clean_airport',\n job_flow_id=\"{{ task_instance.xcom_pull('create_clean_other_data_cluster', key='return_value') }}\",\n step_id=\"{{ task_instance.xcom_pull('add_clean_other_data_step', key='return_value')[0] }}\",\n aws_conn_id=aws_conn_id,\n dag=dag\n )\n clean_demo_checker = EmrStepSensor(\n task_id='check_step_clean_demo',\n job_flow_id=\"{{ task_instance.xcom_pull('create_clean_other_data_cluster', key='return_value') }}\",\n step_id=\"{{ task_instance.xcom_pull('add_clean_other_data_step', key='return_value')[1] }}\",\n aws_conn_id=aws_conn_id,\n dag=dag\n )\n clean_world_temp_checker = EmrStepSensor(\n task_id='check_step_clean_world_temp',\n job_flow_id=\"{{ task_instance.xcom_pull('create_clean_other_data_cluster', key='return_value') }}\",\n step_id=\"{{ task_instance.xcom_pull('add_clean_other_data_step', key='return_value')[2] }}\",\n aws_conn_id=aws_conn_id,\n dag=dag\n )\n clean_ports_checker = EmrStepSensor(\n task_id='check_step_clean_ports',\n job_flow_id=\"{{ task_instance.xcom_pull('create_clean_other_data_cluster', key='return_value') }}\",\n step_id=\"{{ task_instance.xcom_pull('add_clean_other_data_step', key='return_value')[3] }}\",\n aws_conn_id=aws_conn_id,\n dag=dag\n )\n\n other_data_cluster_remover = EmrTerminateJobFlowOperator(\n task_id='remove_emr_cluster',\n job_flow_id=\"{{ task_instance.xcom_pull('create_clean_other_data_cluster', key='return_value') }}\",\n aws_conn_id=aws_conn_id,\n dag=dag\n )\n\n create_clean_other_data_cluster >> add_clean_other_data_step\n\n add_clean_other_data_step >> clean_airport_checker >> clean_demo_checker >> clean_world_temp_checker >> clean_ports_checker\n \n clean_ports_checker >> other_data_cluster_remover\n\n return dag\n","sub_path":"airflow/dags/clean_others_subdag.py","file_name":"clean_others_subdag.py","file_ext":"py","file_size_in_byte":6611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"431218457","text":"def solution(h, w, n):\n div, mod = divmod(n, h)\n floor = mod\n number = div + 1\n\n if mod == 0:\n floor = h\n number -= 1\n\n if number < 10:\n result = str(floor) + '0' + str(number)\n else:\n result = str(floor) + str(number)\n return result\n\n\nT = int(input())\nfor _ in range(T):\n H, W, N = map(int, input().split())\n answer = solution(H, W, N)\n print(answer)\n","sub_path":"solved/hotel_acm.py","file_name":"hotel_acm.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"555654333","text":"from keras.utils import Sequence\nfrom typing import Tuple\nfrom routing.instance import *\nfrom utils.file_utils import *\nimport numpy as np\nimport tensorflow as tf\nfrom routing.constant import *\n\n\ndef mapper(instance: RoutingInstance) -> Tuple[List, List]:\n\ttraffic_matrix = []\n\tlabels = []\n\ttraffic_matrix.extend(instance.video)\n\tlabels.extend(instance.labels[\"video\"])\n\ttraffic_matrix.extend(instance.iot)\n\tlabels.extend(instance.labels[\"iot\"])\n\ttraffic_matrix.extend(instance.voip)\n\tlabels.extend(instance.labels[\"voip\"])\n\ttraffic_matrix.extend(instance.ar)\n\tlabels.extend(instance.labels[\"ar\"])\n\n\treturn traffic_matrix, labels\n\n\nclass ILPGenerator(Sequence):\n\tdef __init__(self, ilp_fns: List[str],\n\t id_: int,\n\t batch_size: int = 32,\n\t n_nodes: int = 66,\n\t n_ksp: int = 3,\n\t n_flows: int = 4):\n\t\tself.id = id_\n\t\tself.ilp_fns = ilp_fns\n\t\tself.batch_size = batch_size\n\t\tself.n_nodes = n_nodes\n\t\tself.n_ksp = n_ksp\n\t\tself.n_flows = n_flows\n\n\tdef __len__(self):\n\t\treturn 128 * len(self.ilp_fns) // self.batch_size\n\n\tdef __getitem__(self, flow_idx):\n\t\tn_batch_per_file = 128 // self.batch_size\n\t\tfile_idx = flow_idx // n_batch_per_file\n\t\toffset_in_file = flow_idx % n_batch_per_file\n\t\tfn = self.ilp_fns[file_idx]\n\t\t# debug(fn)\n\t\tbatch_instances = load_pkl(fn)[\n\t\t self.batch_size * offset_in_file:(offset_in_file + 1) * self.batch_size]\n\n\t\tbatch_x = []\n\t\tbatch_y = []\n\n\t\tn_nodes, n_ksp, n_flows = self.n_nodes, self.n_ksp, self.n_flows\n\t\tid_ = self.id\n\t\tfor instance in batch_instances:\n\t\t\tx, y = mapper(instance)\n\t\t\tbatch_x.append(x)\n\t\t\tbatch_y.append(y)\n\n\t\tbatch_x = np.asarray(batch_x)\n\t\tbatch_y = np.asarray(batch_y)\n\n\t\tbatch_y = np.reshape(batch_y, (-1, n_flows, n_nodes * (n_nodes - 1)))\n\t\tbatch_y = batch_y[:, :, id_ * (n_nodes - 1):(id_ + 1) * (n_nodes - 1)]\n\t\toutput = {}\n\t\tfor flow_idx in range(self.n_flows):\n\t\t\tname = \"output{}\".format(flow_idx)\n\t\t\toutput[name] = batch_y[:, flow_idx, :]\n\t\treturn batch_x, output\n\n\ndef get_ilp_generator(fns: List[str], model_id: int,batch_size=32) -> tf.data.Dataset:\n\tdef map_func1(instance: RoutingInstance):\n\t\ttraffic_matrix = []\n\t\tlabels = []\n\t\ttraffic_matrix.extend(instance.video)\n\t\tlabels.extend(\n\t\t\tinstance.labels[\"video\"][model_id * (n_nodes - 1):(model_id + 1) * (n_nodes - 1)])\n\t\ttraffic_matrix.extend(instance.iot)\n\t\tlabels.extend(\n\t\t\tinstance.labels[\"iot\"][model_id * (n_nodes - 1):(model_id + 1) * (n_nodes - 1)])\n\n\t\ttraffic_matrix.extend(instance.voip)\n\t\tlabels.extend(\n\t\t\tinstance.labels[\"voip\"][model_id * (n_nodes - 1):(model_id + 1) * (n_nodes - 1)])\n\n\t\ttraffic_matrix.extend(instance.ar)\n\t\tlabels.extend(\n\t\t\tinstance.labels[\"ar\"][model_id * (n_nodes - 1):(model_id + 1) * (n_nodes - 1)])\n\n\t\toutput = {}\n\t\tlabels = np.reshape(labels, (n_flows, n_nodes - 1))\n\n\t\tfor flow_idx in range(n_flows):\n\t\t\tname = \"output{}\".format(flow_idx)\n\t\t\toutput[name] = labels[flow_idx, :]\n\n\t\treturn np.asarray(traffic_matrix),output\n\t\t# return traffic_matrix,labels\n\n\t# def mapper2(traffic_matrix,labels):\n\t# \tlabels=np.asarray(labels)\n\t# \ttraffic_matrix=np.asarray(traffic_matrix)\n\t# \toutput = {}\n\t# \tlabels = np.reshape(labels, (n_flows, n_nodes - 1))\n\t#\n\t# \tfor flow_idx in range(n_flows):\n\t# \t\tname = \"output{}\".format(flow_idx)\n\t# \t\toutput[name] = labels[flow_idx, :]\n\t#\n\t# \treturn traffic_matrix, output\n\n\tdef generator():\n\t\tfile_idx = 0\n\t\tcurrent_instances: List[RoutingInstance] = []\n\t\tn_instances = 128 * len(fns)\n\t\tfile_offset=0\n\t\tfor instance_idx in range(n_instances):\n\t\t\tif instance_idx % 128 == 0:\n\t\t\t\tcurrent_instances = load_pkl(fns[file_idx])\n\t\t\t\tfile_idx += 1\n\t\t\t\tfile_offset=0\n\t\t\tres = current_instances[file_offset]\n\t\t\tfile_offset+=1\n\t\t\tyield map_func1(res)\n\n\toutput_types={}\n\tfor flow_idx in range(n_flows):\n\t\toutput_types[\"output{}\".format(flow_idx)]=tf.int8\n\n\tdataset = tf.data.Dataset.from_generator(generator=generator,\n\t output_types=(tf.float32,output_types))\n\tdataset = dataset.prefetch(tf.data.experimental.AUTOTUNE)\n\tdataset=dataset.batch(batch_size)\n\t# dataset=dataset.batch(batch_size).map(\n\t# \tmapper2,\n\t# \tnum_parallel_calls=tf.data.experimental.AUTOTUNE\n\t# )\n\tdataset=dataset.cache()\n\treturn dataset\n","sub_path":"routing/nn/dataset_generator.py","file_name":"dataset_generator.py","file_ext":"py","file_size_in_byte":4197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"222851752","text":"#!/usr/bin/env python3\n\nimport re\nimport collections\n\nif __name__ == '__main__':\n with open('input', 'r') as f:\n depth, = [int(i) for i in re.findall(r'\\d+', f.readline())]\n target = tuple([int(i) for i in re.findall(r'\\d+', f.readline())])\n\n def index(x, y, cache = {target:0}):\n if y == 0:\n cache[x, y] = x*16807\n if x == 0:\n cache[x, y] = y*48271\n if (x, y) in cache:\n return cache[(x, y)]\n return erosion(x-1, y)[0]*erosion(x, y-1)[0]\n\n def erosion(x, y, cache = {}):\n if (x, y) in cache:\n return cache[(x, y)]\n level = (index(x, y) + depth)%20183\n t = {0:'.',1:'=',2:'|'}[level%3]\n cache[x, y] = (level, t)\n return level, t\n\n def risk(x, y, cache = {}):\n if (x, y) in cache:\n return cache[(x, y)]\n _, t = erosion(x, y)\n cache[(x, y)] = {'.':0,'=':1,'|':2}[t]\n return cache[(x, y)]\n\n def risk_region(xi, yi, xf, yf):\n return sum(risk(x, y) for x in range(xi, xf + 1) for y in range(yi, yf + 1))\n\n print(risk_region(0, 0, target[0], target[1]))\n\n inf = float('inf')\n shortest = collections.defaultdict(lambda:{'torch':inf,'gear':inf,'neither':inf})\n shortest[(0,0)] = {'torch':0,'gear':7,'neither':inf}\n\n compatible = {'.':['torch','gear'],\n '=':['gear','neither'],\n '|':['torch','neither']}\n\n def neighbours(x, y):\n n = [(x + 1, y), (x - 1, y), (x, y - 1), (x, y + 1)]\n for xi, yi in n:\n if xi >= 0 and yi >= 0:\n yield xi, yi\n\n def change_gear(x, y):\n d = shortest[(x, y)]\n t = erosion(x, y)[1]\n ta, tb = sorted(compatible[t], key = lambda x : d[x])\n if d[ta] == inf:\n return\n d[tb] = min(d[tb], d[ta] + 7)\n\n def minimize(x, y):\n t = erosion(x, y)[1]\n for tool in compatible[t]:\n m = min(shortest[(xn, yn)][tool] for xn, yn in neighbours(x, y)) + 1\n shortest[(x, y)][tool] = min(shortest[(x, y)][tool], m)\n change_gear(x, y)\n \n search_buffer = 20 # might be larger to ensure shortest path found\n passes = 2\n for _ in range(passes):\n for y in range(target[1] + search_buffer):\n for x in range(target[0] + search_buffer):\n minimize(x, y)\n [minimize(xn, yn) for xn, yn in neighbours(x, y)]\n \n print(shortest[target]['torch'])\n\n","sub_path":"2018/day_22/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"372558120","text":"\nfrom EmbeddingRST import EmbeddingRST_model\nfrom feature_generation_train import ConvertSequence2Feature\nfrom model_evaluation import evaluation\n\nfrom keras.models import Sequential, Model\nfrom keras.layers import Input, Dense, Dropout, Activation, Lambda, Permute, Reshape, Flatten, Masking\nfrom keras.layers import Multiply, Dot, RepeatVector,Concatenate\nfrom keras.layers import Embedding\nfrom keras.layers import LSTM,Bidirectional,BatchNormalization\nfrom keras.layers import Conv1D, MaxPooling1D\nfrom keras.layers import TimeDistributed,Add\nfrom keras.models import load_model\n\nimport matplotlib.pyplot as plt\nfrom keras.utils import plot_model\nfrom keras.callbacks import TensorBoard\n\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\n\nimport os\nfrom feature_generation_train import ConvertSequence2Feature\nfrom model_evaluation import evaluation\n\ndata_all = pd.read_csv('AMPs_Experiment_Dataset\\\\AMP_sequecnces\\\\seq_all_data.csv', index_col=0)\n\ntrain = data_all.iloc[0:1424].reset_index(drop=True)\ntune = data_all.iloc[1424:2132].reset_index(drop=True)\ntest = data_all.iloc[2132:3556].reset_index(drop=True)\ntrain_tune = data_all.iloc[0:2132].reset_index(drop=True)\ntrain_tune_test = data_all.iloc[0:3556].reset_index(drop=True)\n\n\n\nx_train_index, x_train_length, x_train_pssm, x_train_onehot,x_train_aac,y_train = ConvertSequence2Feature(sequence_data=train, pssmdir=os.path.join('AMPs_Experiment_Dataset','PSSM_files','train'))\nx_test_index, x_test_length, x_test_pssm, x_test_onehot, x_test_aac, y_test = ConvertSequence2Feature(sequence_data=test, pssmdir=os.path.join('AMPs_Experiment_Dataset','PSSM_files','test'))\n#x_tune_index, x_tune_length, x_tune_pssm, x_tune_onehot,x_tune_aac,y_tune= ConvertSequence2Feature(sequence_data=tune, pssmdir=os.path.join('AMPs_Experiment_Dataset','PSSM_files','tune'))\n#x_train_tune_index, x_train_tune_length, x_train_tune_pssm, x_train_tune_onehot,x_train_tune_aac,y_train_tune= ConvertSequence2Feature(sequence_data=train_tune, pssmdir=os.path.join('AMPs_Experiment_Dataset','PSSM_files','train_tune'))\n#x_train_tune_test_index, x_train_tune_test_length, x_train_tune_test_pssm, x_train_tune_test_onehot,x_train_tune_test_aac,y_train_tune_test= ConvertSequence2Feature(sequence_data=train_tune_test, pssmdir=os.path.join('AMPs_Experiment_Dataset','PSSM_files','train_tune_test'))\n\n\n\nmodel = load_model('models//ACEP_model_train_241_9304.h5',\n custom_objects={'EmbeddingRST_model': EmbeddingRST_model})\nprint(model.evaluate([x_test_aac,x_test_onehot, x_test_pssm], y_test, batch_size=16, verbose=0))\nprint(model.summary())\n#plot_model(model, to_file='test1.png',show_shapes=True)\nevaluation(model.predict([x_test_aac,x_test_onehot, x_test_pssm]).flatten(), y_test)\n\n\n\nfrom sklearn.manifold import TSNE\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import silhouette_score\n\n\n\n#-------------------------attention intendity---------------------------------------------\nattention_weights = Model(inputs=model.input,\n outputs=model.get_layer('attention_weights_pm').output)\n#attention_weights.summary()\nx_pm_p= x_train_pssm[0:712]\nx_ot_p= x_train_onehot[0:712]\nx_aac_p= x_train_aac[0:712]\nattention_weights = attention_weights.predict([x_aac_p,x_ot_p,x_pm_p])\n\nmotifts_index = [245,206,356,67,26,18,135,105,216,269]\nattention_weights_p10 = attention_weights[motifts_index,:]\n\n#print(train.iloc[:,0])\n#print(attention_weights)\ncol_lab = list(range(1,41))\ncol_lab = ['P'+\"{:0>2d}\".format(i) for i in col_lab]\ncol_lab.insert(0,'Sequences')\nattention_seq = pd.DataFrame(data = np.hstack([train.iloc[0:712,0].values.reshape(-1,1),attention_weights]),\n columns=col_lab)\n#print(attention_motifs)\n# print(np.max(attention_weights.flatten()))\n# print(np.min(attention_weights.flatten()))\n# print(np.mean(attention_weights.flatten()))\nattention_seq.to_csv('experiment_results\\\\attention_motifs.csv',index=False)\n\nmotifs_list = []\nattention_motifs_np = attention_seq.values\nfor i in range(712):\n for j in range(1,41):\n if attention_motifs_np[i,j]>= 0.2:\n sequence_str = attention_motifs_np[i,0]\n str_end = (40-j)*5\n if str_end+5 <= len(sequence_str) and str_end != 0:\n hit_str = sequence_str[-(str_end+5):-(str_end)]\n else:\n if str_end == 0:\n hit_str = sequence_str[-(str_end+5):]\n else:\n hit_str = sequence_str[0:-str_end]\n hit_str = '-'*(5-len(hit_str)) + hit_str\n #print(hit_str)\n motifs_list.append([hit_str,1])\n\n#print(motifs_list)\n\ndef str_align(x,y,str1_len,str2_len):\n count = 0\n #print(x,' ',y)\n for i in range(str1_len):\n iter_len1 = str1_len-(i+1)\n pos = y.find(x[i],0,str2_len)\n if pos != -1:\n iter_len2 = str2_len-(pos+1)\n if iter_len1>0 and iter_len2>0:\n count = str_align(x[i+1:],y[pos+1:],iter_len1,iter_len2)\n return count + 1\n return count\n\ndef find_align(s1,s2,max_align):\n for i in range(len(s1)-max_align+1):\n align_length = str_align(s1[i:],s2,len(s1[i:]),len(s2))\n #print(align_length)\n if align_length>=max_align:\n return True\n return False\n\n#find_align('a0bcde000','120ab000c',4)\n\n\nmotifs_group = []\nmotifs_group_count = []\nmotifs_list_len = len(motifs_list)\nfor i in range(motifs_list_len-1):\n if motifs_list[i][1] == 1:\n one_group = [motifs_list[i][0]]\n one_count = 1\n for j in range(i+1,motifs_list_len):\n if motifs_list[j][1] == 1 and find_align(motifs_list[i][0],motifs_list[j][0],3):\n one_group.append(motifs_list[j][0])\n one_count = one_count+1\n motifs_list[j][1] = 0\n motifs_group.append(one_group)\n motifs_group_count.append(one_count)\nif motifs_list[-1][1]==1:\n motifs_group.append(motifs_list[-1][1])\n motifs_group_count.append(1)\n\n#print(motifs_group)\n#print(motifs_group_count)\n\nmotifs_sort = list(zip(motifs_group,motifs_group_count))\nmotifs_sort.sort(key= lambda x : x[1],reverse=True)\nfor i in motifs_sort:\n print(i[1])\n print(i[0])\nmotifs_sort_goup,motifs_sort_count = zip(*motifs_sort)\nmotifts_count_np = np.array(motifs_sort_count)\nmotifts_group_np = np.array(list(motifs_sort_goup))\nmotifts_count_group_np = np.hstack([motifts_count_np.reshape(-1,1),motifts_group_np.reshape(-1,1)])\nmotifts_count_group_pd = pd.DataFrame(motifts_count_group_np)\nmotifts_count_group_pd.to_csv('experiment_results\\\\motifs_group_rank.csv',index=False)\n\n#-------------------------------------------------------\n\n\nsamp_seq = train.iloc[motifts_index,0]\nprint(samp_seq)\n\ndef cut_str(x,n):\n cut_list = []\n seg = int(len(x)/n)\n seg_mod = len(x)%n\n if seg_mod!=0:\n cut_list.append(x[0:seg_mod])\n for i in range(seg):\n cut_list.append(x[seg_mod+i*5:seg_mod+i*5+5])\n return cut_list\n\ndef format_seq(x):\n format_list = []\n for i in range(len(x)):\n cut_list = cut_str(x[i],5)\n pad_list = ['-']*(40-len(cut_list))\n pad_list.extend(cut_list)\n format_list.append(pad_list)\n return format_list\n\nsequence_list = format_seq(samp_seq.values.tolist())\nsequen_pd = np.array(sequence_list)[:,30:40]\n#print(sequen_pd)\n\n\npos_lab = list(range(1,41))\npos_lab = ['P'+\"{:0>2d}\".format(i) for i in pos_lab]\nseq_lab = list(range(1,11))\nseq_lab = ['Seq'+str(i) for i in seq_lab]\natt_p10_pd = pd.DataFrame(data=attention_weights_p10,index=seq_lab,\n columns=pos_lab)\natt_p10_pd_2 = att_p10_pd.iloc[:,30:40]\n#print(att_p10_pd_2)\n\nsns.set(style=\"white\")\nf, axes = plt.subplots(nrows=1, ncols=1,figsize=(10, 5))\n\ncmap = sns.diverging_palette(220, 10, as_cmap=True)\n#cmap='YlGnBu'\ng = sns.heatmap(att_p10_pd_2, annot=sequen_pd,fmt=\"s\",\n cmap=cmap, vmax=.3, center=0.025, linewidths=.5, cbar_kws={\"shrink\": .5},ax=axes)\n#g = sns.heatmap(att_p10_pd_2, cmap=cmap, vmax=.3, center=0, linewidths=.2, square=True, cbar_kws={\"shrink\": .5},ax=axes)\nplt.setp(g.get_yticklabels(), rotation='horizontal')\nplt.setp(g.get_xticklabels(), rotation='horizontal')\nplt.title('Attention intensity of 10 AMPs',fontsize=14)\n\nplt.xticks(fontsize=12)\nplt.yticks(fontsize=12)\n#plt.savefig('experiment_results//motifts_31_40.png',dpi=600,format='png')\nplt.show()\n\n","sub_path":"ACME_codes/ACEP_attention_motif.py","file_name":"ACEP_attention_motif.py","file_ext":"py","file_size_in_byte":8386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"328954665","text":"import requests\nimport time\nimport json\n\n\n\nwhile True: \n\tr = requests.get('http://128.61.14.86:3000/rover').json()\n\tprint(r)\n\n\tdirection = r['direction']\n\tlength = r['length']\n\tbearing = r['bearing']\n\temergency = r['emergency']\n\tend = r['ended']\n\tarrived = r['arrived']\n\thome = r['gotHome']\n\n\ttime.sleep(1)\n\n\n\n\n\n\n\n\n","sub_path":"guardianAngel/rover.py","file_name":"rover.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"366033650","text":"## Create column names during read_csv\r\ndf = pd.read_csv(file, names=['MY COLUMN A','MY COLUMN C'])\r\n\r\n## filter columns brought in during read_csv\r\ndf = pd.read_csv(file, usecols=['MY COLUMN A','MY COLUMN C'])\r\n\r\n## Reorder columns by column name\r\ndf = df[['A', 'D', 'C', 'Z']]\r\n\r\n\r\n\r\n## Insert column at position\r\ndf.insert(3, 'MY COLUMN Z', 'Default Value')\r\n\r\n## Return distinct rows based on column value via dropping duplicates\r\ndf = df.drop_duplicates(subset ='MY COLUMN', keep = 'first')\r\n\r\n## New\r\n","sub_path":"pandas.py","file_name":"pandas.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"41854485","text":"'''analyze.py'''\n\nimport math\n\nimport numpy as np\n\nfrom auto_editor.utils.progressbar import ProgressBar\n\ndef get_np_list(inp, audio_samples, sample_rate, fps, func):\n if(audio_samples is not None):\n sample_count = audio_samples.shape[0]\n sample_rate_per_frame = sample_rate / fps\n audio_frame_count = int(math.ceil(sample_count / sample_rate_per_frame))\n return func((audio_frame_count), dtype=np.bool_)\n\n import cv2\n cap = cv2.VideoCapture(inp.path)\n total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + 1\n return func((total_frames), dtype=np.bool_)\n\n\ndef audio_detection(audio_samples, sample_rate, silent_threshold, fps, log):\n # type: (np.ndarray, int, float, float, Any) -> np.ndarray\n log.conwrite('Analyzing audio volume.')\n\n def get_max_volume(s):\n # type: (np.ndarray) -> float\n maxv = float(np.max(s))\n minv = float(np.min(s))\n return max(maxv, -minv)\n\n max_volume = get_max_volume(audio_samples)\n sample_count = audio_samples.shape[0]\n\n sample_rate_per_frame = sample_rate / fps\n audio_frame_count = int(math.ceil(sample_count / sample_rate_per_frame))\n hasLoudAudio = np.zeros((audio_frame_count), dtype=np.bool_)\n\n if(max_volume == 0):\n log.error('The entire audio is completely silent.')\n\n # Calculate when the audio is loud or silent.\n for i in range(audio_frame_count):\n start = int(i * sample_rate_per_frame)\n end = min(int((i+1) * sample_rate_per_frame), sample_count)\n audiochunks = audio_samples[start:end]\n if(get_max_volume(audiochunks) / max_volume >= silent_threshold):\n hasLoudAudio[i] = True\n\n return hasLoudAudio\n\n\ndef motion_detection(inp, threshold, log, width, dilates, blur):\n # type: (Any, float, Any, int, int, int) -> np.ndarray\n\n # Based on this post:\n # https://pyimagesearch.com/2015/05/25/basic-motion-detection-and-tracking-with-python-and-opencv/\n\n import cv2\n\n log.conwrite('Analyzing video motion.')\n\n cap = cv2.VideoCapture(inp.path)\n\n total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + 1\n\n log.debug(' - Cutting total_frames: {}'.format(total_frames))\n prevFrame = None\n gray = None\n has_motion = np.zeros((total_frames), dtype=np.bool_)\n total = None\n\n def resize(image, width=None, height=None, inter=cv2.INTER_AREA):\n if(width is None and height is None):\n return image\n\n h, w = image.shape[:2]\n if(width is None):\n r = height / h\n dim = (int(w * r), height)\n else:\n r = width / w\n dim = (width, int(h * r))\n\n return cv2.resize(image, dim, interpolation=inter)\n\n progress = ProgressBar(total_frames, 'Detecting motion')\n\n while cap.isOpened():\n if(gray is None):\n prevFrame = None\n else:\n prevFrame = gray\n\n ret, frame = cap.read()\n\n if(not ret):\n break\n\n cframe = int(cap.get(cv2.CAP_PROP_POS_FRAMES)) # current frame\n\n frame = resize(frame, width=width)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Convert frame to grayscale.\n if(blur > 0):\n gray = cv2.GaussianBlur(gray, (blur, blur), 0)\n\n if(prevFrame is not None):\n frameDelta = cv2.absdiff(prevFrame, gray)\n thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]\n\n # Dilate the thresholded image to fill in holes.\n if(dilates > 0):\n thresh = cv2.dilate(thresh, None, iterations=dilates)\n\n if(total is None):\n total = thresh.shape[0] * thresh.shape[1]\n\n if(np.count_nonzero(thresh) / total >= threshold):\n has_motion[cframe] = True\n\n progress.tick(cframe)\n\n cap.release()\n cv2.destroyAllWindows()\n\n log.conwrite('')\n\n return has_motion\n","sub_path":"auto_editor/analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":3892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"44836000","text":"from typing import Dict, List\n\nfrom cognite.client.data_classes._base import *\nfrom cognite.client.data_classes.labels import Label, LabelFilter\nfrom cognite.client.data_classes.shared import TimestampRange\n\n\nclass Geometry(dict):\n \"\"\"Represents the points, curves and surfaces in the coordinate space.\n\n Args:\n type (str): The geometry type. One of 'Point', 'MultiPoint', 'LineString', 'MultiLineString', 'Polygon', or 'MultiPolygon'.\n coordinates (List): An array of the coordinates of the geometry. The structure of the elements in this array is determined by the type of geometry.\n\n Point:\n Coordinates of a point in 2D space, described as an array of 2 numbers.\n\n Example: `[4.306640625, 60.205710352530346]`\n\n\n LineString:\n Coordinates of a line described by a list of two or more points.\n Each point is defined as a pair of two numbers in an array, representing coordinates of a point in 2D space.\n\n Example: `[[30, 10], [10, 30], [40, 40]]`\n\n\n Polygon:\n List of one or more linear rings representing a shape.\n A linear ring is the boundary of a surface or the boundary of a hole in a surface. It is defined as a list consisting of 4 or more Points, where the first and last Point is equivalent.\n Each Point is defined as an array of 2 numbers, representing coordinates of a point in 2D space.\n\n Example: `[[[35, 10], [45, 45], [15, 40], [10, 20], [35, 10]], [[20, 30], [35, 35], [30, 20], [20, 30]]]`\n type: array\n\n MultiPoint:\n List of Points. Each Point is defined as an array of 2 numbers, representing coordinates of a point in 2D space.\n\n Example: `[[35, 10], [45, 45]]`\n\n MultiLineString:\n List of lines where each line (LineString) is defined as a list of two or more points.\n Each point is defined as a pair of two numbers in an array, representing coordinates of a point in 2D space.\n\n Example: `[[[30, 10], [10, 30]], [[35, 10], [10, 30], [40, 40]]]`\n\n MultiPolygon:\n List of multiple polygons.\n\n Each polygon is defined as a list of one or more linear rings representing a shape.\n\n A linear ring is the boundary of a surface or the boundary of a hole in a surface. It is defined as a list consisting of 4 or more Points, where the first and last Point is equivalent.\n\n Each Point is defined as an array of 2 numbers, representing coordinates of a point in 2D space.\n\n Example: `[[[[30, 20], [45, 40], [10, 40], [30, 20]]], [[[15, 5], [40, 10], [10, 20], [5, 10], [15, 5]]]]`\n\n\n\n \"\"\"\n\n def __init__(self, type: str, coordinates: List):\n valid_types = [\"Point\", \"MultiPoint\", \"LineString\", \"MultiLineString\", \"Polygon\", \"MultiPolygon\"]\n if type not in valid_types:\n raise ValueError(\"type must be one of \" + str(valid_types))\n self.type = type\n self.coordinates = coordinates\n\n type = CognitePropertyClassUtil.declare_property(\"type\")\n coordinates = CognitePropertyClassUtil.declare_property(\"coordinates\")\n\n @classmethod\n def _load(self, raw_geometry: Dict[str, Any]):\n return Geometry(type=raw_geometry[\"type\"], coordinates=raw_geometry[\"coordinates\"])\n\n def dump(self, camel_case: bool = False):\n dump_key = lambda key: key if not camel_case else utils._auxiliary.to_camel_case(key)\n return {dump_key(key): value for key, value in self.items()}\n\n\nclass GeometryFilter(dict):\n \"\"\"Represents the points, curves and surfaces in the coordinate space.\n\n Args: type (str): The geometry type. One of 'Point', 'LineString', 'MultiLineString', 'Polygon', or 'MultiPolygon'.\n coordinates (List): An array of the coordinates of the geometry. The structure of the elements in this array is determined by the type of geometry.\n \"\"\"\n\n def __init__(self, type: str, coordinates: List):\n valid_types = [\"Point\", \"LineString\", \"MultiLineString\", \"Polygon\", \"MultiPolygon\"]\n if type not in valid_types:\n raise ValueError(\"type must be one of \" + str(valid_types))\n self.type = type\n self.coordinates = coordinates\n\n type = CognitePropertyClassUtil.declare_property(\"type\")\n coordinates = CognitePropertyClassUtil.declare_property(\"coordinates\")\n\n\nclass GeoLocation(dict):\n \"\"\"A GeoLocation object conforming to the GeoJSON spec.\n\n Args: type (str): The GeoJSON type. Currently only 'Feature' is supported.\n geometry (object): The geometry type. One of 'Point', 'MultiPoint, 'LineString', 'MultiLineString', 'Polygon', or 'MultiPolygon'.\n properties (object): Optional additional properties in a String key -> Object value format.\n \"\"\"\n\n def __init__(self, type: str, geometry: Geometry, properties: dict = None):\n if type != \"Feature\":\n raise ValueError(\"Only the 'Feature' type is supported.\")\n self.type = type\n self.geometry = geometry\n self.properties = properties\n\n type = CognitePropertyClassUtil.declare_property(\"type\")\n geometry = CognitePropertyClassUtil.declare_property(\"geometry\")\n properties = CognitePropertyClassUtil.declare_property(\"properties\")\n\n @classmethod\n def _load(self, raw_geoLocation: Dict[str, Any]):\n return GeoLocation(\n type=raw_geoLocation.get(\"type\", \"Feature\"),\n geometry=raw_geoLocation[\"geometry\"],\n properties=raw_geoLocation.get(\"properties\"),\n )\n\n def dump(self, camel_case: bool = False):\n dump_key = lambda key: key if not camel_case else utils._auxiliary.to_camel_case(key)\n return {dump_key(key): value for key, value in self.items()}\n\n\nclass GeoLocationFilter(dict):\n \"\"\"Return only the file matching the specified geographic relation.\n\n Args: relation (str): One of the following supported queries: INTERSECTS, DISJOINT, WITHIN.\n shape (GeometryFilter): Represents the points, curves and surfaces in the coordinate space.\n \"\"\"\n\n def __init__(self, relation: str, shape: GeometryFilter):\n self.relation = relation\n self.shape = shape\n\n relation = CognitePropertyClassUtil.declare_property(\"relation\")\n shape = CognitePropertyClassUtil.declare_property(\"shape\")\n\n @classmethod\n def _load(self, raw_geoLocation_filter: Dict[str, Any]):\n return GeoLocationFilter(relation=raw_geoLocation_filter[\"relation\"], shape=raw_geoLocation_filter[\"shape\"])\n\n def dump(self, camel_case: bool = False):\n dump_key = lambda key: key if not camel_case else utils._auxiliary.to_camel_case(key)\n return {dump_key(key): value for key, value in self.items()}\n\n\nclass FileMetadata(CogniteResource):\n \"\"\"No description.\n\n Args:\n external_id (str): The external ID provided by the client. Must be unique for the resource type.\n name (str): Name of the file.\n source (str): The source of the file.\n mime_type (str): File type. E.g. text/plain, application/pdf, ..\n metadata (Dict[str, str]): Custom, application specific metadata. String key -> String value. Limits: Maximum length of key is 32 bytes, value 512 bytes, up to 16 key-value pairs.\n directory (str): Directory associated with the file. Must be an absolute, unix-style path.\n asset_ids (List[int]): No description.\n data_set_id (int): The dataSet Id for the item.\n labels (List[Label]): A list of the labels associated with this resource item.\n geo_location (GeoLocation): The geographic metadata of the file.\n source_created_time (int): The timestamp for when the file was originally created in the source system.\n source_modified_time (int): The timestamp for when the file was last modified in the source system.\n security_categories (List[int]): The security category IDs required to access this file.\n id (int): A server-generated ID for the object.\n uploaded (bool): Whether or not the actual file is uploaded. This field is returned only by the API, it has no effect in a post body.\n uploaded_time (int): The number of milliseconds since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.\n created_time (int): The number of milliseconds since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.\n last_updated_time (int): The number of milliseconds since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.\n cognite_client (CogniteClient): The client to associate with this object.\n \"\"\"\n\n def __init__(\n self,\n external_id: str = None,\n name: str = None,\n source: str = None,\n mime_type: str = None,\n metadata: Dict[str, str] = None,\n directory: str = None,\n asset_ids: List[int] = None,\n data_set_id: int = None,\n labels: List[Label] = None,\n geo_location: GeoLocation = None,\n source_created_time: int = None,\n source_modified_time: int = None,\n security_categories: List[int] = None,\n id: int = None,\n uploaded: bool = None,\n uploaded_time: int = None,\n created_time: int = None,\n last_updated_time: int = None,\n cognite_client=None,\n ):\n if geo_location is not None and not isinstance(geo_location, GeoLocation):\n raise TypeError(\"FileMetadata.geo_location should be of type GeoLocation\")\n self.external_id = external_id\n self.name = name\n self.directory = directory\n self.source = source\n self.mime_type = mime_type\n self.metadata = metadata\n self.asset_ids = asset_ids\n self.data_set_id = data_set_id\n self.labels = Label._load_list(labels)\n self.geo_location = geo_location\n self.source_created_time = source_created_time\n self.source_modified_time = source_modified_time\n self.security_categories = security_categories\n self.id = id\n self.uploaded = uploaded\n self.uploaded_time = uploaded_time\n self.created_time = created_time\n self.last_updated_time = last_updated_time\n self._cognite_client = cognite_client\n\n @classmethod\n def _load(cls, resource: Union[Dict, str], cognite_client=None):\n instance = super(FileMetadata, cls)._load(resource, cognite_client)\n instance.labels = Label._load_list(instance.labels)\n if instance.geo_location is not None:\n instance.geo_location = GeoLocation._load(instance.geo_location)\n return instance\n\n\nclass FileMetadataFilter(CogniteFilter):\n \"\"\"No description.\n\n Args:\n name (str): Name of the file.\n mime_type (str): File type. E.g. text/plain, application/pdf, ..\n metadata (Dict[str, str]): Custom, application specific metadata. String key -> String value. Limits: Maximum length of key is 32 bytes, value 512 bytes, up to 16 key-value pairs.\n asset_ids (List[int]): Only include files that reference these specific asset IDs.\n asset_external_ids (List[str]): Only include files that reference these specific asset external IDs.\n root_asset_ids (List[Dict[str, Any]]): Only include files that have a related asset in a tree rooted at any of these root assetIds.\n data_set_ids (List[Dict[str, Any]]): Only include files that belong to these datasets.\n labels (LabelFilter): Return only the files matching the specified label(s).\n geo_location (GeoLocationFilter): Only include files matching the specified geographic relation.\n asset_subtree_ids (List[Dict[str, Any]]): Only include files that have a related asset in a subtree rooted at any of these assetIds (including the roots given). If the total size of the given subtrees exceeds 100,000 assets, an error will be returned.\n source (str): The source of this event.\n created_time (Union[Dict[str, Any], TimestampRange]): Range between two timestamps.\n last_updated_time (Union[Dict[str, Any], TimestampRange]): Range between two timestamps.\n uploaded_time (Union[Dict[str, Any], TimestampRange]): Range between two timestamps.\n source_created_time (Dict[str, Any]): Filter for files where the sourceCreatedTime field has been set and is within the specified range.\n source_modified_time (Dict[str, Any]): Filter for files where the sourceModifiedTime field has been set and is within the specified range.\n external_id_prefix (str): Filter by this (case-sensitive) prefix for the external ID.\n directory_prefix (str): Filter by this (case-sensitive) prefix for the directory provided by the client.\n uploaded (bool): Whether or not the actual file is uploaded. This field is returned only by the API, it has no effect in a post body.\n cognite_client (CogniteClient): The client to associate with this object.\n \"\"\"\n\n def __init__(\n self,\n name: str = None,\n mime_type: str = None,\n metadata: Dict[str, str] = None,\n asset_ids: List[int] = None,\n asset_external_ids: List[str] = None,\n root_asset_ids: List[Dict[str, Any]] = None,\n data_set_ids: List[Dict[str, Any]] = None,\n labels: LabelFilter = None,\n geo_location: GeoLocationFilter = None,\n asset_subtree_ids: List[Dict[str, Any]] = None,\n source: str = None,\n created_time: Union[Dict[str, Any], TimestampRange] = None,\n last_updated_time: Union[Dict[str, Any], TimestampRange] = None,\n uploaded_time: Union[Dict[str, Any], TimestampRange] = None,\n source_created_time: Dict[str, Any] = None,\n source_modified_time: Dict[str, Any] = None,\n external_id_prefix: str = None,\n directory_prefix: str = None,\n uploaded: bool = None,\n cognite_client=None,\n ):\n self.name = name\n self.mime_type = mime_type\n self.metadata = metadata\n self.asset_ids = asset_ids\n self.asset_external_ids = asset_external_ids\n self.root_asset_ids = root_asset_ids\n self.data_set_ids = data_set_ids\n self.labels = labels\n self.geo_location = geo_location\n self.asset_subtree_ids = asset_subtree_ids\n self.source = source\n self.created_time = created_time\n self.last_updated_time = last_updated_time\n self.uploaded_time = uploaded_time\n self.source_created_time = source_created_time\n self.source_modified_time = source_modified_time\n self.external_id_prefix = external_id_prefix\n self.directory_prefix = directory_prefix\n self.uploaded = uploaded\n self._cognite_client = cognite_client\n\n if labels is not None and not isinstance(labels, LabelFilter):\n raise TypeError(\"FileMetadataFilter.labels must be of type LabelFilter\")\n if geo_location is not None and not isinstance(geo_location, GeoLocationFilter):\n raise TypeError(\"FileMetadata.geo_location should be of type GeoLocationFilter\")\n\n @classmethod\n def _load(cls, resource: Union[Dict, str], cognite_client=None):\n instance = super(FileMetadataFilter, cls)._load(resource, cognite_client)\n if isinstance(resource, Dict):\n if instance.created_time is not None:\n instance.created_time = TimestampRange(**instance.created_time)\n if instance.last_updated_time is not None:\n instance.last_updated_time = TimestampRange(**instance.last_updated_time)\n if instance.uploaded_time is not None:\n instance.uploaded_time = TimestampRange(**instance.uploaded_time)\n if instance.labels is not None:\n instance.labels = [Label._load(label) for label in instance.labels]\n if instance.geo_location is not None:\n instance.geo_location = GeoLocationFilter._load(**instance.geo_location)\n return instance\n\n def dump(self, camel_case: bool = False):\n result = super(FileMetadataFilter, self).dump(camel_case)\n if isinstance(self.labels, LabelFilter):\n result[\"labels\"] = self.labels.dump(camel_case)\n if isinstance(self.geo_location, GeoLocationFilter):\n result[\"geoLocation\"] = self.geo_location.dump(camel_case)\n return result\n\n\nclass FileMetadataUpdate(CogniteUpdate):\n \"\"\"Changes will be applied to file.\n\n Args:\n \"\"\"\n\n class _PrimitiveFileMetadataUpdate(CognitePrimitiveUpdate):\n def set(self, value: Any) -> \"FileMetadataUpdate\":\n return self._set(value)\n\n class _ObjectFileMetadataUpdate(CogniteObjectUpdate):\n def set(self, value: Dict) -> \"FileMetadataUpdate\":\n return self._set(value)\n\n def add(self, value: Dict) -> \"FileMetadataUpdate\":\n return self._add(value)\n\n def remove(self, value: List) -> \"FileMetadataUpdate\":\n return self._remove(value)\n\n class _ListFileMetadataUpdate(CogniteListUpdate):\n def set(self, value: List) -> \"FileMetadataUpdate\":\n return self._set(value)\n\n def add(self, value: List) -> \"FileMetadataUpdate\":\n return self._add(value)\n\n def remove(self, value: List) -> \"FileMetadataUpdate\":\n return self._remove(value)\n\n class _LabelFileMetadataUpdate(CogniteLabelUpdate):\n def add(self, value: Union[str, List[str]]) -> \"FileMetadataUpdate\":\n return self._add(value)\n\n def remove(self, value: Union[str, List[str]]) -> \"FileMetadataUpdate\":\n return self._remove(value)\n\n @property\n def external_id(self):\n return FileMetadataUpdate._PrimitiveFileMetadataUpdate(self, \"externalId\")\n\n @property\n def directory(self):\n return FileMetadataUpdate._PrimitiveFileMetadataUpdate(self, \"directory\")\n\n @property\n def source(self):\n return FileMetadataUpdate._PrimitiveFileMetadataUpdate(self, \"source\")\n\n @property\n def mime_type(self):\n return FileMetadataUpdate._PrimitiveFileMetadataUpdate(self, \"mimeType\")\n\n @property\n def metadata(self):\n return FileMetadataUpdate._ObjectFileMetadataUpdate(self, \"metadata\")\n\n @property\n def asset_ids(self):\n return FileMetadataUpdate._ListFileMetadataUpdate(self, \"assetIds\")\n\n @property\n def source_created_time(self):\n return FileMetadataUpdate._PrimitiveFileMetadataUpdate(self, \"sourceCreatedTime\")\n\n @property\n def source_modified_time(self):\n return FileMetadataUpdate._PrimitiveFileMetadataUpdate(self, \"sourceModifiedTime\")\n\n @property\n def data_set_id(self):\n return FileMetadataUpdate._PrimitiveFileMetadataUpdate(self, \"dataSetId\")\n\n @property\n def labels(self):\n return FileMetadataUpdate._LabelFileMetadataUpdate(self, \"labels\")\n\n @property\n def geoLocation(self):\n return FileMetadataUpdate._PrimitiveFileMetadataUpdate(self, \"geoLocation\")\n\n @property\n def security_categories(self):\n return FileMetadataUpdate._ListFileMetadataUpdate(self, \"securityCategories\")\n\n\nclass FileAggregate(dict):\n \"\"\"Aggregation results for files\n\n Args:\n count (int): Number of filtered items included in aggregation\n \"\"\"\n\n def __init__(self, count: int = None, **kwargs):\n self.count = count\n self.update(kwargs)\n\n count = CognitePropertyClassUtil.declare_property(\"count\")\n\n\nclass FileMetadataList(CogniteResourceList):\n _RESOURCE = FileMetadata\n _UPDATE = FileMetadataUpdate\n","sub_path":"cognite/client/data_classes/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":19722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"132285412","text":"import sys\n\nTT_NUM = 0\nTT_PLUS = 1\nTT_MUL = 2\nTT_OPEN = 3\nTT_CLOSE = 4\n\nclass Token:\n def __init__(self, token_type, pos, val):\n self.token_type = token_type\n self.pos = pos\n self.val = val\n\n def __repr__(self):\n return 'Token(token_type={}, pos={}, val=\"{}\")'.format(self.token_type, self.pos, self.val)\n\n\ndef raise_error(line, pos, message):\n print(line)\n print((' ' * pos) + '^')\n print('Error (pos {}): {}'.format(pos, message))\n raise Exception(message)\n\n\ndef lex(line):\n pos = 0\n tokens = []\n\n def skip_space():\n nonlocal pos\n while pos < len(line) and line[pos] == ' ':\n pos += 1\n\n while True:\n skip_space()\n if pos >= len(line):\n break\n\n if line[pos].isnumeric():\n end = pos\n while end < len(line) and line[end].isnumeric():\n end += 1\n tokens.append(Token(TT_NUM, pos, int(line[pos:end])))\n pos = end\n elif line[pos] == '+':\n tokens.append(Token(TT_PLUS, pos, '+'))\n pos += 1\n elif line[pos] == '*':\n tokens.append(Token(TT_MUL, pos, '*'))\n pos += 1\n elif line[pos] == '(':\n tokens.append(Token(TT_OPEN, pos, '('))\n pos += 1\n elif line[pos] == ')':\n tokens.append(Token(TT_CLOSE, pos, ')'))\n pos += 1\n else:\n raise_error(line, pos, 'Invalid symbol {}'.format(line[pos]))\n\n return tokens\n\n\ndef parse(line, tokens):\n idx = 0\n\n def fatal(message):\n nonlocal idx\n raise_error(line, tokens[idx].pos, message)\n\n def is_type(types):\n nonlocal idx\n return tokens[idx].token_type in types\n\n def must_accept(types, err_message):\n nonlocal idx\n if not is_type(types):\n fatal(err_message)\n val = tokens[idx]\n idx += 1\n return val\n\n def may_accept(types):\n nonlocal idx\n if not is_type(types):\n return None\n val = tokens[idx]\n idx += 1\n return val\n\n def has_tokens_left():\n nonlocal idx\n return idx < len(tokens)\n\n def p_brac_expr():\n must_accept([TT_OPEN], 'Expected \"(\"')\n val = p_mul_expr()\n must_accept([TT_CLOSE], 'Expected \")\"')\n return val\n\n def p_value():\n if is_type([TT_OPEN]):\n return p_brac_expr()\n else:\n return must_accept([TT_NUM], 'Expected number or \"(\"').val\n\n def p_add_expr():\n res = p_value()\n\n while has_tokens_left():\n if not may_accept([TT_PLUS]):\n break\n res += p_value()\n\n return res\n\n def p_mul_expr():\n res = p_add_expr()\n\n while has_tokens_left():\n if not may_accept([TT_MUL]):\n break\n res *= p_add_expr()\n\n return res\n\n res = p_mul_expr()\n if has_tokens_left():\n fatal('Expected EOF')\n return res\n\n\ndef main():\n total = 0\n\n for line in sys.stdin:\n line = line.strip()\n tokens = lex(line)\n result = parse(line, tokens)\n total += result\n\n print(total)\n\n\nmain()\n","sub_path":"18/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":3192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"548344307","text":"import cv2, dlib, sys\r\nimport numpy as np\r\nimport time\r\n\r\nscaler = 0.2\r\nprev_time = 0\r\nFPS = 10\r\n\r\ndetector = dlib.get_frontal_face_detector()\r\npredictor = dlib.shape_predictor('D:/python Project/opencv (2)/shape_predictor_68_face_landmarks.dat')\r\n\r\nimg = cv2.imread(\"D:/python Project/opencv (2)/jimin.jpg\", cv2.IMREAD_ANYCOLOR)\r\noverlay = cv2.imread('D:/python Project/opencv (2)/mask/wmask.png',cv2.IMREAD_UNCHANGED)\r\n\r\ndef overlay_transparent(background_img, img_to_overlay_t, x, y, overlay_size=None):\r\n try :\r\n bg_img = background_img.copy()\r\n # convert 3 channels to 4 channels\r\n if bg_img.shape[2] == 3:\r\n bg_img = cv2.cvtColor(bg_img, cv2.COLOR_BGR2BGRA)\r\n\r\n if overlay_size is not None:\r\n img_to_overlay_t = cv2.resize(img_to_overlay_t.copy(), overlay_size)\r\n\r\n b, g, r, a = cv2.split(img_to_overlay_t)\r\n\r\n mask = cv2.medianBlur(a, 5)\r\n\r\n h, w, _ = img_to_overlay_t.shape\r\n roi = bg_img[int(y-h/2):int(y+h/2), int(x-w/2):int(x+w/2)]\r\n\r\n img1_bg = cv2.bitwise_and(roi.copy(), roi.copy(), mask=cv2.bitwise_not(mask))\r\n img2_fg = cv2.bitwise_and(img_to_overlay_t, img_to_overlay_t, mask=mask)\r\n\r\n bg_img[int(y-h/2):int(y+h/2), int(x-w/2):int(x+w/2)] = cv2.add(img1_bg, img2_fg)\r\n\r\n # convert 4 channels to 4 channels\r\n bg_img = cv2.cvtColor(bg_img, cv2.COLOR_BGRA2BGR)\r\n return bg_img\r\n except Exception : return background_img\r\n\r\nwhile True:\r\n #img = cv2.resize(img,(int(img.shape[1] * scaler), int(img.shape[0] * scaler)))\r\n ori = img.copy()\r\n img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n #faces = detector(img_gray,1)\r\n faces = detector(img)\r\n # 인식된 얼굴 개수 출력\r\n print(\"Number of faces detected: {}\".format(len(faces)))\r\n for face in faces:\r\n #dlib_shape = predictor(img_gray,face)\r\n dlib_shape = predictor(img,face)\r\n shape_2d = np.array([[p.x, p.y] for p in dlib_shape.parts()])\r\n\r\n top_left = np.min(shape_2d, axis=0)\r\n bottom_right = np.max(shape_2d, axis=0)\r\n #print(\"top_left,bottom_right: {0}, {1}\".format(top_left,bottom_right))\r\n face_size = max(bottom_right-top_left)\r\n center_x, center_y = np.mean(shape_2d, axis=0).astype(np.int)\r\n #print(\"center_x, center_y: {0}, {1}\".format(center_x,center_y))\r\n result = overlay_transparent(ori, overlay, center_x, center_y+25, overlay_size=(face_size, face_size))\r\n\r\n img = cv2.rectangle(img, pt1=(face.left(), face.top()), pt2=(face.right(), face.bottom()),color=(255,255,255),\r\n thickness=2,lineType=cv2.LINE_AA)\r\n\r\n for s in shape_2d:\r\n cv2.circle(img, center=tuple(s), radius=1, color=(255,255,255),thickness=2, lineType=cv2.LINE_AA)\r\n\r\n cv2.circle(img, center=tuple((center_x,center_y)),radius=1,color=(0,0,255),thickness=2,lineType=cv2.LINE_AA)\r\n cv2.imshow('result',result)\r\n cv2.imshow('img',img)\r\n\r\n if cv2.waitKey(1) == ord('q'): break\r\n\r\ncv2.destroyAllWindows()\r\n","sub_path":"image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":3132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"371227320","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 16 11:34:47 2021\n\n\n\"\"\"\nimport string\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport spacy\nfrom collections import Counter\nimport plotly.express as px\n\ndf = pd.read_csv('./df.csv', converters={'lemmas': eval, 'entities':eval, \n 'entity labels':eval, 'label definitions':eval})\nsarcastic = df.loc[df['is_sarcastic']==1]\nnon = df.loc[df['is_sarcastic']!=1]\nnlp = spacy.load(\"en_core_web_sm\")\n\n\n#most popular lemmas\ns_lemmas = pd.DataFrame(sarcastic.lemmas.explode().value_counts())\nn_lemmas = pd.DataFrame(non.lemmas.explode().value_counts())\ns_lemmas['is_sarcastic'] = 1\nn_lemmas['is_sarcastic'] = 0\nlemmas = pd.concat([s_lemmas, n_lemmas], axis=0)\n\n\n#most popular entities\ns_entities = pd.DataFrame({'entities':sarcastic.entities.explode(),\n 'entity labels':sarcastic['entity labels'].explode(),\n 'label definitions':sarcastic['label definitions'].explode()}).value_counts().iloc[1:].reset_index()\nn_entities = pd.DataFrame({'entities':non.entities.explode(),\n 'entity labels':non['entity labels'].explode(),\n 'label definitions':non['label definitions'].explode()}).value_counts().iloc[1:].reset_index()\n\ns_entities['Article Type'] = 'Sarcastic'\nn_entities['Article Type'] = 'Legitimate'\nentities = pd.concat([s_entities, n_entities], axis=0)\nentities.columns = ['entities', 'entity labels', 'label definitions', 'number of instances', 'article type']\nprint(entities['entity labels'].unique())\nvc = entities[['entity labels', 'label definitions']].value_counts().reset_index()\nvc.to_csv('./vc.csv')\n\nlemmas.to_csv('./lemmas.csv')\nentities.to_csv('./entities1.csv')\n\n\n\n\n","sub_path":"prep.py","file_name":"prep.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"298035326","text":"import imghdr\nimport re\nfrom django.db.models.signals import post_save, pre_delete, pre_save\nfrom django.dispatch import receiver\nfrom .models import ImageModel, GroupImage, Groups\nfrom my_utils.add_wa import add_wa\n\n\n@receiver(pre_delete, sender=ImageModel)\ndef delete_image_num(sender, instance=None, **kwargs):\n \"\"\"\n 当删除一张图片时\n \"\"\"\n # 减少上传数目\n user = instance.user\n user.upload_nums -= 1\n user.save()\n\n\n@receiver(pre_save, sender=ImageModel)\ndef do_something_if_changed(sender, instance, **kwargs):\n \"\"\"\n 在图片保存之前, 需要检查图片的类别是否是已存在的类别\n 不是的话回退类别\n \"\"\"\n try:\n obj = sender.objects.get(id=instance.id)\n except sender.DoesNotExist:\n # 图片才被创建\n pass\n else:\n if obj.cates != instance.cates:\n if '/' in obj.cates or '、' in obj.cates:\n cates = re.split('[/、]', obj.cates)\n for cate in cates:\n group = Groups.objects.filter(name=cate)\n if not group.count() or group[0].level == 2:\n # 回退\n obj.cates = instance.cates\n break\n\n\n@receiver(post_save, sender=ImageModel)\ndef create_group_image(sender, instance=None, created=False, **kwargs):\n \"\"\"\n 当上传图片动作发生\n \"\"\"\n if created:\n # 增加上传数目\n user = instance.user\n user.upload_nums += 1\n user.save()\n # 保存图片格式\n pattern = imghdr.what(instance.image.path)\n instance.pattern = pattern\n # 保存图片种类\n cates = instance.cates.split(\" \")\n cate_str = ''\n for cate in cates:\n if cate:\n group = Groups.objects.filter(name=cate)\n if group.count():\n\n group = group[0]\n GroupImage(image=instance, name=cate, group=group).save()\n\n tmp_str = group.name\n\n while group.parent:\n tmp_str = group.parent.name + '/' + tmp_str\n group = group.parent\n\n cate_str = cate_str + '、' + tmp_str\n else:\n cate_str = cate_str + '、' + cate\n # 没有该分类也不创建该分类\n # group = Groups(name=cate)\n # group.save()\n # GroupImage(image=instance, name=cate, group=group).save()\n\n instance.cates = cate_str[1:]\n instance.save()\n\n # 生成水印图\n path = instance.image.path\n name = path.rsplit('/', 1)[1]\n add_wa(path, name)\n","sub_path":"whutGalleryMgmtSysAPI/TS_WHUT/apps/images/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":2735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"79542363","text":"import torch as torch\nimport torch.distributions\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport pickle\nimport os\n\nfrom first_neural_network.node import Node\n\nclass Get_input():\n\n def __init__(self, ls_nodes, vector_size, kernel_depth = 2, features_size = 4):\n self.vector_size = vector_size\n self.feature_size = features_size\n self.kernel_depth = kernel_depth\n self.ls_nodes = ls_nodes\n\n\n def get_input(self):\n for node in self.ls_nodes:\n ''' \n We are going to create the sliding window. Taking as reference the book,\n we are going to set the kernel depth of our windows as 2. We consider into the window\n the node and its children.\n Question for ourselves: if we decide to increase the kernel depth to 3, should be\n appropiate to take node: its children and its grand-children or node, parent and children?\n\n We are going to calculate the parameters of the sliding window when its kernel depth\n is fixed to 2.\n In case we change the depth of the window, we have to change the parameters of each tensor\n '''\n if node.children:\n vector_matrix, w_t_coeffs, w_l_coeffs, w_r_coeffs = self.sliding_window_tensor(node)\n node.set_matrix_and_coeffs(vector_matrix, w_t_coeffs, w_l_coeffs, w_r_coeffs)\n\n\n\n def sliding_window_tensor(self, node):\n # We create a list with all combined vectors\n vectors = [node.vector]\n # Parameters used to calculate the convolutional matrix for each node\n n = len(node.children)\n # If there is only one child, then we set n = 2 because n cannot be 1 \n # (eta_r uses n -1 as denominator)\n if n == 1:\n n = 2\n d = self.kernel_depth\n # The nodes children are at the bottom\n d_i = 1\n # First node is the node at the top: d_i=2, p_i=1, n=2\n w_t_list = [(2-1)/(d-1)]\n w_r_list = [0]\n w_l_list = [0]\n i = 1\n for child in node.children:\n # We save the position of each node in the sliding window\n p_i = i\n w_t_list.append((d_i-1)/(d-1))\n w_r_list.append((1-w_t_list[i])*((p_i-1)/(n-1)))\n w_l_list.append((1-w_t_list[i])*(1-w_r_list[i]))\n i += 1\n # We save the combined vector of each node\n vectors.append(child.vector)\n\n # We create a matrix with all the vectors\n vector_matrix = torch.stack(tuple(vectors), 0)\n del vectors\n # We create a tensor with the parameters associated to the top matrix\n w_t_params = torch.tensor(w_t_list)\n del w_t_list\n # We create a tensor with the parameters associated to the left matrix\n w_l_params = torch.tensor(w_l_list)\n del w_l_list\n # We create a tensor with the parameters associated to the right matrix\n w_r_params = torch.tensor(w_r_list)\n del w_r_list\n # Reshape the matrices and vectors and create 3D tensors\n vector_matrix, w_t_params, w_l_params, w_r_params = self.reshape_matrices_and_vectors(vector_matrix, w_t_params, w_l_params, w_r_params)\n return vector_matrix, w_t_params, w_l_params, w_r_params\n\n # Reshape the matrices and vectors and create 3D tensors\n def reshape_matrices_and_vectors(self, vector_matrix, w_t_params, w_l_params, w_r_params):\n # We create a 3D tensor for the vector matrix: shape(nb_nodes, 30, 1)\n vector_matrix = torch.unsqueeze(vector_matrix, 2)\n\n # We create a 3D tensor for the parameters associated to the top matrix: shape(nb_nodes, 1, 1)\n w_t_params = torch.unsqueeze(w_t_params, 1)\n w_t_params = torch.unsqueeze(w_t_params, 1)\n\n # We create a 3D tensor for the parameters associated to the left matrix: shape(nb_nodes, 1, 1)\n w_l_params = torch.unsqueeze(w_l_params, 1)\n w_l_params = torch.unsqueeze(w_l_params, 1)\n\n # We create a 3D tensor for the parameters associated to the right matrix: shape(nb_nodes, 1, 1)\n w_r_params = torch.unsqueeze(w_r_params, 1)\n w_r_params = torch.unsqueeze(w_r_params, 1)\n\n return vector_matrix, w_t_params, w_l_params, w_r_params","sub_path":"get_input.py","file_name":"get_input.py","file_ext":"py","file_size_in_byte":4270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"483422864","text":"from execution.abstract.querie import * \nfrom storageManager import jsonMode as admin\n\nclass Create(Querie):\n '''\n replace: es un parametro booleano valores true or false\n mode: un numero entero de 0 a 3 (entero)\n name: nombre que le queremos dar a la base de datos(cadena)\n row: numero de fila(entero)\n column:numero de columna\n\n '''\n def __init__(self,replace, mode, name, column,row):\n Querie.__init__(self,column, row)\n self.replace = replace\n self.mode = mode\n self.name = name\n \n def execute(self, environment):\n if not isinstance(self.name,str):\n return {'Error': 'El nombre indicado de la base de datos no es una cadena.', 'Fila':self.row, 'Columna': self.column }\n result = 3\n result = admin.createDatabase(self.name) #<---------------------------\n if result == 0:\n #Se creo la base de datos correctamente.\n environment.createDataBase(self.name)#Guardamos la metadata en el entorno global.\n return 'La base de datos ' + self.name + ' ha sido creada con éxito.' \n elif result == 1:\n #Error al crear\n return {'Error':'Ocurrió un error en el storage manager. ' + self.name + ' no pudo ser creada.', 'Fila':self.row, 'Columna':self.column}\n elif result == 2:\n #Base de datos existente\n if self.replace == True:\n admin.dropDatabase(self.name) \n result = admin.createDatabase(self.name)\n environment.deleteDataBase(self.name)\n environment.createDataBase(self.name) \n switcher = {\n 0:'La base de datos ' + self.name +' ha sido reemplazada con éxito',\n 1:{'Error':'Ocurrió un error en el storage manager.' + self.name + ' no pudo ser reemplazada.', 'Fila':self.row, 'Columna':self.column},\n 2:{'Error':'La Base de datos' + self.name +'no pudo ser reemplazada.', 'Fila':self.row, 'Columna':self.column}\n }\n return switcher.get(result, {'Error':'Error desconocido al intentar realizar el replace de ' + self.name,'Fila': self.row, 'Columna': self.column})\n else:\n return {'Error': \"La base de datos que se desea crear ya existe.\", 'Fila': self.row, 'Columna': self.column}\n else:\n return {'Error': \"Error desconocido en el storage manager.\", 'Fila': self.row, 'Columna': self.column}","sub_path":"parser/team27/G-27/execution/querie/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"187436196","text":"import os\n\ndef readprint():\n readprint = str(input(\"what file do you want to read 1 , 2 , 3 ? \"))\n file = open(readprint,\"r\")\n if file.mode == 'r' :\n contents =file.read()\n print(contents)\n\ndef overwrite():\n overwrite = str(input(\"what file do you want to edit 1 , 2 , 3 ? \"))\n write = str(input(\"what do you want to write? \"))\n file = open(overwrite,\"w\")\n file.write(\"{}\".format(write))\n print(\"the file now says\".format(write))\n\ndef createfolder():\n os.chdir('G:\\My Drive')\n foldy = str(input(\" folder name: \"))\n os.mkdir(foldy)\n print(\"Folder created called {}\".format(foldy))\n\ndef createfile():\n createfile = str(input(\"what do you want to name the file? \"))\n file = open(createfile,\"w+\")\n\nreadprint()\noverwrite()\nreadprint()\n\n","sub_path":"test 2.py","file_name":"test 2.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"338152511","text":"from pyramid.view import view_config\nfrom pyramidstarter import DnD\nimport threading, time, os\n\nimport logging\nlog = logging.getLogger(__name__)\n\nif 'OPENSHIFT_BUILD_NAME' in os.environ:\n place = \"server\"\n apppath = \"/opt/app-root/src/pyramidstarter/\"\nelse:\n place = \"localhost\"\n apppath = \"pyramidstarter/\"\nprint(place)\n\n\nclass TimeoutError(Exception):\n pass\n\n@view_config(route_name='home', renderer='templates/index.pt')\ndef my_view(request): # serving static basically.\n return dict()\n\n@view_config(route_name='carlos', renderer='templates/Carlos.pt')\ndef carlos(request): # serving static basically.\n return dict()\n\nfrom pyramidstarter import VCF_mapper\n@view_config(route_name='carlos_submit', renderer='json')\ndef carlos_submit(request):\n open('temp.gb','wb').write(request.POST['genbank'].value)\n open('vcf.csv', 'wb').write(request.POST['vcf'].value)\n VCF_mapper.tabulator('temp.gb', 'vcf.csv', 'out.csv')\n return open('out.csv','r').read()\n\n@view_config(route_name='dnd', renderer='templates/DnD.pt')\ndef dnder(request):\n beastial = ''\n for name in sorted([DnD.Creature.beastiary[beast]['name'] for beast in DnD.Creature.beastiary], key=str.lower):\n beastial += ''\n return {'beasts': beastial}\n\n@view_config(route_name='ajax_dnd', renderer='json')\ndef ajacean_dnder(request):\n try:\n wwe = DnD.Encounter(*request.json_body)\n w = threading.Thread(target=wwe.go_to_war, args=(1000,))\n w.start()\n time.sleep(10)\n wwe.KILL = True\n response = wwe.battle(1, 1).summary()\n print('Battle done...')\n add_to_tales(wwe)\n return response\n except Exception as e:\n return {'battles': \"Error: \" + str(e)}\n\ndef line_prepender(filename, line):\n with open(filename, 'r+', encoding='utf-8') as f:\n content = f.read()\n f.seek(0, 0)\n f.write(line.rstrip('\\r\\n') + '\\n' + content)\n\ndef add_to_tales(battle):\n line_prepender(apppath+\"tales.txt\",str(battle))\n\n@view_config(route_name='dnd_review', renderer='string')\ndef dnd_reviewer(request):\n return open(apppath+\"tales.txt\", encoding='utf-8').read().replace(\"
    \",\"\\n\")\n","sub_path":"pyramidstarter/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"183499218","text":"import copy\nimport Candidate\nimport pickle\n\ndef prob_cover_genes_lst(candidate, genes_lst):\n cover_all = 1\n for gene in genes_lst:\n cover_all *= candidate.genes_score_dict[gene]\n return cover_all\n\ndef find_set_cover(best_permutations_DS, sg_genes_dict, thr, genes_sg_dict = None):\n '''for now, might won't work in a case when there is a gene that isn't covered by any of the permutations in the best_permutations_DS. not finished. can make it more readble'''\n temp_best_perm_DS = copy.copy(best_permutations_DS)\n res = list()#[temp_best_perm_DS[0]]\n if genes_sg_dict:\n for gene, targets in genes_sg_dict.items():\n if len(targets) == 0:\n print(\"no targets for gene \" + gene)\n genes_name_lst.remove(gene)\n continue\n c = Candidate.Candidate(targets[0])\n c.fill_default_fildes(sg_genes_dict[targets[0]])\n temp_best_perm_DS.append(c)\n\n uncovered_genes = set()\n for sg, genesLst in sg_genes_dict.items():\n for gene in genesLst:\n uncovered_genes.add(gene)\n while(len(uncovered_genes)) > 0 and len(temp_best_perm_DS) > 0:\n #print(uncovered_genes)\n #for gene in uncovered_genes:\n #print(gene) \n ##going over all the permutations, and return the permutation that cover the maximal amount of genes haven't been covered yet, in the highest probability among the maximal covered permutations\n #print('len uncovered genes', len(uncovered_genes))\n best_current_perm, best_num_of_coverd, best_prob_of_covered = None, 0,0 #best_current_perm is the hole tuple\n i = 0\n while i < (len(temp_best_perm_DS)):\n new_genes_coverd = list()#0\n for gene, score in temp_best_perm_DS[i].genes_score_dict.items():\n if gene in uncovered_genes and score >= thr:\n new_genes_coverd.append(gene)\n #uncovered_genes.remove(gene)\n if len(new_genes_coverd) == 0:\n i+=1\n continue\n #del temp_best_perm_DS[i]\n elif len(new_genes_coverd) >= best_num_of_coverd:## and temp_best_perm_DS[i][2] > best_prob_of_covered: ##need to check if 2 is the right index, and not 1.\n #print(new_genes_coverd)\n if len(new_genes_coverd) > best_num_of_coverd or prob_cover > best_prob_of_covered: # cover more gene or cover the same amount with greater prob.\n prob_cover = prob_cover_genes_lst(temp_best_perm_DS[i], new_genes_coverd)\n\t\t\t\t#if prob_cover > best_prob_of_covered:\n best_num_of_coverd, best_prob_of_covered = len(new_genes_coverd), prob_cover\n best_current_perm = temp_best_perm_DS[i]\n i+=1\n if(best_current_perm):\n res.append(best_current_perm)\n for gene, score in best_current_perm.genes_score_dict.items():\n if gene in uncovered_genes and score >= thr: #there is a probability that this gene had already been covered bya prevuis sgRNA\n uncovered_genes.remove(gene)\n return res\n\ndef test1(path = '/bioseq/data/results/multicrispr/1516613143' , thr = 0.45):\n\tbest_permutations_DS, sg_genes_dict = pickle.load(open(\"/\".join([path, \"res_in_lst.p\"]),'rb')), pickle.load(open(\"/\".join([path, \"sg_genes_dict.p\"]), 'rb'))\n\tfind_set_cover(best_permutations_DS, sg_genes_dict, thr)","sub_path":"python/set_cover_greedy.py","file_name":"set_cover_greedy.py","file_ext":"py","file_size_in_byte":3440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"110234710","text":"from RPi import GPIO\nfrom time import sleep\nimport os\nimport glob\nimport time\nimport gaugette.gpio\nimport gaugette.ssd1306\nimport gaugette.platform\nimport Adafruit_BMP.BMP085 as BMP085 # Imports the BMP library\n\n\n\n#Rotary encoder\n\n\nclk = 16\ndt = 20\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(clk, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(dt, GPIO.IN, pull_up_down=GPIO.PUD_UP)\ncounter = 1\nclkLastState = GPIO.input(clk)\n\n\n#Dallas\n\n\nos.system('modprobe w1-gpio')\nos.system('modprobe w1-therm')\n\nbase_dir = '/sys/bus/w1/devices/'\ndevice_folder = glob.glob(base_dir + '28*')[0]\ndevice_file = device_folder + '/w1_slave'\n\n\ndef read_temp_raw():\n f = open(device_file, 'r')\n lines = f.readlines()\n f.close()\n return lines\n\n\ndef read_temp():\n lines = read_temp_raw()\n equals_pos = lines[1].find('t=')\n if equals_pos != -1:\n temp_string = lines[1][equals_pos + 2:]\n temp_c = float(temp_string) / 1000.0\n return temp_c\n\n\n#BMP180\n\n\nsensor = BMP085.BMP085()\n\n\n#DISPLAY\n\n\nspi_bus = 0\nspi_device = 0\ngpio = gaugette.gpio.GPIO()\nspi = gaugette.spi.SPI(spi_bus, spi_device)\nRESET_PIN = 15 # WiringPi pin 15 is GPIO14.\nDC_PIN = 16 # WiringPi pin 16 is GPIO15.\n\nled = gaugette.ssd1306.SSD1306(gpio, spi, reset_pin=RESET_PIN, dc_pin=DC_PIN, rows=64, cols=128) # Change rows & cols values depending on your display dimensions.\n\nled.begin()\nled.clear_display()\nled.display()\nled.invert_display()\ntime.sleep(0.5)\nled.normal_display()\ntime.sleep(0.5)\n\n\nhodnota = (str)(read_temp())+\" *C\"\npristroj = \"DALLAS\"\nvelicina = \"Teplota\"\n\nled.clear_display()\nled.draw_text2(0, 0, str(pristroj), 2)\nled.draw_text2(0, 20, str(velicina)+\":\", 2)\nled.draw_text2(0, 50, str(hodnota), 2)\nled.display()\n\n\ndef getConnection():\n hostname = \"nag-iot.zcu.cz\"\n response = os.system(\"ping -c 1 \" + hostname)\n if response == 0:\n return True\n else:\n return False\n\nwhile True:\n clkState = GPIO.input(clk)\n if clkState != clkLastState:\n dtState = GPIO.input(dt)\n if dtState != clkState:\n counter += 1\n else:\n counter -= 1\n if counter > 8:\n counter = 1\n if counter < 1:\n counter = 8\n \n if counter == 1:\n pristroj = \"DALLAS\"\n velicina = \"Teplota\"\n hodnota = (str)(read_temp())+\" *C\"\n elif counter == 2:\n pristroj = \"BMP180\"\n velicina = \"Tlak -more\"\n hodnota = (str)(sensor.read_sealevel_pressure())+\" Pa\"\n elif counter == 3:\n pristroj = \"BMP180\"\n velicina = \"Tlak -local\"\n hodnota = (str)(sensor.read_pressure())+\" Pa\"\n elif counter == 4:\n pristroj = \"BMP180\"\n velicina = \"Teplota\"\n hodnota = (str)(sensor.read_temperature())+\" *C\"\n elif counter == 5:\n pristroj = \"BMP180\"\n velicina = \"Altitude\"\n hodnota = (str)((int)(sensor.read_altitude()))+\" m.n.m\"\n elif counter == 6:\n pristroj = \"RPi\"\n velicina = \"Datum\"\n hodnota = time.strftime(\"%d-%m-%Y\")\n elif counter == 7:\n pristroj = \"RPi\"\n velicina = \"Cas\"\n hodnota = time.strftime(\"%H:%M\")\n elif counter == 8:\n pristroj = \"Spojenie so\"\n velicina = \"serverom\"\n if getConnection():\n hodnota = \"Connected\"\n else:\n hodnota = \"Connection failed\"\n led.clear_display()\n led.draw_text2(0, 0, str(pristroj), 2)\n led.draw_text2(0, 20, str(velicina)+\":\", 2)\n led.draw_text2(0, 50, str(hodnota), 2)\n led.display()\nclkLastState = clkState\n","sub_path":"Ex.3/3d.py","file_name":"3d.py","file_ext":"py","file_size_in_byte":3675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"607759504","text":"\n\"\"\"\n호출자가 전달하는 변수의 타입에 따라 다르게 처리\n • 변경가능 변수(mutable)\n • 변경불가 변수(immutable)\n\n\"\"\"\n\n\n\"\"\"\n변경불가 변수 사용\n\"\"\"\nn = 10\nm = 20\ndef add(x, y):\n return x + y\n\n# 레퍼런스로 전달된 값으로 함수 실행\nresult = add(n, m)\nprint(result)\n\n\n\nx=40 #변경불가 변수 선언\ndef plus(x, y):\n x=4 #값이 4인 객체가 생성되고 x에 레퍼런스가 할당됩니다.\n return x + y\n\nresult = plus(x, m)\nprint(result)\n\nprint(x)\n#함수 내에서 변경한 사항이 함수 외부에 영향을 주지 않습니다.\n\n\n\n\"\"\"\n변경가능 변수 사용\n\"\"\"\n\ndef changeChar(x):\n x[0]='F' #list x의 0번째 아이템을 'F'로 변경 \n\n \nstrlist=['P', 'Y', 'T', 'H', 'O', 'N']\nchangeChar(strlist)\n#changeChar()가 호출자의 객체에 영향을 미칩니다.\nprint(strlist)\n","sub_path":"PythonMain/src/ch08-function/ex08.py","file_name":"ex08.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"222571627","text":"import os\nimport argparse\nos.chdir(os.path.dirname(os.path.realpath(__file__)))\nfrom job_utils import draws, parsers\n\n\n##############################################################################\n# class to calculate attribution\n##############################################################################\n\nclass AttributeMale(draws.SquareImport):\n\n def __init__(self, me_map, **kwargs):\n # super init\n super(AttributeMale, self).__init__(**kwargs)\n\n # store data by me in this dict \n # key=me_id, val=dataframe\n self.me_map = me_map\n self.me_dict = {}\n\n # import every input\n for v in me_map.values():\n inputs = v.get(\"srcs\", {})\n for me_id in inputs.values():\n self.me_dict[me_id] = self.import_square(\n gopher_what={\"modelable_entity_id\": me_id},\n source=\"epi\")\n\n def remove_negatives(self, df):\n positive = df.copy()\n positive[positive<0.] = 0.\n assert (positive < 0.0).any().any() == False\n return positive\n\n def calc_residual(self):\n\n # compile keys\n env_prim_key = self.me_map[\"env\"][\"srcs\"][\"prim\"]\n env_sec_key = self.me_map[\"env\"][\"srcs\"][\"sec\"]\n kline_bord_key = self.me_map[\"kline\"][\"srcs\"][\"bord\"]\n kline_mild_key = self.me_map[\"kline\"][\"srcs\"][\"mild\"]\n kline_asym_key = self.me_map[\"kline\"][\"srcs\"][\"asym\"]\n idio_prim_key = self.me_map[\"idio\"][\"trgs\"][\"prim\"]\n idio_sec_key = self.me_map[\"idio\"][\"trgs\"][\"sec\"]\n cong_uro_inf_only_key = self.me_map[\"cong_uro\"][\"srcs\"][\"inf_only\"]\n cong_uro_ag_key = self.me_map[\"cong_uro\"][\"srcs\"][\"ag\"]\n cong_uro_uti_key = self.me_map[\"cong_uro\"][\"srcs\"][\"uti\"]\n cong_uro_imp_key = self.me_map[\"cong_uro\"][\"srcs\"][\"imp\"]\n cong_uro_ag_uti_key = self.me_map[\"cong_uro\"][\"srcs\"][\"ag_uti\"]\n cong_uro_ag_imp_key = self.me_map[\"cong_uro\"][\"srcs\"][\"ag_imp\"]\n cong_uro_imp_uti_key = self.me_map[\"cong_uro\"][\"srcs\"][\"imp_uti\"]\n cong_uro_ag_imp_uti_key = self.me_map[\"cong_uro\"][\"srcs\"][\"ag_imp_uti\"]\n\n # sum up klinefelter\n sigma_kline = (\n self.me_dict[kline_bord_key] + self.me_dict[kline_mild_key] +\n self.me_dict[kline_asym_key])\n\n #sum up congenital urogenital\n sigma_cong_uro = (\n self.me_dict[cong_uro_inf_only_key] + self.me_dict[cong_uro_ag_key] +\n self.me_dict[cong_uro_uti_key] + self.me_dict[cong_uro_imp_key] +\n self.me_dict[cong_uro_ag_uti_key] + self.me_dict[cong_uro_ag_imp_key] +\n self.me_dict[cong_uro_imp_uti_key] + self.me_dict[cong_uro_ag_imp_uti_key]\n )\n\n # subtract klinefleter and congenital urogenital from total primary\n idio_prim = self.me_dict[env_prim_key] - sigma_kline - sigma_cong_uro\n idio_prim = self.remove_negatives(idio_prim)\n self.me_dict[idio_prim_key] = idio_prim\n self.me_dict[idio_sec_key] = self.me_dict[env_sec_key]\n\n##############################################################################\n# function to run attribution\n##############################################################################\n\n\ndef male_attribution(me_map, location_id, out_dir):\n\n # declare calculation dimensions\n dim = AttributeMale.default_idx_dmnsns\n dim[\"location_id\"] = location_id\n dim[\"measure_id\"] = [5]\n dim[\"sex_id\"] = [1]\n\n # run attribution\n attributer = AttributeMale(me_map=me_map, idx_dmnsns=dim)\n attributer.calc_residual()\n\n # save results to disk\n for mapper in me_map.values():\n outputs = mapper.get(\"trgs\", {})\n for me_id in outputs.values():\n fname = str(location_id[0]) + \".h5\"\n out_df = attributer.me_dict[me_id].reset_index()\n out_df.to_hdf(os.path.join(out_dir, str(me_id), fname), \n key=\"draws\", format=\"table\", data_columns=dim.keys())\n\n##############################################################################\n# when called as a script\n##############################################################################\n\nif __name__ == \"__main__\":\n\n # parse command line args\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--me_map\", help=\"json style string map of ops\",\n required=True, type=parsers.json_parser)\n parser.add_argument(\"--out_dir\", help=\"root directory to save stuff\",\n required=True)\n parser.add_argument(\"--location_id\", help=\"which year to use\",\n type=parsers.int_parser, nargs=\"*\", required=True)\n args = vars(parser.parse_args())\n\n # call function\n male_attribution(me_map=args[\"me_map\"], out_dir=args[\"out_dir\"],\n location_id=args[\"location_id\"])\n","sub_path":"gbd_2019/nonfatal_code/infertility/male_attr.py","file_name":"male_attr.py","file_ext":"py","file_size_in_byte":4796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"561918865","text":"from setuptools import setup, find_packages\nimport os\n\nversion = '0.4'\n\nsetup(name='valentine.multiparagraphpage',\n version=version,\n description=\"A page content type with multiple paragraphs(text bodies) without being folderish.\",\n long_description=open(\"README.txt\").read() + \"\\n\" +\n open(os.path.join(\"docs\", \"HISTORY.txt\")).read(),\n # Get more strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n \"Programming Language :: Python\",\n ],\n keywords='archetype, plone, richtext, multi paragrah',\n author='Sasha Vincic',\n author_email='sasha dot vincic at valentinewebsystems dot se',\n url='http://svn.plone.org/svn/collective/valentine.multiparagraphpage/trunk/',\n license='GPL',\n packages=find_packages(exclude=['ez_setup']),\n namespace_packages=['valentine'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n 'valentine.multiparagraphfield',\n 'valentine.contentportlets',\n ],\n entry_points=\"\"\"\n # -*- Entry points: -*-\n \"\"\",\n )\n","sub_path":"pypi_install_script/valentine.multiparagraphpage-0.4/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"2095337","text":"#! /usr/bin/env python\nimport roslib; roslib.load_manifest('C42_ZMPWalk')\nimport rospy\nimport copy\nfrom atlas_msgs.msg import AtlasState\nfrom std_msgs.msg import Int32, Float64\n\ndef none(iterable):\n for k in iterable:\n if k:\n return False\n return True\n\nclass contact_reflex():\n def __init__(self,buffer_len = 20):\n self._treshold = 100;\n self._state = {'l':1,'r':1}\n self._states_buffer = {'l':[True for k in xrange(buffer_len)],'r':[True for k in xrange(buffer_len)]}\n\n def Update(self,r_foot_z,l_foot_z):\n l_state = (l_foot_z > self._treshold)\n r_state = (r_foot_z > self._treshold)\n for leg in self._state:\n if leg == 'l':\n state = l_state\n else:\n if leg == 'r':\n state = r_state\n\n buf = self._states_buffer[leg]\n buf.insert(0,state)\n buf.pop()\n if all(buf):\n self._state[leg] = 1\n else:\n if none(buf):\n self._state[leg] = 0\n return self._state['r'],self._state['l'] \n\n\n\nif __name__ == '__main__':\n rospy.init_node('test')\n class test(object):\n def __init__(self):\n self.sub = rospy.Subscriber('/atlas/atlas_state',AtlasState,self.on_update)\n self.pub = rospy.Publisher('/contact_reflex',Int32)\n self.reflex = contact_reflex()\n def on_update(self,msg):\n # print 1\n r,l = self.reflex.Update(msg.r_foot.force.z,msg.l_foot.force.z)\n self.pub.publish(Int32(r))\n\n testinger = test()\n rospy.spin()\n","sub_path":"C42_ZMPWalk/scripts/contact_reflex.py","file_name":"contact_reflex.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"52921072","text":"\n# simple Interest\n# si = p * T * /100\n\n\ndef interest(Value1, Value2, Value3):\n si = (Value1 * Value2 * Value3)/100\n print(\"The simple interest of above numbers\", si)\n return si\nPrincipal = int( input( \"Please enter your principal amount :\" ) )\nTime = int( input( \"Please enter your time:\" ) )\nRate = int( input( \"Please enter your rate:\" ) )\ninterest( Principal, Time, Rate )\n\n\n# A = P(1 + R/100) t\n# Compound Interest = A – P\n\ndef compoundinterest(principal,rate,time):\n amount = principal * (pow((1+ rate / 100),time))\n print( \"The total amount is\", amount )\n ci = amount - principal\n print(\"The compound interest is:\", ci)\ncompoundinterest( 10, 20, 30 )","sub_path":"simpleinterest.py","file_name":"simpleinterest.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"144998455","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nimport requests\nfrom bs4 import BeautifulSoup\n\n\ndef webscrape():\n #get data \n data = requests.get('https://www.hockey-reference.com/leagues/NHL_2020_standings.html')\n\n # Load data into bs4\n soup = BeautifulSoup(data.text, 'html.parser')\n\n standings = soup.find('table',{'id': 'standings'})\n tbody = standings.find('tbody')\n\n for tr in tbody.find_all('tr'):\n place = tr.find_all('td')[0].text.strip()\n record = tr.find_all('td')[1].text.strip()\n\n \n print(\"\\nTeam name: \"+ place+ \"\\nRecord: \"+ record)\n ","sub_path":"webscrape.py","file_name":"webscrape.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"424860193","text":"\"\"\"Python script to test the filetypes_utils\n\"\"\"\nimport sys\nimport os.path\nimport unittest\nimport logging\nimport filetype_utils\n\nlogger = logging.getLogger(__name__)\n\nfilelist_file = None\nft_to_category_history = {}\n\nclass TestFileTypes(unittest.TestCase):\n def _check_category(self, path, filetype, category):\n if ft_to_category_history.has_key(filetype):\n # check that filetype always maps to same category\n (prev_cat, prev_path) = ft_to_category_history[filetype]\n self.assertEqual(prev_cat, category,\n \"Filetype %s has inconsistent category mappings: %s maps to category %s, %s maps to category %s\" %\n (filetype, prev_cat, prev_path, category, path))\n else:\n ft_to_category_history[filetype] = (category, path)\n \n def _tc(self, path, filetype, category, indexable):\n \"\"\"The work for running a single testcase\"\"\"\n (t, c) = filetype_utils.get_file_description_and_category(path)\n self.assertEqual(t, filetype,\n \"Expecting filetype %s for %s, got %s\" %\n (filetype, path, t))\n self.assertEqual(c, category,\n \"Expecting category %s for %s, got %s\" %\n (category, path, c))\n self._check_category(path, t, c)\n i = filetype_utils.is_indexable_file(path)\n self.assertEqual(i, indexable,\n \"Path %s is %sindexable, expecting %sindexable\" %\n (path, \"\" if i else \"not \", \"\" if indexable else \"not \"))\n \n def testNameRule(self):\n self._tc(\"foo/bar/LICENSE\", \"License file\", \"text\", True)\n\n def testExtnRule(self):\n self._tc(\"foo/bar/baz/foo.pdf\", \"Portable Document File\", \"text\", False)\n\n def testFiletypesLibRule(self):\n self._tc(\"foo/bar/testing.mp3\", 'MP3 Audio File', 'audio', False)\n\n def testDefaultRule(self):\n self._tc(\"foo/bar/alkjedlk33jhdl3jlc\", \"unknown\", \"unknown\", False)\n\n def testSubtitleRules(self):\n self._tc(\"/Applications/Aquamacs.app/Contents/Resources/etc/srecode/wisent.srt\",\n \"Emacs SRecode file\", \"development\", True)\n self._tc(\"/Developer/usr/share/automake-1.10/config.sub\",\n \"Automake Configuration Script\", \"development\", True)\n self._tc(\"foo/bar/subtitles.srt\",\n \"Subtitle File\", \"text\", True)\n self._tc(\"foo/bar/subtitles.sub\",\n \"Subtitle File\", \"text\", True)\n\n def testFileList(self):\n \"\"\"Optionally check all the filetype => category mappings for a list of\n paths provided in a file.\n \"\"\"\n if filelist_file:\n logging.info(\"Running filelist test using file %s\" % filelist_file)\n with open(filelist_file, \"rb\") as f:\n for line in f:\n path = line.decode(\"utf-8\").rstrip()\n (t, c) = filetype_utils.get_file_description_and_category(path)\n self._check_category(path, t, c)\n else:\n logging.info(\"Skipping filelist test. To run, specify --filelist=path, where path is a path to a list of files\")\n \nif __name__ == '__main__':\n logging.basicConfig(level=logging.DEBUG)\n args = sys.argv\n for i in range(1,len(sys.argv)):\n if sys.argv[i].startswith(\"--filelist=\"):\n filelist_file = os.path.abspath(os.path.expanduser(sys.argv[i][len(\"--filelist=\"):]))\n if not os.path.exists(filelist_file):\n sys.stderr.write(\"Filelist file %s does not exist\\n\" % filelist_file)\n sys.exit(1)\n args = sys.argv[0:i] + sys.argv[i+1:]\n break\n \n unittest.main(argv=args)\n","sub_path":"blox/filename_categorizer__1_0/test_filetypes.py","file_name":"test_filetypes.py","file_ext":"py","file_size_in_byte":3784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"221720883","text":"import tensorflow as tf\nimport numpy as np\nimport click\nimport pickle\nimport gzip\nimport csv\n\n\ndef momentum_update(momentum, lr, old, new):\n return (momentum * old) - (lr * new / tf.to_float(tf.shape(new)[0]))\n\n\nclass RBM:\n def __init__(self, num_visible, num_hidden, k, lr, momentum):\n self.num_visible = num_visible\n self.num_hidden = num_hidden\n self.k = k\n self.lr = lr\n self.momentum = momentum\n\n self.input = tf.placeholder(tf.float32,\n [None, self.num_visible],\n name='input')\n\n self.weights = tf.Variable(\n tf.random_normal([self.num_visible, self.num_hidden],\n mean=0.0, stddev=1./np.sqrt(self.num_visible)),\n name='weights',\n dtype=tf.float32)\n self.visible_bias = tf.Variable(tf.zeros([self.num_visible]),\n name='visible_bias',\n dtype=tf.float32)\n self.hidden_bias = tf.Variable(tf.zeros([self.num_hidden]),\n name='hidden_bias',\n dtype=tf.float32)\n\n self.weight_grad = tf.Variable(\n tf.zeros([self.num_visible, self.num_hidden]), dtype=tf.float32)\n self.visible_bias_grad = tf.Variable(\n tf.zeros([self.num_visible]), dtype=tf.float32)\n self.hidden_bias_grad = tf.Variable(\n tf.zeros([self.num_hidden]), dtype=tf.float32)\n\n self.param_updaters = None\n self.grad_updaters = None\n\n # self.visible_space = None\n # self.logZ = None\n # self.nll_val = None\n # self.data_len = None\n\n self._init_vars()\n init = tf.global_variables_initializer()\n\n self.sess = tf.Session()\n self.sess.run(init)\n\n def prob_h_given_v(self, v):\n return tf.nn.sigmoid(tf.matmul(v, self.weights)\n + self.hidden_bias)\n\n def sample_h_given_v(self, v):\n bernoulli = tf.distributions.Bernoulli(probs=self.prob_h_given_v(v),\n dtype=tf.float32)\n return bernoulli.sample()\n\n def prob_v_given_h(self, h):\n return tf.nn.sigmoid(tf.matmul(h, self.weights, transpose_b=True)\n + self.visible_bias)\n\n def sample_v_given_h(self, h):\n bernoulli = tf.distributions.Bernoulli(probs=self.prob_v_given_h(h),\n dtype=tf.float32)\n return bernoulli.sample()\n\n def gibbs_step(self, i, v0, h0):\n v = self.sample_v_given_h(h0)\n h = self.sample_h_given_v(v)\n return [i+1, v, h]\n\n def gibbs_sampling(self, v0):\n h0 = self.sample_h_given_v(v0)\n i0 = tf.constant(0)\n [_, v, h] = tf.while_loop(lambda i, v, h: tf.less(i, self.k),\n self.gibbs_step,\n [i0, v0, h0],\n shape_invariants=[\n i0.get_shape(),\n tf.TensorShape([None, self.num_visible]),\n tf.TensorShape([None, self.num_hidden])])\n\n return v0, h0, v, h, self.prob_h_given_v(v)\n\n def _init_vars(self):\n v0, h0, vk, hk, phk = self.gibbs_sampling(self.input)\n\n pos_weight_grad = tf.matmul(tf.transpose(v0), h0)\n neg_weight_grad = tf.matmul(tf.transpose(vk), phk)\n\n new_weight_grad = momentum_update(self.momentum,\n self.lr,\n self.weight_grad,\n neg_weight_grad - pos_weight_grad)\n new_vb_grad = momentum_update(self.momentum,\n self.lr,\n self.visible_bias_grad,\n tf.reduce_mean(vk - self.input, 0))\n new_hb_grad = momentum_update(self.momentum,\n self.lr,\n self.hidden_bias_grad,\n tf.reduce_mean(phk - h0, 0))\n\n weight_grad_updater = self.weight_grad.assign(new_weight_grad)\n vb_grad_updater = self.visible_bias_grad.assign(new_vb_grad)\n hb_grad_updater = self.hidden_bias_grad.assign(new_hb_grad)\n\n weight_updater = self.weights.assign_add(weight_grad_updater)\n visible_bias_updater = self.visible_bias.assign_add(vb_grad_updater)\n hidden_bias_updater = self.hidden_bias.assign_add(hb_grad_updater)\n\n self.param_updaters = [weight_updater,\n visible_bias_updater,\n hidden_bias_updater]\n self.grad_updaters = [weight_grad_updater,\n vb_grad_updater,\n hb_grad_updater]\n\n # self.data_len = tf.convert_to_tensor(-float('inf'), dtype=tf.float32)\n # self.visible_space = self.generate_visible_space()\n # self.logZ = self.log_partition()\n # self.nll_val = self.nll()\n\n def train(self, data, epochs, batch_size):\n for ep in range(epochs+1):\n np.random.shuffle(data)\n\n batches = [data[batch_start:(batch_start + batch_size)]\n for batch_start in range(0, len(data), batch_size)]\n\n # if ep % 100 == 0:\n # logZ = self.sess.run(self.logZ)\n # nll = self.sess.run(self.nll_val,\n # feed_dict={\n # self.input: data,\n # self.logZ: logZ,\n # self.data_len: len(data)\n # })\n # print(nll / len(data))\n\n if ep == epochs:\n break\n\n for batch in batches:\n self.sess.run(self.param_updaters + self.grad_updaters,\n feed_dict={self.input: batch})\n\n def get_params(self):\n return (self.sess.run(self.weights),\n self.sess.run(self.visible_bias),\n self.sess.run(self.hidden_bias))\n\n def free_energy(self, v):\n visible_bias_term = tf.matmul(v,\n tf.reshape(self.visible_bias, [-1, 1]))\n hidden_bias_term = tf.reduce_sum(tf.nn.softplus(\n tf.matmul(v, self.weights) + self.hidden_bias\n ), axis=1, keepdims=True)\n return visible_bias_term + hidden_bias_term\n\n def generate_visible_space(self):\n space = np.zeros((1 << self.num_visible, self.num_visible))\n\n for i in range(1 << self.num_visible):\n d = i\n for j in range(self.num_visible):\n d, r = divmod(d, 2)\n space[i, self.num_visible - j - 1] = int(r)\n\n return tf.convert_to_tensor(space, dtype=tf.float32)\n\n def log_partition(self):\n free_energies = self.free_energy(self.visible_space)\n return tf.reduce_logsumexp(free_energies)\n\n def nll(self):\n total_free_energy = tf.reduce_sum(self.free_energy(self.input))\n return (self.data_len*self.logZ) - total_free_energy\n\n\n@click.group(context_settings={\"help_option_names\": ['-h', '--help']})\ndef cli():\n \"\"\"Simple tool for training an RBM\"\"\"\n pass\n\n\ndef load_train(L):\n data = np.load(\"/home/data/critical-2d-ising/L={}/q=2/configs.npy\"\n .format(L))\n data = data.reshape(data.shape[0], L*L)\n return data.astype('float32')\n\n\n@cli.command(\"benchmark\")\n@click.option('-n', '--num-hidden', default=None, type=int,\n help=(\"number of hidden units in the RBM; defaults to \"\n \"number of visible units\"))\n@click.option('-e', '--epochs', default=250, show_default=True, type=int)\n@click.option('-b', '--batch-size', default=32, show_default=True, type=int)\n@click.option('-k', multiple=True, type=int,\n help=\"number of Contrastive Divergence steps\")\n@click.option('-l', '--learning-rate', default=1e-3,\n show_default=True, type=float)\n@click.option('-m', '--momentum', default=0.0, show_default=True, type=float,\n help=(\"value of the momentum parameter; ignored if \"\n \"using SGD or Adam optimization\"))\n@click.option('-o', '--output-file', type=click.Path(),\n help=\"where to save the benchmarks csv file.\")\ndef benchmark(num_hidden, epochs, batch_size,\n k, learning_rate, momentum, output_file):\n \"\"\"Trains RBM on several datasets and measures the training time\"\"\"\n from os import listdir\n from os.path import isdir, join\n import time\n\n dataset_sizes = [int(f.split('=')[-1])\n for f in listdir('/home/data/critical-2d-ising/')\n if isdir(join('/home/data/critical-2d-ising/', f))]\n\n with open(output_file, 'w') as f:\n writer = csv.DictWriter(f, ['L', 'k', 'time'])\n for L in sorted(dataset_sizes):\n for k_ in k:\n print(\"L = {}; k = {}\".format(L, k_))\n train_set = load_train(L)\n\n num_hidden = (train_set.shape[-1]\n if num_hidden is None\n else num_hidden)\n\n rbm = RBM(num_visible=train_set.shape[-1],\n num_hidden=num_hidden,\n k=k_, lr=learning_rate,\n momentum=momentum)\n\n time_elapsed = -time.perf_counter()\n rbm.train(train_set, epochs, batch_size)\n time_elapsed += time.perf_counter()\n\n writer.writerow({'L': L,\n 'k': k_,\n 'time': time_elapsed})\n\n\n@cli.command(\"train\")\n@click.option('--train-path', default='../data/Ising2d_L4.pkl.gz',\n show_default=True, type=click.Path(exists=True),\n help=\"path to the training data\")\n@click.option('-n', '--num-hidden', default=None, type=int,\n help=(\"number of hidden units in the RBM; defaults to \"\n \"number of visible units\"))\n@click.option('-e', '--epochs', default=1000, show_default=True, type=int)\n@click.option('-b', '--batch-size', default=100, show_default=True, type=int)\n@click.option('-k', default=1, show_default=True, type=int,\n help=\"number of Contrastive Divergence steps\")\n@click.option('-l', '--learning-rate', default=1e-3,\n show_default=True, type=float)\n@click.option('-m', '--momentum', default=0.5, show_default=True, type=float,\n help=(\"value of the momentum parameter; ignored if \"\n \"using SGD or Adam optimization\"))\ndef train(train_path, num_hidden, epochs, batch_size,\n k, learning_rate, momentum):\n \"\"\"Train an RBM\"\"\"\n with gzip.open(train_path) as f:\n train_set = pickle.load(f, encoding='bytes')\n\n num_hidden = train_set.shape[-1] if num_hidden is None else num_hidden\n\n rbm = RBM(num_visible=train_set.shape[-1],\n num_hidden=num_hidden,\n k=k, lr=learning_rate,\n momentum=momentum)\n\n rbm.train(train_set, epochs, batch_size)\n\n\nif __name__ == '__main__':\n cli()\n","sub_path":"tools/benchmarks/tensorflow/rbm_alt.py","file_name":"rbm_alt.py","file_ext":"py","file_size_in_byte":11357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"182927176","text":"#!/usr/bin/python3\n\n# -----> System Imports <-----\nimport os\nimport sys\nfrom time import *\nimport datetime\nimport shutil\nimport threading\n# -----> Tkinter Imports <------\nimport tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import messagebox\nfrom tkinter import *\n# -----> Matplotlib Imports <------\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')\nimport matplotlib as mpl\nmpl.use(\"TkAgg\")\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk\nfrom matplotlib.figure import Figure\nimport matplotlib.animation as animation\nfrom matplotlib import style\n# -----> Auxiliary Imports <------\nfrom gui_widgets import *\n# from cannibix_components_HH import *\n# # -----> RPi Imports <------\n# import RPi.GPIO as GPIO\n# import time\n# import os\n# import Adafruit_ADS1x15 as ADS\n# import serial\n# from pathlib import Path\n\n# GPIO.setmode(GPIO.BOARD)\n# adc = ADS.ADS1115(0x48)\n# adc2 = ADS.ADS1115(0x49)\n#\n# #ADC2\n# sensor1 = MOS(adc2, 0)\n# sensor2 = MOS(adc2, 1)\n# sensor3 = MOS(adc2, 2)\n# sensor4 = MOS(adc2, 3)\n#\n# #ADC1\n# sensor5 = MOS(adc, 0)\n# sensor6 = MOS(adc, 1)\n# sensor7 = MOS(adc, 2)\n# sensor8 = MOS(adc, 3)\n#\n# all_sensors = all_sensors(sensor1,sensor2,sensor3,sensor4)\n# # all_sensors2 = all_sensors(sensor5,sensor6,sensor7,sensor8)\n# # Temperature sensor\n# Temp_adc_channel = 1\n# temperatureSensor = TemperatureSensor(adc, Temp_adc_channel)\n# #Pressure Sensor\n# Press_adc_channel = 0\n# pressureSensor = PressureSensor(adc,Press_adc_channel)\n\n##################################################\n#################### Data Array ####################\n# DO NOT TOUCH # -teehee touched\ndataVector = []\ntimeVector = []\ntest_type_Vector = []\nparam_vector = []\n#################### Color Settings ####################\nwarning_color = '#FFC300'\ntabBar_color = '#85929E'\ntabBarActive_color = '#AEB6BF'\nrunBtn_color = '#9DE55F'\nstopBtn_color = '#FF4E4E'\ndefault_bg_color = '#22487d'\n#################### GUI ####################\n\nprojectName = 'Cannibix Manual GUI'\nclass CannibixManGUI(tk.Tk):\n def __init__(self, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs) #Passes all aguments to the parent class.\n\n self.title(projectName + ' GUI') #Title of the master window.\n self.geometry('640x480') #Initial size of the master window.\n # self.resizable(0,0) #The allowance for the master window to be adjusted by.\n\n canvas = tk.Frame(self, bg = default_bg_color) #Creates the area for which pages will be displayed.\n canvas.place(relx=0, rely=0, relheight=0.9, relwidth=1) #Defines the area which each page will be displayed.\n canvas.grid_rowconfigure(0, weight=1) #DO NOT ADJUST. Forces each frame to overlap.\n canvas.grid_columnconfigure(0, weight=1) #DO NOT ADJUST. Forces each frame to overlap.\n\n self.tabBar = tk.Frame(self, bg=tabBar_color) #Creates the area for which control buttons will be placed.\n self.tabBar.place(relx=0, rely=0.9, relheight=0.1, relwidth=1) #Defines the area for which control buttons will be placed.\n\n self.frames = {} #Dictonary to store each frame after creation.\n\n for f in (HomePage, DataPage):#, ManualControlPage): #For pages to be added, do the following:\n frame = f(canvas,self) #Creates a frame of the above classes.\n self.frames[f] = frame #Add the created frame to the 'frames' dictionary.\n frame.grid(row=0, column=0, sticky=\"nsew\") #Overlaps the frame in the same grid space.\n self.show_frame(HomePage) #Sets the default page.\n\n #Setup controls for fullscreen\n self.attributes(\"-fullscreen\", True)\n self.fullscreen = True\n self.bind(\"\", self.toggle_fullscreen)\n self.bind(\"\", self.end_fullscreen)\n\n print('System ready.')\n\n def show_frame(self, cont): #Control buttons will run this command for their corresponding pages.\n frame = self.frames[cont] #Obtain frame object from the dictionary.\n frame.tkraise()\n\n def toggle_fullscreen(self, event=None):\n self.fullscreen = not self.fullscreen # Just toggling the boolean.\n self.attributes(\"-fullscreen\", self.fullscreen) #Pass the fullcreen boolean to tkinter.\n return \"break\"\n\n def end_fullscreen(self, event=None):\n self.fullscreen = False\n self.attributes(\"-fullscreen\", False)\n return \"break\"\n\n def shutdown(self):\n os.system(\"sudo shutdown -h now\")\n\nclass HomePage(tk.Frame):\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent, bg = default_bg_color)\n control_btn = tk.Button(controller.tabBar, text='Home', bg=tabBar_color, activebackground=tabBarActive_color, bd=0, command=lambda: controller.show_frame(HomePage)) #Creates a control button in the tabs bar.\n control_btn.pack(side='left', expand= True, fill = 'both')\n\n title = tk.Label(self, text=projectName, font=14, relief='solid')\n title.place(relx=0.2,rely=0.3,relwidth=0.6,relheight=0.15)\n\n intro = '''Microfluidic-based THC detector. Developed by ATF Lab\n [F11: Toggle Fullscreen]\n [Esc: Exit Fullscreen]'''\n\n introduction = tk.Label(self, text=intro, anchor='n')\n introduction.place(relx=0.1,rely=0.55,relheight=0.35,relwidth=0.8)\n\n #Hash this out if no such functionallity is required. Or if there are bugs.\n self.exitBtn = tk.Button(self, text='Exit Fullscreen', command=lambda:controller.end_fullscreen())\n self.exitBtn.place(relx=0.1,rely=0.8,relheight=0.2,relwidth=0.3)\n self.shutdownBtn = tk.Button(self, text='Shutdown', command=lambda:controller.shutdown())\n self.shutdownBtn.place(relx=0.6,rely=0.8,relheight=0.2,relwidth=0.3)\n\nclass DataPage(tk.Frame):\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent, bg = default_bg_color)\n control_btn = tk.Button(controller.tabBar, text='Data', bg=tabBar_color, activebackground=tabBarActive_color, bd=0, command=lambda: controller.show_frame(DataPage))\n control_btn.pack(side='left', expand= True, fill = 'both')\n\n seq1Frame = tk.Frame(self,borderwidth = 5,relief = GROOVE)\n seq1Frame.place(relx = .05,rely = 0, relheight = 0.2, relwidth = .9)\n self.seq1Label = tk.Label(seq1Frame, text='This is step 1',font=20)\n self.seq1Label.place(relx = 0, rely = .5, relheight = .4, relwidth = .5)\n self.seq1button = tk.Button(seq1Frame, )\n self.run_and_stop = tk.Frame(self)\n self.run_and_stop.place(relx=0.8,rely=0.9,relheight=0.1,relwidth=0.2)\n self.run_and_stop.grid_rowconfigure(0, weight=1) #DO NOT ADJUST. Forces buttons to overlap.\n self.run_and_stop.grid_columnconfigure(0, weight=1) #DO NOT ADJUST.\n\n self.stopBtn = tk.Button(self.run_and_stop, text='STOP', bg=stopBtn_color, activebackground=stopBtn_color, command=lambda:end_testing())\n self.stopBtn.grid(row=0, column=0, sticky=\"nsew\")\n\n self.contFill = tk.Button(self.run_and_stop, text='CONTINUE', bg=runBtn_color, activebackground=runBtn_color, command=lambda:start_fill_thread())\n self.contFill.grid(row=0, column=0, sticky=\"nsew\")\n\n self.runBtn = tk.Button(self.run_and_stop, text='RUN', bg=runBtn_color, activebackground=runBtn_color, command=lambda:start_purge_thread())\n self.runBtn.grid(row=0, column=0, sticky=\"nsew\")\n\n\n\n# self.timer = Timer(self)\n# self.timer.place(relx = .5, rely = .5, relheight = .5, relwidth = 0.5)\n# self.status = tk.StringVar()\n# self.status.set('Ready for Sample Sequence')\n#\n# self.progressTitle = tk.Label(self, textvariable = self.status, anchor='w')\n# self.progressTitle.place(relx=0,rely=0.9,relheight=0.07,relwidth=0.8)\n#\n# self.progressbar = ttk.Progressbar(self, orient='horizontal', mode='determinate', maximum=100)\n# self.progressbar.place(relx=0,rely=0.97,relheight=0.03,relwidth=0.8)\n\n# def fill_cup():\n# messagebox.showwarning(\"Sample Gas Testing\",\"Insert Sample Gas line into Cup and Press OK\")\n# app.frames[DataPage].timer.reset()\n# responseFrame = tk.Frame(self)\n# responseFrame.place(relx=0.8,rely=0,relheight=0.3,relwidth=0.2)\n#\n# self.filenamelbl = tk.Label(responseFrame,text='Filename (Optional)',anchor='w')\n# self.filenamelbl.place(relx=0,rely=0.7,relheight = 0.5,relwidth = 1)\n# #self.filename_add = tk.StringVar()\n# self.filenamefiller = tk.Entry(responseFrame)\n# self.filenamefiller.place(relx=0,rely=.8,relwidth=1)\n\ntry:\n app = CannibixManGUI()\n app.mainloop()\nexcept KeyboardInterrupt:\n #GPIO.cleanup()\n pass\nfinally:\n #GPIO.cleanup()\n pass\n","sub_path":"Devices/Archive/manual/can_manual_test.py","file_name":"can_manual_test.py","file_ext":"py","file_size_in_byte":8615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"62222931","text":"import pytest\nfrom steps.object import get_item_from\nfrom steps.object import correspond_selected_object\nfrom random import randint\nfrom utils.getter import get_time_in_format\nfrom steps.waitings import waiting_tasks_processing\n\n\n@pytest.allure.CRITICAL\n@pytest.allure.feature('REST.Functional - Предприятие - Настройки опция \"Включать НДС в себестоимость\"')\n@pytest.mark.functional_tests\n@pytest.mark.func_group_1\n@pytest.mark.includevatinprimecost\nclass TestFunctionalTestsIncludeVatInPrimeCost:\n # Background\n @pytest.fixture()\n def background(self, rest_api):\n background_result = dict()\n\n # Добавляем поставщика\n provider_1 = rest_api.send_create(\n 'warehouse.providers',\n 'Organization',\n {'shortName': 'Юр. лицо %s' % randint(0, 5555)}\n )\n\n # Выбираем НДС 18%\n vat_list = rest_api.select_objects('core.dictionaries.vat')['ds']\n vat_18 = get_item_from(vat_list, table={'title': '18.00000 %'})\n\n # Запрашиваем информацию о складе\n store_list = rest_api.select_objects('warehouse.store')['ds']\n store_1 = get_item_from(store_list, table={'title': 'Склад 1'})\n\n # Создаем товар 1\n background_result['singleproduct_1'] = rest_api.send_create(\n 'warehouse.nomenclature.singleproduct', 'item',\n {\n 'name': 'Товар 1 -%s' % randint(0, 3333),\n 'designator': 'single'\n }\n )\n\n # Создаём Приходную Накладную и заполняем её\n current_time = get_time_in_format(format_time='invoicedate', offset_min=0)\n background_result['incoming_1'] = rest_api.send_create(\n 'warehouse.documents.incoming', 'item',\n {\n 'provider': provider_1,\n 'store': store_1,\n 'invoiceDate': current_time\n }\n )\n\n rest_api.send_create(\n 'warehouse.documents.items.common', 'item',\n payload_table={\n 'product': background_result['singleproduct_1'],\n 'actualAmount': 100,\n 'measureUnit': background_result['singleproduct_1']['measureUnit'],\n 'price': 10,\n 'fixedTotalSumWithoutVat': 1000,\n 'fixedTotalSum': 1180,\n 'vat': vat_18\n },\n params={\n 'owner_object': background_result['incoming_1']\n }\n )\n\n # Запрашиваем единицы измерения\n measure_list = rest_api.select_objects('core.dictionaries.measureunits')['ds']\n\n background_result['measure_kg'] = get_item_from(measure_list, table={'title': 'кг'})\n background_result['measure_sht'] = get_item_from(measure_list, table={'title': 'шт'})\n background_result['measure_l'] = get_item_from(measure_list, table={'title': 'л'})\n background_result['measure_pc'] = get_item_from(measure_list, table={'title': 'пц'})\n\n return background_result\n\n # Case 1\n @pytest.allure.story('Тестирование с включенной опцией \"Включать НДС в себестоимость\"')\n @pytest.mark.case_1\n def test_includevatinprimecost_case_1(self, rest_api, background, psql):\n with pytest.allure.step('Step 1 - Изменяем настройки организации'):\n\n org_settings = rest_api.select_objects('core.company')['ds'][0]['object']\n\n org_settings['includeVatInPrimeCost'] = True\n\n rest_api.send_update(\n 'core.company',\n org_settings,\n params={\n 'custom_params': {\n 'dialogResult[]': 'reprocessYes'\n }\n }\n )\n\n with pytest.allure.step('Step 2 - Проводим ПН 1 и проверяем себестоимость товара'):\n\n # Проводим Приходную Накладную 1\n rest_api.send_action(\n 'warehouse.documents.incoming',\n payload_table={\n 'ids': [background['incoming_1']['id']],\n 'actionName': 'process'\n }\n )\n\n waiting_tasks_processing(psql)\n\n # Проверяем себестоимость товара\n singleproduct_list = rest_api.select_objects('warehouse.nomenclature.singleproduct')['ds']\n correspond_selected_object(\n singleproduct_list,\n select_option={\n 'title': background['singleproduct_1']['name']\n },\n table={\n 'title': background['singleproduct_1']['name'],\n 'currentPrimeCost': 11.8,\n 'ratio': 1\n }\n )\n\n # Case 2\n @pytest.allure.story('Тестирование с выключенной опцией \"Включать НДС в себестоимость\"')\n @pytest.mark.case_2\n def test_decomposition_case_2(self, rest_api, background, psql):\n with pytest.allure.step('Step 1 - Изменяем настройки организации'):\n org_settings = rest_api.select_objects('core.company')['ds'][0]['object']\n\n org_settings['includeVatInPrimeCost'] = False\n\n rest_api.send_update(\n 'core.company',\n payload_table=org_settings,\n params={\n 'custom_params': {\n 'dialogResult[]': 'reprocessYes'\n }\n }\n )\n\n with pytest.allure.step('Step 2 - Проводим ПН 1 и проверяем себестоимость товара'):\n rest_api.send_action(\n 'warehouse.documents.incoming',\n payload_table={\n 'actionName': 'process',\n 'ids': [background['incoming_1']['id']]\n }\n )\n\n waiting_tasks_processing(psql)\n\n # Проверяем себестоимость товара\n singleproduct_list = rest_api.select_objects('warehouse.nomenclature.singleproduct')['ds']\n correspond_selected_object(\n singleproduct_list,\n select_option={\n 'title': background['singleproduct_1']['title']\n },\n table={\n 'title': background['singleproduct_1']['title'],\n 'currentPrimeCost': 10,\n 'ratio': 1\n }\n )\n","sub_path":"scenarios/rest/functional_tests/documents/test_functional_includevatinprimecost.py","file_name":"test_functional_includevatinprimecost.py","file_ext":"py","file_size_in_byte":6830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"222231350","text":"# -*- coding: utf-8 -*-\r\n\r\nimport os\r\nimport six\r\nfrom jinja2 import nodes\r\nfrom jinja2.ext import Extension\r\nfrom jinja2.runtime import Undefined\r\nfrom .xlnode import XvCell\r\n\r\nclass NodeExtension(Extension):\r\n tags = set(['row', 'cell', 'node', 'extra'])\r\n\r\n def __init__(self, environment):\r\n super(self.__class__, self).__init__(environment)\r\n environment.extend(sheet_pos = None)\r\n\r\n def parse(self, parser):\r\n lineno = next(parser.stream).lineno\r\n args = [parser.parse_expression()]\r\n body = []\r\n return nodes.CallBlock(self.call_method('_node', args),\r\n [], [], body).set_lineno(lineno)\r\n\r\n def _node(self, key, caller):\r\n node = self.environment.sheet_pos.get_node(key)\r\n return key\r\n\r\nclass SegmentExtension(Extension):\r\n tags = set(['seg'])\r\n\r\n def parse(self, parser):\r\n lineno = next(parser.stream).lineno\r\n args = [parser.parse_expression()]\r\n body = parser.parse_statements(['name:endseg'], drop_needle=True)\r\n return nodes.CallBlock(self.call_method('_seg', args),\r\n [], [], body).set_lineno(lineno)\r\n\r\n def _seg(self, key, caller):\r\n segment = self.environment.sheet_pos.get_node(key)\r\n rv = caller()\r\n rv = segment.process_rv(rv)\r\n return rv\r\n\r\nclass XvExtension(Extension):\r\n tags = set(['xv'])\r\n\r\n def parse(self, parser):\r\n lineno = next(parser.stream).lineno\r\n args = [parser.parse_expression()]\r\n body = []\r\n return nodes.CallBlock(self.call_method('_xv', args),\r\n [], [], body).set_lineno(lineno)\r\n\r\n def _xv(self, xv, caller):\r\n segment = self.environment.sheet_pos.current_node\r\n if xv is None or type(xv) is Undefined:\r\n xv = ''\r\n if isinstance(segment._parent, XvCell):\r\n segment._parent.rv = xv\r\n rv = six.text_type(xv)\r\n return rv\r\n\r\ntry:\r\n pil = True\r\n from PIL.ImageFile import ImageFile\r\nexcept:\r\n pil = False\r\n\r\nclass ImageExtension(Extension):\r\n tags = set(['img'])\r\n\r\n def parse(self, parser):\r\n lineno = next(parser.stream).lineno\r\n args = [parser.parse_expression()]\r\n if parser.stream.skip_if('comma'):\r\n args.append(parser.parse_expression())\r\n else:\r\n args.append(nodes.Const(0))\r\n body = []\r\n return nodes.CallBlock(self.call_method('_image', args),\r\n [], [], body).set_lineno(lineno)\r\n\r\n def _image(self, image_ref, image_key, caller):\r\n if not pil:\r\n return ''\r\n node = self.environment.sheet_pos.current_node\r\n if not isinstance(image_ref, ImageFile):\r\n fname = six.text_type(image_ref)\r\n if not os.path.exists(fname):\r\n image_ref = ''\r\n node.set_image_ref(image_ref, image_key)\r\n return 'image'\r\n\r\nclass RangeExtension(Extension):\r\n tags = set(['crange'])\r\n\r\n def parse(self, parser):\r\n lineno = next(parser.stream).lineno\r\n args = [parser.parse_expression()]\r\n body = []\r\n return nodes.CallBlock(self.call_method('_range', args),\r\n [], [], body).set_lineno(lineno)\r\n\r\n def _range(self, key, caller):\r\n sheet_pos = self.environment.sheet_pos\r\n cr = sheet_pos.get_crange(key)\r\n cr.set_parent(sheet_pos)\r\n return key\r\n","sub_path":"xltpl/xlext.py","file_name":"xlext.py","file_ext":"py","file_size_in_byte":3468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"220058506","text":"# -*- coding: utf-8 -*-\n#import tensorflow.contrib.learn as skflow\n\n\n\"\"\"\n神经网络设计:选用3层BP神经网络。\n输入层为近红外、红光、绿光、短波红外数据。\n隐含层传递函数为双曲S型正切函数“tansig”。\n输出层采用的是线性函数“purelin”来拟合水质参数。\n水质参数选择:\n\"\"\"\nimport numpy as np \n \n \n\n \n#定义NeuralNetwork 神经网络算法 \nclass NeuralNetwork: \n\t#初始化,layes表示的是一个list,eg[10,10,3]表示第一层10个神经元,第二层10个神经元,第三层3个神经元\n\tdef __init__(self, layers, activation='tanh'): \n\t\t\"\"\" \n\t\t:param layers: layes表示的是一个list,包含了每一层的神经元数目. \n\t\t至少包括2层神经网络,也就是list至少有2个数。 \n\t\t:param activation: 激活函数 \"logistic\" 或 \"tanh\" \n\t\t\"\"\" \n\t\tif activation == 'logistic': \n\t\t\tself.activation = self.logistic \n\t\t\tself.activation_deriv = self.logistic_derivative \n\t\telif activation == 'tanh': \n\t\t\tself.activation = self.tanh \n\t\t\tself.activation_deriv = self.tanh_deriv \n\t\t# 存储权值矩阵\n\t\tself.weights = [] \n\t\t#循环从1开始,相当于以第二层为基准,进行权重的初始化 \n\t\tfor i in range(1, len(layers) - 1): \n\t\t\t#对当前神经节点的前驱赋值 \n\t\t\tself.weights.append((2*np.random.random((layers[i - 1] + 1, layers[i] + 1))-1)*0.25) \n\t\t\t#对当前神经节点的后继赋值 \n\t\t\tself.weights.append((2*np.random.random((layers[i] + 1, layers[i + 1]))-1)*0.25) \n\n\t#定义双曲函数和他们的导数\n\tdef tanh(self,x): \n\t\treturn np.tanh(x) \n\n\tdef tanh_deriv(self,x): \n\t\treturn 1.0 - np.tanh(x)**2 \n\n\tdef logistic(self,x): \n\t\treturn 1/(1 + np.exp(-x)) \n\n\tdef logistic_derivative(self,x): \n\t\treturn logistic(x)*(1-logistic(x)) \n\t#训练函数 ,X矩阵,每行是一个实例 ,y是每个实例对应的结果,learning_rate 学习率, \n\t# epochs,表示抽样的方法对神经网络进行更新的最大次数 \n\tdef fit(self, x, y, learning_rate=0.05, epochs=10000): \n\t\t#print ('正在进行训练')\n\t\tX = np.atleast_2d(x) #确定X至少是二维的数据 \n\t\ttemp = np.ones([X.shape[0], X.shape[1]+1]) #初始化矩阵 \n\t\ttemp[:, 0:-1] = X # adding the bias unit to the input layer \n\t\tX = temp \n\t\ty = np.array(y) #把list转换成array的形式 \n\n\t\tfor k in range(epochs):\n\t\t\t#if k%1000 == 0:\n\t\t\t#\tprint ('迭代第{}次'.format(k)) \n\t\t\t#随机选取一行,对神经网络进行更新 \n\t\t\ti = np.random.randint(X.shape[0]) \n\t\t\ta = [X[i]] \n\n\t\t\t#完成所有正向的更新 \n\t\t\tfor l in range(len(self.weights)):\n\t\t\t\tdot_value = np.dot(a[l], self.weights[l]) # 权值矩阵中每一列代表该层中的一个结点与上一层所有结点之间的权值\n\t\t\t\tactivation = self.activation(dot_value)\n\t\t\t\ta.append(activation) \n\t\t\t# \n\t\t\terror = y[i] - a[-1] \n\t\t\tdeltas = [error * self.activation_deriv(a[-1])] \n\n\t\t\t#开始反向计算误差,更新权重 \n\t\t\tfor l in range(len(a) - 2, 0, -1): # we need to begin at the second to last layer \n\t\t\t\tdeltas.append(deltas[-1].dot(self.weights[l].T)*self.activation_deriv(a[l])) \n\t\t\tdeltas.reverse() \n\t\t\tfor i in range(len(self.weights)): \n\t\t\t\tlayer = np.atleast_2d(a[i]) \n\t\t\t\tdelta = np.atleast_2d(deltas[i]) \n\t\t\t\tself.weights[i] += learning_rate * layer.T.dot(delta) \n\n\t#预测函数 \n\tdef predict(self, x): \n\t\tx = np.array(x) \n\t\ttemp = np.ones(x.shape[0]+1) \n\t\ttemp[0:-1] = x \n\t\ta = temp # a为输入向量(行向量)\n\t\tfor l in range(0, len(self.weights)): \n\t\t\ta = self.activation(np.dot(a, self.weights[l])) \n\t\treturn a \n\n\tdef test(self,X,Y,error):\n\t\tcount = 0\n\t\tnumber = len(Y)\n\t\tprint ('设定可接受的数据误差为{}'.format(error))\n\t\tfor i in range(number):\n\t\t\tresult = self.predict(X[i])\n\t\t\tprint ('预测数据为{},实际数据为{}'.format(result,Y[i]))\n\t\t\tif abs((Y[i]-result).sum()) < error:\n\t\t\t\tcount = count + 1\n\t\tCorrect_rate = (count/number)*100\n\t\tprint ('测试正确的数量为{}条,测试样本为{}条'.format(count,number))\n\t\tprint ('测试正确率为[{}%]'.format(Correct_rate))\n\t\t\n\n\n\n\n\n\nif __name__ == '__main__':\n\tnn = NeuralNetwork(layers=[4,3,2]) # 网络结构: 2输入1输出,1个隐含层(包含2个结点)\n\n\tX = np.array([[0, 0 ,0 ,0 ], # 输入矩阵(每行代表一个样本,每列代表一个特征)\n [0, 1, 0 ,1 ],\n [1, 0, 1, 0],\n [1, 1, 1, 1]])\n\n\t#Y = np.array([[0, 1, 1, 1],\n\t#\t\t\t[0,1,1,1]])\n\t\n\tY = np.array([[0,0],\n\t\t\t\t [1,1],\n\t\t\t\t [1,1],\n\t\t\t\t [1,1]])\n\tnn.fit(X, Y) # 训练网络 \n\n\tnn.test(X,Y,0.1)\n\t#print ('w:', nn.weights) # 调整后的权值列表\n\n\t\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"bp_neuralnetwork.py","file_name":"bp_neuralnetwork.py","file_ext":"py","file_size_in_byte":4698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"91365910","text":"\"\"\"\nIndeed API\n\"\"\"\n\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options;\nfrom flask import Flask\nfrom flask import request\nfrom flask import Response\nfrom indeed import *\nimport json\nfrom flask_cors import CORS\napp = Flask(__name__)\nCORS(app) #allow the api to accessed from any origin NOT SECURE\n\n\noptions = Options();\noptions.add_argument(\"--headless\"); #run in headless mode\nenv = \"dev\";\n\nif(env == \"prod\"):\n driver = webdriver.Chrome(\"/usr/bin/chromedriver\", options=options);\nelse:\n #assume dev\n driver = webdriver.Chrome(options=options);\n\n@app.route(\"/api/indeed\")\ndef it_works():\n return \"The server works\";\n\n\n@app.route(\"/api/indeed/\")\ndef test_driver(company):\n url = \"https://www.\" + company + \".com\";\n driver.get(url);\n return(\"Got \" + company + \" page\");\n\n@app.route(\"/api/indeed//\")\ndef get_all(company, position):\n url = buildQuery(company, position);\n currentDriver = driver.get(url);\n print(\"Successfully fetched \" + url);\n nullPageCheck = driver.find_elements_by_class_name('cmp-ZrpPromo-text');\n if(len(nullPageCheck) > 0 ):\n data = {\n \"responseType\": 404,\n \"responseMessage\": \"Indeed data not available for this position at this company\"\n }\n else:\n data = {\n \"position\": getPrettyText(position, \"+\"),\n \"company\": getPrettyText(company, \"-\"),\n \"rating\": getAvgRating(),\n \"reviews\": getReviews(),\n \"pros\": getPros(),\n \"cons\": getCons()\n } \n print(\"Succesfully fetched all data\");\n response = Response(json.dumps(data), status=200, mimetype=\"application/json\"); #use json.dumps to correctly encode the dict into a json object\n return response;\n\ndef getAvgRating():\n rawRatingsData = driver.find_elements_by_class_name('cmp-ratingNumber');\n print(\"Got ratings data\");\n return processRatings(rawRatingsData);\n\ndef getReviews():\n rawReviewsData = driver.find_elements_by_class_name('cmp-review-text');\n print(\"Got reviews data\");\n return processReviews(rawReviewsData);\n\ndef getPros():\n rawProsData = driver.find_elements_by_class_name('cmp-review-pro-text');\n print(\"Got pros data\");\n return processPros(rawProsData);\n\ndef getCons():\n rawConsData = driver.find_elements_by_class_name('cmp-review-con-text');\n print(\"Got cons data\");\n return processCons(rawConsData);\n\ndef getPrettyText(company, separator):\n return prettyText(company, separator);\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=8080);\n","sub_path":"indeed-data/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"534828095","text":"from pydantic import BaseModel\n\n\nclass AppDomainException(Exception):\n def __init__(self, status_code: int, code: str, message: str):\n self.status_code = status_code\n self.code = code\n self.message = message\n\n def __str__(self):\n return f\"Error: \\n\\nCode: {self.code}\\n\\nMessage: {self.message}\"\n\n\nclass BadRequestException(AppDomainException):\n def __init__(self, message: str):\n status_code = 400\n code = \"BadRequest\"\n super().__init__(status_code, code, message)\n\n\nclass ForbiddenException(AppDomainException):\n def __init__(self, username: str = None):\n status_code = 403\n code = \"Forbidden\"\n message = \"Unauthorized: user is not allowed to access or change this resource\"\n\n if username:\n message = f\"Unauthorized: {username} is not allowed to access or change this resource\"\n\n super().__init__(status_code, code, message)\n\n\nclass NotFoundException(AppDomainException):\n def __init__(self, message: str = None, name: str = None, key: BaseModel = None):\n status_code = 404\n code = \"NotFound\"\n\n if not message and (name and key):\n message = f\"Resource \\\"{name}\\\" ({key}) was not found\"\n elif not message:\n raise ValueError(\"Pass \\\"message\\\" argument or a combination of \\\"name\\\" and \\\"key\\\"\")\n\n super().__init__(status_code, code, message)\n\n\nclass SystemErrorException(AppDomainException):\n def __init__(self, message: str = None):\n status_code = 500\n code = \"SystemError\"\n\n if not message:\n message = \"An unexpected error occured. Please try again or confirm current operation status\"\n\n super().__init__(status_code, code, message)\n\n\nclass UnauthorizedRequestException(AppDomainException):\n def __init__(self, message: str):\n status_code = 401\n code = \"Unauthorized\"\n super().__init__(status_code, code, message)\n","sub_path":"app/exceptions/app_exceptions.py","file_name":"app_exceptions.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"262689670","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 2 23:16:39 2018\n\n@author: Ethan Cheng\n\"\"\"\n\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.image as mpimg\nimport numpy as np\nimport pandas as pd\nfrom sklearn.utils import shuffle\n\n\nclass behaviorCloneData(object):\n \n def __init__(self, path ):\n self.path = path + '/'\n self.df = pd.read_csv(self.path + 'driving_log.csv')\n self.df_train, self.df_valid = train_test_split(self.df, test_size=0.2)\n self.x_valid, self.y_valid = self.df2xy(self.df_valid)\n self.trainSize = len(self.df_train)\n self.validSize = len(self.df_valid)\n \n def df2xy(self, dff, random_flip = False):\n images = []\n y = [] #np.array(dff.steering)\n for i in range(len(dff)):\n try:\n im = mpimg.imread(self.path + dff.center.iloc[i])\n except:\n raise ValueError('Error reading image {}'.format(self.path + dff.center.iloc[i]))\n \n yi = dff.steering.iloc[i]\n if random_flip and np.random.rand() > 0.5:\n im = np.fliplr(im) \n yi = -yi\n images.append(im)\n y += [yi]\n return np.array(images), np.array(y)\n \n def trainBatchGenerator(self, batch_size=32, random_flip = True):\n while 1: # Loop forever so the generator never terminates\n shuffle(self.df_train)\n for offset in range(0, batch_size*(len(self.df_train)//batch_size), batch_size):\n yield self.df2xy(self.df_train[offset:offset+batch_size], random_flip)\n \n \n \n \n \n","sub_path":"modules/dataLoader.py","file_name":"dataLoader.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"648406131","text":"import logging\nimport shutil\nimport tempfile\nimport tkinter as tk\nfrom tkinter.filedialog import *\n\nfrom PIL import Image\n\n# 命令提示行的颜色代码\nYELLOW = \"\\033[33m\"\nGREEN = \"\\033[32m\"\nCYAN = \"\\033[36m\"\nGRAY = \"\\033[37m\"\nRESET = \"\\033[0;39m\"\n\n# 临时放置处理文件的文件夹\nTMP_ASSETS_DIR = tempfile.TemporaryDirectory()\n\n# 日志初始化\nlogging.basicConfig(\n level=logging.INFO,\n format=\"{}[{}%(asctime)s{}] [{}%(threadName)s{}/{}%(levelname)s{}] [{}%(filename)s{}]: %(message)s\".format(\n RESET, GRAY, RESET, YELLOW, RESET, GREEN, RESET, CYAN, RESET\n ),\n datefmt=\"%H:%M:%S\"\n)\n\n\ndef find_png(path=\"\", list_in=None):\n \"\"\"\n 一个基本的寻找后缀为 .png 的函数\n :param path: 当前需要递推搜索的文件夹\n :param list_in: 放置文件地址列表的变量\n :return 符合条件的文件地址列表\n \"\"\"\n if list_in is None:\n list_in = []\n for file in os.listdir(path):\n tmp_path = path + \"/\" + file\n if os.path.isdir(tmp_path):\n find_png(tmp_path, list_in)\n elif tmp_path.endswith(\".png\"):\n list_in.append(tmp_path)\n return list_in\n\n\nif __name__ == '__main__':\n # 绘制自己的空窗口,从而避免后面对话框绘制多余的窗口\n root = tk.Tk()\n root.withdraw()\n search_dir = askdirectory(initialdir='./')\n\n # 如果地址不为空,开始进行遍历搜索\n if search_dir:\n # 复制到的位置,复制时该文件夹不允许存在\n # 所以直接调用临时文件夹会导致程序崩溃\n tmp_dir = TMP_ASSETS_DIR.name + \"/Handle\"\n # 拷贝该文件夹到临时文件夹\n shutil.copytree(search_dir, tmp_dir)\n # 获取得到符合条件的文件\n math_list = find_png(tmp_dir)\n # 两个变量,记录改变前后的文件大小\n before_total_size = 0\n after_total_size = 0\n\n # 遍历进行文件压缩处理\n for math in math_list:\n before_size = os.path.getsize(math)\n before_total_size += before_size\n Image.open(math).save(math)\n after_size = os.path.getsize(math)\n after_total_size += after_size\n logging.info(\"压缩率:%.2f%%\" % ((before_size - after_size) / before_size * 100))\n logging.info(\"总压缩率:%.2f%%\" % ((before_total_size - after_total_size) / before_total_size * 100))\n\n # 再度打开窗口,选择放置处理好的文件路径\n place_dir = askdirectory(initialdir=search_dir)\n if place_dir:\n shutil.copytree(tmp_dir, place_dir + \"/压缩过的\")\n else:\n logging.warning(\"未选择放置文件夹,丢弃掉该压缩结果\")\n else:\n logging.warning(\"未选择需要处理的文件夹,退出\")\n","sub_path":"tool/picture_compression.py","file_name":"picture_compression.py","file_ext":"py","file_size_in_byte":2809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"270036529","text":"from prm.Functions import *\nfrom prm.INPUT import *\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom prm.dronePRM import dronePRM\n\n\n\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\ndrones = []\nnodelist = get_randomlist(iterations = ITERATIONS, minRand=5, maxRand=15, obstaclelist= OBSTACLELIST, step = STEP, safesize=SAFE_SIZE)\nk_nearest_nodes(nodelist, k = len(nodelist), step = STEP, safesize=SAFE_SIZE, obstaclelist=OBSTACLELIST)\ngraph = Graph()\n\n\nfor i in range(len(nodelist)):\n for j in range(len(nodelist[i].nearest)):\n graph.add_edge(from_node = nodelist[i], to_node = nodelist[i].nearest[j], weight=nodelist[i].distanceToNearest[j])\n\n\n\nfor i in range(len(START)):\n drones.append(dronePRM(nodelist = nodelist, graph = graph, start = SNODE[i], goal = GNODE[i], ID = i, obstaclelist=OBSTACLELIST,\n stepx = 1, stepy = 1, stepz = 1, dronesize=SAFE_SIZE, ax = ax))\n\npaths = []\nfor i in range(len(drones)):\n paths.append(drones[i].path)\nfor i in range(len(drones)):\n for j in range(len(drones)):\n if j == i:\n pass\n else:\n drones[i].recipents.append(drones[j])\n\nfor i in range(len(drones)):\n drones[i].get_path()\n\n\nsct_obst(OBSTACLELIST, ax = ax, color = 'g')\n\nfor i in range(len(nodelist)):\n ax.scatter(nodelist[i].x,nodelist[i].y,nodelist[i].z, color = 'g' )\nfor i in range(len(drones)):\n for j in range(len(drones[i].path)):\n ax.scatter(drones[i].path[j].x, drones[i].path[j].y, drones[i].path[j].z, color = colors[i])\n\nplt.pause(3)\nplt.cla()\n\nc = ['m', 'k', 'y']\nfor i in range(len(paths)):\n for j in range(len(paths[i])):\n ax.scatter(paths[i][j].x, paths[i][j].y, paths[i][j].z, color = c[i])\nfor i in range(len(drones)):\n for j in range(len(drones[i].pathLines)):\n for k in range(len(drones[i].pathLines[j])):\n ax.scatter(drones[i].pathLines[j][k].x, drones[i].pathLines[j][k].y, drones[i].pathLines[j][k].z)\n\n\nplt.show()\n","sub_path":"dissertationLasr/prm/prmMain.py","file_name":"prmMain.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"362782912","text":"from flask import Blueprint, request, jsonify, render_template\nfrom flask.ext.security import login_required\nimport json\nfrom models.volunteer import Volunteer\nfrom models.group import Group\nfrom models.voter import Voter\nfrom models.person_name import PersonName\nfrom models.address import Address\nfrom models.street_index import StreetIndex\nfrom models.location import Location\n\nmods = Blueprint('mods', __name__, url_prefix='/mods')\n\n\n@mods.route('/group/add', methods=['POST'])\ndef group_add():\n g = Group(request.form)\n gid = g.add()\n return jsonify(group_id=gid)\n\n\n@mods.route('/event/add', methods=['POST'])\ndef event_add():\n from models.event import Event\n\n e = Event(request.form)\n eid = e.add()\n return jsonify(event_id=eid)\n\n\n@mods.route('/person/batch')\n@login_required\ndef volunteer_batch():\n\n cities = Location.get_cities_in_county('81')\n dta = {\n 'cities': cities\n }\n return render_template(\n 'models/volunteer.html',\n title='Volunteer Mgt',\n dta=dta\n )\n\n\n@mods.route('/person/add', methods=['POST'])\ndef person_add():\n vol = Volunteer(json.loads(request.form['person']))\n try:\n vid = vol.add()\n except Exception as e:\n return jsonify(error=e)\n return jsonify(person_id=vid)\n\n\n@mods.route('/person/update', methods=['POST'])\ndef person_update():\n vol = Volunteer(json.loads(request.form['person']))\n try:\n vol.update()\n except Exception as e:\n return jsonify(error=e)\n return jsonify(person_id=vol.id)\n\n\n@mods.route('/person/by_email')\ndef person_by_email():\n email = request.args['email']\n matches = Volunteer.get_by_fuzzy_email(email)\n return jsonify(matches=[vol2dict(m) for m in matches]) if matches else jsonify(\"None\")\n\n\n@mods.route('/person/by_phone')\ndef person_by_phone():\n phone = request.args['phone']\n matches = Volunteer.get_by_phone(phone)\n return jsonify(matches=[vol2dict(m) for m in matches]) if matches else jsonify(\"None\")\n\n\n@mods.route('/person/by_name')\ndef person_by_name():\n matches = get_person_matches(request.args)\n return jsonify(matches=matches) if matches else jsonify(\"None\")\n\n\ndef get_person_matches(d):\n pn = PersonName(d)\n addr = Address(d) if d['address'] else None\n\n candidates = Volunteer.get_candidates(pn.last[0], addr)\n matches = pn.fuzzy_match(candidates)\n return [candidates[match[0]] for match in matches] if matches else None\n\n\n@mods.route('/voter/by_name')\ndef voter_by_name():\n matches = get_voter_matches(request.args)\n return jsonify(matches=matches) if matches else jsonify(\"None\")\n\n\ndef get_voter_matches(d):\n pn = PersonName(d)\n addr = Address(d) if d['address'] else None\n candidates = Voter.get_candidates(pn, addr)\n matches = pn.fuzzy_match(candidates)\n return [candidates[match[0]] for match in matches] if matches else None\n\n\n@mods.route('/street_index', methods=['GET', 'POST'])\ndef street_index():\n if request.method == 'GET':\n cities = [''] + Location.get_cities_in_county('81')\n dta = {\n 'cities': cities\n }\n return render_template(\n 'queries/street_index.html',\n title='Street Index',\n dta=dta\n )\n rec = street_index_lookup(request.form)\n return jsonify(rec) if rec else jsonify(\"None\")\n\n\ndef street_index_lookup(d):\n addr = Address(d)\n index_rec = StreetIndex.get_index_match(addr)\n if not index_rec:\n return None\n addr.zip = getattr(index_rec, 'zipcode', None)\n addr.street_address.pre_direction = getattr(index_rec, 'pre_direction', None)\n addr.street_address.street_name = index_rec.street_name\n addr.street_address.street_type = index_rec.street_type\n addr.street_address.suf_direction = getattr(index_rec, 'suf_direction', None)\n return {\n 'address': str(addr.street_address),\n 'jurisdiction': index_rec.jurisdiction,\n 'ward': index_rec.ward_precinct[0:2],\n 'precinct': index_rec.ward_precinct[2:],\n 'city': StreetIndex.get_city_by_zip(index_rec.zipcode),\n 'zip': index_rec.zipcode,\n 'county': index_rec.county,\n 'congress': index_rec.congress,\n 'state_senate': index_rec.state_senate,\n 'state_house': index_rec.state_house,\n 'county_commissioner': index_rec.county_commissioner,\n 'school_district': index_rec.school_district,\n 'school_precinct': index_rec.school_precinct,\n 'village_code': index_rec.village,\n 'village_precinct': index_rec.village_precinct\n } if index_rec else None\n\n\ndef vol2dict(volunteer):\n d = {\n 'vol_id': volunteer.id,\n 'last_name': volunteer.name.last,\n 'first_name': volunteer.name.first,\n 'middle_name': volunteer.name.middle,\n 'name_suffix': volunteer.name.suffix,\n 'email': volunteer.email,\n 'city': volunteer.address.city,\n 'zip': volunteer.address.zip,\n 'phone1': volunteer.phone1,\n 'phone2': volunteer.phone2,\n 'address': str(volunteer.address.street_address),\n 'voter_id': volunteer.voter_id,\n 'birth_year': volunteer.birth_year,\n 'gender': volunteer.gender\n }\n if volunteer.turf:\n d['jurisdiction'] = volunteer.turf.jurisdiction\n d['ward'] = volunteer.turf.ward\n d['precinct'] = volunteer.turf.precinct\n d['school_code'] = volunteer.turf.school_code\n d['school_precinct'] = volunteer.turf.school_precinct\n d['village_code'] = volunteer.turf.village_code\n d['village_precinct'] = volunteer.turf.village_precinct\n d['state_house'] = volunteer.turf.state_house\n d['state_senate'] = volunteer.turf.state_senate\n d['congress'] = volunteer.turf.congress\n d['county_commissioner'] = volunteer.turf.county_commissioner\n return d\n\n\ndef vol_name_dict(volunteer):\n return {\n 'last_name': volunteer.name.last,\n 'first_name': volunteer.name.first,\n 'middle_name': volunteer.name.middle\n }\n","sub_path":"controllers/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"479082611","text":"import os\nimport argparse\n\nfrom dotenv import load_dotenv\n\nload_dotenv()\nPHOTO_FOLDER = os.getenv('PHOTO_FOLDER') or 'test_photos'\n\n\ndef parse_args():\n \"\"\"Parse args from command line. Available args:\n --log, -l: switch logging level from ERROR to DEBUG\n --timeout, -t: add timeout in seconds\n --path, -p: set path to folder with photos.\"\"\"\n\n parser = argparse.ArgumentParser(description='Start server with async download service')\n\n parser.add_argument('--log', '-l',\n action='store_true',\n default=False,\n help='switch logging level from ERROR to INFO',\n dest='logging_is_active'\n )\n\n parser.add_argument('--timeout', '-t',\n action='store',\n type=int,\n default=os.getenv('TIMEOUT') or 0,\n help='add timeout in seconds',\n dest='timeout'\n )\n\n parser.add_argument('--path', '-p',\n action='store',\n type=str,\n dest='path_to_photos',\n help=f'set path to folder with photos, default is {PHOTO_FOLDER}',\n default=os.path.join(os.getcwd(), PHOTO_FOLDER)\n )\n\n return parser.parse_args()\n","sub_path":"parser_args.py","file_name":"parser_args.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"41721249","text":"##################################################################\n# An exercise working with:\n# 1. Beautiful Soup: to web scrape\n# 2. Pandas: to convert to a DataFrame\n# 3. Pygsheets: to automatcaly export to google sheets\n# 4. Replit secret enviroment\n##################################################################\n\nimport os\nimport time\n#os.system('pip install --upgrade pip')\n#os.system('pip install beautifulsoup4')\n#os.system('pip install lxml')\n#os.system('pip install requests[security]')\n#os.system('pip install pandas')\n#os.system('pip install pygsheets')\n\n\n\n## WebScraping tools\nfrom bs4 import BeautifulSoup\nimport requests\n\n#Data Analisys Tools\nimport pandas as pd\nimport numpy as np\n\n# Getting the countries and flags from the web\ndef flag():\n url = 'https://www.worldometers.info/geography/flags-of-the-world/'\n\n #beatifoulsoup routines to get the data from website\n html_text = requests.get(url).text\n soup = BeautifulSoup(html_text, 'lxml')\n flags = soup.find_all('div', class_='col-md-4')\n\n #cleaning file and initializing counter\n open('flags.txt', 'w').close()\n i = 0\n\n #getting flag name & link and exporting to a file\n for flag in flags:\n i +=1\n try:\n with open('flags.txt','a') as f: \n f.write(f\"{flag.text}_: https://www.worldometers.info{flag.find('a')['href']}\\n\")\n except TypeError:\n print(f'Type Error at line {flag.text}')\n break\n \n #converting file to a DataFrame\n df = pd.read_csv('flags.txt', engine='python', sep=\"_:\")\n df.columns = ['Country',\t'Link']\n print(df)\n\n #authorization to r and w on google sheets\n #import pygsheets\n #paises = '1S_Sj-iRGKo9A7P_WeT2bxrE5dOij3_Q9E9p3v6cKFa0' #key of the sheet\n #client = pygsheets.authorize(custom_credentials = 'API_KEY')\n #client.open_by_key(paises)\n \n \n\n\nif __name__ == \"__main__\":\n flag()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"545733654","text":"\nimport socket\n\nclass SimpleBroadcast(object):\n def __init__(self, host1='localhost', port1=50041):\n self.host = host1\n self.port = port1\n self.conn = None\n \n def broadcast(self,value,connection=None):\n if connection is None and self.conn is None:\n s = socket.socket()\n s.connect((self.host, self.port))\n s.send('P')\n s.send(value)\n s.close\n elif self.conn is not None:\n self.conn.send('P')\n self.conn.send(value)\n elif connection != None:\n self.conn = connection\n self.conn.send('P')\n self.conn.send(value)\n \n def setConnection(self, connection):\n self.conn = connection\n \n def close(self):\n if self.conn is not None:\n self.conn.close\n \n \nif __name__ == \"__main__\":\n sb = SimpleBroadcast(host1=socket.gethostname())\n sb.broadcast('10')\n","sub_path":"lib/SimpleBroadcast.py","file_name":"SimpleBroadcast.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"251569490","text":"class Solution(object):\n def matrixReshape(self, nums, r, c):\n \"\"\"\n :type nums: List[List[int]]\n :type r: int\n :type c: int\n :rtype: List[List[int]]\n \"\"\"\n a = [j for i in nums for j in i]\n if len(a) != r*c :\n return nums\n result = list()\n index = 0\n for i in range(r):\n result.append(list())\n for j in range(c):\n result[i].append(a[index])\n index += 1\n return result\n \n","sub_path":"leetcode/566.py","file_name":"566.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"457485063","text":"#plotlyGUIplots.py\n#Description: Base HEAT GUI plots that are outputs\n#Engineer: T Looby\n#Date: 20200727\nimport pandas as pd\nimport numpy as np\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nimport plotly.figure_factory as ff\nimport plotly.express as px\n\ndef plotlyOpenFOAMplot(data,names):\n \"\"\"\n returns a DASH object for use directly in dash app\n\n data is a list of dataframes, where each list item corresponds to a different\n PFC, whose names are in names\n\n here we plot the output from min/max T against the min/max HF\n \"\"\"\n if type(data) is not list:\n data = [data]\n if type(names) is not list:\n names = [names]\n\n #if we want multiple fields\n# fields = ['T', 'qFVM', 'qINV']\n# units = [' [K]', ' [W/m^2]', ' [W/m^2]']\n# y2 = [False, True, True]\n fields = ['T', 'qFVM']\n units = [' [K]', ' [W/m^2]']\n y2 = [False, True, True]\n\n # Create figure with secondary y-axis\n fig = make_subplots(specs=[[{\"secondary_y\": True}]])\n\n for pfcIdx,name in enumerate(names):\n df = data[pfcIdx]\n for i,field in enumerate(fields):\n mask = df['field'] == field\n t = df[mask].sort_values('# Time')['# Time'].values\n varMax = df[mask].sort_values('# Time')['max'].values\n lineName = field+\" \"+name\n fig.add_trace(go.Scatter(x=t, y=varMax, name=lineName),\n secondary_y=y2[i],\n )\n\n\n fig.update_layout(title='Time History of openFOAM FVM Variables',\n xaxis_title='Time [s]',\n yaxis_title='',\n font=dict(\n family='Arial, sans-serif',\n size=14,\n )\n )\n # Set y-axes titles\n fig.update_yaxes(title_text=\"Maximum PFC Heat Flux [W/m^2]\", secondary_y=True)\n fig.update_yaxes(title_text=\"Maximum PFC Temperature [K]\", secondary_y=False)\n\n return fig\n\n\ndef plotlyqDivPlot(heatFlux, labels, logPlot=False):\n \"\"\"\n returns a DASH object for use directly in dash app\n\n heatFlux is an arrays of heat fluxes on PFC surface\n\n heatFlux will be filtered so no zero points are in array\n\n labels is a list of same length as heatFlux\n\n if logPlot is true plot a log plot\n\n\n if heatFlux and labels are lists, then we add a plot for each item in list to figure\n this is useful when running multiple PFCs\n \"\"\"\n fig = go.Figure()\n for i,hf in enumerate(heatFlux):\n use = np.where(hf>0)\n hf = hf[use]\n label = labels[i]\n\n if logPlot is True:\n hflog = np.log10(hf)\n\n# if i==0:\n# fig = px.histogram(x=hflog,\n# marginal=\"box\",\n# nbins=20,\n# opacity=0.7,\n# labels=label,\n# )\n# else:\n# pass\n fig.add_trace(go.Histogram(\n x=hflog,\n #marginal=\"box\",\n nbinsx=20,\n opacity=0.7,\n name=label,\n )\n )\n\n fig.update_layout(\n title=\"qDiv Distribution Across PFC Surface\",\n xaxis_title=\"log10(qDiv) [MW/m^2]\",\n yaxis_title=\"# of Points (Count)\",\n showlegend=True,\n legend=dict(\n yanchor=\"top\",\n y=0.99,\n xanchor=\"left\",\n x=0.01\n ),\n font=dict(\n family=\"Arial\",\n size=18,\n color=\"Black\"\n ),\n )\n\n return fig\n\n\n\ndef plotlyTprobes(t,T,names):\n \"\"\"\n returns a DASH object for use directly in dash app\n\n t is list of timesteps\n\n T is list of temperature at each corresponding t item\n\n names is name of PFC for that T (element-wise)\n\n both t and T are numpy arrays of the same length at each list index\n \"\"\"\n if type(t) is not list:\n t = [t]\n if type(T) is not list:\n T = [T]\n if type(names) is not list:\n names = [names]\n\n\n fig = go.Figure()\n for i,T in enumerate(T):\n name = 'T{:d} '.format(i) + names[i]\n fig.add_trace(go.Scatter(x=t[i], y=T, name=name))\n\n xMin = min([min(arr) for arr in t])\n xMax = max([max(arr) for arr in t])\n fig.add_trace(go.Scatter(\n x=[xMin, xMax],\n y=[1873, 1873],\n mode=\"lines+markers+text\",\n name=\"Sublimation T\",\n text=[\"Limit\", \"Limit\"],\n textposition=\"top center\",\n line=dict(color='firebrick', width=3, dash='dot'),\n textfont=dict(family=\"Arial\", size=16, color=\"firebrick\"),\n\n ))\n\n fig.update_layout(\n title=\"Temperature Probe Time Evolution\",\n xaxis_title=\"Time [s]\",\n yaxis_title=\"Temperature [K]\",\n font=dict(\n family=\"Arial\",\n size=18,\n color=\"Black\"\n ),\n )\n\n\n\n return fig\n","sub_path":"source/GUIscripts/plotlyGUIplots.py","file_name":"plotlyGUIplots.py","file_ext":"py","file_size_in_byte":5038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"179073673","text":"import urllib.request as url_req\nimport urllib.error as lib_error\nfrom datetime import datetime\nimport time\nimport feedparser\nimport logging\n\ntry:\n from config_parse import SEARCH_API\n\n from data_config import CONFIGS\n from postgres_connection import Postgres_Connect\n\nexcept ImportError:\n pass\nelse:\n log = logging.getLogger(__name__)\n for ids in CONFIGS:\n res = []\n aid = CONFIGS[ids]['appstoreid']\n rv = CONFIGS[ids]['latest_posted_review']\n\n def exec_func(aid, rv):\n for i in range(1, 11):\n request = url_req.Request(\n url='{url}/jp/rss/{media_type}/id={app_id}/sortBy={sort_by}/page={page}/{format}'.format(\n url=SEARCH_API['Base']['url'],\n media_type=SEARCH_API['customerreviews-config']['media-type'],\n sort_by=SEARCH_API['customerreviews-config']['sortBy'],\n format=SEARCH_API['customerreviews-config']['format'],\n app_id=aid,\n page=i)\n )\n time.sleep(1)\n try:\n tmp = url_req.urlopen(request, timeout=15)\n\n except lib_error.HTTPError as e:\n log.error(e)\n continue\n except lib_error.URLError as e:\n log.error(e)\n continue\n else:\n if getattr(tmp, 'code') and getattr(tmp, 'msg'):\n log.info(str(tmp.code)+':'+tmp.msg +\n '[app_id:{app_id},page:{page}]'\n .format(app_id=aid, page=i))\n feed = feedparser.parse(tmp)\n # unko=feed.entries.index(rv)\n for el in feed.entries:\n if rv is not None and el['id'].split('/')[-1] == rv:\n return res\n else:\n res.append({\n 'appstoreid': aid,\n 'reviewid': el['id'].split('/')[-1],\n 'reviewDateTime': datetime.fromisoformat(el['updated']).strftime('%Y/%m/%d %H:%M:%S'),\n 'rating': el['im_rating'],\n 'reviewer': el['author'],\n 'reviewtitle': el['title'],\n 'reviewcontent': el['content'][0]['value'],\n 'votesum': el['im_votesum'],\n 'votecount': el['im_votecount'],\n 'version': el['im_version']\n })\n if len(feed.entries) < 50 or i == 10:\n return res\n\n re = exec_func(aid, rv)\n if len(re) > 0:\n Postgres_Connect.query_entry('ins_02', re)\n","sub_path":"Py_Batch/appstore_review.py","file_name":"appstore_review.py","file_ext":"py","file_size_in_byte":2950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"300628965","text":"\nimport time\nimport client\n\nclient = client.FmuClient(\"localhost\", 8000)\n\nmodel_name = client.model_description.model_name\nprint(\"ModelName={}\".format(model_name))\n\nfmu = client.create_instance()\n\nvariables = fmu.model_variables\nfor key in variables:\n v = variables[key]\n if v.causality == 2:\n print(v)\n\nif fmu.init():\n\n dt = 1.0/100\n start = time.time()\n t = fmu.get_current_time()\n while t < 10:\n step = fmu.step(dt)\n t = step.simulation_time\n if step.status != 0:\n print(\"Error: t={}, FMU returned status {}\".format(t, step.status))\n break\n end = time.time()\n\n print(\"Elapsed={}s\".format(end-start))\n\n reader = fmu.get_reader(\"PistonDisplacement\")\n print(\"PistonDisplacement={}\".format(reader.read_real().value))\n\nprint(\"Terminated with success: {}\".format(fmu.terminate().status == 0))\n\n\n\n","sub_path":"python/grpc-client/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"546904063","text":"import cv2\nimport numpy as np\nimport control\nimport depth as dp\nfrom threading import Thread,currentThread,activeCount\nimport time\nimport finger_detection as fg\nfrozen_period = 3\n\ninterval = 2 # how many frames do we wait till the next calculation\n\nglove_size_limit = 0.01\n#if the glove pixel ratio is less than this value\n#then we assum there's no glove on the screen\n\nprecision = 0.05 # if the change is less than this percentage, consider it not moving\n\ncontinuity = 2\n\nio_continuity = 2\n# \"continuity\" frames in a row define a movement\n# for example, if the hand only moves left in one frame,\n# it is not considered a moving left\n\nclick_continuity = 2\n# the continuity for click should be smaller because people tend to do fast clicks\n\nclick_state_length_limit = 10\n# click consists of finger, fist, finger, each of it's length should be less than this limit\n\nclick_gap = 0\n# the number of frames allowed between two clicks for a double click\n\nmax_axis = 2\n# axis 0 - left/right; axis 1 - up/down; axis 2 - in/out\n\n# counter counts how many continugous frames contains the desired movement\ncounters = [[[0, 0], # in the left/right axis, [# of times prev_pos < curr_pos, prev_pos > curr_pos]\n [0, 0], # in the up/down axis\n [0, 0]], # in the in/out axis,\n # the third number means number of continuous clicks recorded so far, the fourth number means the frame the last click is detected\n # the fifth number means whether click is enabled - clicks are disabled when it's in the invalid region\n [[0, 0], # the below three rows are the same as the above three, but is for orange instead of green\n [0, 0],\n [0, 0]]]\n # we should be able to detect single click and double clicks using green glove\n\n#padding_ratio = 0.05\npadding_ratio = 0.15\n# when the glove moves into the left, right, up and down 10% of the width/height\n# the clicks are ignored. Thus this area is considered \"invalid\"\n# mouse position on the screen are determined by the relative position of the glove to the valid area\n\n# colors\ngreen = 0\norange = 1\n\n# assign roles to the colors\nmouse = green # use green glove to control mouse movements\nbrowser = orange # use orange to control brower specific movements\n\n# axis\nlr = 0 # left/right\nud = 1 # up/down\nio = 2 # in/out\n\nlower_green = np.array([155, 150, 80])\nupper_green = np.array([180, 255, 255])\n# 140 120\n#lower_orange = np.array([5, 140, 120])\n#upper_orange = np.array([15, 255, 255])\nlower_orange = np.array([155, 150, 80])\nupper_orange = np.array([180, 255, 255])\n\n# call this function when the user stops doing a click operation\n# for example, when a user is previously doing a click and currently doing left move\n\n\n# str_if_1lt2 - string to be printed if prev is less than curr\n# str_if_1gt2 - string to be printed if prev is greater than curr\n# return value means whether anything is printed\n# \"max_n\" means the maximum possible value for prev and curr,\n# which is used to calculate how much n has changed\n# axis - 0 means left/right, 1 means up/down, 2 means in/out\n# color - 0 means green and 1 means orange\n# frame_no means \"frame number\", that is the current frame we are looking at\ndef compare_and_print_orange(prev, curr, str_if_1lt2, str_if_1gt2, max_n, axis, frame_no):\n counter = counters[1]\n if prev * curr < 0 or \\\n (axis < io and abs(prev - curr) / max_n < 0.05) or \\\n (axis == io and (max(prev, curr) / min(prev, curr) < 1.012)):\n counter[axis] = [0, 0] #clear the counter on this axis\n return False\n\n if prev < curr:\n direction = 0\n oppo_dir = 1 # opposite direction\n print_str = str_if_1lt2\n else:\n direction = 1\n oppo_dir = 0\n print_str = str_if_1gt2\n\n counter[axis][direction] += 1\n counter[axis][oppo_dir] = 0\n\n if axis < 1:\n counter[io] = [0, 0]\n\n if (counter[axis][direction] == continuity and axis != io) or (axis == io and counter[axis][direction] == io_continuity): # if the number of continuous motions reach the threshold\n counter[axis][direction] = 0\n print(\"orange \" + print_str)\n\n if print_str == \"zooming in\":\n Thread(target = control.enlarge, args=(2,)).start()\n elif print_str == \"zooming out\":\n Thread(target = control.shrink, args=(2,)).start()\n elif print_str == \"moving left\":\n Thread(target = control.shift_to_left_tab).start()\n elif print_str == \"moving right\":\n Thread(target = control.shift_to_right_tab).start()\n elif print_str == \"moving up\":\n Thread(target = control.go_up, args=(10,)).start()\n else:\n Thread(target = control.go_down, args=(10,)).start()\n\n # also clear the count for other axis\n for i in range(max_axis + 1):\n if i != axis:\n #if len(counter[i]) == 2:\n counter[i] = [0, 0]\n # in browser operation, we don't want movements such as up-left (we only want movement in one axis)\n #clear_click_counter()\n return True\n\n return False\n\n\ndef compare_and_print_green(prev, curr, str_if_1lt2, str_if_1gt2, max_n, axis, frame_no):\n\n counter = counters[0]\n if prev * curr < 0 or (axis == io and max(prev, curr) / min(prev, curr) < 1.04):\n return False\n\n if prev < curr:\n direction = 0\n oppo_dir = 1 # opposite direction\n else:\n direction = 1\n oppo_dir = 0\n\n #assert color == mouse and axis == io\n click_counter = counters[mouse][io]\n if direction == 0:\n #print(\"prev \" + str(click_counter))\n click_counter[direction] += 1\n #print(\"now \" + str(click_counter))\n click_counter[oppo_dir] = 0\n else: # direction == 1\n if click_counter[oppo_dir] >= click_continuity:\n click_counter[direction] += 1\n if click_counter[direction] >= click_continuity:\n click_counter[0] = click_counter[1] = 0\n print(\"click frame: \" + str(frame_no))\n control.mouse_single_click()\n return True\n #click_place[0] = screen_x\n #click_place[1] = screen_y\n #print(click_counter)\n return False\n\n\n\n# return a image with only the object with the color specified by the mask\ndef filter_out_color(img, mask):\n imask = mask>0\n colored_obj = np.zeros_like(img, np.uint8)\n colored_obj[imask] = img[imask]\n return colored_obj\n\n# give an image, return a mask that has \n# non zero values only for pixels that are green\n# color==0 means green, and color==1 means orange\n# return mask, rectangle center (-1 means invalid), rectangle area (-1 means invalid)\ndef get_mask_and_rect_info(img, color):\n # first blur the original image\n #img_blurred = cv2.GaussianBlur(img, (13, 13), 0)\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n if color == green:\n mask = cv2.inRange(hsv, lower_green, upper_green)\n elif color == orange:\n mask = cv2.inRange(hsv, lower_orange, upper_orange)\n # then also blur the hsv mask\n temp_mask_blurred = cv2.GaussianBlur(mask, (9, 9), 0)\n null_var, mask_blurred = cv2.threshold(temp_mask_blurred, 10, 255, cv2.THRESH_BINARY)\n\n image, contours, hierarchy = cv2.findContours(mask_blurred, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n\n if len(contours) == 0:\n hand_shape = fg.get_hand_shape(contours)\n return hand_shape, np.zeros(img.shape[:2]), -1, -1\n # among all contours, pick the one with the biggest area, and use it as the main contour\n countour_areas = [cv2.contourArea(contour) for contour in contours]\n max_index = countour_areas.index(max(countour_areas))\n main_contour = contours[max_index]\n\n hand_shape = fg.get_hand_shape(contours)\n\n # get the rectangle (could be rotated) that encloses the contour\n min_rect = cv2.minAreaRect(main_contour)\n # rect[0] is a tuple that represents the rectangle center\n # rect[1][0] is the width of the rectangle\n # rect[1][1] is the height of the rectangle\n # rect[2] is theta, the rotation angle, of the rectangle\n box = cv2.boxPoints(min_rect)\n box = np.int0(box)\n hand_mask = cv2.drawContours(np.zeros(img.shape[:2]), [main_contour], 0, (127, 127, 127), cv2.FILLED)\n\n\n return hand_shape, hand_mask, tuple(int(point) for point in min_rect[0]), min_rect[1][0] * min_rect[1][1]\n\ndef get_left_frame(combined_frame):\n Height, Width = combined_frame.shape[:2]\n img_W = int(Width / 2)\n img_H = Height\n return combined_frame[:img_H, :img_W]\n\ndef main():\n cap = cv2.VideoCapture(1)\n desired_width = 500\n desired_height = 480\n #cap.set(cv2.CAP_PROP_EXPOSURE, -7)\n cap.set(3, 2 * desired_width)\n cap.set(4, desired_height)\n\n loop_count = 0\n last_x = [-1, -1] # for two colors\n last_y = [-1, -1]\n last_depth = [-1, -1] # depth value is bigger when closer to the camera\n last_thread = -1 # last move mouse thread\n last_action = [-1, -1] # last green and orange action\n\n last_fist_interval = [-1, -1] # inclusive interval\n last_finger_interval = [-1, -1] # inclusive interval\n\n prev_screen_x = 0\n prev_screen_y = 0\n #click_place = [0, 0]\n #screen_x = 0\n #screen_y = 0\n width,height = control.get_screen_size()\n #start = time.time()\n while True:\n #time.sleep(0.2)\n #if loop_count % 30 == 0:\n #end = time.time()\n #print(end - start)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n \n loop_count += 1\n #check_for_finish_click(loop_count)\n ret, combined_frame = cap.read()\n #cv2.imshow('cmb_frame', combined_frame)\n #cv2.imwrite('fk.png', combined_frame)\n left_frame = get_left_frame(combined_frame)\n #cv2.imwrite('fk.png', left_frame)\n color = loop_count % interval\n # use the remainder, 0 means green and 1 means orange\n if color > 1:\n continue\n #mask, rect_center, rect_area = get_mask_and_rect_info(left_frame, green)\n #img = np.zeros((480, 640), np.uint8)\n #if rect_center != -1:\n #\tcv2.circle(img,(int(rect_center[0]), int(rect_center[1])), 10, (255, 0, 0), 1)\n #cv2.imshow('frame1', img)\n # in the end product, we will imshow(frame) instead of imshow(mask)\n # so don't worry about recalculating mask here\n\n rows = left_frame.shape[0]\n\n cols = left_frame.shape[1]\n\n #[0] is rows, which is y value\n #[1] is cols, which is x value\n\n if color <= 1:\n #print(\"a loop\")\n hand_shape, mask, rect_center, rect_area = get_mask_and_rect_info(left_frame, color)\n #cv2.imshow('mask', mask)\n if rect_area / (rows * cols) < glove_size_limit or rect_center == -1:\n continue\n\n current_x, current_y = rect_center[0], rect_center[1]\n\n if color == green:\n\n lb = padding_ratio * cols # left boundary\n rb = (1 - padding_ratio) * cols # right boundary\n ub = padding_ratio * rows # up boundary\n bb = (1 - padding_ratio) * rows # bottom boundary\n\n '''\n if current_x < lb or current_x > rb \\\n or current_y < ub or current_y > bb: # remember that upper-left corner is the origin\n counters[mouse][io][4] = 0 # if the mouse is in the padding area, we should ignore the click operations\n else:\n counters[mouse][io][4] = 1\n '''\n\n if hand_shape == fg.FINGER:\n if loop_count == last_finger_interval[1] + interval:\n last_finger_interval[1] += interval\n else: # if previous frame isn't finger\n last_fist_interval_length = last_fist_interval[1] - last_fist_interval[0]\n last_finger_interval_length = last_finger_interval[1] - last_finger_interval[0]\n if last_fist_interval[0] == last_finger_interval[1] + interval \\\n and last_fist_interval_length <= click_state_length_limit and last_fist_interval_length >= int(click_state_length_limit/3) \\\n and loop_count == last_fist_interval[1] + interval:\n print(\"single click\")\n control.mouse_single_click()\n last_finger_interval[0] = last_finger_interval[1] = loop_count\n elif hand_shape == fg.FIST:\n if loop_count == last_fist_interval[1] + interval:\n last_fist_interval[1] += interval\n else:\n last_fist_interval[0] = last_fist_interval[1] = loop_count\n\n if loop_count % 1 == 0 and hand_shape == fg.FINGER:\n screen_x = width - width * (current_x - lb) / (rb - lb)\n screen_y = height * (current_y - ub) / (bb - ub)\n if screen_y > height:\n screen_y = height\n if screen_y < 0:\n screen_y = 0\n if screen_x > width:\n screen_x = width\n if screen_x < 0:\n screen_x = 0\n '''\n if abs(prev_screen_y - screen_y) > 700 or abs(prev_screen_x - screen_x) > 500:\n clear_click_counter()\n print(\"clear 1\")\n '''\n if abs(prev_screen_y - screen_y) > 5 or abs(prev_screen_x - screen_x) > 5:\n #if counters[green][io][2] == 0 and\n #start = time.time()\n #control.move_mouse(screen_x, screen_y)\n #end = time.time()\n #print(end - start)\n temp_thread = Thread(target = control.move_mouse, args = (screen_x, screen_y))\n #if last_thread != -1:\n #\tlast_thread._stop()\n last_thread = temp_thread\n last_thread.start()\n print(\"Mouse move to (\" + str(screen_x) + \",\" + str(screen_y) + \")\")\n prev_screen_x = screen_x\n prev_screen_y = screen_y\n\n #if counters[mouse][io][4] == 1: #we don't need to disable clicking in the padding\n #compare_and_print_green(last_depth[color], current_depth, \"\", \"\", 1, 2, loop_count)\n\n\n #print(last_finger_interval, last_fist_interval)\n else:\n if loop_count - last_action[color] <= frozen_period or hand_shape != fg.PALM:\n continue\n temp_prev = last_action[color]\n last_action[color] = loop_count\n moved_ud = compare_and_print_orange(last_y[color], current_y, \"moving down\", \"moving up\", rows, axis=1, frame_no=loop_count)\n if moved_ud:\n continue\n moved_lr = compare_and_print_orange(last_x[color], current_x, \"moving left\", \"moving right\", cols, axis=0, frame_no=loop_count)\n if moved_lr:\n continue\n # note that left and right seen on the camera is symmetric to the real world\n if loop_count % 2 == 0:\n obj_depth = dp.get_depth(combined_frame, mask)\n print(obj_depth)\n if obj_depth == -1:\n continue\n current_depth = obj_depth\n zoomed = compare_and_print_orange(last_depth[color], current_depth, \"zooming in\", \"zooming out\", 1, axis=2, frame_no=loop_count)\n last_depth[color] = current_depth\n if not zoomed:\n last_action[color] = temp_prev\n last_x[color] = current_x\n last_y[color] = current_y\n\n cap.release()\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n main()","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":16136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"65276735","text":"#/usr/bin/env python3\n\nimport logging\n\ndef logger_init():\n# logging.basicConfig(filename='uapi.log',level=logging.DEBUG)\n logger=logging.getLogger()\n handler=logging.StreamHandler()\n# formatter=logging.Formatter('%(asctime)s %s(name)-12s $(levelname)-8s %(message)s')\n formatter=logging.Formatter('%(levelname)-5s %(message)s')\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n #logger.setLevel(logging.INFO)\n return logger\n\n","sub_path":"discodos/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"525756108","text":"# -*- coding:utf-8 -*-\n\ndef getGrades(fname):\n try:\n gradesFile = open(fname, 'r')\n except IOError:\n raise ValueError('getGrades could not open ', fname)\n grades = list()\n for line in gradesFile:\n try:\n grades.append(float(line))\n except:\n raise ValueError('Unable to convert line to float ')\n return grades\n\nif __name__ == \"__main__\":\n\n try:\n grades = getGrades('quiz1grades.txt')\n grades.sort()\n median = grades[len(grades) // 2]\n print('Median grade is ', median)\n\n except ValueError as errorMsg:\n print('Whoops.', errorMsg)\n","sub_path":"MIT/m070201.py","file_name":"m070201.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"226616448","text":"#!/usr/bin/env python3\nfrom collections import deque\n\"\"\"\nJosephus-Problem(Wikipedia):\nDas Josephus-Problem oder die Josephus-Permutation ist ein theoretisches Problem aus der Informatik oder Mathematik.\nEs werden nummerierte Objekte im Kreis angeordnet; dann wird, beginnend mit der Nummer, jedes n-te Objekt entfernt,\nwobei der Kreis immer wieder geschlossen wird.\n\"\"\"\n\nKANDIDATEN = 40\nSELECTOR = 10\n\nkandidaten = [(number) for number in range(1, KANDIDATEN + 1)]\nquere = deque(kandidaten)\nkandidaten.clear()\nloop = 0\nwhile quere:\n select = quere.popleft()\n loop += 1\n if loop % SELECTOR:\n quere.append(select)\n else:\n kandidaten.append(select)\n\nprint(kandidaten)","sub_path":"schnipsel/josephus.py","file_name":"josephus.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"338421669","text":"\"\"\"Test Ambient PWS diagnostics.\"\"\"\nfrom homeassistant.components.ambient_station import DOMAIN\nfrom homeassistant.components.diagnostics import REDACTED\nfrom homeassistant.core import HomeAssistant\n\nfrom tests.components.diagnostics import get_diagnostics_for_config_entry\nfrom tests.typing import ClientSessionGenerator\n\n\nasync def test_entry_diagnostics(\n hass: HomeAssistant,\n config_entry,\n hass_client: ClientSessionGenerator,\n data_station,\n setup_config_entry,\n) -> None:\n \"\"\"Test config entry diagnostics.\"\"\"\n ambient = hass.data[DOMAIN][config_entry.entry_id]\n ambient.stations = data_station\n assert await get_diagnostics_for_config_entry(hass, hass_client, config_entry) == {\n \"entry\": {\n \"entry_id\": config_entry.entry_id,\n \"version\": 2,\n \"domain\": \"ambient_station\",\n \"title\": REDACTED,\n \"data\": {\"api_key\": REDACTED, \"app_key\": REDACTED},\n \"options\": {},\n \"pref_disable_new_entities\": False,\n \"pref_disable_polling\": False,\n \"source\": \"user\",\n \"unique_id\": REDACTED,\n \"disabled_by\": None,\n },\n \"stations\": {\n \"devices\": [\n {\n \"macAddress\": REDACTED,\n \"lastData\": {\n \"dateutc\": 1642631880000,\n \"tempinf\": 70.9,\n \"humidityin\": 29,\n \"baromrelin\": 29.953,\n \"baromabsin\": 25.016,\n \"tempf\": 21,\n \"humidity\": 87,\n \"winddir\": 25,\n \"windspeedmph\": 0.2,\n \"windgustmph\": 1.1,\n \"maxdailygust\": 9.2,\n \"hourlyrainin\": 0,\n \"eventrainin\": 0,\n \"dailyrainin\": 0,\n \"weeklyrainin\": 0,\n \"monthlyrainin\": 0.409,\n \"totalrainin\": 35.398,\n \"solarradiation\": 11.62,\n \"uv\": 0,\n \"batt_co2\": 1,\n \"feelsLike\": 21,\n \"dewPoint\": 17.75,\n \"feelsLikein\": 69.1,\n \"dewPointin\": 37,\n \"lastRain\": \"2022-01-07T19:45:00.000Z\",\n \"deviceId\": REDACTED,\n \"tz\": REDACTED,\n \"date\": \"2022-01-19T22:38:00.000Z\",\n },\n \"info\": {\"name\": \"Side Yard\", \"location\": REDACTED},\n \"apiKey\": REDACTED,\n }\n ],\n \"method\": \"subscribe\",\n },\n }\n","sub_path":"tests/components/ambient_station/test_diagnostics.py","file_name":"test_diagnostics.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"318223972","text":"\"\"\" manage site settings \"\"\"\nfrom django.contrib.auth.decorators import login_required, permission_required\nfrom django.shortcuts import redirect\nfrom django.template.response import TemplateResponse\nfrom django.utils.decorators import method_decorator\nfrom django.views import View\n\nfrom bookwyrm import emailing, forms, models\n\n\n# pylint: disable= no-self-use\n@method_decorator(login_required, name=\"dispatch\")\n@method_decorator(\n permission_required(\"bookwyrm.edit_instance_settings\", raise_exception=True),\n name=\"dispatch\",\n)\nclass Site(View):\n \"\"\"manage things like the instance name\"\"\"\n\n def get(self, request):\n \"\"\"edit form\"\"\"\n site = models.SiteSettings.objects.get()\n data = {\"site_form\": forms.SiteForm(instance=site)}\n return TemplateResponse(request, \"settings/site.html\", data)\n\n def post(self, request):\n \"\"\"edit the site settings\"\"\"\n site = models.SiteSettings.objects.get()\n form = forms.SiteForm(request.POST, request.FILES, instance=site)\n if not form.is_valid():\n data = {\"site_form\": form}\n return TemplateResponse(request, \"settings/site.html\", data)\n form.save()\n\n return redirect(\"settings-site\")\n\n\n@login_required\n@permission_required(\"bookwyrm.edit_instance_settings\", raise_exception=True)\ndef email_preview(request):\n \"\"\"for development, renders and example email template\"\"\"\n template = request.GET.get(\"email\")\n data = emailing.email_data()\n data[\"subject_path\"] = f\"email/{template}/subject.html\"\n data[\"html_content_path\"] = f\"email/{template}/html_content.html\"\n data[\"text_content_path\"] = f\"email/{template}/text_content.html\"\n data[\"reset_link\"] = \"https://example.com/link\"\n data[\"invite_link\"] = \"https://example.com/link\"\n data[\"confirmation_link\"] = \"https://example.com/link\"\n data[\"confirmation_code\"] = \"AKJHKDGKJSDFG\"\n return TemplateResponse(request, \"email/preview.html\", data)\n","sub_path":"bookwyrm/views/admin/site.py","file_name":"site.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"138359196","text":"# -*- coding: utf-8 -*-\n\n#***************************************************************************\n#* *\n#* Copyright (c) 2015 Dan Falck *\n#* *\n#* This program is free software; you can redistribute it and/or modify *\n#* it under the terms of the GNU Lesser General Public License (LGPL) *\n#* as published by the Free Software Foundation; either version 2 of *\n#* the License, or (at your option) any later version. *\n#* for detail see the LICENCE text file. *\n#* *\n#* This program is distributed in the hope that it will be useful, *\n#* but WITHOUT ANY WARRANTY; without even the implied warranty of *\n#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n#* GNU Library General Public License for more details. *\n#* *\n#* You should have received a copy of the GNU Library General Public *\n#* License along with this program; if not, write to the Free Software *\n#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *\n#* USA *\n#* *\n#***************************************************************************\n''' Used for CNC machine to load cutting Tool ie M6T3'''\n\nimport FreeCAD,FreeCADGui,Path,PathGui\nimport PathScripts, PathUtils\nfrom PathScripts import PathProject\nfrom PySide import QtCore,QtGui\n\n# Qt tanslation handling\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def translate(context, text, disambig=None):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def translate(context, text, disambig=None):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass LoadTool:\n def __init__(self,obj):\n obj.addProperty(\"App::PropertyIntegerConstraint\", \"ToolNumber\",\"Tool\", translate( \"Tool Number\", \"The active tool\"))\n obj.ToolNumber = (0,0,10000,1)\n obj.addProperty(\"App::PropertyFloat\", \"SpindleSpeed\", \"Tool\", translate(\"Spindle Speed\",\"The speed of the cutting spindle in RPM\"))\n obj.addProperty(\"App::PropertyEnumeration\", \"SpindleDir\", \"Tool\", translate(\"Spindle Dir\",\"Direction of spindle rotation\"))\n obj.SpindleDir = ['Forward','Reverse']\n obj.Proxy = self\n mode = 2\n obj.setEditorMode('Placement',mode)\n\n\n\n def execute(self,obj):\n commands = \"\"\n commands = 'M6T'+str(obj.ToolNumber)+'\\n'\n\n if obj.SpindleDir =='Forward':\n commands +='M3S'+str(obj.SpindleSpeed)+'\\n'\n\n else:\n commands +='M4S'+str(obj.SpindleSpeed)+'\\n'\n\n obj.Path = Path.Path(commands)\n obj.Label = \"Tool\"+str(obj.ToolNumber)\n\n\n def onChanged(self,obj,prop):\n mode = 2\n obj.setEditorMode('Placement',mode)\n if prop == \"ToolNumber\":\n proj = PathUtils.findProj() \n for g in proj.Group:\n if not(isinstance(g.Proxy, PathScripts.PathLoadTool.LoadTool)):\n g.touch() \n \n \nclass _ViewProviderLoadTool:\n def __init__(self,vobj): #mandatory\n vobj.Proxy = self\n mode = 2\n vobj.setEditorMode('LineWidth',mode)\n vobj.setEditorMode('MarkerColor',mode)\n vobj.setEditorMode('NormalColor',mode)\n vobj.setEditorMode('ShowFirstRapid',mode)\n vobj.setEditorMode('DisplayMode',mode)\n vobj.setEditorMode('BoundingBox',mode)\n vobj.setEditorMode('Selectable',mode)\n vobj.setEditorMode('ShapeColor',mode)\n vobj.setEditorMode('Transparency',mode)\n vobj.setEditorMode('Visibility',mode)\n\n def __getstate__(self): #mandatory\n return None\n\n def __setstate__(self,state): #mandatory\n return None\n\n def getIcon(self): #optional\n return \":/icons/Path-LoadTool.svg\"\n\n def onChanged(self,vobj,prop): #optional\n mode = 2\n vobj.setEditorMode('LineWidth',mode)\n vobj.setEditorMode('MarkerColor',mode)\n vobj.setEditorMode('NormalColor',mode)\n vobj.setEditorMode('ShowFirstRapid',mode)\n vobj.setEditorMode('DisplayMode',mode)\n vobj.setEditorMode('BoundingBox',mode)\n vobj.setEditorMode('Selectable',mode)\n vobj.setEditorMode('ShapeColor',mode)\n vobj.setEditorMode('Transparency',mode)\n vobj.setEditorMode('Visibility',mode)\n\n def updateData(self,vobj,prop): #optional\n # this is executed when a property of the APP OBJECT changes\n pass\n\n def setEdit(self,vobj,mode): #optional\n # this is executed when the object is double-clicked in the tree\n pass\n\n def unsetEdit(self,vobj,mode): #optional\n # this is executed when the user cancels or terminates edit mode\n pass\n\nclass CommandPathLoadTool:\n def GetResources(self):\n return {'Pixmap' : 'Path-LoadTool',\n 'MenuText': QtCore.QT_TRANSLATE_NOOP(\"PathLoadTool\",\"Tool Number to Load\"),\n 'Accel': \"P, T\",\n 'ToolTip': QtCore.QT_TRANSLATE_NOOP(\"PathLoadTool\",\"Tool Number to Load\")}\n\n def IsActive(self):\n return not FreeCAD.ActiveDocument is None\n def Activated(self):\n FreeCAD.ActiveDocument.openTransaction(translate(\"Current Tool\",\"Tool Number to Load\"))\n FreeCADGui.addModule(\"PathScripts.PathLoadTool\")\n snippet = '''\nimport Path\nimport PathScripts\nfrom PathScripts import PathProject, PathUtils\nprjexists = False\nobj = FreeCAD.ActiveDocument.addObject(\"Path::FeaturePython\",\"Tool\")\nPathScripts.PathLoadTool.LoadTool(obj)\n\nPathScripts.PathLoadTool._ViewProviderLoadTool(obj.ViewObject)\n\nPathUtils.addToProject(obj)\n'''\n FreeCADGui.doCommand(snippet)\n FreeCAD.ActiveDocument.commitTransaction()\n FreeCAD.ActiveDocument.recompute()\n\nif FreeCAD.GuiUp: \n # register the FreeCAD command\n FreeCADGui.addCommand('Path_LoadTool', CommandPathLoadTool())\n \nFreeCAD.Console.PrintLog(\"Loading PathLoadTool... done\\n\")\n\n\n\n\n\n","sub_path":"SourceCode/FreeCAD_x86/src/Mod/Path/PathScripts/PathLoadTool.py","file_name":"PathLoadTool.py","file_ext":"py","file_size_in_byte":6433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"563541573","text":"from django.db import models\nfrom vizApps.domain.Board import BoardEntity\nfrom yamlfield.fields import YAMLField\nfrom vizApps.services.lumen.util import SpecYamlCreator\nimport os\nfrom sudBoard.settings import BASE_DIR\n\npath = BASE_DIR + '/vizApps/services/intake/'\n\n\nclass TargetEntity(models.Model):\n name = models.CharField(max_length=30)\n specYaml = YAMLField(blank=True)\n board = models.ForeignKey(BoardEntity, on_delete=models.CASCADE)\n\n def get_spec(self):\n views = [view.specYaml for view in self.viewentity_set.all()]\n filters = [filter.specYaml for filter in self.filterentity_set.all()]\n source = {'type': 'intake',\n 'uri': os.path.join(path, 'catalog.yml'),\n 'dask': False\n }\n\n return {'name':self.name,'title':self.name, 'source':source,'views' : views, 'filters':filters}\n\n def save(self, *args, **kwargs):\n self.saveSpec()\n super().save(*args, **kwargs)\n\n\n def saveSpec(self):\n views = self.get_spec()['views']\n filters = self.get_spec()['filters']\n source = self.get_spec()['source']\n title = self.get_spec()['title']\n name= self.get_spec()['name']\n p = {\n 'name': name,\n 'title': title ,\n 'source':source\n }\n if len(views) > 0:\n if views[0]:\n p['views'] = views\n if len(filters) > 0:\n if filters[0]:\n p['filters'] = filters\n\n spec = SpecYamlCreator(**p)\n self.specYaml = spec.to_yaml()","sub_path":"vizApps/domain/lumen/target.py","file_name":"target.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"472093899","text":"# -*- coding: utf-8 -*-\n\n# Define here the models for your scraped items\n#\n# See documentation in:\n# http://doc.scrapy.org/en/latest/topics/items.html\n\nimport scrapy\n\n\nclass EstateItem(scrapy.Item):\n # define the fields for your item here like:\n ESTATE_ADDRESS = scrapy.Field() # 住房地址\n ESTATE_NAME = scrapy.Field() # 名字\n ESTATE_PRICE = scrapy.Field() # 房价\n ESTATE_URL = scrapy.Field() # 房源url\n ESTATE_WHEN = scrapy.Field()\n","sub_path":"estate/estate/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"119346239","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\nPredict result for Inaturalist competition on Kaggle\n\"\"\"\n\nimport csv\nimport json\nimport operator\nimport os\n\nimport numpy as np\nfrom PIL import Image, ImageFilter\nfrom keras.models import load_model\n\nMDL = 'VGG16'\nIMG_SIZE = 128, 128, 3\n\nif __name__ == '__main__':\n model = load_model(MDL + '.h5')\n with open('test2018.json') as in_test:\n in_test_dict = json.load(in_test)\n with open(MDL + '_result.csv', mode='w') as res_csv:\n csv_file = csv.writer(res_csv)\n csv_file.writerow(['id', 'predicted'])\n num_imgs = len(in_test_dict['images'])\n p = 1\n for img in in_test_dict['images']:\n timg = Image.open(os.path.join('data', 'test2018', img['file_name']))\n if timg.mode != 'RGB':\n timg = timg.convert('RGB')\n timg = timg.resize(IMG_SIZE, Image.LANCZOS).filter(ImageFilter.SHARPEN)\n np_timg = np.asarray(timg, dtype=np.float32) / 255.0\n predictions = list(model.predict(np_timg, batch_size=1))[0]\n results = list()\n for _ in range(3):\n index, value = max(enumerate(predictions), key=operator.itemgetter(1))\n results.append(index)\n predictions.pop(index)\n csv_file.writerow([str(img['id']), ' '.join(results)])\n print('Prediction progression :', str(p / num_imgs))\n","sub_path":"data_processing/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"67151191","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 20 23:22:57 2020\n\n@author: Qin Lei\n\"\"\"\n\n\n\nfrom util.ECA import getInitState\nfrom util.ECA import ECA\nimport numpy as np \nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nENTROPY_SURFACE1 = \"data/classificaiton2_sampling_Surface_for_draw.csv\"\nENTROPY_SURFACE2 = \"data/entropy_sys_c10_for_draw.csv\"\ndf_entropy1 = pd.read_csv(ENTROPY_SURFACE1)\ndf_entropy2 = pd.read_csv(ENTROPY_SURFACE2)\n\nn_cell = 100\nrun_num = 100\ndef space2ndarray(space, ndspace):\n for i, row in enumerate(space):\n ndspace[i,:] = list(row)\n \ndef get_entropy_u(df,rule,crit_str = \"mean\"):\n D = df[df.rule == rule][\"d_ini\"].unique().tolist()\n Alpha = df[df.rule == rule].alpha.unique().tolist()\n u = np.empty([len(Alpha), len(D)])\n \n for i, alpha in enumerate(Alpha):\n u[i,:] = df[df.rule == rule][df.alpha == alpha][crit_str].tolist()\n \n return D, Alpha, u\n\nrule_list1 = [8, 140]\nrule_list2 = [2,38]\nrule_list3 = [23,33]\nrule_list4 = [6,18]\nrule_list5 = [156,170]\nis_class3 = False\n\nrule_list = rule_list3\ncmap = plt.get_cmap(\"Greys\")\n\nfig = plt.figure(figsize = (10.6, 6))\n\ntitle_list2 = [\"(a)\",\"(b)\",\"(c)\",\"(d)\",\"(e)\",\"(f)\"]\ninit_state = getInitState(n_cell, 0.5)\nfor i, rule in enumerate(rule_list):\n \n \n eca1 = ECA(rule, init_state=init_state, run_num=run_num, alpha=1)\n eca2 = ECA(rule, init_state=init_state, run_num=run_num, alpha=0.8)\n eca3 = ECA(rule, init_state=init_state, run_num=run_num, alpha=0.3)\n \n ca_list = [eca1, eca2, eca3]\n \n ax = fig.add_subplot(2,4,1+i*4,projection='3d')\n if is_class3:\n x,y,Z = get_entropy_u(df_entropy2, rule, \"System_entropy\")\n else:\n x,y,Z = get_entropy_u(df_entropy1, rule, \"System_entropy\")\n X, Y = np.meshgrid(x, y)\n ax.plot_wireframe(X,Y,Z, label=\"entropy\")\n ax.set_xlabel(r\"$d_{ini}$\")\n ax.set_ylabel(r\"$\\alpha$\")\n ax.set_zlabel(r\"$g_{H_N}$\")\n ax.set_title(\"(\"+str(i+1)+\")\"\" AECA \"+ str(rule_list[i]))\n ndsp = np.zeros([run_num, n_cell])\n for j,ca in enumerate(ca_list):\n ca.run(isPrint=False)\n \n \n space2ndarray(ca.space, ndsp)\n ax = fig.add_subplot(2,4,j+2+i*4)\n ax.imshow(ndsp, interpolation='none', cmap=cmap)\n\n ax.set_title(title_list2[i*3 + j] + \" \" + r\"$\\alpha=$\"+str(ca.alpha))\n ax.set_xticks([])\n ax.set_yticks([])\n \nplt.tight_layout(pad=5) \nplt.show()\n#plt.savefig(\"test1.eps\", dpi = 600, format= \"eps\")\n","sub_path":"classification2.py","file_name":"classification2.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"609693912","text":"\ndef greedy_density(capacity, items):\n\n sorted_items = sorted(items, key=lambda x: float(x.value) / x.weight, reverse=True)\n #sorted_items = sorted(items, key=lambda x: float(x.weight), reverse=True)\n \n # a trivial greedy algorithm for filling the knapsack\n # it takes items in-order until the knapsack is full\n value = 0\n weight = 0\n taken = [0]*len(items)\n\n for item in sorted_items:\n if weight + item.weight <= capacity:\n taken[item.index] = 1\n value += item.value\n weight += item.weight\n\n return (value, taken)\n","sub_path":"Greedy.py","file_name":"Greedy.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"632641461","text":"# Author: Gatlin Lawson\r\n\r\nclass Criminal:\r\n def __init__(self, first_name, last_name, gender, crime_type, in_jail, description):\r\n self.first_name = first_name\r\n self.last_name = last_name\r\n self.gender = gender\r\n self.crime_type = crime_type\r\n self.in_jail = in_jail\r\n self.description = description\r\n\r\n def is_match(self, gender, crime_type):\r\n if self.in_jail == True:\r\n return False\r\n\r\n if gender == self.gender and crime_type == self.crime_type:\r\n return True\r\n\r\n return False\r\n\r\n def display(self):\r\n jail_desc = \"Not Incarcerated\"\r\n\r\n if self.in_jail == True:\r\n jail_desc = \"Incarcerated\"\r\n\r\n print(f\"\"\"\r\n {self.first_name} {self.last_name}\r\n Gender: {self.gender}\r\n Crime: {self.crime_type}\r\n {jail_desc}\r\n {self.description}\r\n \"\"\")","sub_path":"Exercises/April13th/criminal.py","file_name":"criminal.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"42611877","text":"from redis import Redis\nfrom time import sleep\n\ndef main(**kwargs):\n\tr = Redis(host=\"redis\", port=6379, db=0)\n\tr.set('HELLO','WORLD')\n\tprint('HELLO')\n\twhile True:\n\t\tr.publish('test_channel','ping!')\n\t\tsleep(1)\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"pub/lib/publisher.py","file_name":"publisher.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"444516871","text":"import csv, re, pickle\n# from sklearn.neural_network import MLPClassifier\n\ndef gen_csv():\n\tf_r = open('AllTeams.csv', 'r')\n\tf_w = open('diff_data.csv', 'wb')\n\tcsv_r = csv.reader(f_r)\n\tcsv_w = csv.writer(f_w)\n\n\theader = csv_r.next()\n\theader_line = header[1:13] + header[17:22] + [header[23]] + [header[27]] + ['HOME'] \n\tclass_lbl = ['CLASS']\n\ttotal_header = header_line + class_lbl\n\tstats_dict = {}\n\n\tcsv_w.writerow(total_header)\n\n\n\tfor line in csv_r:\n\t\thome = False\n\t\tgame_id = line[14]\n\t\tstats_line = line[1:13] + line[17:22] + [line[23]] + [line[27]] + [line[29]]\n\n\t\ts_group = re.search('@', line[15])\n\t\tif s_group is not None:\n\t\t\thome = True\n\n\t\tif game_id in stats_dict:\n\t\t\tw_l = 1 if stats_dict[game_id][-1] == 'W' else -1\n\t\t\tif home:\n\t\t\t\tstats_dict[game_id] = stats_line[:-1] + [1] + stats_dict[game_id][:-1] + [0] + [w_l]\n\t\t\telse:\n\t\t\t\tstats_dict[game_id] = stats_dict[game_id][:-1] + [1] + stats_line[:-1] + [0] + [w_l]\n\t\telse:\n\t\t\tstats_dict[game_id] = stats_line\n\n\tfor key in stats_dict.keys():\n\t\tteam1 = stats_dict[key][0:(40/2)]\n\t\tteam2 = stats_dict[key][(40/2):-1]\n\t\tdiff = []\n\n\t\tfor i in range(len(team1)):\n\t\t\tdiff.append(float(team1[i]) - float(team2[i]))\n\n\t\tcsv_w.writerow(diff + [stats_dict[key][-1]])\n\tf_r.close()\n\tf_w.close()\n\ndef get_player_csv(file_list, data_directory):\n\n\tgame_dict = {}\n\tplayer_dict = {}\n\n\tgame_ctr = 0\n\tplayer_ctr = 0\n\n\tgame_index = 14\n\tplayer_index = 33\n\tdrop_indices = []\n\n\tfor f in file_list:\n\t\tf_r = open(data_directory + f, 'r')\n\t\tcsv_r = csv.reader(f_r)\n\n\t\theader_line = csv_r.next()\n\t\theader = header_line[1:13] + header_line[17:21] + [header_line[22]] + [header_line[24]] + [header_line[25]] + [header_line[27]]\n\n\t\tfor line in csv_r:\n\n\t\t\tstats_line = line[1:13] + line[17:21] + [line[22]] + [line[24]] + [line[25]]\n\t\t\tplayer_ident = line[player_index]\n\n\t\t\tif line[35] != '':\n\t\t\t\tgame_id = (line[game_index].lstrip('0'), line[35])\n\t\t\t\t\n\t\t\t\tif game_id not in game_dict.keys():\n\t\t\t\t\tgame_dict[game_id] = [line[27], line[33]]\n\t\t\t\telse:\n\t\t\t\t\tgame_dict[game_id].append(line[33])\n\n\t\t\tif player_ident not in player_dict.keys():\n\t\t\t\tplayer_dict[player_ident] = stats_line\n\t\t\telse:\n\t\t\t\tplayer_dict[player_ident] = sum_arr(player_dict[player_ident], stats_line)\n\t\tplayer_ctr += 1\n\t\tf_r.close()\n\n\tnew_dict = {}\n\tfor k,v in game_dict.iteritems():\n\t\tif len(game_dict[k]) >= 5:\n\t\t\tnew_dict[k] = v\n\n\tfor k,v in new_dict.iteritems():\n\t\twl_list = [new_dict[k][0]]\n\t\tcurr_stats_list = []\n\t\tfor player in new_dict[k]:\n\t\t\tif player in player_dict.keys():\n\t\t\t\tif len(curr_stats_list) == 0:\n\t\t\t\t\tcurr_stats_list = player_dict[player]\n\t\t\t\telse:\n\t\t\t\t\tsum_arr(curr_stats_list, player_dict[player])\n\t\tnew_dict[k] = curr_stats_list + wl_list\n\n\tend_dict = {}\n\tfor k,v in new_dict.iteritems():\n\t\tif k[0] not in end_dict.keys():\n\t\t\tend_dict[k[0]] = [v]\n\t\telse:\n\t\t\tend_dict[k[0]].append(v)\n\n\tfor k,v in end_dict.iteritems():\n\t\tclass_val = end_dict[k][0][-1]\n\t\tcombined_stats = sub_arr(end_dict[k][0][:-1], end_dict[k][1][:-1])\n\t\tif class_val == 'W':\n\t\t\tclass_val = 1\n\t\telif class_val == 'L':\n\t\t\tclass_val = -1\n\n\t\tend_dict[k] = combined_stats + [class_val]\n\n\tf_w = open('player_diff.csv', 'wb')\n\tcsv_w = csv.writer(f_w)\n\tcsv_w.writerow(header)\n\t# print header\n\tfor k,v in end_dict.iteritems():\n\t\tcsv_w.writerow(v)\n\t\t# print v \n\t\t# print \"---------------------------------\"\n\n\tf_w.close()\n\n\n\tpickle.dump(player_dict, open('players.p', 'wb'))\n\t\t\n\n\t# for k in player_dict.keys():\n\t# \tnew_arr = []\n\t# \tfor val in player_dict[k]:\n\t# \t\tif type(val) is not str:\n\t# \t\t\tnew_arr.append(val/float(player_ctr))\n\t# \tplayer_dict[k] = new_arr\n\n\t# for k,v in player_dict.iteritems():\n\t# \tprint k, v\n\t# \tprint \"---------------------------------\"\n\n\ndef sub_arr(arr1, arr2):\n\t# print arr1, arr2\n\tsum_arr = []\n\tfor i in range(len(arr1)):\n\t\tsum_arr.append(float(arr1[i])-float(arr2[i]))\n\n\treturn sum_arr\n\t\t\n\ndef sum_arr(arr1, arr2):\n\t# print arr1, arr2\n\tsum_arr = []\n\tfor i in range(len(arr1)):\n\t\tsum_arr.append(float(arr1[i])+float(arr2[i]))\n\n\treturn sum_arr\n\ndef getTPdict(file_list, data_directory):\n\n\tplayer_team_dict = {}\n\tfor f in file_list:\n\t\tf_r = open(data_directory + f, 'r')\n\t\tcsv_r = csv.reader(f_r)\n\t\tcsv_r.next()\n\n\t\tfor line in csv_r:\n\t\t\tteam_iden = line[35]\n\t\t\t# print line[33]\n\t\t\tif team_iden not in player_team_dict.keys():\n\t\t\t\tplayer_team_dict[team_iden] = [line[33]]\n\t\t\telif line[33] not in player_team_dict[team_iden]:\n\t\t\t\tplayer_team_dict[team_iden].append(line[33])\n\n\t\tf_r.close()\n\n\t# print player_team_dict\n\tpickle.dump(player_team_dict, open('players_team.p', 'wb'))\n\n\nif __name__ == '__main__':\n\tfile_list = ['AllGames.csv']\n\tdata_directory = '../../data/'\n\tget_player_csv(file_list, data_directory)\n\tgetTPdict(file_list, data_directory)\n\n\t# gen_csv()\n\t# print \"works\"","sub_path":"src/formatting/format_data.py","file_name":"format_data.py","file_ext":"py","file_size_in_byte":4684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"180478702","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nimport scrapy, os, requests, pymongo, time\n\n\nclass MeinvtuPipeline(object):\n def process_item(self, item, spider):\n for file_name in item['atlas_names']:\n dir_path = 'G:/学习/github/scrapy_learning/meinvtu/image/%s/' % file_name\n\n '''if not os.path.exists(dir_path):\n os.makedirs(dir_path)'''\n return item\n\n\nclass MongoDBPipeline(object):\n def __init__(self):\n try:\n connect = pymongo.MongoClient(host='localhost', port=27017)\n except:\n print('Datebase is busying.....')\n time.sleep(2)\n connect = pymongo.MongoClient(host='localhost', port=27017)\n db = connect['spiders']\n self.collection = db['meinvtu']\n self.collection.drop()\n\n def process_item(self, item, spider):\n info = dict(item)\n self.collection.insert(info)\n return item\n","sub_path":"meinvtu/meinvtu/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"293139025","text":"'''\nproblem URL: https://www.hackerrank.com/contests/projecteuler/challenges/euler089/problem\n-sohailshaukat ( https://github.com/sohailshaukat )\n-sohail47k@gmail.com\n'''\ndef rtod_converter(roman):\n roman_arr = [c for c in roman]\n for i,el in enumerate(roman_arr):\n if el == 'I':\n roman_arr[i]=1\n elif el == 'V':\n roman_arr[i]=5\n elif el == 'X':\n roman_arr[i]=10\n elif el == 'L':\n roman_arr[i]=50\n elif el == 'C':\n roman_arr[i]=100\n elif el == 'D':\n roman_arr[i]=500\n elif el == 'M':\n roman_arr[i]=1000\n else :\n roman_arr[i]=0\n anchor = max(roman_arr)\n flip = -1\n value = 0\n for i,el in enumerate(roman_arr):\n if el == anchor:\n flip = 1\n value += (flip) * el\n return value\n\ndef dtor_converter(num):\n num_arr = [i for i in str(num)]\n num_arr = num_arr[::-1]\n roman_arr = []\n m_arr = num_arr[3:]\n m_count = ''.join(m_arr[::-1])\n m_app = ''\n if m_count:\n m_count = int(m_count)\n m_app = 'M'*m_count\n for i,el in enumerate(num_arr):\n unit = ''\n penta= ''\n deca = ''\n if i == 0:\n unit = 'I'\n penta = 'V'\n deca = 'X'\n elif i == 1:\n unit = 'X'\n penta = 'L'\n deca = 'C'\n elif i == 2:\n unit = 'C'\n penta = 'D'\n deca = 'M'\n if el == '1':\n roman_arr.append(unit)\n elif el == '2':\n roman_arr.append(unit*2)\n elif el == '3':\n roman_arr.append(unit*3)\n elif el == '4':\n roman_arr.append(penta+unit)\n elif el == '5':\n roman_arr.append(penta)\n elif el == '6':\n roman_arr.append(unit+penta)\n elif el == '7':\n roman_arr.append((unit*2)+penta)\n elif el == '8':\n roman_arr.append((unit*3)+penta)\n elif el == '9':\n roman_arr.append(deca+unit)\n roman_arr.append(m_app)\n roman = ''.join(roman_arr)\n return(roman[::-1])\n\ntimes = int(input())\nwhile times:\n s=str(input())\n value = rtod_converter(s)\n result = dtor_converter(value)\n print(result)\n times -= 1\n","sub_path":"ProjectEuler-89-Roman-numerals/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"481192345","text":"\"\"\"\n가장 먼 노드 https://programmers.co.kr/learn/courses/30/lessons/49189\n\"\"\"\nfrom collections import deque\n\n\ndef solution(n, edge):\n distance = [int(1e9) for _ in range(n + 1)]\n path = [[] for _ in range(n + 1)]\n for a, b in edge:\n path[a].append(b)\n path[b].append(a)\n\n q = deque([[1, 0]])\n distance[1] = 0\n while q:\n now, dist = q.popleft()\n\n for node in path[now]:\n if distance[node] > dist + 1:\n distance[node] = dist + 1\n q.append([node, dist + 1])\n distance = distance[1:]\n print(distance)\n return distance.count(max(distance))\n\n\nprint(solution(6, [[3, 6], [4, 3], [3, 2], [1, 3], [1, 2], [2, 4], [5, 2]]))\n","sub_path":"4주차 그래프,DP/프로그래머스/가장먼노드/하현준.py","file_name":"하현준.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"327906529","text":"nodeIndex = 0\n\nclass Node(object):\n def __init__(self):\n global nodeIndex\n self.next = []\n self.id = nodeIndex\n nodeIndex = nodeIndex + 1\n\n def addCircle(self, val):\n e = Edge(val, self)\n self.next.append(e)\n n = Node()\n e = Edge(False, n)\n self.next.append(e)\n return n\n\n def addEdge(self, val):\n n = Node()\n e = Edge(val, n)\n self.next.append(e)\n return n\n\nclass Edge(object):\n def __init__(self, val, target):\n self.val = val\n self.target = target\n\nclass Solution(object):\n def walk(self, crt, s):\n possibilities = crt.next\n if len(possibilities) == 0 and len(s) == 0:\n return True\n if len(s) == 0:\n c = False\n else:\n c = s[0]\n\n for e in possibilities:\n val = e.val\n if val == False:\n if self.walk(e.target, s):\n return True\n if c != False and (val == '.' or val == c):\n if self.walk(e.target, s[1:]):\n return True\n return False\n\n def isMatch(self, s, p):\n start = Node()\n init = start\n lastCircle = False\n for i in range(0, len(p)):\n c = p[i]\n if c == '*':\n continue\n if i < len(p)-1:\n n = p[i+1]\n if n == '*':\n if c != lastCircle:\n start = start.addCircle(c)\n lastCircle = c\n else:\n start = start.addEdge(c)\n lastCircle = False\n else:\n start = start.addEdge(c)\n lastCircle = False\n\n return self.walk(init, s)\n\ns = Solution()\nprint(s.isMatch(\"aaaabaa\", \"a*a*a*.*a*b*a*\"))","sub_path":"10_regExMatching.py","file_name":"10_regExMatching.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"492419569","text":"#!/usr/bin/env python3\n\nfrom typing import Optional\nimport os\nimport subprocess\nfrom argparse import ArgumentParser\nfrom pathlib import Path\nfrom dataclasses import dataclass\nfrom shutil import rmtree\n\nroot = Path(__file__).resolve().parent\n\n\ndef run(cmd, env={}, cwd=None):\n print(f\"\\nRunning {cmd}\" + (f\" at '{cwd}'\" if cwd is not None else \"\") + \"\\n\", flush=True)\n subprocess.run(cmd, env={**os.environ, **env}, cwd=cwd, check=True)\n\n\n@dataclass\nclass Compiler:\n name: str\n version: Optional[int]\n\n @staticmethod\n def from_str(str):\n parts = str.split(\"-\")\n if len(parts) == 1:\n return Compiler(parts[0], None)\n elif len(parts) == 2:\n return Compiler(parts[0], int(parts[1]))\n else:\n raise RuntimeError(f\"Bad compiler string: {str}. Expected 'name[-version]'\")\n\n def binaries(self):\n ver = f\"-{self.version}\" if self.version is not None else \"\"\n if self.name == \"gcc\":\n return (f\"gcc{ver}\", f\"g++{ver}\")\n elif self.name == \"clang\":\n return (f\"clang{ver}\", f\"clang++{ver}\")\n else:\n raise RuntimeError(f\"Unknown compiler name: {self.name}. Expected 'gcc' or 'clang'\")\n\n def env(self):\n cc, cxx = self.binaries()\n return {\"CC\": cc, \"CXX\": cxx}\n\n\n@dataclass\nclass Project:\n build_dir: Path\n compiler: Compiler\n clean: bool\n\n def prepare(self):\n if self.build_dir.exists():\n if self.clean:\n rmtree(self.build_dir)\n\n if not self.build_dir.exists():\n self.build_dir.mkdir()\n\n run([\"cmake\", \"-DCMAKE_BUILD_TYPE=Debug\", root], env=self.compiler.env(), cwd=self.build_dir)\n\n def build(self):\n self.prepare()\n\n run([\"cmake\", \"--build\", self.build_dir, \"--parallel\", str(os.cpu_count())])\n\n def test(self):\n self.build()\n\n run([self.build_dir / \"rcore_test\"])\n run([self.build_dir / \"rstd_test\"])\n run([self.build_dir / \"rtest_test\"])\n\n\nactions = [\n (\"prepare\", Project.prepare),\n (\"build\", Project.build),\n (\"test\", Project.test),\n]\n\n\nparser = ArgumentParser()\nparser.add_argument(\"build_dir\", type=Path, help=\"build directory path\")\nparser.add_argument(\"action\", type=str, choices=[a[0] for a in actions], help=\"action\")\nparser.add_argument(\"--compiler\", type=str, default=\"gcc\")\nparser.add_argument(\"--clean\", action=\"store_true\", help=\"recreate build directory\")\n\n\nargs = parser.parse_args()\n\ncore = Project(\n build_dir=args.build_dir.resolve(),\n compiler=Compiler.from_str(args.compiler),\n clean=args.clean,\n)\n\n{k: v for k, v in actions}[args.action](core)\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":2653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"166049808","text":"# This File contains all the sql functions requireed in the project including a) Create Account b) Transaction option with Bank -> Bank, Bank-> Customer, Customer -> Bank, c) Transaction History, d) Delete Account\nimport mysql.connector\nfrom datetime import date, datetime\nfrom date_verifier import date_input\nfrom credentials import Credentials\n\nDate = date.today().strftime('%Y/%m/%d')\nmydb = mysql.connector.connect(**Credentials)\nmycursor = mydb.cursor(buffered=False)\nmycursor1 = mydb.cursor(buffered=False)\n# mycursor.execute('Create database if not exists bank_Management')\n# mycursor.execute('Use Bank_Management')\nmycursor.execute('create table if not exists user(account char(17) Primary Key, name Varchar(20) Not Null, Phone char(11) Not Null,email varchar(35) Unique Not Null, Balance int(10) check(Balance >-1) Not Null, transid varchar(25) not null, TOA varchar(10) Not Null, DOC date Not Null)')\nmycursor.execute('create table if not exists trans(Sender char(17) references user(account), Beneficiary char(17) references user(account), transid varchar(25) not null, date date not null, amount int(10))')\nmycursor.execute(\n 'create table if not exists amount(transid varchar(25) not null Primary Key,Sender_amount char(17), Beneficiary_amount char(17) )')\n\ndef check_details(email):\n mycursor.execute('Select email from user')\n if(mycursor):\n for j in mycursor:\n if(email in j):\n return (False, 'Email Already Exists in database')\n return (True,)\n\ndef new_user(name, phone, email):\n if not(phone.isdigit() and len(phone) == len(phone)):\n return (False, \"Please Enter Digits in Mobile number and/or Enter mobile number without country code\\n\")\n if not(check_details(email)[0]):\n return check_details(email)\n if(len(name) <= 20):\n if(len(email) <= 35):\n pass\n else:\n return(False, \"Kindly Enter Email within 35 characters\\n\")\n else:\n return(False, \"Kindly Enter Name within 20 Characters\\n\")\n\n account = datetime.today().strftime('%Y%m%d%H%M%S%f')[:16]\n mycursor.execute(\"Insert into user values(%s,%s,%s,%s,%s,%s,%s,%s)\",\n (account, name, phone, email, 1000, account+'1', \"savings\", Date))\n mycursor.execute(\"Insert into trans values('Self', %s, %s, %s, %s)\",\n (account, account+'1', Date, 1000))\n mycursor.execute(\"Insert into amount values(%s,%s,%s)\",\n (account+'1', \"Null\", 1000))\n mydb.commit()\n return (True, \"Successfully new Account Created with account number - \"+account+\"\\nFirst Transaction id is \" + account+'1')\n\ndef account_details(reciever):\n mycursor.execute(\n \"Select account, name, email, Balance from user where account = %s\", (reciever,))\n f = mycursor.fetchall()\n return f\n\ndef check_balance(account):\n mycursor.execute(\"select balance from user where account = %s\", (account,))\n a = mycursor.fetchall()\n return a[0][0]\n\ndef account_number(Name):\n mycursor.execute(\n 'select account, name from user where name like %s', ('%'+Name+'%',))\n return mycursor.fetchall()\n\ndef transid(account):\n mycursor.execute(\"select transid from user where account = %s\", (account,))\n for i in mycursor:\n print(account + str(int(i[0][16:])+1))\n return (account + str(int(i[0][16:])+1))\n\ndef trans(amount, mode, account, reciever='Self'):\n if(mode == 1):\n if(int(check_balance(str(account))) >= 1000+int(amount)):\n if(amount < 1):\n return \"Please Enter Valid Amount\"\n mycursor.execute(\n \"Select account, name, email from user where account = %s\", (reciever,))\n for i in mycursor:\n print(i, end='')\n print()\n a = input(\n 'Press Y if the above details about the reciever are correct\\n').lower()\n if(a == 'y'):\n tid = str(int(transid(account))+1)\n mycursor.execute(\"insert into trans values(%s,%s,%s,%s,%s)\", (\n account, reciever, tid, date.today().strftime('%Y/%m/%d'), amount))\n mycursor.execute(\"insert into amount values(%s,%s,%s)\", (tid, check_balance(\n str(account)) - amount, check_balance(str(account)) + amount))\n mycursor1.execute(\n \"Update user set balance = balance - %s where account = %s\", (amount, account))\n mycursor1.execute(\n \"Update user set balance = balance + %s and transid = %s where account = %s\", (amount, tid, reciever))\n mydb.commit()\n return f\"{amount} Rs has been transferred from {account} to {reciever}\"\n return \"Transaction is Aborted\"\n return \"Insufficient Balance\"\n\n if(mode == 2):\n tid = str(int(transid(account))+1)\n if(check_balance(str(account)) >= amount+1000):\n mycursor.execute(\"insert into trans values(%s,'self',%s,%s,%s)\",\n (account, tid, date.today().strftime('%Y/%m/%d'), amount))\n mycursor.execute(\"insert into amount values(%s,%s,%s)\",\n (tid, check_balance(amount)-amount, \"Null\"))\n mycursor.execute(\n \"update user set balance = balance -%s where account = %s\", (amount, account))\n mycursor.execute(\n \"update user set balance = balance +%s and transid = %s where account = %s\", (amount, tid, reciever))\n mydb.commit()\n return str(amount) + \" Rs has been withdrawn from \" + account\n return \"Insufficient Balance\"\n\n if(mode == 3):\n tid = str(int(transid(account))+1)\n mycursor.execute(\"insert into trans values('self', %s, %s, %s,%s)\",\n (account, tid, date.today().strftime('%Y/%m/%d'), amount))\n mycursor.execute(\"insert into amount values(%s,%s,%s)\",\n (tid, \"Null\", check_balance(str(account))+int(amount)))\n mycursor.execute(\n \"update user set balance = balance + %s where account = %s\", (amount, account))\n mycursor.execute(\n \"update user set transid = %s where account = %s\", (tid, account))\n mydb.commit()\n return f'{amount} rs has been credited to {account}'\n\n if(mode == 4):\n tid = str(int(transid(account))+1)\n mycursor.execute(\"insert into trans values(%s,'self',%s,%s,%s)\", (account,\n tid, date.today().strftime('%Y/%m/%d'), check_balance(str(account))))\n mycursor.execute(\n \"insert into amount values(%s,%s,%s)\", (tid, 0, \"Null\"))\n mycursor.execute(\"delete from user where account = %s\", (account,))\n mycursor.execute(\n \"update user set balance = balance +%s and transid = %s where account = %s\", (amount, tid, reciever))\n mydb.commit()\n return str(amount) + \" Rs has been withdrawn from \" + account + \" with transid \"+tid+\" and Account Has been Closed\"\n\ndef istransid(account, transid):\n mycursor.execute(\n \"Select transid from trans where sender = %s or beneficiary = %s\", (account, account))\n for i in mycursor.fetchall():\n if i[0] == transid:\n return True\n return False\n\ndef trans_history(account):\n while(True):\n a = input(\"Enter \\n1. For only Transid Searched Transaction \\n2. For Transaction between Specific Date Range \\n3. For Transaction Made on a day\\n\")\n if(a.isdigit()):\n a = int(a)\n if(a in range(1, 4)):\n if(a == 1):\n transid = input(\"Enter transid\\n\")\n if(istransid(account, transid)):\n i = []\n mycursor.execute(\n \"select transid, sender, beneficiary, date, sender_amount from trans natural join amount where trans.transid = %s and sender = %s\", (transid, account))\n i.append(mycursor.fetchone())\n mycursor1.execute(\n \"select transid, sender, beneficiary, date, Beneficiary_amount from trans natural join amount where trans.transid = %s and beneficiary = %s\", (transid, account))\n i.append(mycursor1.fetchone())\n return(True, i)\n return(False, \"Incorrect transid Provided\")\n if(a == 2):\n b = date_input()\n if(b[0] is True):\n print('Enter Second Date')\n c = date_input()\n if(c[0]):\n mycursor.execute(\n \"select transid, sender, beneficiary, date, sender_amount from trans natural join amount where sender = %s and Date between %s and %s\", (str(account), b[1], c[1]))\n e = mycursor.fetchall()\n mycursor1.execute(\n \"select transid, sender, beneficiary, date, beneficiary_amount from trans natural join amount where Date between %s and %s and beneficiary = %s\", (b[1], c[1], account))\n f = mycursor1.fetchall()\n i = [e, f]\n return (True, i)\n return (False, c[1])\n return (False, b[1])\n b = date_input()\n if(b[0] is True):\n i = []\n mycursor.execute(\n \"select transid, sender, beneficiary, date, sender_amount from trans natural join amount where Date = %s and sender = %s\", (b[1], account))\n i.append(mycursor.fetchall())\n mycursor1.execute(\n \"select transid, sender, beneficiary, date, Beneficiary_amount from trans natural join amount where Date = %s and beneficiary = %s\", (b[1], account))\n i.append(mycursor1.fetchall())\n return (True, i)\n return (False, b[1])\n\ndef close_account(account):\n if(check_balance(str(account)) == '0'):\n k = input(\n \"Are you Sure to delete Account, Press Y to continue, Else press any key to exit\").lower()\n if(k != 'y'):\n return \"Operation Cancelled\"\n mycursor.execute(\"delete from user where account = %s\", (account,))\n mydb.commit()\n return \"Account deleted Successfully\"\n balance = check_balance(str(account))\n trans(check_balance(account), 4, account)\n mycursor.execute(\"delete from user where account = %s\", (account,))\n mydb.commit()\n return f\"Account deleted succesfully and Rs {balance} will be returned to you as cash\"\n\ndef select_account(name):\n k, j = 0, []\n l = \"Srno. Name Account_Number\".split()\n mycursor.execute(\n 'select name, account from user where name like %s', (name,))\n for i in mycursor.fetchall():\n if(k == 0):\n for m in l:\n print(m, end='')\n print()\n j.append(i)\n print(str(k+1)+'>', i[0], i[1], '\\n')\n k += 1\n if(k == 0):\n return (False, \"Account Does't Exsist\\n\")\n while(True):\n a = input(\"\\nEnter Serial number\\n\")\n if(a.isdigit()):\n a = int(a)\n if(a > 0 and a < int(k+1)):\n return (True, j[int(a)-1][1])\n print(\"Please Select from given\\n\")\n else:\n print(\"Please enter digits only\\n\")\n","sub_path":"Employee_end.py","file_name":"Employee_end.py","file_ext":"py","file_size_in_byte":11538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"530048295","text":"class tet:\r\n def __init__(self):\r\n self.tetramino_types = ['i', 'j', 'l', 'o', 's', 't', 'z']\r\n self.gameboard_dimensions = [10, 20]\r\n self.x_min = 1\r\n self.x_max = self.gameboard_dimensions[0]\r\n self.y_min = 1\r\n self.y_max = self.gameboard_dimensions[1]\r\n \r\n def gen_tetramino(self):\r\n import random\r\n self.tetramino_type = random.choice(self.tetramino_types)\r\n return self.tetramino_type\r\n \r\n def gen_initial_coords(self, tetramino_type):\r\n import random\r\n self.coords=[]\r\n if self.tetramino_type == 'i':\r\n self.initial_coord = random.randint(self.x_min,self.x_max-3)\r\n self.coords.append([self.initial_coord + 0, 1])\r\n self.coords.append([self.initial_coord + 1, 1])\r\n self.coords.append([self.initial_coord + 2, 1])\r\n self.coords.append([self.initial_coord + 3, 1])\r\n return self.coords\r\n if self.tetramino_type == 'j':\r\n self.initial_coord = random.randint(self.x_min,self.x_max-2)\r\n self.coords.append([self.initial_coord + 0, 1])\r\n self.coords.append([self.initial_coord + 1, 1])\r\n self.coords.append([self.initial_coord + 2, 1])\r\n self.coords.append([self.initial_coord + 2, 2])\r\n return self.coords\r\n if self.tetramino_type == 'l':\r\n self.initial_coord = random.randint(self.x_min,self.x_max-2)\r\n self.coords.append([self.initial_coord + 0, 1])\r\n self.coords.append([self.initial_coord + 1, 1])\r\n self.coords.append([self.initial_coord + 2, 1])\r\n self.coords.append([self.initial_coord + 0, 2])\r\n return self.coords\r\n if self.tetramino_type == 'o':\r\n self.initial_coord = random.randint(self.x_min,self.x_max-1)\r\n self.coords.append([self.initial_coord + 0, 1])\r\n self.coords.append([self.initial_coord + 1, 1])\r\n self.coords.append([self.initial_coord + 0, 2])\r\n self.coords.append([self.initial_coord + 1, 2])\r\n return self.coords\r\n if self.tetramino_type == 's':\r\n self.initial_coord = random.randint(self.x_min+1,self.x_max-1)\r\n self.coords.append([self.initial_coord + 1, 1])\r\n self.coords.append([self.initial_coord + 2, 1])\r\n self.coords.append([self.initial_coord + 0, 2])\r\n self.coords.append([self.initial_coord + 1, 2])\r\n return self.coords\r\n if self.tetramino_type == 't':\r\n self.initial_coord = random.randint(self.x_min,self.x_max-2)\r\n self.coords.append([self.initial_coord + 0, 1])\r\n self.coords.append([self.initial_coord + 1, 1])\r\n self.coords.append([self.initial_coord + 2, 1])\r\n self.coords.append([self.initial_coord + 1, 2])\r\n return self.coords\r\n if self.tetramino_type == 'z':\r\n self.initial_coord = random.randint(self.x_min,self.x_max-2)\r\n self.coords.append([self.initial_coord + 0, 1])\r\n self.coords.append([self.initial_coord + 1, 1])\r\n self.coords.append([self.initial_coord + 1, 2])\r\n self.coords.append([self.initial_coord + 2, 3])\r\n return self.coords\r\n \r\n def drop (self, coords):\r\n temp=[]\r\n for i in range(len(self.coords)):\r\n temp.append([self.coords[i][0], self.coords[i][1]+1])\r\n self.dropped_coords = temp\r\n return self.dropped_coords\r\n \r\n \r\n def move_horizontal(self, coords, delta):\r\n temp=[]\r\n for i in range(len(self.coords)):\r\n temp.append([self.coords[i][0]+delta, self.coords[i][1]])\r\n self.slid_ocords = temp\r\n return self.slid_coords\r\n \r\n def rotate(self, tetramino_type, coords, direction):\r\n subtractor = []\r\n temp = []\r\n temp2 = []\r\n rotated_coords = []\r\n if self.tetramino_type == 'i' or 'j' or 'l' or 't' or 'z':\r\n subtractor=self.coords[1]\r\n elif self.tetramino_type == 's':\r\n subtractor=self.coords[0] \r\n for i in range(len(self.coords)):\r\n if direction == \"cw\":\r\n temp.append([self.coords[i][0]-subtractor[0], self.coords[i][1]-subtractor[1]])\r\n temp2.append([-temp[i][0], temp[i][1]])\r\n rotated_coords.append([temp2[i][0]+subtractor[0], temp2[i][1]+subtractor[1]])\r\n elif direction == \"ccw\":\r\n temp.append([self.coords[i][0]-subtractor[0], self.coords[i][1]-subtractor[1]])\r\n temp2.append([temp[i][0], -temp[i][1]])\r\n rotated_coords.append([temp2[i][0]+subtractor[0], temp2[i][1]+subtractor[1]])\r\n return rotated_coords\r\n \r\n def collision_check(self):\r\n #returns True if collision, False if no collision\r\n collision = False\r\n #checks for duplicate coordinates i.e. overlapping tetramino blocks\r\n for i in range(len(self.dropped_coords)):\r\n for j in range(len(game_pieces)):\r\n if self.dropped_coords[i] in game_pieces[j]:\r\n collision = True\r\n break\r\n #checks for tetramino block are out of bounds\r\n for coordinate_pair in self.dropped_coords:\r\n if coordinate_pair[0] > game_instance.x_max or coordinate_pair[0] < game_instance.x_min or coordinate_pair[1] > game_instance.y_max or coordinate_pair[1] < game_instance.y_min:\r\n collision = True\r\n break\r\n return collision\r\n \r\n def coord_change(self, collision, operation):\r\n if collision == False:\r\n if operation == 'rotate':\r\n self.coords = self.rotated_coords\r\n if operation == 'drop':\r\n self.coords = self.dropped_coords\r\n if operation == 'slide':\r\n self.coords = self.slid_coords\r\n return self.coords\r\n if collision == True or operation == 'none':\r\n return self.coords\r\n \r\n def draw_gameboard(self):\r\n self.gen_tetramino()\r\n self.gen_initial_coords(self.tetramino_type)\r\n\r\ndef gamepiece_append():\r\n game_pieces.append(game_instance.coords)\r\n return game_pieces\r\n \r\ndef row_clear_check():\r\n import itertools\r\n reduced_game_pieces = list(itertools.chain.from_iterable(game_pieces))\r\n i = game_instance.y_min\r\n for j in range(game_instance.y_min, game_instance.y_max+1):\r\n while i <= game_instance.x_max:\r\n if [i, j] in reduced_game_pieces:\r\n i+=1\r\n if i == game_instance.x_max:\r\n for i in range(game_instance.x_min, game_instance.x_max+1):\r\n reduced_game_pieces.remove([i, j])\r\n else:\r\n break\r\n\r\ngame_pieces=[]\r\ngame_instance = tet()\r\n\r\ngame_instance.draw_gameboard()\r\nfor i in range(0,42):\r\n game_instance.drop(game_instance.coords)\r\n game_instance.collision_check()\r\n row_clear_check()\r\n #print(\"running game_instance.collision_check() with\")\r\n #print(\"game_instance.dropped_coords = %s\" % game_instance.dropped_coords)\r\n #print(\"result of game_instance.collision_check() = %s \" % game_instance.collision_check())\r\n if game_instance.collision_check() == False:\r\n #allow rotation\r\n print(\"No collision detected, so dropping one space.\")\r\n #print(\"Current game_instance.coords are %s\" % game_instance.coords)\r\n print(\"Current game_instance.dropped_coords are %s\" % game_instance.dropped_coords)\r\n game_instance.coord_change(False, 'drop')\r\n #print(\"New game_instance.coords are %s\" % game_instance.coords)\r\n #print(\"New game_instance.dropped_coords are %s\" % game_instance.dropped_coords)\r\n print(\"Set of all coords is: %s\" % game_pieces)\r\n print(\"\\n\")\r\n if game_instance.collision_check() == True:\r\n #print(\"Collision detected, so appending game piece with coords %s\" % game_instance.coords)\r\n #print(\"Current game_instance.dropped_coords are %s\" % game_instance.dropped_coords)\r\n #print(\"Current game_instance.coords are %s\" % game_instance.coords)\r\n game_instance.coord_change(True, 'none')\r\n gamepiece_append()\r\n #print(\"game_instance.coords set equal to game_instance.dropped cords\")\r\n print(\"Set of all coords is %s\" % game_pieces)\r\n game_instance.draw_gameboard()\r\n print(\"\\n\")\r\n\r\n'''\r\n Pass other working coord sets (dropped_coords, rotated_coords, slid_coords) to collision_check()\r\n Don't append coords if collision is found for rotate/slide AND the coord still has room to fall;\r\n instead, disallow rotate/slide but let it continue to fall until there is no more room\r\n \r\n Flatten game_pieces by default so no need for reduced_game_pieces in row_clear_check().\r\n Rework any functions that use game_pieces?\r\n \r\n Game end is signaled by collision of tetramino as soon as it is created. How to check for this?\r\n \r\n Scan for inputs 30 times/sec\r\n Get input, store input type for passing as operation argument to coord_change\r\n For drop every 1 second\r\n'''\r\n","sub_path":"tetris.py","file_name":"tetris.py","file_ext":"py","file_size_in_byte":9224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"10295400","text":"class Solution:\n def minimumXORSum(self, nums1, nums2) -> int:\n import math\n nums1.sort(reverse=True)\n nums2.sort(reverse=True)\n ans = 0\n while nums1 and nums2:\n nums1.sort(reverse=True)\n nums2.sort(reverse=True)\n if nums1[0] == 0 or nums2[0]==0:\n ans+=nums1.pop(0)^nums2.pop(0)\n else:\n m,n=int(math.log2(nums1[0])),int(math.log2(nums2[0]))\n if m>n:\n nums1.append(nums1.pop(0)-2**m)\n ans+=2**m\n elif m=2**m:\n i = 0\n while i=2**n:\n if nums1[a]^nums2[i] d(lnl)/du = d(lnl)/dv * dv/du\n# dv/du = 1. / prior(v)\ndef gradient(x):\n \"\"\"Multivariate normal log-likelihood gradient.\"\"\"\n dlnl_dv = -np.dot(Cinv, x) # standard gradient\n jac = np.diag(np.full_like(x, 20.)) # Jacobian\n return np.dot(jac, dlnl_dv) # transformed gradient\n\n# initialize our nested sampler\nsampler = dynesty.NestedSampler(loglikelihood, prior_transform, ndim, nlive=1500)\n\n# sample from the target distribution\nsampler.run_nested()\n\nres = sampler.results # grab our results\nprint('Keys:', res.keys(),'\\n') # print accessible keys\nres.summary() # print a summary\n\n\n# ADDED BY ME TO TRY SAVING THINGS\nimport pickle\ndirec = '/Users/jonathancohn/Documents/dyn_mod/nest_out/'\nout_name = direc + 'dynesty_demo_output.pkl'\nwith open(out_name, 'wb+') as newfile: # 'wb' because binary format\n pickle.dump(res, newfile, pickle.HIGHEST_PROTOCOL) # res.samples\n print('results pickle dumped!')\n\nwith open(out_name, 'rb') as pk:\n u = pickle._Unpickler(pk)\n u.encoding = 'latin1'\n dyn_res = u.load()\nprint(dyn_res['samples'].shape)\n\n# 3-D plots of position and likelihood, colored by weight\nfig = plt.figure(figsize=(30, 10))\nax = fig.add_subplot(121, projection='3d')\n\n# plotting the initial run\np = ax.scatter(res.samples[:, 0], res.samples[:, 1], res.samples[:, 2],\n marker='o', c=np.exp(res.logwt) * 1e7, linewidths=(0.,), cmap='coolwarm')\nax.set_xlim(-10., 10.)\nax.set_xticks(np.linspace(-10., 10., 5))\nax.set_xlabel(r'$x$', labelpad=25)\nax.set_ylim(-10., 10.)\nax.set_yticks(np.linspace(-10., 10., 5))\nax.set_ylabel(r'$y$', labelpad=25)\nax.set_zlim(-10., 10.)\nax.set_zticks(np.linspace(-10., 10., 5))\nax.set_zlabel(r'$z$', labelpad=25)\nax.set_title('Initial Run')\ncb = fig.colorbar(p)\ncb.set_label('Weight (1e-6)', labelpad=50., rotation=270.)\nplt.tight_layout()\nplt.show()\n\n# plotting the extended run\nfig = plt.figure(figsize=(30, 10))\nax = fig.add_subplot(121, projection='3d')\np = ax.scatter(dyn_res['samples'][:, 0], dyn_res['samples'][:, 1], dyn_res['samples'][:, 2],\n marker='o', c=np.exp(dyn_res['logwt']) * 1e7, linewidths=(0.,), cmap='coolwarm')\nax.set_xlim(-10., 10.)\nax.set_xticks(np.linspace(-10., 10., 5))\nax.set_xlabel(r'$x$', labelpad=25)\nax.set_ylim(-10., 10.)\nax.set_yticks(np.linspace(-10., 10., 5))\nax.set_ylabel(r'$y$', labelpad=25)\nax.set_zlim(-10., 10.)\nax.set_zticks(np.linspace(-10., 10., 5))\nax.set_zlabel(r'$z$', labelpad=25)\nax.set_title('Initial Run')\ncb = fig.colorbar(p)\ncb.set_label('Weight (1e-6)', labelpad=50., rotation=270.)\nplt.tight_layout()\nplt.show()\n\n# How to do quantiles!\nfrom dynesty import utils as dyfunc\nweights = np.exp(dyn_res['logwt'] - dyn_res['logz'][-1]) # normalized weights\nfor i in range(dyn_res['samples'].shape[1]): # for each parameter\n quantiles_3 = dyfunc.quantile(dyn_res['samples'][:, i], [0.025, 0.5, 0.975], weights=weights)\n quantiles_1 = dyfunc.quantile(dyn_res['samples'][:, i], [0.16, 0.5, 0.84], weights=weights)\n print(quantiles_3)\n print(quantiles_1)\n\nfrom dynesty import plotting as dyplot\n# initialize figure\nfig, axes = plt.subplots(3, 7, figsize=(35, 15))\naxes = axes.reshape((3, 7)) # reshape axes\n\n# add white space\n[a.set_frame_on(False) for a in axes[:, 3]]\n[a.set_xticks([]) for a in axes[:, 3]]\n[a.set_yticks([]) for a in axes[:, 3]]\n\n# plot initial run (res1; left)\nfg, ax = dyplot.cornerplot(res, color='blue', truths=np.zeros(ndim),\n truth_color='black', show_titles=True,\n max_n_ticks=3, quantiles=None,\n fig=(fig, axes[:, :3]))\n\n# plot extended run (res2; right)\nfg, ax = dyplot.cornerplot(dyn_res, color='dodgerblue', truths=np.zeros(ndim),\n truth_color='black', show_titles=True,\n quantiles=None, max_n_ticks=3,\n fig=(fig, axes[:, 4:]))\nplt.show()\n","sub_path":"dynesty_demo.py","file_name":"dynesty_demo.py","file_ext":"py","file_size_in_byte":5664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"150456685","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom photologue.sitemaps import GallerySitemap, PhotoSitemap\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'appleroad.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n url(r'^appleroad/', include('oursite.urls')),\n url(r'^photologue/', include('photologue.urls', namespace='photologue')),\n)\n\n\nsitemaps = {\n 'photologue_galleries': GallerySitemap,\n 'photologue_photos': PhotoSitemap,\n \n }","sub_path":"appleroad/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"568134956","text":"from django.urls import path\n\nfrom . import views\nurlpatterns = [\n path(\"comida/\", views.comidaView, name=\"comidaView\"),\n path(\"refeicoes/\", views.refeicoesView, name=\"refeicoesView\"),\n path(\"comida//\", views.comidaViewComprar, name=\"comidaViewComprar\"),\n path(\"refeicoes//\", views.refeicoesViewComprar, name=\"refeicoesViewComprar\"),\n path(\"refeicoes//\", views.ConfirmarRefeicao, name=\"refeicoesConfirmarRefeicao\"),\n path(\"comida//\", views.ConfirmarComida, name=\"Confirmar\"),\n path(\"\", views.home, name=\"home\"),\n path(\"home/\", views.home, name=\"home\"),\n path(\"conta/\", views.conta, name=\"conta\"),\n path(\"conta/\", views.conta1, name=\"conta1\"),\n path(\"delete/12345\", views.delete, name=\"delete\"),\n path(\"conta//comida//\", views.QrCodeComida, name=\"QrCodeComida\"),\n path(\"conta//refeicoes//\", views.QrCodeRefeicoes, name=\"QrCodeRefeicoes\"),\n path(\"qrcode//comida/\", views.QrCodeComida1, name=\"QrCodeComida1\"),\n path(\"qrcode//refeicoes/\", views.QrCodeRefeicoes1, name=\"QrCodeRefeicoes1\"),\n \n]\n","sub_path":"mysite/main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"187639450","text":"import numpy as np\nimport os, sys\nimport json\nfrom skimage.io import imread\nfrom skimage.transform import resize\nfrom skimage.color import rgb2grey\n\nDATADIR = '../data/'\nIMG_SIZE = 128 # unet uses 512x512\n\ndef load_breast_cancer():\n from sklearn.datasets import load_breast_cancer\n X, y = load_breast_cancer(True)\n X = (X - X.mean(0)) / (X.std(0)+1e-8)\n return X, y\n\ndef load_wine():\n from sklearn.datasets import load_wine\n X, y = load_wine(True)\n y[y == 2] = 1\n X = (X - X.mean(0)) / (X.std(0)+1e-8)\n return X, y\n\ndef _load_images(dirname):\n img_file = os.path.join(dirname, 'X.npy')\n if os.path.exists(img_file):\n X = np.load(img_file)\n else:\n imgs_dirname = os.path.join(dirname, 'imgs', 'seg')\n imgs_files = sorted(os.listdir(imgs_dirname))\n imgs = []\n for i, filename in enumerate(imgs_files):\n sys.stdout.write('\\r%s/imgs: %4.1f%%' % (dirname, 100*i/len(imgs_files)))\n img = imread(os.path.join(imgs_dirname, filename))\n img = resize(img, (IMG_SIZE, IMG_SIZE), mode='constant', anti_aliasing=True)\n imgs.append(img)\n X = np.array(imgs, np.float32)\n np.save(img_file, X)\n mask_file = os.path.join(dirname, 'y.npy')\n if os.path.exists(mask_file):\n y = np.load(mask_file)\n else:\n masks_dirname = os.path.join(dirname, 'masks', 'seg')\n masks_files = sorted(os.listdir(masks_dirname))\n masks = []\n for i, filename in enumerate(masks_files):\n sys.stdout.write('\\r%s/masks: %4.1f%%' % (dirname, 100*i/len(masks_files)))\n mask = imread(os.path.join(masks_dirname, filename), True)\n mask = resize(mask, (IMG_SIZE, IMG_SIZE), mode='constant', anti_aliasing=True)\n masks.append(mask)\n y = np.array(masks)\n y = np.round(y[:, :, :, np.newaxis]).astype(np.int32)\n np.save(mask_file, y)\n sys.stdout.write('\\r \\r')\n return X, y\n\ndef load_images(dataset):\n dirname = os.path.join(DATADIR, dataset)\n with open(dirname + '.json') as f:\n aug = json.load(f)\n return _load_images(os.path.join(dirname, 'train')), \\\n _load_images(os.path.join(dirname, 'validation')), \\\n _load_images(os.path.join(dirname, 'test')), \\\n aug\n\ndef load_csv(filename):\n data = np.loadtxt('../data/%s' % dataset, delimiter=',')\n X = data[:, :-1]\n y = data[:, -1]\n X = (X - X.mean(0)) / (X.std(0)+1e-8)\n return X, y\n","sub_path":"mydatasets.py","file_name":"mydatasets.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"530753635","text":"import logging\n\n\nclass LoggingServiceFactory(object):\n __logger = None\n\n def __init__(self):\n if self.__logger is None:\n self.__set_logger()\n\n @classmethod\n def __set_logger(cls):\n if cls.__logger is None:\n cls.__logger = logging.getLogger('vvp-ci.logger')\n\n @classmethod\n def get_logger(cls):\n if cls.__logger is None:\n cls.__set_logger()\n return cls.__logger\n","sub_path":"services/logging_service.py","file_name":"logging_service.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"31356997","text":"\"\"\"article_extractor URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf.urls import url\nfrom rest_framework import routers\nfrom article.views import ArticleListView, SingleArticleView\n\nrouter = routers.DefaultRouter()\n\nrouter.register(r'user-article-posts', ArticleListView)\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('blog/', include('blog.urls')),\n path('', include('miscellaneous.urls')),\n path('article/', include('article.urls')),\n url(r'^accounts/', include('allauth.urls')),\n path('api/', include(router.urls)),\n path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n path('api/article-extractor/', SingleArticleView.as_view()),\n]\n","sub_path":"article_extractor/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"304499721","text":"from typing import Dict\nfrom PyQt5 import QtWidgets, QtCore\n\nfrom appGUI.ColumnarFlowLayout import ColumnarFlowLayout\nfrom appGUI.preferences.OptionUI import OptionUI\nfrom appGUI.preferences.OptionsGroupUI import OptionsGroupUI\n\n\nclass PreferencesSectionUI(QtWidgets.QWidget):\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.layout = ColumnarFlowLayout() # QtWidgets.QHBoxLayout()\n self.setLayout(self.layout)\n\n self.groups = self.build_groups()\n for group in self.groups:\n group.setMinimumWidth(250)\n self.layout.addWidget(group)\n\n def build_groups(self) -> [OptionsGroupUI]:\n return []\n\n def option_dict(self) -> Dict[str, OptionUI]:\n result = {}\n for group in self.groups:\n groupoptions = group.option_dict()\n result.update(groupoptions)\n return result\n\n def build_tab(self):\n scroll_area = QtWidgets.QScrollArea()\n scroll_area.setWidget(self)\n scroll_area.setWidgetResizable(True)\n return scroll_area\n\n def get_tab_id(self) -> str:\n raise NotImplementedError\n\n def get_tab_label(self) -> str:\n raise NotImplementedError\n","sub_path":"HSRWLaserTool_APP/FlatCAM_beta_8.994_sources/appGUI/preferences/PreferencesSectionUI.py","file_name":"PreferencesSectionUI.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"462932333","text":"#!/usr/bin/env python\n#encoding=utf-8\n\n\"\"\"\n@author ZHAOPENGCHENG on 2017/8/9.\n\"\"\"\n\nfrom captcha.image import ImageCaptcha # pip install captcha\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport random,time,os\n\n# 验证码中的字符, 就不用汉字了\nnumber = ['0','1','2','3','4','5','6','7','8','9']\n# 验证码一般都无视大小写;验证码长度4个字符\ncaptchaCharacterLength = 4\ncaptchaBoxWidth = 160\ncaptchaBoxHeight = 60\n\n\n\ndef random_captcha_text(char_set=number, captcha_size=captchaCharacterLength):\n\tcaptcha_text = []\n\tfor i in range(captcha_size):\n\t\tc = random.choice(char_set)\n\t\tcaptcha_text.append(c)\n\treturn captcha_text\n\n# 生成字符对应的验证码\ndef gen_captcha_text_and_image():\n\t\"\"\"\n\t生成字符序列和对应的图片数据\n\t:return:\n\t\"\"\"\n\timage = ImageCaptcha(width=captchaBoxWidth, height=captchaBoxHeight)\n\n\tcaptcha_text = random_captcha_text()\n\tcaptcha_text = ''.join(captcha_text)\n\n\tcaptcha = image.generate(captcha_text)\n\n\tcaptcha_image = Image.open(captcha)\n\tcaptcha_image = np.array(captcha_image)\n\treturn captcha_text, captcha_image\n\nif __name__ == '__main__':\n\t# 测试\n\twhile(1):\n\t\ttext, image = gen_captcha_text_and_image()\n\n\t\tprint(image.shape, \"no chinese\")\n\t\tprint('%d, %.4f'% (15, 15.234587))\n\n\t\tprint('begin ' + time.strftime(\"%Y-%m-%d %H:%M:%S\") + str(type(image)))\n\t\tf = plt.figure()\n\t\tax = f.add_subplot(111)\n\t\tax.text(0.1, 0.9,text, ha='center', va='center', transform=ax.transAxes)\n\t\tplt.imshow(image)\n\n\n\t\tplt.show()\n\t\tprint('end ' + time.strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n","sub_path":"com/huitong/captchaRecognisev1/genCaptcha.py","file_name":"genCaptcha.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"492430702","text":"\nclass SpaceAge():\n def __init__(self, age_in_second):\n self.seconds = age_in_second\n self.planets = {'on_earth': 31557600,\n 'on_mercury': 7600530.24,\n 'on_venus': 19413907.2,\n 'on_mars': 59354294.4,\n 'on_jupiter': 374335776,\n 'on_saturn': 929596608,\n 'on_uranus': 2661041808,\n 'on_neptune': 5200418592,\n }\n\n def __getattr__(self, name):\n if name in self.planets:\n def func():\n return round((self.seconds / self.planets[name]), 2)\n return func\n else:\n raise AttributeError\n\n","sub_path":"python/space-age/space_age.py","file_name":"space_age.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"448175986","text":"import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport time\nimport numpy as np\nimport pickle\n\n\nsince = time.time()\n\n\ndata_dir = '../data/'\nsave_dir = '../saves/'\ndf_train = pd.read_csv(data_dir+\"train.csv\")\n\ndf = pd.read_csv(data_dir+\"members.csv\",\n dtype={'city': np.uint8,\n 'bd': np.uint8,\n 'gender': 'category',\n 'registered_via': np.uint8,\n 'msno': 'category'\n },\n parse_dates=['registration_init_time',\n 'expiration_date']\n )\ndf_test = pd.read_csv(data_dir+\"test.csv\")\n\n\nprint('creating custom member.')\n\nset1 = set(df_train['msno'])\nset2 = set(df_test['msno'])\nunion_member = set.union(set1, set2)\n# print(len(union_member))\ndf.set_index('msno', inplace=True)\ndf = df.loc[union_member]\ndf.to_csv(save_dir+'custom_members.csv')\nprint('dtypes of df:')\nprint('>'*20)\nprint(df.dtypes)\nprint('number of columns:', len(df.columns))\nprint('<'*20)\n# print(d)\n# pickle.dump(d, open(save_dir+\"custom_member_dict.save\", \"wb\"))\n# xxxx = pickle.load(open(\"xxx.save\", \"rb\"))\nprint('done.')\nprint()\ntime_elapsed = time.time() - since\nprint('[timer]: complete in {:.0f}m {:.0f}s'.format(\n time_elapsed // 60, time_elapsed % 60))\n\n","sub_path":"kaggle_song_git/code_box/playground_V1005/custom_member_V1001.py","file_name":"custom_member_V1001.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"559037424","text":"#!/bin/python3\r\n\r\n# Complete the countTriplets function below.\r\ndef countTriplets(arr, r):\r\n q = 0\r\n arr_q = {}\r\n for i in reversed(arr):\r\n arr_q[i] = arr_q.get(i, 0) + 1\r\n q += arr_q.get(i * r, 0) * arr_q.get(i * r * r, 0)\r\n return q\r\n\r\nif __name__ == \"__main__\":\r\n\r\n nr = input().rstrip().split()\r\n n = int(nr[0])\r\n r = int(nr[1])\r\n arr = list(map(int, input().rstrip().split()))\r\n ans = countTriplets(arr, r)\r\n print(ans)\r\n","sub_path":"Interview Preparation Kit/Count Triplets/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"430003874","text":"# File: EnigmaConstants.py\n\n\"\"\"\nThis module defines the constants used in the Enigma simulator.\n\"\"\"\n\n# The letters of the alphabet\n\nALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\n# Constants that specify the size of the Enigma image.\n\nENIGMA_WIDTH = 818\nENIGMA_HEIGHT = 694\n\n# The early German Enigma machines include three rotors, which advance\n# at different speeds. The rotor on the right is the \"fast\" rotor,\n# which advances on every keystroke. The rotor in the middle is the\n# \"medium\" rotor, which advances when the fast rotor has made a\n# complete revolution. The rotor at the left is the \"slow\" rotor,\n# which advances when the medium rotor has made a complete cycle.\n# The ROTOR_PERMUTATION array lists the three rotors from left to\n# right: the slow rotor, the medium rotor, and the fast rotor.\n#\n# Each rotor implements a letter-substitution cipher, which is\n# represented by a string of 26 uppercase letters that shows how\n# the letters in the alphabet are mapped to new letters as the\n# internal signal flows across the rotor from right to left. For\n# example, the slow rotor corresponds to the following mapping\n# when it is in its initial position:\n#\n# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z\n# | | | | | | | | | | | | | | | | | | | | | | | | | |\n# E K M F L G D Q V Z N T O W Y H X U S P A I B R C J\n\nROTOR_PERMUTATIONS = [\n \"EKMFLGDQVZNTOWYHXUSPAIBRCJ\", # Permutation for slow rotor \n \"AJDKSIRUXBLHWTMCQGZNPYFVOE\", # Permutation for medium rotor \n \"BDFHJLCPRTXVZNYEIWGAKMUSQO\" # Permutation for fast rotor \n]\n\n# Constants that control the display of the current rotor setting \n\nROTOR_BGCOLOR = \"#BBAA77\" # Background color for the rotor \nROTOR_WIDTH = 24 # Width of the setting indicator \nROTOR_HEIGHT = 26 # Height of the setting indicator \nROTOR_COLOR = \"Black\" # Text color of the rotor \nROTOR_LABEL_DY = 9 # Offset from center to baseline \nROTOR_FONT = \"24px 'Helvetica Neue','Arial','Sans-Serif'\"\n\n# This array specifies the coordinates of each rotor display \n\nROTOR_LOCATIONS = [\n (244, 95),\n (329, 95),\n (412, 95)\n]\n\n# To the left of the slow rotor, the Enigma machine includes a\n# component called the \"reflector,\" which implements a fixed\n# permutation that remains unchanged as the rotors advance. The\n# constant REFLECTOR_PERMUTATION defines the mapping of the reflector.\n# Note that the reflector is symmetric. If A is transformed to I,\n# then I is transformed to A.\n\nREFLECTOR_PERMUTATION = \"IXUHFEZDAOMTKQJWNSRLCYPBVG\"\n\n# Constants that define the keys on the Enigma keyboard \n\nKEY_RADIUS = 24 # Outer radius of a key in pixels \nKEY_BORDER = 3 # Width of the key border \nKEY_BORDER_COLOR = \"#CCCCCC\" # Fill color of the key border \nKEY_BGCOLOR = \"#666666\" # Background color of the key \nKEY_UP_COLOR = \"#CCCCCC\" # Text color when the key is up \nKEY_DOWN_COLOR = \"#CC3333\" # Text color when the key is down \nKEY_LABEL_DY = 10 # Offset from center to baseline \nKEY_FONT = \"bold 28px 'Helvetica Neue','Arial','Sans-Serif'\"\n\n# This array determines the coordinates of a key for each letter index \n\nKEY_LOCATIONS = [\n (140, 566), # A\n (471, 640), # B\n (319, 639), # C\n (294, 567), # D\n (268, 495), # E\n (371, 567), # F\n (448, 567), # G\n (523, 567), # H\n (650, 496), # I\n (598, 567), # J\n (674, 567), # K\n (699, 641), # L\n (624, 641), # M\n (547, 640), # N\n (725, 497), # O\n ( 92, 639), # P\n (115, 494), # Q\n (345, 495), # R\n (217, 566), # S\n (420, 496), # T\n (574, 496), # U\n (395, 639), # V\n (192, 494), # W\n (242, 639), # X\n (168, 639), # Y\n (497, 496) # Z \n]\n\n# Constants that define the lamps above the Enigma keyboard \n\nLAMP_RADIUS = 23 # Radius of a lamp in pixels \nLAMP_BORDER_COLOR = \"#111111\" # Line color of the lamp border \nLAMP_BGCOLOR = \"#333333\" # Background color of the lamp \nLAMP_OFF_COLOR = \"#666666\" # Text color when the lamp is off \nLAMP_ON_COLOR = \"#FFFF99\" # Text color when the lamp is on \nLAMP_LABEL_DY = 9 # Offset from center to baseline \nLAMP_FONT = \"bold 24px 'Helvetica Neue','Arial','Sans-Serif'\"\n\n# This array determines the coordinates of a lamp for each letter index \n\nLAMP_LOCATIONS = [\n (144, 332), # A\n (472, 403), # B\n (321, 402), # C\n (296, 333), # D\n (272, 265), # E\n (372, 333), # F\n (448, 334), # G\n (524, 334), # H\n (650, 266), # I\n (600, 335), # J\n (676, 335), # K\n (700, 403), # L\n (624, 403), # M\n (549, 403), # N\n (725, 267), # O\n ( 94, 401), # P\n (121, 264), # Q\n (347, 265), # R\n (220, 332), # S\n (423, 265), # T\n (574, 266), # U\n (397, 402), # V\n (197, 264), # W\n (246, 402), # X\n (170, 401), # Y\n (499, 265) # Z \n]\n","sub_path":"Enigma/EnigmaConstants.py","file_name":"EnigmaConstants.py","file_ext":"py","file_size_in_byte":5080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"371638088","text":"from pathlib import Path\nfrom time import ctime\nimport shutil\n\npath = Path(\"ecommerce/__init__.py\")\n# path.exists()\n# path.rename(\"init.txt\")\n# path.unlink() # delete the file\n\n# returns info about this file\n# this info is an object with several attributes like\n# st_size, st_ctime: creation time, st_mtime: modified time\n# the time values are in seconds after epoch (the start of time on a computer)\nprint(path.stat())\n\n# print human readable format of time\nprint(ctime(path.stat().st_ctime)) # Tue Nov 20 12:31:48 2018\n\n# reading data fron a file\n# returns the content of the file as a bytes object\n# for representing binary data\npath.read_bytes()\n\n# return the content of a file as a string\npath.read_text()\n\n# this is simpler to use than the open() method that returns a file\n# these ones take care of opening and closing a file\n\n# you can write bytes or text to a file\npath.write_bytes()\npath.write_text(\"...\")\n\n# when it comes to copying a file, the Path object is not the ideal way to go\nsource = Path(\"ecommerce/__init__.py\")\ntarget = Path() / \"__init__.py\"\n\n# to copy\ntarget.write_text(source.read_text()) # this is a little bit tedious\n\n# the better way is to use shutil\n# this is cleaner and easier than using a Path object\nshutil.copy(source, target)\n","sub_path":"machine learning/complete_python_programming_for_beginners/python standard library/working with files/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"210673940","text":"from io import StringIO\n\nf = StringIO()\nf.write(\"a\"*100)\nf.seek(0)\nprint(f.read())\nf.close()\nf1 = StringIO(\"\"\"- 일종의 파일을 흉내내는 객체. \n문자열 데이터를 파일로 저장한 다음 여러가지 처리를 하게 되는데, \n그 파일이 다시 쓰이지 않을 때 유용함. \n처리 과정에서 동적으로 파일의 확장자나 내용이 바뀌는 데이터(파일)에서도 유용할 거라고 생각함. \n\"\"\")\nprint(f1.getvalue())\nf1.close()\n","sub_path":"PythonBasic/StandardLibrary/prac_StringIO.py","file_name":"prac_StringIO.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"103016156","text":"import torch\nimport numpy as np\nimport random\nfrom data import getTrainingValidationTestingData\nfrom utils import config\nimport utils\nfrom sklearn import metrics\nfrom torch.nn.functional import softmax\nimport argparse as arg\nfrom glob import glob\nfrom PIL import Image\nimport matplotlib.cm as cm\nimport cv2\nimport os\n\nfrom model import Net\nfrom res50 import Res50\nfrom dense121 import Dense121\nfrom dense169 import Dense169\nfrom mob_v2 import Mob_v2\nfrom squeeze import Squeeze\n\ntorch.manual_seed(42)\nnp.random.seed(42)\nrandom.seed(42)\n\ndef colorize(value, vmin=10, vmax=1000, cmap=\"viridis\"):\n\n value = value.cpu().numpy()[0, :, :]\n\n # normalize \n vmin = value.min() if vmin is None else vmin \n vmax = value.max() if vmax is None else vmax \n if vmin != vmax:\n value = (value - vmin) / (vmax - vmin)\n else:\n value = value * 0 \n \n cmapper = cm.get_cmap(cmap)\n value = cmapper(value, bytes=True) \n\n img = value[:,:,:3]\n\n return img.transpose((2, 0, 1))\n\ndef load_images(image_files):\n loaded_images = []\n for file in image_files:\n x = np.clip(np.asarray(Image.open( file ).resize((640, 480)), dtype=float) / 255, 0, 1).transpose(2, 0, 1)\n \n loaded_images.append(x)\n return np.stack(loaded_images, axis=0)\n\n\ndef main(device=torch.device('cuda:0')):\n # Model\n modelSelection = input('Please input the type of model to be used(res50,dense121,dense169,mob_v2,mob):')\n if modelSelection.lower() == 'res50':\n model = Res50()\n elif modelSelection.lower() == 'dense121':\n model = Dense121()\n elif modelSelection.lower() == 'mob_v2':\n model = Mob_v2()\n elif modelSelection.lower() == 'dense169':\n model = Dense169()\n elif modelSelection.lower() == 'mob':\n model = Net()\n elif modelSelection.lower() == 'squeeze':\n model = Squeeze()\n else:\n assert False, 'Wrong type of model selection string!'\n model = model.to(device)\n\n # Attempts to restore the latest checkpoint if exists\n print(\"Loading unet...\")\n model, start_epoch, stats = utils.restore_checkpoint(model, utils.config(modelSelection+\".checkpoint\"))\n\n # Get Test Images \n img_list = glob(\"examples/\"+\"*.png\")\n \n # Set model to eval mode \n model.eval()\n model = model.to(device)\n\n # Begin testing loop \n print(\"Begin Test Loop ...\")\n \n for idx, img_name in enumerate(img_list):\n\n img = load_images([img_name]) \n img = torch.Tensor(img).float().to(device) \n print(\"Processing {}, Tensor Shape: {}\".format(img_name, img.shape))\n\n with torch.no_grad():\n preds = model(img).squeeze(0) \n\n output = colorize(preds.data)\n output = output.transpose((1, 2, 0))\n cv2.imwrite(img_name.split(\".\")[0]+\"_\"+modelSelection+\"_result.png\", output)\n\n print(\"Processing {} done.\".format(img_name))\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":".history/visualize_20210427225204.py","file_name":"visualize_20210427225204.py","file_ext":"py","file_size_in_byte":2947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"555092499","text":"# TOSHIBA - Toshiba Software Development Vietnam\n# Team: PHOcr\n# Author: Tai Phung Dinh\n# Email: tai.phungdinh@toshiba-tsdv.com\n# Date create: 09/01/2019\n# Description: Run script to validate a specification json file\nimport json\nimport sys\nfrom argparse import ArgumentParser\n\nimport sys_path\nfrom configs.database import TestcaseConfig\n\nsys_path.insert_sys_path()\nfrom database.lib_test_case.specification import Specification\n\n\ndef parse_arguments():\n \"\"\"\n Handle arguments passed to run script\n\n Returns\n -------\n ArgumentParser\n\n \"\"\"\n parser = ArgumentParser(\n description='Validate a specification file of a test case'\n )\n parser.add_argument('-f', '--file-path',\n required=True,\n help='Optional: Path to specification file of test '\n 'case which is in json format')\n return parser\n\n\ndef main():\n \"\"\"\n Main\n\n \"\"\"\n # Get parser argument object\n parser = parse_arguments()\n # Parse arguments\n args = parser.parse_args()\n\n # Print help\n if args.file_path is None:\n parser.print_help()\n sys.exit(1)\n with open(args.file_path) as f:\n spec_json = json.loads(f.read())\n\n spec = Specification(json_data=spec_json, required=True)\n spec.validate()\n spec.add_meta_field_to_error(\n TestcaseConfig.SPEC_FILE\n )\n spec.print_errors()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Run_PHocr_test/Mekong/utilities/utilities/validate/validate_specification_file.py","file_name":"validate_specification_file.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"291674677","text":"# HealthCareNow/routing.py\nfrom channels.auth import AuthMiddlewareStack\nfrom channels.routing import ProtocolTypeRouter, URLRouter\nimport chat.routing\n\n\"\"\"\nchannel_routing = [\n route('websocket.receive', 'chat.consumers.ws_echo'),\n route('websocket.connect', 'chat.consumers.ws_add',\n path=r'^/chat2/(?P\\w+)$'),\n]\n\"\"\"\napplication = ProtocolTypeRouter({\n # (http->django views is added by default)\n 'websocket': AuthMiddlewareStack(\n URLRouter(\n chat.routing.websocket_urlpatterns\n )\n ),\n})\n","sub_path":"src/HealthCareNow/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"226608284","text":"\"\"\"line chart visualization.\"\"\"\n\nfrom apps.managers.team_mgr.models import Team\n\n\ndef supply(request, page_name):\n \"\"\" Handle the request for viz_chart widget.\"\"\"\n\n _ = page_name\n _ = request\n\n all_lounges = Team.objects.order_by('name').all()\n\n return {\n \"all_lounges\": all_lounges,\n }\n","sub_path":"makahiki/apps/widgets/viz_chart/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"305267248","text":"'''\nGiven an input string, reverse the string word by word.\n\nFor example,\nGiven s = \"the sky is blue\",\nreturn \"blue is sky the\".\n\nUpdate (2015-02-12):\nFor C programmers: Try to solve it in-place in O(1) space.\n\nclick to show clarification.\n\nClarification:\nWhat constitutes a word?\nA sequence of non-space characters constitutes a word.\nCould the input string contain leading or trailing spaces?\nYes. However, your reversed string should not contain leading or trailing spaces.\nHow about multiple spaces between two words?\nReduce them to a single space in the reversed string.\n'''\nclass Solution(object):\n def reverseWords(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n if not s or len(s) == 0:\n return \"\"\n\n sArr = s.split(\" \")\n result = []\n for i in range(len(sArr) - 1, -1, -1):\n if sArr[i] != \"\":\n result.append(sArr[i])\n result.append(\" \")\n return \"\" if len(result) == 0 else \"\".join(result[0: -1])\n","sub_path":"Python/leetcode/151-ReverseWordInAString.py","file_name":"151-ReverseWordInAString.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"108284904","text":"from django.template import Context, Template\nfrom django.template.loader import get_template\nfrom django.db import models\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.contrib.sites.models import Site\nfrom django.contrib.auth.models import User\nfrom django.contrib.contenttypes import generic\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.db.models.signals import post_save, post_delete\nfrom django.dispatch import receiver\n\nfrom email_templates import send_templated_mail\n\nfrom review.models import Comment, Vote\nfrom chunks.models import Submission\nimport datetime\nimport sys\n\n\nclass Notification(models.Model):\n REPLY = 'R'\n DIRECT_COMMENT = 'C'\n VOTE = 'V'\n ACTIVITY_ON_OTHERS_CODE = 'A'\n ACTIVITY_ON_MY_CODE = 'U'\n REASON_CHOICES = (\n (REPLY, 'Received reply'),\n (DIRECT_COMMENT, 'Received comment on submission'),\n (VOTE, 'Received vote on comment'),\n (ACTIVITY_ON_OTHERS_CODE, 'There is activity on code you have reviewed before'),\n (ACTIVITY_ON_MY_CODE, 'There is activity on your code'),\n )\n\n submission = models.ForeignKey(Submission, blank=True, null=True, related_name='notifications')\n comment = models.ForeignKey(Comment, blank=True, null=True, related_name='notifications')\n vote = models.ForeignKey(Vote, blank=True, null=True, related_name='notifications')\n recipient = models.ForeignKey(User, related_name='notifications')\n reason = models.CharField(max_length=1, blank=True, choices=REASON_CHOICES)\n created = models.DateTimeField(auto_now_add=True)\n email_sent = models.BooleanField(default=False)\n seen = models.BooleanField(default=False)\n\n class Meta:\n ordering = [ '-created' ]\n\n\nNEW_SUBMISSION_COMMENT_SUBJECT_TEMPLATE = Template(\n \"[{{ site.name }}] {{ comment.author.get_full_name|default:comment.author.username }} commented on your code\")\n\nNEW_REPLY_SUBJECT_TEMPLATE = Template(\n \"[{{ site.name }}] {{ comment.author.get_full_name|default:comment.author.username }} replied to your comment\")\n\n# How these notifications work, with simple pseudocode:\n# let's say sub = Submission(author = 'maxg')\n# 'pnomario' comments on sub\n# 'sarivera' comments on sub\n# 'peipeipei' replies to 'pnomario'\n#\n# in this scenario, the following notifications would be created:\n# 'maxg' gets a notification from 'pnomario', with reason 'C' (comment on submission)\n# 'maxg' gets a notification from 'peipeipei', with reason 'U' (activity on chunk = user's code)\n# 'maxg' gets a notification from 'sarivera', with reason 'C' (comment on submission)\n#\n# 'pnomario' gets a notification from 'peipeipei', with reason 'R' (reply on comment)\n# 'pnomario' gets a notification from 'sarivera', with reason 'A' (comment on submission)\n#\n# 'sarivera' gets a notification from 'pnomario', with reason 'A' (comment on submission)\n# 'sarivera' gets a notification from 'peipeipei', with reason 'A' (comment on submission)\n#\n# 'peipeipei' gets a notification from 'sarivera', with reason 'A' (comment on submission)\n#\n# nested replies should send a notification with reason 'R' all the way up the reply tree.\n\n@receiver(post_save, sender=Vote)\ndef add_vote_notification(sender, instance, created=False, raw=False, **kwargs):\n if created and not raw:\n# context = Context({\n# 'site': site,\n# 'vote': instance,\n# 'comment_author': instance.comment.author\n# })\n site = Site.objects.get_current()\n\n # past_vote_notifications = Notification.objects.filter(recipient=instance.comment.author, comment=instance.comment ,reason='V')\n notification = Notification(recipient = instance.comment.author, reason='V', comment=instance.comment, vote=instance, \\\n submission=instance.comment.chunk.file.submission)\n notification.save()\n return\n\n#Note: comment in the args and in the 'comment': comment line might need to be instance\n#i.e. ...(sender, instance...) and 'comment': instance\n@receiver(post_save, sender=Comment)\ndef add_comment_notification(sender, instance, created=False, raw=False, **kwargs):\n '''\n Creates a new Notification object for replies and new comments on a users submission.\n '''\n if created and not raw:\n# context = Context({\n# 'site': site,\n# 'comment': instance,\n# 'chunk': instance.chunk,\n# 'submission': instance.chunk.file.submission\n# 'submission_authors': instance.chunk.file.submission.authors.all()\n# })\n notified_users = set()\n site = Site.objects.get_current()\n chunk = instance.chunk\n submission = instance.chunk.file.submission\n submission_authors = instance.chunk.file.submission.authors.all() #this is a list of User objects!\n\n #if the comment has a reply and the reply is not from the person who made the comment.\n #create a second variable to crawl up the reply tree for correct notification alerts.\n reply = instance\n while reply.parent is not None:\n if ((reply.parent.author != reply.author)):\n notification = Notification(recipient = instance.parent.author, reason='R', submission=submission, comment=instance)\n notification.save()\n notified_users.add(instance.parent.author)\n reply = reply.parent #this is used to go up the reply tree.\n\n #otherwise, if the comment is a new comment on one of the users submissions.\n if instance.parent == None:\n for author in submission_authors:\n if instance.author != author:\n notification = Notification(recipient = author, reason='C', submission=submission, comment=instance)\n notification.save()\n notified_users.add(author)\n\n #send the other users that have commented on the code in the past a notification\n #with reason='A'\n\n #list of all users who submitted or have commented on the code\n #TODO: make related_users a set and find a way to extend it by submission_authors\n #we want a set for performance, since duplicates are taken care of by the notified_users.add(user)\n #call in the for loop below.\n\n related_users = {comment.author for comment in chunk.comments.all()}\n related_users.update(submission_authors)\n\n for user in related_users:\n if user not in notified_users and user != instance.author:\n notification = Notification(recipient = user, submission=submission, comment=instance)\n if user in submission_authors: #check if author equality works (or do we need to compare id's?)\n #user gets an 'activity on their code' notification\n notification.reason='U'\n else:\n #user gets an 'activity on other code' notification\n notification.reason='A'\n notification.save()\n notified_users.add(user)\n\n#Note: This method was used to send emails when people got a reply to a comment\n#they made, but the email functionality was scrapped and the code basically created\n#notifications when there was a reply, and only if the user had an email listed on\n#caesar. I have rewritten this method, sans email functionality, in the methods above,\n#but I leave this for future devs who may wish to implement emailing about replies.\n#\n#@receiver(post_save, sender=Comment)\n#def send_comment_notification(sender, instance, created=False, raw=False, **kwargs):\n# if created and not raw:\n# site = Site.objects.get_current()\n# context = Context({\n# 'site': site,\n# 'comment': instance,\n# 'chunk': instance.chunk\n# })\n# #comment gets a reply, the reply is not by the original author\n# if instance.parent and instance.parent.author.email \\\n# and instance.parent.author != instance.author:\n# to = instance.parent.author.email\n# subject = NEW_REPLY_SUBJECT_TEMPLATE.render(context)\n# notification = Notification(recipient = instance.parent.author, reason='R')\n# notification.submission = instance.chunk.file.submission\n# notification.comment = instance\n# notification.save()\n#\n# #sent = send_templated_mail(\n# # subject, None, (to,), 'new_reply',\n# # context, template_prefix='notifications/')\n# #notification.email_sent = sent\n# #notification.save()\n# return\n#\n# return # NOTE(TFK): The code below is broken since submissions can have multiple authors.\n# submission_author = instance.chunk.file.submission.author\n# submission = instance.chunk.file.submission\n# #comment gets made on a submission after code review deadline has passed\n# if submission_author and submission_author.email \\\n# and instance.author != submission_author\\\n# and instance.author.username != \"checkstyle\" \\\n# and datetime.datetime.now() > submission.code_review_end_date():\n# to = submission_author.email\n# subject = NEW_SUBMISSION_COMMENT_SUBJECT_TEMPLATE.render(context)\n# notification = Notification(recipient = submission_author, reason='C')\n# notification.submission = instance.chunk.file.submission\n# notification.comment = instance\n# notification.save()\n#\n# #sent = send_templated_mail(\n# # subject, None, (to,), 'new_submission_comment',\n# # context, template_prefix='notifications/')\n# # notification.email_sent = sent\n# #notification.save()\n# pass\n\n","sub_path":"notifications/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"446169418","text":"#!/usr/bin/env python3\n\n\"\"\" Usage:\n GaAs_ED_prism_kinematic.py \n\"\"\"\n\nfrom docopt import docopt\nimport pycrystem as pc\nimport pymatgen as pmg\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom pycrystem.utils.pyprismatic_io_utils import *\nfrom matplotlib import pyplot as plt\nimport pyprismatic as pr\n\nargs = docopt(__doc__)\n\nalpha_divider = float(args[\"\"]) #3 or nearer to 1 than that\nprobe_divider = float(args[\"\"]) #3 or nearer to 1 than that\nxy_size = float(args[\"\"])\nz_size = float(args[\"\"])\n\n\n## Set up our structure ##\nGa = pmg.Element(\"Ga\")\nAs = pmg.Element(\"As\")\nlattice = pmg.Lattice.cubic(5.65)\nstructure = pmg.Structure.from_spacegroup(\"F-43m\",lattice, [Ga,As], [[0, 0, 0],[0.5,0.5,0.5]])\nstructure.make_supercell([xy_size,xy_size,z_size]) #square to remain compatible with kinematic\n\n## Set up our microscope ##\nediff = pc.ElectronDiffractionCalculator(200., 0.025)\n\n## Run our simulations ##\nmeta_params = {}\nmeta_params['save4DOutput'] = True\nmeta_params['save3DOutput'] = False\nmeta_params['scanWindowXMin'] = 0.495\nmeta_params['scanWindowXMax'] = 0.50\nmeta_params['scanWindowYMin'] = 0.495\nmeta_params['scanWindowYMax'] = 0.50\nmeta_params['alphaBeamMax'] = 0.024/alpha_divider\nmeta_params['probeSemiangle'] = 0.02/probe_divider\nediff.calculate_ed_data_dynamic(structure,meta_params)\n\noutput = pr.fileio.readMRC('PP_output_X1_Y0_FP1.mrc')\noutput = output.reshape([output.shape[1],output.shape[2]])\noutput = np.fft.fftshift(output)\nplt.figure()\nplt.imshow(np.power(output,0.25),cmap='viridis')\nplt.draw()\nplt.savefig('image.png')\n\"\"\"\n# The line above has been excuted, the output is stored in an .mrc file\nstructure = pmg.Structure.from_spacegroup(\"F-43m\",lattice, [Ga,As], [[0, 0, 0],[0.5,0.5,0.5]]) \nstructure.make_supercell([4,4,1]) #no depth needed for kinematic\ndd_kinematic = ediff.calculate_ed_data_kinematic(structure,reciprocal_radius=2.5)\n\n## Post Processing ##\n\nddd_buffer = import_pyprismatic_data(meta)\npltable_dd_d = np.squeeze(np.sum(ddd_buffer,axis=2))\nplt.imshow(pltable_dd_d)\nplt.draw()\n\npltable_dd_k = pc.ElectronDiffraction(dd_kinematic.as_signal(512,0.05,2.5).data)\npltable_dd_k.plot()\nplt.draw()\n\"\"\"\n\n\n#plt.show() #to hold figures at the end of the script\n","sub_path":"GaAs_ED_prism_kinematic.py","file_name":"GaAs_ED_prism_kinematic.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"75533197","text":"\"\"\"\r\nAuthor: sapatel91\r\nDate: March 2, 2014\r\nFile: getControl4Items.py\r\n\r\nPurpose: Prints ID and Name of various items from a Control4 system\r\n\r\nDisclaimer: USE AT YOUR RISK, I TAKE NO RESPONSIBILITY\r\n Most likely there won't be any though\r\n\"\"\"\r\n\r\nfrom bs4 import BeautifulSoup\r\nfrom PyControl4 import connection\r\n\r\n# Insert the IP of your Control4 system here. Can be obtained from Composer.\r\nTCP_IP = \"192.168.1.25\" # Will need to change for your system's IP\r\nTCP_PORT = 5021\r\nBUFFER_SIZE = 8192\r\n\r\n# Function used to extract text between tags\r\n# For example \" 43 \" returns 43\r\ndef getText(soupData, tag):\r\n tag = soupData.find(tag)\r\n try:\r\n text_parts = tag.findAll(text=True)\r\n text = \"\".join(text_parts)\r\n return text.strip()\r\n except:\r\n return \"Value not found!\"\r\n\r\n\r\n# Connect to Director and issue soap command to get all items on system.\r\nconnection.C4SoapConn(TCP_IP, TCP_PORT)\r\nMESSAGE = '0'\r\ndata_soup = connection.C4SoapConn.Send(MESSAGE)\r\ndata = str(data_soup)\r\nout_string = \"\"\r\nwhile not \"\" in data:\r\n out_string += data\r\n if \"\" in data:\r\n break\r\nsoapData = BeautifulSoup(out_string, \"lxml-xml\")\r\n# directorConn.close()\r\n\r\n# Parse SOAP data\r\nitems = soapData.findAll(\"item\")\r\nfor item in items:\r\n \"\"\"\r\n Change the type value for the following:\r\n 2 - Site\r\n 3 - Building\r\n 4 - Floor\r\n 6 - Device Type\r\n 7 - Device\r\n 8 - Room\r\n \"\"\"\r\n if getText(item, \"type\") == \"7\":\r\n print(\"{1}, {2}\".format(getText(item, \"id\"), getText(item, \"name\")))\r\n\r\n","sub_path":"Scripts/getControl4Items.py","file_name":"getControl4Items.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"179292972","text":"def factorial(num):\r\n r = 1\r\n for i in range(1, num + 1):\r\n r = r * i\r\n return r\r\n\r\n\r\ndef combination(N, K):\r\n return factorial(N) / (factorial(K) * factorial(N - K))\r\n\r\n\r\nfile = open(\"p128.txt\", \"r\")\r\n\r\nfor line in file:\r\n N, K = [int(i) for i in line.split(\" \")]\r\n print(int(combination(N, K)))\r\n","sub_path":"P125-P150/p128.py","file_name":"p128.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"354155840","text":"\"\"\"\n2.\nИзучить список открытых API (https://www.programmableweb.com/category/all/apis). \nНайти среди них любое, требующее авторизацию (любого типа). Выполнить запросы к нему, пройдя авторизацию. \nОтвет сервера записать в файл.\nЕсли нет желания заморачиваться с поиском, возьмите API вконтакте (https://vk.com/dev/first_guide). \nСделайте запрос, чтб получить список всех сообществ на которые вы подписаны.\n\n\"\"\"\n\nimport requests\n\n# insert own params\naccess_token = '######'\nuser_id = '#####'\n\nmain_link = 'https://api.vk.com/method/'\nmethod = 'groups.get'\nparams = {\n 'user_id': user_id,\n 'extended': '1',\n 'count': '1000',\n 'access_token': access_token,\n 'v': '5.124'\n }\n\nresponse = requests.get(main_link + method, params=params).json()\n\nwith open('hw01_02out.txt', 'w', encoding='utf8') as f_out:\n f_out.writelines([str(i['name']) + '\\n' for i in response['response']['items']])\n","sub_path":"HW/HW01/hw01_02.py","file_name":"hw01_02.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"625811721","text":"\"\"\"\nEnd-to-end behaviour test for TbgMod -- tests the operation of the\nTbgMod application against the behaviour defined in behaviour.txt.\n\nbehaviour.txt is referred to as the 'behavioural file'\n\"\"\"\n\nimport alti\nimport main\n\n\ndef run_tests_at(file: str) -> bool:\n return alti.test_behaviour(\"behaviours/{}\".format(file),\n 27277, main.TbgMod(\"vapors\", False))\n\n\ndef run_all_tests():\n files = [\n \"commands/modify.txt\"\n , \"commands/reset.txt\"\n , \"commands/servermod.txt\"\n , \"commands/show.txt\"\n , \"commands/start.txt\"\n , \"commands/stop.txt\"\n , \"commands/stopforme.txt\"\n , \"commands/training_points.txt\"\n , \"maps.txt\"\n ]\n\n for file in files:\n if not run_tests_at(file):\n return\n print(\" ************** \")\n print(\"** Passed all tests. **\")\n\n\nif __name__ == \"__main__\":\n run_all_tests()\n","sub_path":"test_behaviour.py","file_name":"test_behaviour.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"197501067","text":"\n# coding: utf-8\n\n# In[2]:\n\nfrom datetime import datetime\nfrom elasticsearch import Elasticsearch\n\n\n# In[3]:\n\nfrom pymongo import MongoClient\nclient = MongoClient('mongodb://202.30.23.40:27017')\nes = Elasticsearch([{'host':'localhost', 'port':9200}])\n\n\n# In[4]:\n\ndb = client.trec\n\n\n# In[5]:\n\ncollection = db.article\n\n\n# In[6]:\n\ncursor = collection.find()\ndata = cursor.next()\n\n\n# In[6]:\n\ntarget = open('pmcidList.csv', 'w')\ncount = 0\nwhile(data):\n try:\n pmcid = data['articleMeta']['pmcid']\n target.write(pmcid + '\\n')\n data = cursor.next()\n count += 1\n except:\n print(\"finish {0}\".format(count))\n target.close()\nprint(\"finished List\")\n\n","sub_path":"py/makePmcidList.py","file_name":"makePmcidList.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"598688999","text":"import sys\nsys.path.append('./ERNIE')\nimport numpy as np\nfrom sklearn.metrics import f1_score\nimport paddle as P\nimport paddle.fluid as F\nimport paddle.fluid.layers as L\nimport paddle.fluid.dygraph as D\n\nfrom ernie.tokenizing_ernie import ErnieTokenizer\nfrom ernie.modeling_ernie import ErnieModelForSequenceClassification\n\nBATCH=32\nMAX_SEQLEN=300\nLR=5e-5\nEPOCH=10\n\nD.guard().__enter__()\n\nernie = ErnieModelForSequenceClassification.from_pretrained('ernie-1.0', num_labels=3)\noptimizer = F.optimizer.Adam(LR, parameter_list=ernie.parameters())\ntokenizer = ErnieTokenizer.from_pretrained('ernie-1.0')\n\ndef make_data(path):\n data = []\n for i, l in enumerate(open(path)):\n if i == 0:\n continue\n l = l.strip().split('\\t')\n text, label = l[0], int(l[1])\n text_id, _ = tokenizer.encode(text)\n text_id = text_id[:MAX_SEQLEN]\n text_id = np.pad(text_id, [0, MAX_SEQLEN-len(text_id)], mode='constant')\n label_id = np.array(label+1)\n data.append((text_id, label_id))\n return data\n\ntrain_data = make_data('./chnsenticorp/train/part.0')\ntest_data = make_data('./chnsenticorp/dev/part.0')\n\ndef get_batch_data(data, i):\n d = data[i*BATCH: (i + 1) * BATCH]\n feature, label = zip(*d)\n feature = np.stack(feature) \n label = np.stack(list(label))\n feature = D.to_variable(feature)\n label = D.to_variable(label)\n return feature, label\n\nfor i in range(EPOCH):\n np.random.shuffle(train_data)\n #train\n for j in range(len(train_data) // BATCH):\n feature, label = get_batch_data(train_data, j)\n loss, _ = ernie(feature, labels=label)\n loss.backward()\n optimizer.minimize(loss)\n ernie.clear_gradients()\n if j % 10 == 0:\n print('train %d: loss %.5f' % (j, loss.numpy()))\n # evaluate\n if j % 100 == 0:\n all_pred, all_label = [], []\n with D.base._switch_tracer_mode_guard_(is_train=False): \n ernie.eval()\n for j in range(len(test_data) // BATCH):\n feature, label = get_batch_data(test_data, j)\n loss, logits = ernie(feature, labels=label)\n all_pred.extend(L.argmax(logits, -1).numpy())\n all_label.extend(label.numpy())\n ernie.train()\n f1 = f1_score(all_label, all_pred, average='macro')\n acc = (np.array(all_label) == np.array(all_pred)).astype(np.float32).mean()\n print('acc %.5f' % acc)\n","sub_path":"doc/simple-case.py","file_name":"simple-case.py","file_ext":"py","file_size_in_byte":2509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"212236616","text":"from typing import TypedDict, List, Any\n\nimport requests\nimport logging\n\n# https://docs.citadelid.com\n# Header which using in private api calls\nApiHeaders = TypedDict('ApiHeaders', {\n 'X-Access-Secret': str,\n 'X-Access-Client-Id': str,\n 'Content-Type': str\n})\n\n\nclass NaiveApiClient:\n \"\"\"\n A naive api client to show how flow works,\n without errors processing and other like that\n \"\"\"\n API_URL: str\n API_HEADERS: ApiHeaders\n PRODUCT_TYPE: str\n\n def __init__(self,\n secret: str,\n client_id: str,\n product_type: str,\n ):\n self.API_URL = 'https://prod.citadelid.com/v1/'\n self.PRODUCT_TYPE = product_type\n self.API_HEADERS = {\n 'X-Access-Secret': secret,\n 'X-Access-Client-Id': client_id,\n 'Content-Type': 'application/json;charset=UTF-8',\n }\n\n def get_bridge_token(self) -> Any:\n \"\"\"\n https://docs.citadelid.com/?python#bridge-tokens_create\n :param public_token:\n :return:\n \"\"\"\n logging.info(\"CITADEL: Requesting bridge token from https://prod.citadelid.com/v1/bridge-tokens\")\n class BridgeTokenRequest(TypedDict):\n product_type: str\n client_name: str\n tracking_info: str\n\n request_data: BridgeTokenRequest = {\n 'product_type': self.PRODUCT_TYPE,\n 'client_name': 'Citadel Quickstart',\n 'tracking_info': '1337'\n }\n\n tokens: Any = requests.post(\n self.API_URL + 'bridge-tokens/',\n json=request_data,\n headers=self.API_HEADERS,\n ).json()\n return tokens\n\n def get_access_token(self, public_token: str) -> str:\n \"\"\"\n https://docs.citadelid.com/?python#exchange-token-flow\n :param public_token:\n :return:\n \"\"\"\n logging.info(\"CITADEL: Exchanging a public_token for an access_token from https://prod.citadelid.com/v1/link-access-tokens\")\n logging.info(\"CITADEL: Public Token - %s\", public_token)\n class AccessTokenRequest(TypedDict):\n public_token: str\n\n class AccessTokenResponse(TypedDict):\n access_token: str\n link_id: str\n\n request_data: AccessTokenRequest = {\n 'public_token': public_token,\n }\n\n tokens: AccessTokenResponse = requests.post(\n self.API_URL + 'link-access-tokens/',\n json=request_data,\n headers=self.API_HEADERS,\n ).json()\n return tokens['access_token']\n\n def get_employment_info_by_token(self, access_token: str) -> Any:\n \"\"\"\n https://docs.citadelid.com/#employment-verification\n :param access_token:\n :return:\n \"\"\"\n logging.info(\"CITADEL: Requesting employment verification data using an access_token from https://prod.citadelid.com/v1/verifications/employments\")\n logging.info(\"CITADEL: Access Token - %s\", access_token)\n class VerificationRequest(TypedDict):\n access_token: str\n\n request_data: VerificationRequest = {'access_token': access_token}\n\n return requests.post(\n self.API_URL + 'verifications/employments/',\n json=request_data,\n headers=self.API_HEADERS,\n ).json()\n\n def get_income_info_by_token(self, access_token: str) -> Any:\n \"\"\"\n https://docs.citadelid.com/#income-verification\n :param access_token:\n :return:\n \"\"\"\n\n logging.info(\"CITADEL: Requesting income verification data using an access_token from https://prod.citadelid.com/v1/verifications/incomes\")\n logging.info(\"CITADEL: Access Token - %s\", access_token)\n class VerificationRequest(TypedDict):\n access_token: str\n\n request_data: VerificationRequest = {'access_token': access_token}\n\n return requests.post(\n self.API_URL + 'verifications/incomes/',\n json=request_data,\n headers=self.API_HEADERS,\n ).json()\n\n def get_employee_directory_by_token(self, access_token: str) -> Any:\n \"\"\"\n https://docs.citadelid.com/#payroll-admin\n :param access_token:\n :return:\n \"\"\"\n\n logging.info(\"CITADEL: Requesting employee directory data using an access_token from https://prod.citadelid.com/v1/administrators/directories\")\n logging.info(\"CITADEL: Access Token - %s\", access_token)\n class DirectoryRequest(TypedDict):\n access_token: str\n\n request_data: DirectoryRequest = {'access_token': access_token}\n\n return requests.post(\n self.API_URL + 'administrators/directories/',\n json=request_data,\n headers=self.API_HEADERS,\n ).json()\n\n def request_payroll_report(self, access_token: str, start_date: str , end_date: str) -> Any:\n \"\"\"\n https://docs.citadelid.com/#payroll-admin\n :param access_token:\n :param start_date:\n :param end_date:\n :return: Payroll report ID\n \"\"\"\n\n logging.info(\"CITADEL: Requesting a payroll report be created using an access_token from https://prod.citadelid.com/v1/administrators/payrolls\")\n logging.info(\"CITADEL: Access Token - %s\", access_token)\n class PayrollReportRequest(TypedDict):\n access_token: str\n start_date: str\n end_date: str\n\n request_data: PayrollReportRequest = {\n 'access_token': access_token,\n 'start_date': start_date,\n 'end_date': end_date\n }\n\n return requests.post(\n self.API_URL + 'administrators/payrolls/',\n json=request_data,\n headers=self.API_HEADERS,\n ).json()\n\n def get_payroll_report_by_id(self, report_id: str) -> Any:\n \"\"\"\n https://docs.citadelid.com/#payroll-admin\n :param report_id:\n :return:\n \"\"\"\n\n logging.info(\"CITADEL: Requesting a payroll report using a report_id from https://prod.citadelid.com/v1/administrators/payrolls/{report_id}\")\n logging.info(\"CITADEL: Report ID - %s\", report_id)\n return requests.get(\n self.API_URL + f'administrators/payrolls/{report_id}',\n headers=self.API_HEADERS,\n ).json()","sub_path":"python/src/naive_api_client.py","file_name":"naive_api_client.py","file_ext":"py","file_size_in_byte":6317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"107291306","text":"#!/usr/bin/env python\n\nimport numpy as np\nfrom pycrazyswarm import *\n\nZ = 1.5\n\nif __name__ == \"__main__\":\n swarm = Crazyswarm()\n timeHelper = swarm.timeHelper\n allcfs = swarm.allcfs\n\n allcfs.crazyfliesById[9].setGroup(1)\n allcfs.crazyfliesById[10].setGroup(2)\n\n allcfs.takeoff(targetHeight=Z, duration=1.0 + Z, group = 1)\n timeHelper.sleep(1.5 + Z)\n allcfs.land(targetHeight=0.06, duration=1.0 + Z)\n timeHelper.sleep(1.5 + Z)\n","sub_path":"ros_ws/src/crazyswarm/scripts/testGroup.py","file_name":"testGroup.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"464758004","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019-08-16 17:39 \n# @Author : 徐秋影 \n# @Site : \n# @File : main.py\nfrom setting import APPNAME\nfrom utils.device_utils import get_android_devices\nfrom TestLibrary.run import Run\n\n\ndef start():\n app = dict(APPNAME.values())\n print(APPNAME.values())\n devices = get_android_devices()\n for device in devices:\n for package, activity in app.values():\n print(activity,package)\n start = Run(device, activity, devices)\n start.run()\n\n\nif __name__ == '__main__':\n start()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"602273663","text":"import os\nfrom win32com import client as win32 # 发送邮件模块\nfrom win32com.client.gencache import EnsureDispatch as Dispatch # 读取邮件模块\n\n__author__ = 'Evan'\n\n\ndef read_outlook_mailbox():\n \"\"\"连接Outlook邮箱,读取收件箱内的邮件内容\"\"\"\n # 使用MAPI协议连接Outlook\n account = Dispatch('Outlook.Application').GetNamespace('MAPI')\n\n # 获取收件箱所在位置\n inbox = account.GetDefaultFolder(6) # 数字6代表收件箱\n # 获取收件箱下的所有邮件\n mails = inbox.Items\n mails.Sort('[ReceivedTime]', True) # 邮件按时间排序\n\n # 读取收件箱内前3封邮件的所有信息(下标从1开始)\n for index in range(1, 4):\n print('正在读取第[{}]封邮件...'.format(index))\n mail = mails.Item(index)\n print('接收时间:{}'.format(str(mail.ReceivedTime)[:-6]))\n print('发件人:{}'.format(mail.SenderName))\n print('收件人:{}'.format(mail.To))\n print('抄送人:{}'.format(mail.CC))\n print('主题:{}'.format(mail.Subject))\n print('邮件正文内容:{}'.format(mail.Body))\n print('邮件附件数量:{}'.format(mail.Attachments.Count))\n print('邮件MessageID:{}'.format(mail.EntryID))\n print('会话主题:{}'.format(mail.ConversationTopic))\n print('会话ID:{}'.format(mail.ConversationID))\n print('会话记录相对位置:{}'.format(mail.ConversationIndex))\n\n # 保存邮件中的附件,如果没有附件不会执行也不会产生异常\n attachment = mail.Attachments\n for each in attachment:\n save_attachment_path = os.getcwd() # 保存附件到当前路径\n each.SaveAsFile(r'{}\\{}'.format(save_attachment_path, each.FileName))\n print('附件({})保存完毕'.format(each.FileName))\n\n\ndef send_mail():\n \"\"\"\n 连接Outlook邮箱,发送邮件\n :return:\n \"\"\"\n outlook = win32.Dispatch('Outlook.Application') # 连接Outlook\n\n mail_item = outlook.CreateItem(0) # 创建新邮件\n mail_item.Recipients.Add('test@test.com') # 收件人邮箱\n mail_item.Subject = 'Mail Test' # 主题\n mail_item.BodyFormat = 2 # 使用HTML格式编写正文\n mail_item.HTMLBody = \"\"\"\"\n

    Hello, This is a test mail.

    \n Hello World.\n \"\"\"\n # mail_item.Attachments.Add('test.csv') # 添加附件\n mail_item.Send() # 发送邮件\n\n\nif __name__ == '__main__':\n read_outlook_mailbox()\n send_mail()\n","sub_path":"function_module/email_operation_example/outlook_mailbox.py","file_name":"outlook_mailbox.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"345078090","text":"from infi.clickhouse_orm import migrations\n\nfrom posthog.clickhouse.client.migration_tools import run_sql_with_exceptions\nfrom posthog.client import sync_execute\nfrom posthog.models.event.sql import (\n EVENTS_TABLE_JSON_MV_SQL,\n KAFKA_EVENTS_TABLE_JSON_SQL,\n)\nfrom posthog.settings import CLICKHOUSE_CLUSTER\n\nADD_COLUMNS_BASE_SQL = \"\"\"\nALTER TABLE {table}\nON CLUSTER '{cluster}'\nADD COLUMN IF NOT EXISTS inserted_at Nullable(DateTime64(6, 'UTC')) DEFAULT NULL\n\"\"\"\n\n\ndef add_columns_to_required_tables(_):\n sync_execute(ADD_COLUMNS_BASE_SQL.format(table=\"events\", cluster=CLICKHOUSE_CLUSTER))\n sync_execute(ADD_COLUMNS_BASE_SQL.format(table=\"writable_events\", cluster=CLICKHOUSE_CLUSTER))\n sync_execute(ADD_COLUMNS_BASE_SQL.format(table=\"sharded_events\", cluster=CLICKHOUSE_CLUSTER))\n\n\noperations = [\n run_sql_with_exceptions(f\"DROP TABLE IF EXISTS events_json_mv ON CLUSTER '{CLICKHOUSE_CLUSTER}'\"),\n run_sql_with_exceptions(f\"DROP TABLE IF EXISTS kafka_events_json ON CLUSTER '{CLICKHOUSE_CLUSTER}'\"),\n migrations.RunPython(add_columns_to_required_tables),\n run_sql_with_exceptions(KAFKA_EVENTS_TABLE_JSON_SQL()),\n run_sql_with_exceptions(EVENTS_TABLE_JSON_MV_SQL()),\n]\n","sub_path":"posthog/clickhouse/migrations/0047_add_insertion_timestamp_to_events.py","file_name":"0047_add_insertion_timestamp_to_events.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"423722961","text":"# -*- coding: utf-8 -*-\n\n# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is\n# holder of all proprietary rights on this computer program.\n# You can only use this computer program if you have closed\n# a license agreement with MPG or you get the right to use the computer\n# program from someone who is authorized to grant you that right.\n# Any use of the computer program without a valid license is prohibited and\n# liable to prosecution.\n#\n# Copyright©2019 Max-Planck-Gesellschaft zur Förderung\n# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute\n# for Intelligent Systems. All rights reserved.\n#\n# Contact: ps-license@tuebingen.mpg.de\n#\n# Author: Joachim Tesch, Max Planck Institute for Intelligent Systems, Perceiving Systems\n#\n# Create keyframed animated skinned SMPL mesh from .pkl pose description\n#\n# Generated mesh will be exported in FBX or glTF format\n#\n# Notes:\n# + Male and female gender models only\n# + Script can be run from command line or in Blender Editor (Text Editor>Run Script)\n# + Command line: Install mathutils module in your bpy virtualenv with 'pip install mathutils==2.81.2'\n\nimport os\nimport sys\nimport bpy\nimport time\nimport platform\n# import joblib\nimport argparse\nimport numpy as np\nimport addon_utils\nfrom math import radians\nfrom mathutils import Matrix, Vector, Quaternion, Euler\n\n\n# Globals\n# Add your UNIX paths here!\nmale_model_path = '/home/yusun/Desktop/all_files/animation/SMPL_unity_v.1.0.0/smpl/Models/SMPL_m_unityDoubleBlends_lbs_10_scale5_207_v1.0.0.fbx'\nfemale_model_path = '/home/yusun/Desktop/all_files/animation/SMPL_unity_v.1.0.0/smpl/Models/SMPL_f_unityDoubleBlends_lbs_10_scale5_207_v1.0.0.fbx'\n# Handle fall back if files don't exist, also keeping the unix version before attempting the windows version.\nplt = platform.system()\nif plt == \"Windows\":\n # Add your Windows paths here!\n male_model_path = \"C:/temp/mocap/smpl/SMPL_m_unityDoubleBlends_lbs_10_scale5_207_v1.0.0.fbx\"\n female_model_path = \"C:/temp/mocap/smpl/SMPL_f_unityDoubleBlends_lbs_10_scale5_207_v1.0.0.fbx\"\n \n'''\npython romp/lib/utils/convert_fbx.py --input=demo/videos/dance_tracking_result.npz --output=demo/videos/dance.fbx --gender=female\n'''\n\nfps_source = 24\nfps_target = 24\n\ngender = 'female' #female\n\nstart_origin = 1\nperson_id = 0\nargs = []\n\nbone_name_from_index = {\n 0 : 'Pelvis',\n 1 : 'L_Hip',\n 2 : 'R_Hip',\n 3 : 'Spine1',\n 4 : 'L_Knee',\n 5 : 'R_Knee',\n 6 : 'Spine2',\n 7 : 'L_Ankle',\n 8: 'R_Ankle',\n 9: 'Spine3',\n 10: 'L_Foot',\n 11: 'R_Foot',\n 12: 'Neck',\n 13: 'L_Collar',\n 14: 'R_Collar',\n 15: 'Head',\n 16: 'L_Shoulder',\n 17: 'R_Shoulder',\n 18: 'L_Elbow',\n 19: 'R_Elbow',\n 20: 'L_Wrist',\n 21: 'R_Wrist',\n 22: 'L_Hand',\n 23: 'R_Hand'\n}\n\n\nbone_name_from_index_character = {\n 0 : 'Hips',\n 1 : 'RightUpLeg',\n 2 : 'LeftUpLeg',\n 3 : 'Spine',\n 4 : 'RightLeg',\n 5 : 'LeftLeg',\n 6 : 'Spine1',\n 7 : 'RightFoot',\n 8: 'LeftFoot',\n 9: 'Spine2',\n 10: 'LeftToeBase',\n 11: 'RightToeBase',\n 12: 'Neck',\n 13: 'LeftHandIndex1',\n 14: 'RightHandIndex1',\n 15: 'Head',\n 16: 'LeftShoulder',\n 17: 'RightShoulder',\n 18: 'LeftArm',\n 19: 'RightArm',\n 20: 'LeftForeArm',\n 21: 'RightForeArm',\n 22: 'LeftHand',\n 23: 'RightHand'\n}\n\n# Helper functions\n\n# Computes rotation matrix through Rodrigues formula as in cv2.Rodrigues\n# Source: smpl/plugins/blender/corrective_bpy_sh.py\ndef Rodrigues(rotvec):\n theta = np.linalg.norm(rotvec)\n r = (rotvec/theta).reshape(3, 1) if theta > 0. else rotvec\n cost = np.cos(theta)\n mat = np.asarray([[0, -r[2], r[1]],\n [r[2], 0, -r[0]],\n [-r[1], r[0], 0]])\n return(cost*np.eye(3) + (1-cost)*r.dot(r.T) + np.sin(theta)*mat)\n\n\n# Setup scene\ndef setup_scene(model_path, fps_target):\n scene = bpy.data.scenes['Scene']\n\n ###########################\n # Engine independent setup\n ###########################\n\n scene.render.fps = fps_target\n\n # Remove default cube\n if 'Cube' in bpy.data.objects:\n bpy.data.objects['Cube'].select_set(True)\n bpy.ops.object.delete()\n\n # Import gender specific .fbx template file\n bpy.ops.import_scene.fbx(filepath=model_path)\n\n\n# Process single pose into keyframed bone orientations\ndef process_pose(current_frame, pose, trans, pelvis_position):\n\n if pose.shape[0] == 72:\n rod_rots = pose.reshape(24, 3)\n else:\n rod_rots = pose.reshape(26, 3)\n\n mat_rots = [Rodrigues(rod_rot) for rod_rot in rod_rots]\n\n # Set the location of the Pelvis bone to the translation parameter\n armature = bpy.data.objects['Armature']\n bones = armature.pose.bones\n\n # Pelvis: X-Right, Y-Up, Z-Forward (Blender -Y)\n\n # Set absolute pelvis location relative to Pelvis bone head\n try:\n bones[bone_name_from_index[0]].location = Vector((100*trans[1], 100*trans[2], 100*trans[0])) - pelvis_position\n except :\n # Handle missing / wrong gender bones. This will change the models gender if a problem is found and continue on.\n bonename = bone_name_from_index[0]\n if \"m_\" in bonename:\n for bone in bone_name_from_index:\n bone_name_from_index[bone] = bone_name_from_index[bone].replace(\"m_\", \"f_\")\n \n bone_name_from_index[0] = bonename.replace(\"m_\", \"f_\")\n bones[bonename.replace(\"m_\", \"f_\")].location = Vector((100*trans[1], 100*trans[2], 100*trans[0])) - pelvis_position\n \n \n if \"f_\" in bonename:\n for bone in bone_name_from_index:\n bone = bone.replace(\"f_\", \"m_\")\n bone_name_from_index[0] = bonename.replace(\"f_\", \"m_\")\n bones[bonename.replace(\"f_\", \"m_\")].location = Vector((100*trans[1], 100*trans[2], 100*trans[0])) - pelvis_position\n \n # bones['Root'].location = Vector(trans)\n bones[bone_name_from_index[0]].keyframe_insert('location', frame=current_frame)\n\n for index, mat_rot in enumerate(mat_rots, 0):\n if index >= 24:\n continue\n\n bone = bones[bone_name_from_index[index]]\n\n bone_rotation = Matrix(mat_rot).to_quaternion()\n quat_x_90_cw = Quaternion((1.0, 0.0, 0.0), radians(-90))\n quat_x_n135_cw = Quaternion((1.0, 0.0, 0.0), radians(-135))\n quat_x_p45_cw = Quaternion((1.0, 0.0, 0.0), radians(45))\n quat_y_90_cw = Quaternion((0.0, 1.0, 0.0), radians(-90))\n quat_z_90_cw = Quaternion((0.0, 0.0, 1.0), radians(-90))\n\n if index == 0:\n # Rotate pelvis so that avatar stands upright and looks along negative Y avis\n bone.rotation_quaternion = (quat_x_90_cw @ quat_z_90_cw) @ bone_rotation\n else:\n bone.rotation_quaternion = bone_rotation\n\n bone.keyframe_insert('rotation_quaternion', frame=current_frame)\n\n return\n\n\n# Process all the poses from the pose file\ndef process_poses(\n input_path,\n gender,\n fps_source,\n fps_target,\n start_origin,\n person_id=0,\n):\n\n print('Processing: ' + input_path)\n\n poses, trans = [], []\n subject_ids = 0 #list(data.keys())\n data = np.load(input_path, allow_pickle=True)['results'][()]\n if '_ts_results' in os.path.basename(input_path):\n subject_ids = 1\n print('Exporting motion sequence of subject {}'.format(subject_ids))\n data = data[subject_ids]\n frame_nums = list(data.keys())\n poses, trans = np.zeros((len(frame_nums), 72)), np.zeros((len(frame_nums), 3))\n for inds, frame_id in enumerate(frame_nums):\n poses[inds] = data[frame_id]['poses']\n trans[inds] = data[frame_id]['trans']\n else:\n print('Exporting motion sequence of subject {}'.format(subject_id))\n frame_nums = list(data.keys())\n poses, trans = np.zeros((len(frame_nums), 72)), np.zeros((len(frame_nums), 3))\n for inds, frame_id in enumerate(frame_nums):\n poses[inds] = data[frame_id][subject_id]['poses']\n trans[inds] = data[frame_id][subject_id]['trans']\n\n if gender == 'female':\n model_path = female_model_path\n for k,v in bone_name_from_index.items():\n bone_name_from_index[k] = 'f_avg_' + v\n elif gender == 'male':\n model_path = male_model_path\n for k,v in bone_name_from_index.items():\n bone_name_from_index[k] = 'm_avg_' + v\n elif gender == 'character':\n model_path = character_model_path\n for k,v in bone_name_from_index.items():\n bone_name_from_index[k] = 'mixamorig1:' + v\n else:\n print('ERROR: Unsupported gender: ' + gender)\n sys.exit(1)\n\n # Limit target fps to source fps\n if fps_target > fps_source:\n fps_target = fps_source\n\n print('Gender:',gender)\n print('Number of source poses: ',poses.shape[0])\n print('Source frames-per-second: ', fps_source)\n print('Target frames-per-second: ', fps_target)\n print('--------------------------------------------------')\n\n setup_scene(model_path, fps_target)\n\n scene = bpy.data.scenes['Scene']\n sample_rate = int(fps_source/fps_target)\n scene.frame_end = (int)(poses.shape[0]/sample_rate)\n\n # Retrieve pelvis world position.\n # Unit is [cm] due to Armature scaling.\n # Need to make copy since reference will change when bone location is modified.\n armaturee = bpy.data.armatures[0]\n ob = bpy.data.objects['Armature']\n armature = ob.data\n\n bpy.ops.object.mode_set(mode='EDIT')\n # get specific bone name 'Bone'\n pelvis_bone = armature.edit_bones[bone_name_from_index[0]]\n # pelvis_bone = armature.edit_bones['f_avg_Pelvis']\n pelvis_position = Vector(pelvis_bone.head)\n bpy.ops.object.mode_set(mode='OBJECT')\n\n source_index = 0\n frame = 1\n\n offset = np.array([0.0, 0.0, 0.0])\n\n while source_index < poses.shape[0]:\n print('Adding pose: ' + str(source_index))\n\n # Go to new frame\n scene.frame_set(frame)\n\n process_pose(frame, poses[source_index], (trans[source_index] - offset), pelvis_position)\n source_index += sample_rate\n frame += 1\n\n return frame\n\ndef rotate_armature(use):\n if use == True:\n # Switch to Pose Mode\n bpy.ops.object.posemode_toggle()\n \n # Find the Armature & Bones\n ob = bpy.data.objects['Armature']\n armature = ob.data\n bones = armature.bones\n rootbone = bones[0]\n \n # Find the Root bone\n for bone in bones:\n if \"avg_root\" in bone.name:\n rootbone = bone\n \n rootbone.select = True\n \n # Rotate the Root bone by 90 euler degrees on the Y axis. Set --rotate_Y=False if the rotation is not needed.\n bpy.ops.transform.rotate(value=1.5708, orient_axis='Y', orient_type='GLOBAL', orient_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), orient_matrix_type='GLOBAL', constraint_axis=(False, True, False), mirror=True, use_proportional_edit=False, proportional_edit_falloff='SMOOTH', proportional_size=1, use_proportional_connected=False, use_proportional_projected=False, release_confirm=True)\n # Revert back to Object Mode\n bpy.ops.object.posemode_toggle()\n \n\n\ndef export_animated_mesh(output_path):\n # Create output directory if needed\n output_dir = os.path.dirname(output_path)\n if not os.path.isdir(output_dir):\n os.makedirs(output_dir, exist_ok=True)\n\n # Fix Rotation\n rotate_armature(args.rotate_y)\n\n # Select only skinned mesh and rig\n bpy.ops.object.select_all(action='DESELECT')\n bpy.data.objects['Armature'].select_set(True)\n bpy.data.objects['Armature'].children[0].select_set(True)\n\n if output_path.endswith('.glb'):\n print('Exporting to glTF binary (.glb)')\n # Currently exporting without shape/pose shapes for smaller file sizes\n bpy.ops.export_scene.gltf(filepath=output_path, export_format='GLB', export_selected=True, export_morph=False)\n elif output_path.endswith('.fbx'):\n print('Exporting to FBX binary (.fbx)')\n bpy.ops.export_scene.fbx(filepath=output_path, use_selection=True, add_leaf_bones=False)\n else:\n print('ERROR: Unsupported export format: ' + output_path)\n sys.exit(1)\n\n return\n\n\nif __name__ == '__main__':\n \n person_id = 0\n try:\n if bpy.app.background:\n\n parser = argparse.ArgumentParser(description='Create keyframed animated skinned SMPL mesh from VIBE output')\n parser.add_argument('--input', dest='input_path', type=str, default='../demo/videos/sample_video2_results.npz',\n help='Input file or directory')\n parser.add_argument('--output', dest='output_path', type=str, default='../demo/videos/sample_video2.fbx',\n help='Output file or directory')\n parser.add_argument('--fps_source', type=int, default=fps_source,\n help='Source framerate')\n parser.add_argument('--fps_target', type=int, default=fps_target,\n help='Target framerate')\n parser.add_argument('--gender', type=str, default=gender,\n help='Always use specified gender')\n parser.add_argument('--start_origin', type=int, default=start_origin,\n help='Start animation centered above origin')\n parser.add_argument('--person_id', type=int, default=0,\n help='Detected person ID to use for fbx animation')\n parser.add_argument('--rotate_y',type = bool,default = True,help = 'whether to rotate the root bone on the Y axis by -90 on export. Otherwise it may be rotated incorrectly')\n \n args = parser.parse_args()\n\n input_path = args.input_path\n output_path = args.output_path\n\n if not os.path.exists(input_path):\n print('ERROR: Invalid input path')\n sys.exit(1)\n\n fps_source = args.fps_source\n fps_target = args.fps_target\n\n gender = args.gender\n\n start_origin = args.start_origin\n\n # end if bpy.app.background\n\n startTime = time.perf_counter()\n\n # Process data\n cwd = os.getcwd()\n\n # Turn relative input/output paths into absolute paths\n if not input_path.startswith(os.path.sep):\n input_path = os.path.join(cwd, input_path)\n\n if not output_path.startswith(os.path.sep):\n output_path = os.path.join(cwd, output_path)\n\n print('Input path: ' + input_path)\n print('Output path: ' + output_path)\n\n if not (output_path.endswith('.fbx') or output_path.endswith('.glb')):\n print('ERROR: Invalid output format (must be .fbx or .glb)')\n sys.exit(1)\n\n # Process pose file\n poses_processed = process_poses(\n input_path=input_path,\n gender=gender,\n fps_source=fps_source,\n fps_target=fps_target,\n start_origin=start_origin,\n person_id=person_id\n )\n export_animated_mesh(output_path)\n\n print('--------------------------------------------------')\n print('Animation export finished.')\n print('Poses processed: ', poses_processed)\n print('Processing time : ', time.perf_counter() - startTime)\n print('--------------------------------------------------')\n except SystemExit as ex:\n print(\"closing\")\n if ex.code is None:\n exit_status = 0\n else:\n exit_status = ex.code\n\n print('Exiting. Exit status: ' + str(exit_status))\n\n # Only exit to OS when we are not running in Blender GUI\n if bpy.app.background:\n sys.exit(exit_status)\n","sub_path":"romp/exports/convert_fbx.py","file_name":"convert_fbx.py","file_ext":"py","file_size_in_byte":15912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"482009124","text":"import boto3\nfrom threading import Thread\nimport os\nimport sys\nimport time\n\n# sign of Alarm, False means no Alarm\nstate = False\n\n\ndef invoke_lambda(interval):\n while True:\n os.system(\"./distribute.sh -n 1 -i 0\")\n time.sleep(interval)\n \n\ndef alarm_puller(function_name):\n print(function_name)\n global state\n\n # Memory alarm\n cloudwatch.put_metric_alarm(\n AlarmName=memory_alarm,\n ActionsEnabled=True, OKActions=[], AlarmActions=[], InsufficientDataActions=[],\n MetricName='memory_utilization',\n Namespace='LambdaInsights',\n Statistic='Maximum',\n Dimensions=[\n {\n 'Name': 'function_name',\n 'Value': function_name\n },\n ],\n Period=60,\n EvaluationPeriods=5,\n DatapointsToAlarm=5,\n Threshold=45,\n ComparisonOperator='GreaterThanThreshold',\n TreatMissingData='notBreaching'\n )\n\n # CPU alarm\n cloudwatch.put_metric_alarm(\n AlarmName=cpu_alarm,\n ActionsEnabled=True, OKActions=[], AlarmActions=[], InsufficientDataActions=[],\n MetricName='cpu_total_time',\n Namespace='LambdaInsights',\n Statistic='Maximum',\n Dimensions=[\n {\n 'Name': 'function_name',\n 'Value': function_name\n },\n ],\n Period=60,\n EvaluationPeriods=5,\n DatapointsToAlarm=5,\n Threshold=150,\n ComparisonOperator='GreaterThanThreshold',\n TreatMissingData='notBreaching'\n )\n\n paginator = cloudwatch.get_paginator('describe_alarms')\n\n while True:\n for response in paginator.paginate(AlarmNames=[memory_alarm, cpu_alarm]):\n for alarm in response['MetricAlarms']:\n print('{} state {}'.format(alarm['AlarmName'], alarm['StateValue']))\n if alarm['StateValue'] == 'ALARM':\n state = True\n return\n \n time.sleep(60)\n\nif __name__ == '__main__':\n\n function_name = sys.argv[1]\n print(function_name)\n\n soaking_time = int(sys.argv[2])\n print(soaking_time)\n\n emitter_interval = int(sys.argv[3])\n print(emitter_interval)\n\n # alarms\n memory_alarm='adot_lambda_py38_memory-'+function_name\n cpu_alarm='adot_lambda_py38_cpu-'+function_name\n\n cloudwatch = boto3.client('cloudwatch')\n\n # emitter thread\n Thread(target=invoke_lambda, name='emitter', args=(emitter_interval,), daemon=True).start()\n \n alarm_thread = Thread(target=alarm_puller, name='alarm_puller', args=(function_name,), daemon=True)\n alarm_thread.start()\n alarm_thread.join(soaking_time)\n\n # if alarm\n if state:\n print('Soaking test failed!')\n exit(1)\n else:\n print('Soaking test succeed!')\n # If no problem, delete alarm\n cloudwatch.delete_alarms(AlarmNames=[memory_alarm, cpu_alarm])\n exit(0)\n","sub_path":"sample-apps/python-lambda/tools/soaking.py","file_name":"soaking.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"34159730","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jun 9 21:46:34 2021\r\n\r\n@author: jakee/pythonpadawanexe\r\n\r\n\r\n\"\"\"\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.pyplot import subplots\r\nimport numpy as np\r\nfrom pathlib import Path\r\nimport statsmodels.api as sm\r\nfrom statsmodels.tsa.ar_model import AutoReg\r\nfrom statsmodels.tsa.stattools import adfuller\r\nfrom statsmodels.graphics.tsaplots import plot_pacf\r\nfrom statsmodels.tsa.ar_model import ar_select_order\r\nfrom scipy.sparse import load_npz\r\nimport modred as mr\r\nimport meshio\r\nimport os\r\nimport json\r\nfrom scipy.signal import find_peaks\r\n\r\ndef main(filename: Path,Re, start_n: int = 3000,end_n: int =15000,probetype= None,vorticity = None):\r\n\r\n Re = int(Re) \r\n \r\n \r\n downsampling = 1\r\n zeta = vorticity[start_n:end_n]\r\n zeta = zeta[::downsampling] #change zeta\r\n step = np.arange(zeta.size) * downsampling \r\n res = AutoReg(endog=zeta, lags=2,old_names=False).fit()\r\n \r\n print(res.summary())\r\n estcoeff = res.params #estimated model coefficients\r\n print(\"Estimated Model Coefficients:\",estcoeff)\r\n mu = res.roots**-1 # roots\r\n print(\"Roots:\",mu)\r\n s = mu \r\n print(\"s:\", s) \r\n omega = np.angle(s[0])/(2*np.pi*downsampling) \r\n period = np.abs(1 / omega) #1/omega #np.abs(2 * np.pi / omega) \r\n print(\"period:\", period, \" time-steps\") \r\n sigma = np.log(np.abs(s[0]))/ downsampling #s[0].real \r\n print(\"decay time:\", np.abs(1 / sigma), \" time-steps\") \r\n asymptote = estcoeff[0] / (1 - estcoeff[1:].sum()) # see Intertemporal effect of shocks https://en.wikipedia.org/wiki/Autoregressive_model\r\n \r\n dt = 1\r\n t = end_n - start_n\r\n Uyp1 = zeta\r\n smoothed = np.zeros(t)\r\n smoothed[0]=Uyp1[0]\r\n alpha = .03 * dt\r\n for i in range(1,t):\r\n \tsmoothed[i]=(1-alpha)*smoothed[i-1]+alpha*Uyp1[i-1]\r\n \r\n \r\n kmax = np.argmax(zeta) \r\n amplitude = zeta[kmax] - asymptote \r\n \r\n \r\n \r\n fig, ax = subplots() \r\n ax.plot(step, zeta, marker=\".\", linestyle=\"None\", color=\"green\", label=\"data\") \r\n ax.set_xlabel(\"relative time-step\") \r\n ax.set_ylabel(\"vorticity\") \r\n fig.suptitle(\"Eventual Amplitude AR(2) {} @ Re ={}\".format(probetype,Re))\r\n ax.plot( \r\n step, \r\n asymptote + amplitude * np.exp(sigma * (step - kmax * downsampling)),\r\n linestyle=\"dotted\", \r\n color=\"k\", \r\n label=\"AR(2) envelope\", \r\n ) \r\n \r\n ax.vlines( \r\n np.arange(6) * period, \r\n zeta.min(), \r\n asymptote, \r\n linestyle=\"dashed\", \r\n color=\"red\", \r\n label=\"AR(2) period\", \r\n ) \r\n ax.legend() \r\n fig.savefig(\"Eventual Amplitude AR(2) {} @ Re ={} Entire Range.png\".format(probetype,Re))\r\n\r\n return sigma,omega\r\n\r\nif __name__ == \"__main__\":\r\n from argparse import ArgumentParser\r\n for ii in range(2):\r\n chronosi = ii\r\n U = 1.4994965504069229 #np.max(uv0[inlet_dofs]) , can a\r\n nu = np.unique(((0.1*U)/np.arange(70,81,1)))\r\n #nu = [0.1*U/118]\r\n Re_ls = []\r\n GRATES_AFT = []\r\n GRATES_FORE = []\r\n FREQS_AFT = []\r\n FREQS_FORE = []\r\n #U_avg = 1\r\n from cylinder import radius as rad\r\n Diam = 2*rad\r\n \r\n \r\n if ii == 0:\r\n probetype = \"Fore Vorticity Probe\"\r\n if ii == 1: \r\n probetype = \"Aft Vorticity Probe\"\r\n \r\n for i in range(len(nu)):\r\n Re = round((U*Diam)/nu[i],4)\r\n Re_ls.append(int(Re))\r\n parser = ArgumentParser()\r\n parser.add_argument(\r\n \"-f\",\r\n \"--filename\",\r\n type=Path,\r\n default=Path(str(os.path.dirname(__file__))+'\\\\'+'SIM_XDMF\\\\'\r\n +\"st08_navier_stokes_cylinder\"+\r\n \"_Re_{}.xdmf\".format(str(Re).replace('.','-'))),\r\n )\r\n args = parser.parse_args()\r\n # print(args)\r\n \r\n \r\n \r\n \r\n \r\n filename= Path(args.filename)\r\n probes = np.array([4, 5])\r\n with meshio.xdmf.TimeSeriesReader(filename) as reader:\r\n \r\n points, _ = reader.read_points_cells()\r\n print(\"Points:\", points[probes, :2])\r\n \r\n time = []\r\n vorticity = []\r\n steps = reader.num_steps\r\n for k in range(steps):\r\n t, pd, _ = reader.read_data(k)\r\n time.append(t)\r\n vorticity.append(pd[\"vorticity\"][probes])\r\n \r\n vorticity = np.array(vorticity).T\r\n \r\n vorticity = vorticity[ii]\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n GRATE,FREQ = main(Path(args.filename),Re,probetype=probetype,vorticity=vorticity)\r\n if ii == 0:\r\n GRATES_FORE.append(GRATE)\r\n FREQS_FORE.append(FREQ)\r\n elif ii == 1: \r\n GRATES_AFT.append(GRATE)\r\n FREQS_AFT.append(FREQ)\r\n else:\r\n print(\"Error!\")\r\n if not os.path.exists(str(os.path.dirname(__file__))+'\\INTERVAL_I_SUBCRIT_JSON'):\r\n try:\r\n os.makedirs(str(os.path.dirname(__file__))+'\\INTERVAL_I_SUBCRIT_JSON')\r\n except OSError as e:\r\n if e.errno != errno.EEXIST:\r\n raise\r\n if chronosi == 0:\r\n with open(str(os.path.dirname(__file__))+'\\INTERVAL_I_SUBCRIT_JSON'+'\\GRATES_FORE.json', 'w') as f:\r\n # indent=2 is not needed but makes the file human-readable\r\n json.dump(GRATES_FORE, f, indent=2) \r\n with open(str(os.path.dirname(__file__))+'\\INTERVAL_I_SUBCRIT_JSON'+'\\FREQS_FORE.json', 'w') as f:\r\n # indent=2 is not needed but makes the file human-readable\r\n json.dump(FREQS_FORE, f, indent=2) \r\n \r\n elif chronosi == 1:\r\n with open(str(os.path.dirname(__file__))+'\\INTERVAL_I_SUBCRIT_JSON'+'\\GRATES_AFT.json', 'w') as f:\r\n # indent=2 is not needed but makes the file human-readable\r\n json.dump(GRATES_AFT, f, indent=2) \r\n with open(str(os.path.dirname(__file__))+'\\INTERVAL_I_SUBCRIT_JSON'+'\\FREQS_AFT.json', 'w') as f:\r\n # indent=2 is not needed but makes the file human-readable\r\n json.dump(FREQS_AFT, f, indent=2) \r\n else:\r\n print(\"Error!\")\r\n \r\n \r\n \r\n # fig,ax = plt.subplots()\r\n # ax.scatter(Re_ls,FREQS_FORE,label=\"Fore Probe\",marker='+')\r\n # ax.scatter(Re_ls,FREQS_AFT,label=\"Aft Probe\",marker='x')\r\n # ax.set(xlabel = 'Reynolds Number (Re)', ylabel = 'Frequency')\r\n # ax.grid()\r\n # plt.legend()\r\n # fig.suptitle(\"Steady State Supercritical Frequency AR(2)\")\r\n # fig.savefig(\"Steady State Supercritical Frequency AR(2)\")\r\n # plt.show() \r\n \r\n \r\n \r\n # fig,ax = plt.subplots()\r\n # ax.scatter(Re_ls,GRATES_FORE,label=\"Fore Probe\",marker='+')\r\n # ax.scatter(Re_ls,GRATES_AFT,label=\"Aft Probe\",marker='x')\r\n # ax.set(xlabel = 'Reynolds Number (Re)', ylabel = 'Growth Rate')\r\n # ax.grid()\r\n # plt.legend()\r\n # fig.suptitle(\"Steady State Supercritical Growth Rate AR(2)\")\r\n # fig.savefig(\"Steady State Supercritical Growth Rate AR(2)\")\r\n # plt.show()\r\n \r\n \r\n \r\n ","sub_path":"AR2_INTERVAL_I_PROBE.py","file_name":"AR2_INTERVAL_I_PROBE.py","file_ext":"py","file_size_in_byte":7907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"209733955","text":"import torch\nimport torch.nn as nn\nimport torchvision.models as models\nimport torch.nn.functional as F\nimport copy\nfrom heapq import heappush, heappop\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nclass EncoderCNN(nn.Module):\n def __init__(self, embed_size):\n super(EncoderCNN, self).__init__()\n resnet = models.resnet50(pretrained=True)\n for param in resnet.parameters():\n param.requires_grad_(False)\n\n modules = list(resnet.children())[:-1]\n self.resnet = nn.Sequential(*modules)\n self.bn = nn.BatchNorm1d(resnet.fc.in_features)\n self.embed = nn.Linear(resnet.fc.in_features, embed_size)\n\n def forward(self, images):\n features = self.resnet(images) # shape: batch_size, 2048, 1, 1\n features = features.view(features.size(0), -1) # shape: batch_size, 2048\n features = self.bn(features)\n features = self.embed(features)\n return features\n\n\nclass DecoderRNN(nn.Module):\n def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1):\n super().__init__()\n\n self.hidden_size = hidden_size\n self.word_embeddings = nn.Embedding(vocab_size, embed_size)\n\n self.lstm = nn.LSTM(input_size=embed_size,\n hidden_size=hidden_size,\n num_layers=1,\n bias=True,\n batch_first=True,\n dropout=0,\n bidirectional=False)\n\n self.linear = nn.Linear(hidden_size, vocab_size)\n\n def init_hidden(self, batch_size):\n \"\"\"shape: (num_layers, batch_size, hidden_dim)\"\"\"\n return (torch.zeros((1, batch_size, self.hidden_size), device=device),\n torch.zeros((1, batch_size, self.hidden_size), device=device))\n\n def forward(self, features, captions):\n \"\"\"features.shape: (batch_size, embed_size)\"\"\"\n\n batch_size = features.shape[0]\n self.hidden = self.init_hidden(batch_size)\n\n # 去掉每个caption的标识\n captions = captions[:, :-1]\n embeddings = self.word_embeddings(captions)\n # embeddings shape:(batch_size, caption length, embed_size),为了和embeddings拼接,unsqueeze features\n embeddings = torch.cat((features.unsqueeze(1), embeddings), dim=1)\n\n # Get the output and hidden state\n lstm_out, self.hidden = self.lstm(embeddings, self.hidden)\n\n # Fully connected layer, (batch_size, caption length, vocab_size)\n outputs = self.linear(lstm_out)\n\n return outputs\n\n def sample(self, inputs, states=None, max_len=20):\n \" accepts pre-processed image tensor (inputs) and returns predicted sentence (list of tensor ids of length max_len) \"\n output = []\n # batch_size is 1 at inference\n batch_size = inputs.shape[0] # (1, 1, embed_size)\n hidden = self.init_hidden(batch_size)\n\n while True:\n lstm_out, hidden = self.lstm(inputs, hidden)\n outputs = self.linear(lstm_out) # (1, 1, vocab_size)\n outputs = outputs.squeeze(1)\n _, max_indice = torch.max(outputs, dim=1)\n\n output.append(max_indice.cpu().numpy()[0].item())\n\n # if we get word, break\n if (max_indice == 1):\n break\n\n inputs = self.word_embeddings(max_indice)\n inputs = inputs.unsqueeze(1)\n\n return output\n\n def beam_search_sample(self, inputs, beam=3):\n # batch_size is 1 at reference\n batch_size = inputs.shape[0]\n hidden = self.init_hidden(batch_size)\n\n # sequences[0][0] : log probability of the word seq predicted\n # sequences[0][1] : index of word of this seq, initialize a Tensor([0]) for programming convenient\n # sequences[0][2] : hidden state related of the last word\n # sequences[0][3] : count of words in this seq except start and end word\n sequences = [[.0, [torch.Tensor([0]).long().to(device)], hidden, 0]]\n max_len = 20\n sorted_seqs = []\n\n # Step 1\n # Predict the first word \n outputs, hidden = DecoderRNN.get_outputs(self, inputs, hidden)\n softmax_score = F.log_softmax(outputs, dim=1) # Define a function to sort the cumulative socre\n sorted_score, indices = torch.sort(-softmax_score, dim=1)\n word_preds = indices[0][:beam]\n best_scores = sorted_score[0][:beam]\n _, max_indice = torch.max(outputs, dim=1)\n\n for i in range(beam):\n seq = copy.deepcopy(sequences[0])\n seq[1].append(word_preds[i])\n if word_preds[i] != 1:\n seq[3] += 1\n seq[0] = (seq[0] + best_scores[i]) / seq[3]\n seq[2] = hidden\n heappush(sorted_seqs, seq)\n sequences = sorted_seqs[:beam]\n\n # self.echo_sequences(sequences, beam)\n\n sorted_seqs=[]\n\n l = 1\n while l < max_len:\n # print(\"l:\", l)\n l += 1\n temp = []\n for seq in sequences:\n inputs = seq[1][-1] # last word index in seqences\n if inputs == 1:\n heappush(sorted_seqs, seq)\n continue\n inputs = inputs.type(torch.cuda.LongTensor)\n # Embed the input word\n inputs = self.word_embeddings(inputs) # inputs shape : (1, embed_size)\n inputs = inputs.reshape((1, 1, -1)) # inputs shape : (1, 1, embed_size)\n\n # retrieve the hidden state\n hidden = seq[2]\n preds, hidden = DecoderRNN.get_outputs(self, inputs, hidden)\n\n # Getting the top (n) predictions\n softmax_score = F.log_softmax(preds, dim=1) # Define a function to sort the cumulative socre\n sorted_score, indices = torch.sort(-softmax_score, dim=1)\n word_preds = indices[0][:beam]\n best_scores = sorted_score[0][:beam]\n for i in range(beam):\n sub_seq = seq.copy()\n sub_seq[1] = seq[1][:]\n sub_seq[1].append(word_preds[i])\n if word_preds[i] != 1:\n sub_seq[3] += 1\n sub_seq[0] = (sub_seq[0] + best_scores[i]) / sub_seq[3]\n sub_seq[2] = hidden\n heappush(sorted_seqs, sub_seq)\n\n sequences = sorted_seqs[:beam]\n sorted_seqs = []\n # self.echo_sequences(sequences, beam)\n\n for i in range(beam):\n sequences[i] = sequences[i][1][1:] # remove the first initialized Tensor([0])\n for j, elem in enumerate(sequences[i]):\n sequences[i][j] = elem.cpu().numpy().item()\n if sequences[i][-1] != 1:\n sequences[i].append(1)\n\n return sequences\n\n def get_outputs(self, inputs, hidden):\n lstm_out, hidden = self.lstm(inputs, hidden) # lstm_out shape: (1, 1, hidden_size)\n outputs = self.linear(lstm_out) # outputs shape: (1, 1, vocab_size)\n outputs = outputs.squeeze(1)\n\n return outputs, hidden\n\n def get_next_word_input(self, max_indice):\n # Prepare to embed the last predicted word to be the new input of the lstm\n inputs = self.word_embeddings(max_indice)\n inputs = inputs.unsqueeze(1)\n\n return inputs\n\n def echo_sequences(self, sequences, beam):\n for i in range(beam):\n p_seq = []\n print(sequences[i][1])\n for j in sequences[i][1]:\n p_seq.append(j.cpu().numpy().item())\n print(p_seq)\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"596654885","text":"\"\"\"\nДано натуральное число A. Определите, каким по счету числом Фибоначчи оно\nявляется, то есть выведите такое число n, что\nF'n=A.\nЕсли А не является числом Фибоначчи, выведите число -1.\n\"\"\"\n\na = int(input('a: '))\n\np = 1 # pred chislo\ne = 1 # eto\ns = 0 # sled\ns2 = 0 # sled 2\n\nfor i in range(1, 100):\n p = e\n e = s2\n s = p + e\n s2 = s\n if s == a:\n print(i)\n break\n elif s > a:\n print(-1)\n break\n\n","sub_path":"mccme/07-while/07-18.py","file_name":"07-18.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"644593822","text":"# Copyright 2020 The Cirq Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport numpy as np\nimport pytest\n\nimport cirq\nfrom cirq.ops.pauli_interaction_gate import PauliInteractionGate\nfrom cirq.circuits.quil_output import QuilOneQubitGate, QuilTwoQubitGate\n\n\ndef _make_qubits(n):\n return [cirq.NamedQubit('q{}'.format(i)) for i in range(n)]\n\n\ndef test_single_gate_no_parameter():\n q0, = _make_qubits(1)\n output = cirq.QuilOutput((cirq.X(q0),), (q0,))\n assert (str(output) == \"\"\"# Created using Cirq.\n\nX 0\\n\"\"\")\n\n\ndef test_single_gate_with_parameter():\n q0, = _make_qubits(1)\n output = cirq.QuilOutput((cirq.X(q0)**0.5,), (q0,))\n assert (str(output) == \"\"\"# Created using Cirq.\n\nRX(0.5) 0\\n\"\"\")\n\n\ndef test_single_gate_named_qubit():\n q = cirq.NamedQubit('qTest')\n output = cirq.QuilOutput((cirq.X(q),), (q,))\n assert (str(output) == \"\"\"# Created using Cirq.\n\nX 0\\n\"\"\")\n\n\ndef test_h_gate_with_parameter():\n q0, = _make_qubits(1)\n output = cirq.QuilOutput((cirq.H(q0)**0.25,), (q0,))\n assert (str(output) == \"\"\"# Created using Cirq.\n\nRY(0.25) 0\nRX(0.25) 0\nRY(-0.25) 0\\n\"\"\")\n\n\ndef test_save_to_file(tmpdir):\n file_path = os.path.join(tmpdir, 'test.quil')\n q0, = _make_qubits(1)\n output = cirq.QuilOutput((cirq.X(q0)), (q0,))\n output.save_to_file(file_path)\n with open(file_path, 'r') as f:\n file_content = f.read()\n assert (file_content == \"\"\"# Created using Cirq.\n\nX 0\\n\"\"\")\n\n\ndef test_quil_one_qubit_gate_repr():\n gate = QuilOneQubitGate(np.array([[1, 0], [0, 1]]))\n assert repr(gate) == (\"\"\"cirq.circuits.quil_output.QuilOneQubitGate(matrix=\n[[1 0]\n [0 1]]\n)\"\"\")\n\n\ndef test_quil_two_qubit_gate_repr():\n gate = QuilTwoQubitGate(\n np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]))\n assert repr(gate) == (\"\"\"cirq.circuits.quil_output.QuilTwoQubitGate(matrix=\n[[1 0 0 0]\n [0 1 0 0]\n [0 0 1 0]\n [0 0 0 1]]\n)\"\"\")\n\n\ndef test_quil_one_qubit_gate_eq():\n gate = QuilOneQubitGate(np.array([[1, 0], [0, 1]]))\n gate2 = QuilOneQubitGate(np.array([[1, 0], [0, 1]]))\n assert (cirq.approx_eq(gate, gate2, atol=1e-16))\n gate3 = QuilOneQubitGate(np.array([[1, 0], [0, 1]]))\n gate4 = QuilOneQubitGate(np.array([[1, 0], [0, 2]]))\n assert (not cirq.approx_eq(gate4, gate3, atol=1e-16))\n\n\ndef test_quil_two_qubit_gate_eq():\n gate = QuilTwoQubitGate(\n np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]))\n gate2 = QuilTwoQubitGate(\n np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]))\n assert (cirq.approx_eq(gate, gate2, atol=1e-8))\n gate3 = QuilTwoQubitGate(\n np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]))\n gate4 = QuilTwoQubitGate(\n np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 1]]))\n assert (not cirq.approx_eq(gate4, gate3, atol=1e-8))\n\n\ndef test_quil_one_qubit_gate_output():\n q0, = _make_qubits(1)\n gate = QuilOneQubitGate(np.array([[1, 0], [0, 1]]))\n output = cirq.QuilOutput((gate.on(q0),), (q0,))\n assert str(output) == \"\"\"# Created using Cirq.\n\nDEFGATE USERGATE1:\n\\t1.0+0.0i, 0.0+0.0i\n\\t0.0+0.0i, 1.0+0.0i\nUSERGATE1 0\n\"\"\"\n\n\ndef test_two_quil_one_qubit_gate_output():\n q0, = _make_qubits(1)\n gate = QuilOneQubitGate(np.array([[1, 0], [0, 1]]))\n gate1 = QuilOneQubitGate(np.array([[2, 0], [0, 3]]))\n output = cirq.QuilOutput((\n gate.on(q0),\n gate1.on(q0),\n ), (q0,))\n assert str(output) == \"\"\"# Created using Cirq.\n\nDEFGATE USERGATE1:\n\\t1.0+0.0i, 0.0+0.0i\n\\t0.0+0.0i, 1.0+0.0i\nUSERGATE1 0\nDEFGATE USERGATE2:\n\\t2.0+0.0i, 0.0+0.0i\n\\t0.0+0.0i, 3.0+0.0i\nUSERGATE2 0\n\"\"\"\n\n\ndef test_quil_two_qubit_gate_output():\n q0, q1, = _make_qubits(2)\n gate = QuilTwoQubitGate(\n np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]))\n output = cirq.QuilOutput((gate.on(q0, q1),), (\n q0,\n q1,\n ))\n assert str(output) == \"\"\"# Created using Cirq.\n\nDEFGATE USERGATE1:\n\\t1.0+0.0i, 0.0+0.0i, 0.0+0.0i, 0.0+0.0i\n\\t0.0+0.0i, 1.0+0.0i, 0.0+0.0i, 0.0+0.0i\n\\t0.0+0.0i, 0.0+0.0i, 1.0+0.0i, 0.0+0.0i\n\\t0.0+0.0i, 0.0+0.0i, 0.0+0.0i, 1.0+0.0i\nUSERGATE1 0 1\n\"\"\"\n\n\ndef test_unsupported_operation():\n q0, = _make_qubits(1)\n\n class UnsupportedOperation(cirq.Operation):\n qubits = (q0,)\n with_qubits = NotImplemented\n\n output = cirq.QuilOutput((UnsupportedOperation(),), (q0,))\n with pytest.raises(ValueError):\n _ = str(output)\n\n\ndef test_i_swap_with_power():\n q0, q1 = _make_qubits(2)\n\n output = cirq.QuilOutput((cirq.ISWAP(q0, q1)**0.25,), (\n q0,\n q1,\n ))\n assert str(output) == \"\"\"# Created using Cirq.\n\nCNOT 0 1\nH 0\nCNOT 1 0\nRZ(0.125) 0\nCNOT 1 0\nRZ(-0.125) 0\nH 0\nCNOT 0 1\n\"\"\"\n\n\ndef test_all_operations():\n qubits = tuple(_make_qubits(5))\n operations = _all_operations(*qubits, include_measurements=False)\n output = cirq.QuilOutput(operations, qubits)\n assert (str(output) == \"\"\"# Created using Cirq.\n\nDECLARE m0 BIT[1]\nDECLARE m1 BIT[1]\nDECLARE m2 BIT[1]\nDECLARE m3 BIT[3]\n\nZ 0\nRZ(0.625) 0\nY 0\nRY(0.375) 0\nX 0\nRX(0.875) 0\nH 1\nCZ 0 1\nCPHASE(0.25) 0 1\nCNOT 0 1\nRY(-0.5) 1\nCPHASE(0.5) 0 1\nRY(0.5) 1\nSWAP 0 1\nPSWAP(0.75) 0 1\nH 2\nCCNOT 0 1 2\nH 2\nCCNOT 0 1 2\nRZ(0.125) 0\nRZ(0.125) 1\nRZ(0.125) 2\nCNOT 0 1\nCNOT 1 2\nRZ(-0.125) 1\nRZ(0.125) 2\nCNOT 0 1\nCNOT 1 2\nRZ(-0.125) 2\nCNOT 0 1\nCNOT 1 2\nRZ(-0.125) 2\nCNOT 0 1\nCNOT 1 2\nH 2\nRZ(0.125) 0\nRZ(0.125) 1\nRZ(0.125) 2\nCNOT 0 1\nCNOT 1 2\nRZ(-0.125) 1\nRZ(0.125) 2\nCNOT 0 1\nCNOT 1 2\nRZ(-0.125) 2\nCNOT 0 1\nCNOT 1 2\nRZ(-0.125) 2\nCNOT 0 1\nCNOT 1 2\nH 2\nCSWAP 0 1 2\nX 0\nX 1\nRX(0.75) 0\nRX(0.75) 1\nY 0\nY 1\nRY(0.75) 0\nRY(0.75) 1\nZ 0\nZ 1\nRZ(0.75) 0\nRZ(0.75) 1\nI 0\nI 0\nI 1\nI 2\nISWAP 2 0\nRZ(-0.111) 1\nRX(0.25) 1\nRZ(0.111) 1\nRZ(-0.333) 1\nRX(0.5) 1\nRZ(0.333) 1\nRZ(-0.777) 1\nRX(-0.5) 1\nRZ(0.777) 1\nWAIT\nMEASURE 0 m0[0]\nMEASURE 2 m1[0]\nMEASURE 3 m2[0]\nMEASURE 2 m1[0]\nMEASURE 1 m3[0]\nX 2 # Inverting for following measurement\nMEASURE 2 m3[1]\nMEASURE 3 m3[2]\n\"\"\")\n\n\ndef _all_operations(q0, q1, q2, q3, q4, include_measurements=True):\n return (\n cirq.Z(q0),\n cirq.Z(q0)**.625,\n cirq.Y(q0),\n cirq.Y(q0)**.375,\n cirq.X(q0),\n cirq.X(q0)**.875,\n cirq.H(q1),\n cirq.CZ(q0, q1),\n cirq.CZ(q0, q1)**0.25, # Requires 2-qubit decomposition\n cirq.CNOT(q0, q1),\n cirq.CNOT(q0, q1)**0.5, # Requires 2-qubit decomposition\n cirq.SWAP(q0, q1),\n cirq.SWAP(q0, q1)**0.75, # Requires 2-qubit decomposition\n cirq.CCZ(q0, q1, q2),\n cirq.CCX(q0, q1, q2),\n cirq.CCZ(q0, q1, q2)**0.5,\n cirq.CCX(q0, q1, q2)**0.5,\n cirq.CSWAP(q0, q1, q2),\n cirq.XX(q0, q1),\n cirq.XX(q0, q1)**0.75,\n cirq.YY(q0, q1),\n cirq.YY(q0, q1)**0.75,\n cirq.ZZ(q0, q1),\n cirq.ZZ(q0, q1)**0.75,\n cirq.IdentityGate(1).on(q0),\n cirq.IdentityGate(3).on(q0, q1, q2),\n cirq.ISWAP(q2, q0), # Requires 2-qubit decomposition\n cirq.PhasedXPowGate(phase_exponent=0.111, exponent=0.25).on(q1),\n cirq.PhasedXPowGate(phase_exponent=0.333, exponent=0.5).on(q1),\n cirq.PhasedXPowGate(phase_exponent=0.777, exponent=-0.5).on(q1),\n cirq.WaitGate(0).on(q0),\n cirq.measure(q0, key='xX'),\n cirq.measure(q2, key='x_a'),\n cirq.measure(q3, key='X'),\n cirq.measure(q2, key='x_a'),\n cirq.measure(q1, q2, q3, key='multi', invert_mask=(False, True)))\n\n\ndef test_fails_on_big_unknowns():\n\n class UnrecognizedGate(cirq.ThreeQubitGate):\n pass\n\n c = cirq.Circuit(UnrecognizedGate().on(*cirq.LineQubit.range(3)))\n with pytest.raises(ValueError, match='Cannot output operation as QUIL'):\n _ = c.to_quil()\n\n\ndef test_pauli_interaction_gate():\n q0, q1, = _make_qubits(2)\n output = cirq.QuilOutput(PauliInteractionGate.CZ.on(q0, q1), (\n q0,\n q1,\n ))\n assert str(output) == \"\"\"# Created using Cirq.\n\nCZ 0 1\n\"\"\"\n","sub_path":"cirq/circuits/quil_output_test.py","file_name":"quil_output_test.py","file_ext":"py","file_size_in_byte":8410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"495174218","text":"from plone import api\n\n\nACTIONS_ORDER = ['overview',\n 'documents-proxy',\n 'assigned_inbox_tasks',\n 'issued_inbox_tasks',\n 'trash-proxy',\n 'journal',\n 'sharing']\n\n\ndef order_actions(context):\n \"\"\" Order the actions on the opengever.inbox.inbox FTI according to the\n order given in ACTIONS_ORDER.\n\n \"\"\"\n types_tool = api.portal.get_tool('portal_types')\n inbox_fti = types_tool['opengever.inbox.inbox']\n\n actions = inbox_fti._actions\n\n ordered_actions = []\n for action_id in ACTIONS_ORDER:\n action = [a for a in actions if a.id == action_id][0]\n ordered_actions.append(action)\n\n remaining_actions = [a for a in actions if a.id not in ACTIONS_ORDER]\n\n all_actions = ordered_actions + remaining_actions\n inbox_fti._actions = all_actions\n\n\ndef installed(site):\n order_actions(site)\n","sub_path":"opengever/inbox/hooks.py","file_name":"hooks.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"184743105","text":"import os\nfrom PIL import Image\nfrom torchvision.transforms import Compose\nimport torchvision.transforms as transforms\nimport logging\nimport shutil\n\nmean = [0.5, 0.5, 0.5]\nstdev = [0.5, 0.5, 0.5]\n\nlogging.basicConfig(filename=\"Data_Processing.log\",\n format='%(asctime)s %(message)s',\n filemode='w')\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\n\n\nclass process_data:\n test_path: str\n train_path: str\n resolution: int\n raw_data: str\n process_data: str\n x: str\n y: str\n\n def __init__(self, data_directory: str, processed_data_directory: str):\n self.resolution = 4 # Preparing for 4x super resolution.\n self.count = 0\n self.raw_data = data_directory\n self.processed_data = processed_data_directory\n self.x = os.path.join(processed_data_directory, \"x\")\n self.y = os.path.join(processed_data_directory, \"y\")\n self.train_transform = Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean, stdev),\n transforms.ToPILImage(),\n ])\n\n def load_images_from_directory(self, folder: str) -> list:\n images: list = list()\n list_name: list = list()\n filename: str\n\n for filename in os.listdir(folder):\n list_name.append(os.path.join(folder, filename))\n list_name.sort()\n for filename in list_name:\n img = Image.open(filename).convert('RGB')\n\n # Applying transforms on the images\n img = self.train_transform(img)\n\n if img is not None:\n images.append(img)\n return images\n\n def process(self):\n self.count = 0\n image_list: list = list()\n\n logger.info(f\"Creating processsed images directory\")\n if os.path.exists(self.processed_data):\n shutil.rmtree(self.processed_data, ignore_errors=True)\n os.mkdir(self.processed_data)\n\n logger.info(f\"Creating directory for inputs\")\n if os.path.exists(self.x):\n shutil.rmtree(self.x, ignore_errors=True)\n os.mkdir(self.x)\n\n logger.info(f\"Creating directory for ground truth\")\n if os.path.exists(self.y):\n shutil.rmtree(self.y, ignore_errors=True)\n os.mkdir(self.y)\n\n # List directory under data directory\n directory_list = os.listdir(os.path.join(self.raw_data))\n for classes in directory_list:\n dir_name = os.path.join(self.raw_data, classes)\n temp_image = self.load_images_from_directory(dir_name)\n logger.info(f\"Loading images from directory - {classes}: size - {len(temp_image)}: DONE\")\n image_list.extend(temp_image)\n\n for image in image_list:\n image.save(os.path.join(self.y, str(self.count) + '.png'))\n image = image.resize((int(image.size[0] / self.resolution), int(image.size[1] / self.resolution)))\n image.save(os.path.join(self.x, str(self.count) + '.png'))\n self.count += 1\n logger.info(f\"Number of LR-HR image pairs Created: {self.count}\")\n\n\nif __name__ == '__main__':\n print(f'Started the Data Fetching and Processing')\n proc = process_data(\"/home/harsh.shukla/Caltech101/Data/101_ObjectCategories\", \"/home/harsh.shukla/Caltech101/Data\"\n \"/SR_Images\")\n print(f'Starting Image Clustering...')\n proc.process()\n","sub_path":"Caltech101/src/Image_Super_Resolution/process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":3535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"54638674","text":"# -*- coding: utf-8 -*-\n\nimport sys\nfrom ixiaerror import IxiaError\nfrom ixiangpf import IxiaNgpf\nfrom ixiautil import PartialClass, make_hltapi_fail\n\nclass IxiaNgpf(PartialClass, IxiaNgpf):\n\tdef emulation_ldp_control(self, mode, handle, **kwargs):\n\t\tr'''\n\t\t#Procedure Header\n\t\t Name:\n\t\t emulation_ldp_control\n\t\t\n\t\t Description:\n\t\t Stop, start or restart the protocol.\n\t\t\n\t\t Synopsis:\n\t\t emulation_ldp_control\n\t\t -mode CHOICES restart\n\t\t CHOICES start\n\t\t CHOICES stop\n\t\t CHOICES restart_down\n\t\t CHOICES abort\n\t\t CHOICES resume_hello\n\t\t CHOICES stop_hello\n\t\t CHOICES resume_keepalive\n\t\t CHOICES stop_keepalive\n\t\tn [-port_handle ANY]\n\t\t -handle ANY\n\t\tn [-advertise ANY]\n\t\tn [-flap_count ANY]\n\t\tn [-flap_down_time ANY]\n\t\tn [-flap_interval_time ANY]\n\t\tn [-flap_routes ANY]\n\t\tn [-withdraw ANY]\n\t\t\n\t\t Arguments:\n\t\t -mode\n\t\t What is being done to the protocol.Valid choices are:\n\t\t restart - Restart the protocol.\n\t\t start- Start the protocol.\n\t\t stop- Stop the protocol.\n\t\t restart_down - Restarts the down sessions.\n\t\t abort- Aborts the protocol.\n\t\t resume_hello - Resumes hello message for the given LDP connected interface.\n\t\t stop_hello - Stops hello message for the given LDP connected Interface.\n\t\t resume_keepalive - Resumes Keepalive message for the given LDP connected interface.\n\t\t stop_keepalive- Stop Keepalive message for the given LDP connected interface.\n\t\tn -port_handle\n\t\tn This argument defined by Cisco is not supported for NGPF implementation.\n\t\t -handle\n\t\t The LDP session handle to act upon.\n\t\tn -advertise\n\t\tn This argument defined by Cisco is not supported for NGPF implementation.\n\t\tn -flap_count\n\t\tn This argument defined by Cisco is not supported for NGPF implementation.\n\t\tn -flap_down_time\n\t\tn This argument defined by Cisco is not supported for NGPF implementation.\n\t\tn -flap_interval_time\n\t\tn This argument defined by Cisco is not supported for NGPF implementation.\n\t\tn -flap_routes\n\t\tn This argument defined by Cisco is not supported for NGPF implementation.\n\t\tn -withdraw\n\t\tn This argument defined by Cisco is not supported for NGPF implementation.\n\t\t\n\t\t Return Values:\n\t\t $::SUCCESS | $::FAILURE\n\t\t key:status value:$::SUCCESS | $::FAILURE\n\t\t If status is failure, detailed information provided.\n\t\t key:log value:If status is failure, detailed information provided.\n\t\t\n\t\t Examples:\n\t\t See files starting with LDP_ in the Samples subdirectory. Also see some of the L2VPN, L3VPN, MPLS, and MVPN sample files for further examples of the LDP usage.\n\t\t See the LDP example in Appendix A, \"Example APIs,\" for one specific example usage.\n\t\t\n\t\t Sample Input:\n\t\t\n\t\t Sample Output:\n\t\t\n\t\t Notes:\n\t\t Coded versus functional specification.\n\t\t\n\t\t See Also:\n\t\t\n\t\t'''\n\t\thlpy_args = locals().copy()\n\t\thlpy_args.update(kwargs)\n\t\tdel hlpy_args['self']\n\t\tdel hlpy_args['kwargs']\n\n\t\tnot_implemented_params = []\n\t\tmandatory_params = []\n\t\tfile_params = []\n\n\t\ttry:\n\t\t\treturn self.__execute_command(\n\t\t\t\t'emulation_ldp_control', \n\t\t\t\tnot_implemented_params, mandatory_params, file_params, \n\t\t\t\thlpy_args\n\t\t\t)\n\t\texcept (IxiaError, ):\n\t\t\te = sys.exc_info()[1]\n\t\t\treturn make_hltapi_fail(e.message)\n","sub_path":"ixia/hlapi/4.98.122.39/library/common/ixiangpf/python/ixiangpf_commands/emulation_ldp_control.py","file_name":"emulation_ldp_control.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"291759705","text":"import os\r\nfrom ehive.runnable.IGFBaseProcess import IGFBaseProcess\r\nfrom igf_data.process.singlecell_seqrun.processsinglecellsamplesheet import ProcessSingleCellSamplesheet\r\n\r\nclass ReplaceSingleCellBarcodes(IGFBaseProcess):\r\n '''\r\n A class for replacing 10X single cell barcodes present on the samplesheet\r\n It checks the Description column of the samplesheet and look for the specific\r\n single_cell_lebel. Also it requires a json format file listing all the single\r\n cell barcodes downloaded from this page\r\n https://support.10xgenomics.com/single-cell-gene-expression/sequencing/doc/\r\n specifications-sample-index-sets-for-single-cell-3\r\n '''\r\n def param_defaults(self):\r\n params_dict=super(ReplaceSingleCellBarcodes,self).param_defaults()\r\n params_dict.\\\r\n update({'output_samplesheet_name':'SampleSheet_SC.csv',\r\n 'singlecell_tag':'10X',\r\n })\r\n return params_dict\r\n\r\n\r\n def run(self):\r\n try:\r\n seqrun_igf_id = self.param_required('seqrun_igf_id')\r\n samplesheet_file = self.param_required('samplesheet')\r\n singlecell_barcode_json = self. param_required('single_cell_barcode_file')\r\n base_work_dir = self.param_required('base_work_dir')\r\n output_samplesheet_name = self.param('output_samplesheet_name')\r\n singlecell_tag = self.param('singlecell_tag')\r\n job_name = self.job_name()\r\n work_dir = \\\r\n os.path.join(\\\r\n base_work_dir,\r\n seqrun_igf_id,\r\n job_name) # get work directory name\r\n if not os.path.exists(work_dir):\r\n os.makedirs(work_dir, 0o770) # create work dir if its not present\r\n\r\n sc_data = \\\r\n ProcessSingleCellSamplesheet(\\\r\n samplesheet_file,\r\n singlecell_barcode_json,\r\n singlecell_tag)\r\n output_samplesheet = \\\r\n os.path.join(\\\r\n work_dir,\r\n output_samplesheet_name) # set output file\r\n if os.path.exists(output_samplesheet):\r\n os.remove(output_samplesheet) # remove existing file\r\n\r\n sc_data.change_singlecell_barcodes(output_samplesheet) # print new samplesheet with sc indexes\r\n self.param('dataflow_params',{'samplesheet':output_samplesheet}) # set data flow\r\n except Exception as e:\r\n message = \\\r\n 'seqrun: {2}, Error in {0}: {1}'.\\\r\n format(\\\r\n self.__class__.__name__,\r\n e,\r\n seqrun_igf_id)\r\n self.warning(message)\r\n self.post_message_to_slack(message,reaction='fail') # post msg to slack for failed jobs\r\n self.post_message_to_ms_team(\r\n message=message,\r\n reaction='fail')\r\n raise","sub_path":"ehive/runnable/process/demultiplexing/ReplaceSingleCellBarcodes.py","file_name":"ReplaceSingleCellBarcodes.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"267590763","text":"from pygame import sprite, transform, image, key, display, time, event, font\r\nfrom pygame import K_LEFT, K_RIGHT, K_SPACE, KEYDOWN, QUIT\r\nfrom random import randint\r\n\r\n\r\nclass GameSprite(sprite.Sprite):\r\n def __init__(self, player_image, player_x, player_y, size_x, size_y, player_speed):\r\n sprite.Sprite.__init__(self)\r\n self.image = transform.scale(image.load(player_image), (size_x, size_y))\r\n self.speed = player_speed\r\n self.rect = self.image.get_rect()\r\n self.rect.x = player_x\r\n self.rect.y = player_y\r\n\r\n def reset(self):\r\n window.blit(self.image, (self.rect.x, self.rect.y))\r\n\r\n\r\nclass Player(GameSprite):\r\n def update(self):\r\n keys = key.get_pressed()\r\n if keys[K_LEFT] and self.rect.x > 5:\r\n self.rect.x -= self.speed\r\n if keys[K_RIGHT] and self.rect.x < win_width - 90:\r\n self.rect.x += self.speed\r\n\r\n def fire(self):\r\n bullet = Bullet('./images/bullet.png', self.rect.x + 45, self.rect.y, 30, 70, 10)\r\n bullets.add(bullet)\r\n\r\n\r\nclass Enemy(GameSprite):\r\n def update(self):\r\n if self.rect.y <= 660:\r\n self.rect.y += self.speed\r\n else:\r\n self.rect.y = randint(-40, 0)\r\n self.rect.x = randint(0, 650)\r\n\r\n\r\nclass Bullet(GameSprite):\r\n def update(self):\r\n if self.rect.y >= 0:\r\n self.rect.y -= self.speed\r\n else:\r\n self.kill()\r\n\r\n\r\nwin_width = 700\r\nwin_height = 500\r\ndisplay.set_caption(\"Shooter\")\r\nwindow = display.set_mode((win_width, win_height))\r\nbackground = image.load(\"./images/grass.png\")\r\nbackground = transform.scale(background, (700, 150))\r\nwindow.blit(background, (0, 390))\r\n\r\nbackground_l = transform.scale(image.load(\"./images/fail.jpg\"), (700, 500))\r\n\r\nbackground_w = transform.scale(image.load(\"./images/trophy.png\"), (394, 500))\r\n\r\nhero = Player(\"./images/hedgehog.png\", 20, 430, 90, 60, 10)\r\n\r\nmonsters = sprite.Group()\r\nfor i in range(1, 6):\r\n monster = Enemy('./images/apple.png', randint(0, 620), randint(-100, 0), 60, 60, randint(3, 7))\r\n monsters.add(monster)\r\n\r\nmain_en = Enemy('./images/evil_apple.png', randint(0, 560), randint(-50, 0), 150, 150, 4)\r\n\r\nfloor = GameSprite('./images/grass.png', 0, 500, 700, 15, 0)\r\n\r\nbullets = sprite.Group()\r\n\r\nmiss = 0\r\nmax_miss = 3\r\nscore = 0\r\nscore_ap_en = 10\r\nscore_en = 0\r\nscore_en_w = 10\r\n\r\nfont.init()\r\nlocal_font = font.Font(None, 36)\r\n\r\nrun = True\r\nfinish = False\r\nwhile run:\r\n time.delay(50)\r\n for e in event.get():\r\n if e.type == QUIT:\r\n run = False\r\n if e.type == KEYDOWN and e.key == K_SPACE:\r\n hero.fire()\r\n\r\n if not finish:\r\n window.fill((95, 173, 245))\r\n window.blit(background, (0, 390))\r\n floor.reset()\r\n hero.update()\r\n hero.reset()\r\n monsters.update()\r\n\r\n for i in monsters:\r\n i.reset()\r\n bullets.update()\r\n for i in bullets:\r\n i.reset()\r\n\r\n collides = sprite.groupcollide(monsters, bullets, True, True)\r\n for c in collides:\r\n monster = Enemy('./images/apple.png', randint(0, 620), randint(-100, 0), 60, 60, randint(3, 7))\r\n monsters.add(monster)\r\n score += 1\r\n\r\n fs = sprite.spritecollide(floor, monsters, True)\r\n for f in fs:\r\n monster = Enemy('./images/apple.png', randint(0, 620), randint(-100, 0), 60, 60, randint(3, 7))\r\n monsters.add(monster)\r\n miss += 1\r\n\r\n collide_lose = sprite.spritecollide(hero, monsters, True)\r\n for _ in collide_lose:\r\n finish = True\r\n window.blit(background_l, (0, 0))\r\n\r\n if miss > max_miss:\r\n finish = True\r\n window.blit(background_l, (0, 0))\r\n\r\n if score > score_ap_en:\r\n main_en.update()\r\n main_en.reset()\r\n\r\n if sprite.collide_rect(hero, main_en):\r\n finish = True\r\n window.blit(background_l, (0, 0))\r\n\r\n collide_main = sprite.spritecollide(main_en, bullets, True)\r\n for m in collide_main:\r\n score_en += 1\r\n if score_en > score_en_w:\r\n finish = True\r\n window.fill((0, 0, 0))\r\n window.blit(background_w, (170, 0))\r\n text_w = local_font.render(\"Wow! \", 1, (240, 207, 46))\r\n text_w2 = local_font.render(\"Good job! \", 1, (240, 207, 46))\r\n text_w3 = local_font.render(\"Win! \", 1, (240, 207, 46))\r\n window.blit(text_w, (10, 100))\r\n window.blit(text_w2, (10, 160))\r\n window.blit(text_w3, (10, 220))\r\n\r\n text = local_font.render(\"Score: \" + str(score), 1, (0, 0, 0))\r\n window.blit(text, (10, 20))\r\n text1 = local_font.render(\"Missed: \" + str(miss), 1, (0, 0, 0))\r\n window.blit(text1, (10, 45))\r\n display.update()\r\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"597265782","text":"from Workshop import Workshop\r\nfrom WorkshopGroup import WorkshopGroup\r\nfrom WorkshopUnit import WorkshopUnit\r\nfrom lib2to3.pgen2.tokenize import group\r\n\r\nclass WorkshopManager:\r\n __groupSet = set()\r\n __unitSet = set()\r\n \r\n def __init__(self):\r\n print(\"Workshop Manager created\")\r\n \r\n def __getGroup(self, groupName):\r\n for group in __groupSet:\r\n if groupName == WorkshopGroup.getName():\r\n return WorkshopGroup\r\n return None\r\n \r\n def __getUnit(self, unitName):\r\n for unit in __unitSet:\r\n if unitName == WorkshopUnit.getName():\r\n return WorkshopUnit\r\n return None\r\n \r\n \r\n def getReferenceMaterial(self, workshopName):\r\n if(workshopName in __groupSet):\r\n workshop = self.__getGroup(workshopName)\r\n elif(workshopName in __unitSet):\r\n workshop = self.__getUnit(workshopName)\r\n else:\r\n return None\r\n return (workshop.getReferenceMaterial())\r\n \r\n def getGroupStatus(self, workshopName):\r\n group = self.__getGroup(workshopName)\r\n return(workshopGroup.getWorkshopStatus)\r\n \r\n def getAvailableWorkshops(self):\r\n availableUnits = set()\r\n for unit in self.__getUnit():\r\n if(unit.isAvailable()):\r\n availableUnits.add(unit)\r\n \r\n return availableUnits\r\n \r\n \r\n def addWorkshopUnit(self, configurations):\r\n newUnit = workshopUnit(configurations)\r\n if(newUnit in __unitSet): #unit already exists\r\n return False\r\n else:\r\n __unitSet.add(newUnit)\r\n return True\r\n \r\n def addWorkshopGroup(self, configurations):\r\n newGroup = WorkshopGroup(configurations)\r\n if(newGroup in __groupSet):\r\n return False\r\n else:\r\n __groupSet.add(newGroup)\r\n return True\r\n\r\n def cloneUnit(self, unitName, numOfClones):\r\n unit = self.__getUnit(unitName)\r\n if(unit is None):\r\n return False\r\n newUnits = unit.cloneUnits(numOfClones)\r\n return(newUnits)\r\n","sub_path":"TestbedManagementSystem/Files/JoshVillegas/WorkshopManager.py","file_name":"WorkshopManager.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"346267223","text":"class InferenceConfig(DetectorConfig):\n GPU_COUNT = 1\n IMAGES_PER_GPU = 2\n\ninference_config = InferenceConfig()\n\n# Recreate the model in inference mode\nmodel = modellib.MaskRCNN(mode='inference',\n config=inference_config,\n model_dir=models_save_DIR)\n\n# Load trained weights (fill in path to trained weights here)\nassert model_path != \"\", \"Provide path to trained weights\"\nprint(\"Loading weights from \", model_path)\nmodel.load_weights(model_path, by_name=True)\n","sub_path":"src/config/InferenceConfig.py","file_name":"InferenceConfig.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"22070875","text":"# -*- coding: utf-8 -*-\nfrom PySide.QtCore import *\n\n\nclass Payment(QObject):\n def __init__(self, order):\n self._order = order\n self.total = self._order.get_total_with_tax()\n self.tendered = 0\n self.change = 0\n self.payment_type = \"\"\n\n def __str__(self):\n return 'Оплата {} на сумму {}'.format(self.payment_type, self.tendered)\n\n\"\"\"\nclass CashPayment(Payment):\n def __init__(self, amount):\n super().__init__(amount)\n\n def authorise(self):\n return True\n\nclass CardPayment(Payment):\n def __init__(self, amount):\n super().__init__(amount)\n\n def authorise(self):\n pass\n\"\"\"\n","sub_path":"spos/models/payment.py","file_name":"payment.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"520681425","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport logging\nimport os\nimport sys\nimport tanker\n\nroot_path = os.path.abspath(os.path.dirname(__file__))\nsys.path.append(root_path)\n\n# Or you can run:\n# gunicorn --access-logfile - --log-level debug --debug -b 0.0.0.0:5000 -w 1 wsgi:application\n\nclass PrefixPathMiddleware(object):\n def __init__(self, app, prefix):\n self.app = app\n self.prefix = prefix\n def __call__(self, environ, start_response):\n environ['SCRIPT_NAME'] = self.prefix\n return self.app(environ, start_response)\n\nif __name__ != '__main__':\n # For uwsgi\n tanker.app.logger.setLevel(logging.INFO)\n stderr_logger = logging.StreamHandler()\n stderr_logger.setLevel(logging.INFO)\n stderr_logger.setFormatter(\n logging.Formatter('%(asctime)s %(levelname)s: %(message)s'))\n tanker.app.logger.addHandler(stderr_logger)\n application = tanker.app\n application.wsgi_app = PrefixPathMiddleware(application.wsgi_app, '/tanker')\n application.config.update(\n APPLICATION_ROOT='/tanker'\n )\n\n # uwsgi\n app = application\n","sub_path":"wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"198851182","text":"#\n# Nested rejection sampler implementation.\n#\n# This file is part of PINTS.\n# Copyright (c) 2017-2019, University of Oxford.\n# For licensing information, see the LICENSE file distributed with the PINTS\n# software package.\n#\n#\nfrom __future__ import absolute_import, division\nfrom __future__ import print_function, unicode_literals\nimport pints\nimport numpy as np\n\ntry:\n # Import logsumexp from its new location in scipy.special\n from scipy.special import logsumexp\nexcept ImportError: # pragma: no cover\n from scipy.misc import logsumexp\n\n\nclass NestedRejectionSampler(pints.NestedSampler):\n \"\"\"\n Creates a nested sampler that estimates the marginal likelihood\n and generates samples from the posterior.\n\n This is the simplest form of nested sampler and involves using\n rejection sampling from the prior as described in the algorithm on page 839\n in [1] to estimate the marginal likelihood and generate weights,\n preliminary samples (with their respective likelihoods), required to\n generate posterior samples.\n\n The posterior samples are generated as described in [1] on page 849 by\n randomly sampling the preliminary point, accounting for their weights and\n likelihoods.\n\n *Extends:* :class:`NestedSampler`\n\n [1] \"Nested Sampling for General Bayesian Computation\", John Skilling,\n Bayesian Analysis 1:4 (2006).\n \"\"\"\n\n def __init__(self, log_likelihood, log_prior):\n super(NestedRejectionSampler, self).__init__(log_likelihood, log_prior)\n\n # Target acceptance rate\n self._active_points = 1000\n\n # Total number of iterations\n self._iterations = 1000\n\n # Total number of posterior samples\n self._posterior_samples = 1000\n\n # Total number of likelihood evaluations made\n self._n_evals = 0\n\n def active_points_rate(self):\n \"\"\"\n Returns the number of active points that will be used in next run.\n \"\"\"\n return self._active_points\n\n def iterations(self):\n \"\"\"\n Returns the total number of iterations that will be performed in the\n next run.\n \"\"\"\n return self._iterations\n\n def posterior_samples(self):\n \"\"\"\n Returns the number of posterior samples that will be returned (see\n :meth:`set_posterior_samples()`).\n \"\"\"\n return self._posterior_samples\n\n def run(self):\n \"\"\" See :meth:`pints.MCMC.run()`. \"\"\"\n\n # Check if settings are sensible\n max_post = 0.25 * (self._iterations + self._active_points)\n if self._posterior_samples > max_post:\n raise ValueError(\n 'Number of posterior samples must not exceed 0.25 times (the'\n ' number of iterations + the number of active points).')\n\n # Set up progress reporting\n next_message = 0\n message_warm_up = 3\n message_interval = 20\n\n # Start logging\n logging = self._log_to_screen or self._log_filename\n if logging:\n # Create timer\n timer = pints.Timer()\n\n if self._log_to_screen:\n # Show current settings\n print('Running nested rejection sampling')\n print('Number of active points: ' + str(self._active_points))\n print('Total number of iterations: ' + str(self._iterations))\n print('Total number of posterior samples: ' + str(\n self._posterior_samples))\n\n # Set up logger\n logger = pints.Logger()\n if not self._log_to_screen:\n logger.set_stream(None)\n if self._log_filename:\n logger.set_filename(self._log_filename, csv=self._log_csv)\n\n # Add fields to log\n logger.add_counter('Iter.', max_value=self._iterations)\n logger.add_counter('Eval.', max_value=self._iterations * 10)\n # TODO: Add other informative fields ?\n logger.add_time('Time m:s')\n\n # Problem dimension\n d = self._n_parameters\n\n # Generate initial random points by sampling from the prior\n m_active = np.zeros((self._active_points, d + 1))\n m_initial = self._log_prior.sample(self._active_points)\n for i in range(0, self._active_points):\n # Calculate likelihood\n m_active[i, d] = self._log_likelihood(m_initial[i, :])\n self._n_evals += 1\n\n # Show progress\n if logging and i >= next_message:\n # Log state\n logger.log(0, self._n_evals, timer.time())\n\n # Choose next logging point\n if i > message_warm_up:\n next_message = message_interval * (\n 1 + i // message_interval)\n\n m_active[:, :-1] = m_initial\n\n # store all inactive points, along with their respective\n # log-likelihoods (hence, d+1)\n m_inactive = np.zeros((self._iterations, d + 1))\n\n # store weights\n w = np.zeros(self._active_points + self._iterations)\n\n # store X values (defined in [1])\n X = np.zeros(self._iterations + 1)\n X[0] = 1\n\n # log marginal likelihood holder\n v_log_Z = np.zeros(self._iterations + 1)\n\n # Run\n i_message = self._active_points - 1\n for i in range(0, self._iterations):\n a_running_log_likelihood = np.min(m_active[:, d])\n a_min_index = np.argmin(m_active[:, d])\n X[i + 1] = np.exp(-(i + 1) / self._active_points)\n w[i] = X[i] - X[i + 1]\n v_log_Z[i] = a_running_log_likelihood\n m_inactive[i, :] = m_active[a_min_index, :]\n\n # Independently samples params from the prior until\n # log_likelihood(params) > threshold.\n # Note a_running_log_likelihood can be -inf, so while is never run\n proposed = self._log_prior.sample()[0]\n log_likelihood = self._log_likelihood(proposed)\n self._n_evals += 1\n while log_likelihood < a_running_log_likelihood:\n proposed = self._log_prior.sample()[0]\n log_likelihood = self._log_likelihood(proposed)\n self._n_evals += 1\n m_active[a_min_index, :] = np.concatenate(\n (proposed, np.array([log_likelihood])))\n\n # Show progress\n if logging:\n i_message += 1\n if i_message >= next_message:\n # Log state\n logger.log(i_message, self._n_evals, timer.time())\n\n # Choose next logging point\n if i_message > message_warm_up:\n next_message = message_interval * (\n 1 + i_message // message_interval)\n\n v_log_Z[self._iterations] = logsumexp(m_active[:, d])\n w[self._iterations:] = float(X[self._iterations]) / float(\n self._active_points)\n m_samples_all = np.vstack((m_inactive, m_active))\n log_Z = logsumexp(v_log_Z, b=w[0:(self._iterations + 1)])\n\n vP = np.exp(m_samples_all[:, d] - log_Z) * w\n m_theta = m_samples_all[:, :-1]\n vIndex = np.random.choice(\n range(0, self._iterations + self._active_points),\n self._posterior_samples, p=vP)\n m_posterior_samples = m_theta[vIndex, :]\n\n return m_posterior_samples, log_Z\n\n def set_active_points_rate(self, active_points):\n \"\"\"\n Sets the number of active points for the next run.\n \"\"\"\n active_points = int(active_points)\n if active_points <= 5:\n raise ValueError('Number of active points must be greater than 5.')\n self._active_points = active_points\n\n def n_hyper_parameters(self):\n \"\"\"\n Returns the number of hyper-parameters for this method (see\n :class:`TunableMethod`).\n \"\"\"\n return 1\n\n def set_hyper_parameters(self, x):\n \"\"\"\n Sets the hyper-parameters for the method with the given vector of\n values (see :class:`TunableMethod`).\n\n Hyper-parameter vector is: ``[active_points_rate]``\n\n Arguments:\n\n ``x`` an array of length ``n_hyper_parameters`` used to set the\n hyper-parameters\n \"\"\"\n\n self.set_active_points_rate(x[0])\n\n def set_iterations(self, iterations):\n \"\"\"\n Sets the total number of iterations to be performed in the next run.\n \"\"\"\n iterations = int(iterations)\n if iterations < 0:\n raise ValueError('Number of iterations cannot be negative.')\n self._iterations = iterations\n\n def set_posterior_samples(self, posterior_samples):\n \"\"\"\n Sets the number of posterior samples to generate from points proposed\n by the nested sampling algorithm.\n \"\"\"\n posterior_samples = int(posterior_samples)\n if posterior_samples < 1:\n raise ValueError(\n 'Number of posterior samples must be greater than zero.')\n self._posterior_samples = posterior_samples\n","sub_path":"pints/_nested/_rejection.py","file_name":"_rejection.py","file_ext":"py","file_size_in_byte":9091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"520222308","text":"# O(n^2) time | O(n) space\n# where n is the length of the array\n#\ndef arrayOfProducts(array):\n products = []\n\n for i in range(len(array)):\n product = 1\n for j in range(len(array)):\n if i == j: continue\n product *= array[j]\n products.append(product)\n\n return products\n\n# O(n) time | O(n) space\n# where n is the length of the array\n#\ndef arrayOfProducts2(array):\n product = 1\n leftProducts = []\n for i in range(len(array)):\n leftProducts.append(product)\n product *= array[i]\n\n product = 1\n rightProducts = []\n for i in reversed(range(len(array))):\n rightProducts.append(product)\n product *= array[i]\n rightProducts = list(reversed(rightProducts))\n\n products = []\n for i in range(len(array)):\n products.append(leftProducts[i] * rightProducts[i])\n\n return products\n\ndef arrayOfProducts3(array):\n products = []\n\n product = 1\n for i in range(len(array)):\n products.append(product)\n product *= array[i]\n\n product = 1\n for i in reversed(range(len(array))):\n products[i] *= product\n product *= array[i]\n\n return products\n\nif __name__ == '__main__':\n array = [ 5, 1, 4, 2 ]\n print(arrayOfProducts(array))\n print(arrayOfProducts2(array))\n print(arrayOfProducts3(array))\n","sub_path":"algoexpert/medium/python/array_of_products.py","file_name":"array_of_products.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"271843910","text":"from service.basedaemon import Daemon\nfrom werkzeug.serving import run_simple\nfrom config import SRV_PORT\nfrom web import wcgiapp\nfrom logger import log\nfrom mailer import Mailer\nfrom mail.provider import mailru as smtp_conn\nfrom multiprocessing import Process\n\n\nclass Hudaemon(Daemon):\n def run(self):\n try:\n Process(target=self._runmailer).start()\n Process(target=self._runweb).start()\n except Exception as e:\n log.error(e)\n\n @staticmethod\n def _runmailer():\n \"\"\"Запускаем мониторинг очереди писем\"\"\"\n\n try:\n Mailer(smtp_conn=smtp_conn).loop()\n except Exception as e:\n log.error(\"Mailer stopped with message: %s\" % e)\n\n @staticmethod\n def _runweb():\n \"\"\"Запускаем прием писем по HTTP\"\"\"\n\n try:\n run_simple(\"0.0.0.0\", SRV_PORT, wcgiapp)\n except Exception as e:\n log.error(\"HTTP service stopped with message: %s\" % e)\n","sub_path":"script/humandaemon.py","file_name":"humandaemon.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"120990197","text":"import os \nimport streamlit as st\n\n# import EDA libraries \nimport numpy as np \nimport pandas as pd \n\n# import visualization tools \nimport matplotlib.pyplot as plt \nimport matplotlib\nmatplotlib.use('Agg')\nimport seaborn as sns \n\n\ndef main(): \n # Our Dataset Explorer App with streamlit \n st.title (\"THE DATASET EXPLORER APP\")\n st.subheader('Powered by StreamLit. ')\n \n html_temp = \"\"\"\n

    Built by I.K Emmanuel

    \n\n \"\"\"\n st.markdown (html_temp, unsafe_allow_html = True) \n \n \n \n\n def file_selector (folder_path = './datasets'):\n filenames = os.listdir(folder_path)\n selected_filename = st.selectbox(\" Select a file to begin exploration.\", filenames)\n return os.path.join(folder_path, selected_filename)\n \n filename = file_selector()\n st.info(\" You have just selected {}\". format(filename))\n\n #Reading datasets \n df= pd.read_csv(filename)\n st.subheader (\"Data Exploration\")\n #Showing data\n if st.checkbox(\"Show Dataset\"):\n number = st.slider(\"select the nummber of rows you would like to view\",0,1000,1,1)\n st.dataframe (df.head(number))\n\n #Showing columns \n if st.checkbox(\" Click here to view the columns of the dataset\"):\n st.write(df.columns)\n #Showing Shape \n if st.checkbox (\"Shape of Dataset\"):\n data_dim = st.radio(\"View the Number of Rows or Columns Present in the data \", (\"Rows\", \"Columns\"))\n if data_dim == 'Rows':\n st.text(\"Number of Rows\")\n st.write (df.shape[0])\n elif data_dim == 'Columns':\n st.text(\"Number of Columns\")\n st.write (df.shape[1])\n else: \n st.write (df.shape)\n #Showing Columns\n if st.checkbox (\"Select a few columns to be displayed\"):\n all_columns = df.columns.tolist()\n selected_columns = st.multiselect(\"Select\", all_columns)\n new_df = df[selected_columns]\n st.dataframe(new_df)\n\n #Showing Values \n if st.button( \"Click here to view the distribution of the Target Variable\"):\n st.text(\"Value Counts By Target Variable\")\n st.write(df.iloc[:,-1].value_counts())\n\n #Showing Datatypes\n if st.button( \"Click here to check the various datatypes present in the data\"):\n st.text(\"Data Types\")\n st.write(df.dtypes)\n\n # Showing Summary \n\n if st.checkbox (\"Statistical Summary of Data set\"):\n st.write(df.describe().T)\n # Plots an dVisualizations \n st.subheader (\"Data Visualization \")\n\n #Correlations \n\n #Seaborn Plots \n if st.checkbox(\"Correlation Plot[ using seaborn]\"):\n st.write(sns.heatmap(df.corr(), annot=True))\n st.pyplot()\n \n #Count plots \n if st.checkbox(\"Plot of Value Counts\"):\n st.text (\"Value Counts by Targets \")\n all_columns_names = df.columns.tolist()\n primary_col = st.selectbox( \"Select primary column to groupby\", all_columns_names)\n selected_columns_names = st.multiselect( \"Select columns\", all_columns_names)\n if st.button(\"Plot\"):\n st.text (\"Generating your plot please wait....\")\n if selected_columns_names:\n vc_plot = df.groupby(primary_col)[selected_columns_names].count()\n else:\n vc_plot = df.iloc[:,-1].value_counts()\n st.write(vc_plot.plot(kind=\"bar\"))\n st.pyplot()\n\n\n \n \n #Customizable Plot \n st.subheader(\"Customizable Plots\")\n all_columns_names = df.columns.tolist()\n types_of_plot = st.selectbox (\"Please select a plot type from the drop-down menu\", [\"area\", \"bar\", \"line\", \"hist\", \"box\", \"kde\"])\n selected_columns_names = st.multiselect( \"Select different columns from the drop-down menu to plot\",all_columns_names )\n\n if st.button(\"Generate Plot\"):\n st.success(\" Generating your {} plot for {} now please wait...\".format(types_of_plot, selected_columns_names))\n\n #main plot \n if types_of_plot == \"area\":\n cust_data = df[selected_columns_names]\n st.area_chart(cust_data)\n\n elif types_of_plot == \"bar\": \n cust_data = df[selected_columns_names]\n st.bar_chart(cust_data)\n\n elif types_of_plot == \"line\": \n cust_data = df[selected_columns_names]\n st.line_chart(cust_data)\n\n elif types_of_plot:\n cust_plot= df[selected_columns_names].plot(kind=types_of_plot)\n st.write(cust_plot)\n st.pyplot()\n\n\n\n\n\nif __name__ == '__main__':\n main()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"601442512","text":"from tkinter import *\r\nfrom tkinter import messagebox\r\nimport random\r\n\r\nimport awnsers\r\n\r\nmainWindow = Tk()\r\n\r\ntitle = mainWindow.title(\"Викторина\")\r\ncanvas = Canvas(mainWindow, width=400, height=320)\r\ncount =1\r\ndef levelCreate(num): # Метод обработки первого вопроса\r\n vallist = awnsers.questions[num]\r\n key = random.choice(list(vallist.keys()))\r\n val = vallist[key]\r\n\r\n def clickCorrectButton(lvlnum=num):\r\n messagebox.showinfo(\"Правильно!\", \"Вы ответили верно!\")\r\n for b in btn:\r\n b.destroy()\r\n question.destroy()\r\n lvlnum+=1\r\n if lvlnum<=len(awnsers.questions.keys()):\r\n levelCreate(lvlnum)\r\n else:\r\n messagebox.showinfo(\"Победа\",\"Вы бы получили миллион но не за 3 вопроса\")\r\n def nonCorrectButton():\r\n messagebox.showinfo(\"Не верный ответ\", 'Правильный ответ: ' + str(val))\r\n for b in btn:\r\n b.destroy()\r\n question.destroy()\r\n levelCreate(1)\r\n\r\n question = Label(mainWindow, text=key, font=\"Helvetica 20\") # Текст вопроса плюс шрифт текста\r\n btn1 = Button(mainWindow, font=\"Helvetica 20\", background=\"#1E90FF\", foreground=\"#FFFFFF\",\r\n width=\"200\") # Далее создаем кнопки с ответами\r\n btn2 = Button(mainWindow, font=\"Helvetica 20\", background=\"#1E90FF\", foreground=\"#FFFFFF\",\r\n width=\"200\")\r\n btn3 = Button(mainWindow, font=\"Helvetica 20\", background=\"#1E90FF\", foreground=\"#FFFFFF\",\r\n width=\"200\")\r\n btn4 = Button(mainWindow, font=\"Helvetica 20\", background=\"#1E90FF\", foreground=\"#FFFFFF\",\r\n width=\"200\")\r\n question.pack()\r\n btn=[btn1,btn2,btn3,btn4]\r\n\r\n for i in range(0,4):\r\n btn[i]['text']=random.choice(awnsers.awnsers)\r\n random.choice(btn)['text'] = val\r\n for i in range(0,4):\r\n if btn[i]['text'] != val:\r\n btn[i]['command'] = nonCorrectButton\r\n else:\r\n btn[i]['command'] = clickCorrectButton\r\n\r\n btn1.pack()\r\n btn2.pack()\r\n btn3.pack()\r\n btn4.pack()\r\n\r\nlevelCreate(1)\r\n\r\nmainWindow.mainloop()","sub_path":"victorina/victorina.py","file_name":"victorina.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"506817545","text":"from django.core.management.base import BaseCommand\r\nfrom django.db import transaction\r\n\r\nfrom constance import config\r\n\r\nfrom ...models import *\r\n\r\n\r\n\r\nclass Command(BaseCommand):\r\n help = ''\r\n\r\n def add_arguments(self, parser):\r\n parser.add_argument('code', choices=('ua', 'kz', 'by'))\r\n\r\n def handle(self, **options):\r\n code = options['code']\r\n rate = {\r\n 'ua': config.UAH_RATE,\r\n 'kz': config.KZT_RATE,\r\n 'by': config.BYN_RATE,\r\n }[code]\r\n default_designer = Designer.objects.using(code).get(id=85)\r\n \r\n def convert_price(price):\r\n if not price:\r\n return price\r\n return int(round(price * rate)) or 1\r\n \r\n for tattoo in Tattoo.objects.all():\r\n qs = Tattoo.objects.using(code).filter(id=tattoo.id)\r\n \r\n # calc prices\r\n base_price = convert_price(tattoo.base_price)\r\n discount_price = convert_price(tattoo.discount_price)\r\n price = discount_price or base_price\r\n \r\n # for existing ones only update prices and add photos\r\n if qs.exists():\r\n qs.update(\r\n base_price=base_price,\r\n discount_price=discount_price,\r\n price=price,\r\n )\r\n external_tattoo = qs.first()\r\n with transaction.atomic(using=code):\r\n external_tattoo.photos.all().delete()\r\n for photo in tattoo.photos.all():\r\n TattooPhoto.objects.using(code).create(\r\n id=photo.id,\r\n tattoo=external_tattoo,\r\n photo=photo.photo,\r\n type=photo.type,\r\n position=photo.position,\r\n )\r\n continue\r\n \r\n # create new one\r\n new_tattoo = Tattoo(\r\n id=tattoo.id,\r\n is_active=tattoo.is_active,\r\n is_available=tattoo.is_available,\r\n is_set=tattoo.is_set,\r\n is_gold=tattoo.is_gold,\r\n is_for_nails=tattoo.is_for_nails,\r\n is_main=tattoo.is_main,\r\n is_wholesale=tattoo.is_wholesale,\r\n name=tattoo.name,\r\n url_slug=tattoo.url_slug,\r\n width=tattoo.width,\r\n height=tattoo.height,\r\n position=tattoo.position,\r\n base_price=base_price,\r\n discount_price=discount_price,\r\n price=price,\r\n wholesale_price=tattoo.wholesale_price,\r\n code=tattoo.code,\r\n barcode=tattoo.barcode,\r\n barcode_image=tattoo.barcode_image,\r\n main_photo=tattoo.main_photo,\r\n hover_photo=tattoo.hover_photo,\r\n h1_title=tattoo.h1_title,\r\n h2_title=tattoo.h2_title,\r\n descr=tattoo.descr,\r\n head_title=tattoo.head_title,\r\n meta_description=tattoo.meta_description,\r\n meta_keywords=tattoo.meta_keywords,\r\n )\r\n if Designer.objects.using(code).filter(id=tattoo.designer_id).exists():\r\n new_tattoo.designer = tattoo.designer\r\n else:\r\n new_tattoo.designer = default_designer\r\n categories = []\r\n for cat in tattoo.categories.all():\r\n try:\r\n external_cat = Category.objects.using(code).get(id=cat.id)\r\n categories.append(external_cat)\r\n except Category.DoesNotExist:\r\n continue\r\n \r\n with transaction.atomic(using=code):\r\n new_tattoo.save(using=code)\r\n if categories:\r\n new_tattoo.categories = categories\r\n for photo in tattoo.photos.all():\r\n TattooPhoto.objects.using(code).create(\r\n id=photo.id,\r\n tattoo=new_tattoo,\r\n photo=photo.photo,\r\n type=photo.type,\r\n position=photo.position,\r\n )\r\n","sub_path":"catalog/management/commands/sync_ua_catalog.py","file_name":"sync_ua_catalog.py","file_ext":"py","file_size_in_byte":4330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"144623852","text":"#%% Import of packages\nfrom ioh import get_problem\nfrom ioh import logger\nimport sys\nimport numpy as np\nimport random\nimport numpy as np\n\n# functions\n#from random import randint\n\n#%% Implementation of Problems\n# OneMax\ndef one_max(binary_list):\n result = sum(binary_list) # number of ones which equals the sum\n fitness = result / len(binary_list) # the optimum is all 1 (=length of list)\n\n return result, fitness\n\n# LeadingOnes\ndef leading_ones(binary_list):\n is_one = True\n index = 0\n optimum = len(binary_list) # optimum is all entries are 1\n\n while is_one:\n # Check whether current index is 0\n if binary_list[index] == 0:\n is_one = False\n else:\n index += 1\n\n # Exit in case optimum was reached\n if index == optimum:\n is_one = False\n\n result = index\n fitness = result / optimum\n return result, fitness\n\n# Low Autocorrelation Binary Sequance (LABS)\n## needed functions\ndef y(x_single_value):\n return 2 * x_single_value - 1\n\ndef e_labs(x_array_list):\n result = 0\n length_list = len(x_array_list)\n\n\n for k in range(0, length_list - 1): # last number in range is not iterated, so this is okay\n intermediate_results = []\n for i in range(0, length_list - 1 - k): # -1 since it is n-k, -1 since k = 0 when mathematical 1\n # for testing if indexing is correct\n # print(i)\n intermediate_results.append(y(x_array_list[i]) * y(x_array_list[i + k]))\n\n result += sum(intermediate_results) ** 2\n\n return result\n\n## Defining function itself\ndef labs(binary_list):\n optimum = 8 # given in slides\n\n result = len(binary_list) ** 2 / (2 * e_labs(binary_list))\n fitness = result / optimum\n return result, fitness\n\n#%%\n\n# testing\ntesting_binary_sequance = [randint(0,1) for x in range(0,10)]\nprint('Used bit string:')\nprint(testing_binary_sequance)\n\nprint('OneMax result and fitness')\nprint(one_max(testing_binary_sequance))\n\nprint('LeadingOnes result and fitness')\nprint(leading_ones(testing_binary_sequance))\n\nprint('LABS result and fitness')\nprint(labs(testing_binary_sequance))\n\n#%% Example code\n# Please replace this `random search` by your `genetic algorithm`.\ndef random_search(func, budget = None):\n # budget of each run: 50n^2\n if budget is None:\n budget = int(func.meta_data.n_variables * func.meta_data.n_variables * 50)\n\n if func.meta_data.problem_id == 18 and func.meta_data.n_variables == 32:\n optimum = 8\n else:\n optimum = func.objective.y\n print(optimum)\n # 10 independent runs for each algorithm on each problem.\n for r in range(10):\n f_opt = sys.float_info.min\n x_opt = None\n for i in range(budget):\n x = np.random.randint(2, size = func.meta_data.n_variables)\n f = func(x)\n if f > f_opt:\n f_opt = f\n x_opt = x\n if f_opt >= optimum:\n break\n func.reset()\n return f_opt, x_opt\n\n# Declaration of problems to be tested.\nom = get_problem(1, dim=50, iid=1, problem_type = 'PBO')\nlo = get_problem(2, dim=50, iid=1, problem_type = 'PBO')\nlabs = get_problem(18, dim=32, iid=1, problem_type = 'PBO')\n\n\n# Create default logger compatible with IOHanalyzer\n# `root` indicates where the output files are stored.\n# `folder_name` is the name of the folder containing all output. You should compress this folder and upload it to IOHanalyzer\nl = logger.Analyzer(root=\"data\", \n folder_name=\"run\", \n algorithm_name=\"random_search\", \n algorithm_info=\"test of IOHexperimenter in python\")\n\n\nom.attach_logger(l)\nrandom_search(om)\n\nlo.attach_logger(l)\nrandom_search(lo)\n\nlabs.attach_logger(l)\nrandom_search(labs)\n\n# This statemenet is necessary in case data is not flushed yet.\ndel l","sub_path":"practical_assignment_1.py","file_name":"practical_assignment_1.py","file_ext":"py","file_size_in_byte":3818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"487182843","text":"\"\"\"\r\nThe datetime module provides date and time objects that are similar to the Date\r\nand Time objects in this chapter, but they provide a rich set of methods and operators. Read the\r\ndocumentation at http: // docs. python. org/ 2/ library/ datetime. html .\r\n1. Use the datetime module to write a program that gets the current date and prints the day of\r\nthe week.\r\n2. Write a program that takes a birthday as input and prints the user’s age and the number of\r\ndays, hours, minutes and seconds until their next birthday.\r\n3. For two people born on different days, there is a day when one is twice as old as the other.\r\nThat’s their Double Day. Write a program that takes two birthdays and computes their Double\r\nDay.\r\n4. For a little more challenge, write the more general version that computes the day when one\r\nperson is n times older than the other\r\n\r\n\"\"\"\r\n\r\n#1\r\nimport datetime\r\n\r\ndef print_date_and_day_of_week():\r\n date = datetime.date.today()\r\n\r\n days_of_week = [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"]\r\n day_of_week = days_of_week[date.weekday()]\r\n print(date, \" : \", day_of_week)\r\nprint_date_and_day_of_week() \r\n\r\n#2\r\n\r\nimport datetime\r\n\r\ndef time_to_next_birthday(birth_year, birth_month, birth_day):\r\n birth = datetime.datetime(birth_year, birth_month, birth_day)\r\n current_time = datetime.datetime.now()\r\n\r\n current_age = current_time.year - birth.year - ((current_time.month, current_time.day) < (birth.month, birth.day))\r\n\r\n if (current_time.month, current_time.day) < (birth.month, birth.day):\r\n next_bday = (current_time.year, birth_month, birth_day)\r\n else:\r\n next_bday = (current_time.year + 1, birth_month, birth_day)\r\n\r\n time_to_next_bday = datetime.datetime(*next_bday) - current_time\r\n\r\n print(\"current age: \", current_age)\r\n print(\"time to next birthday: \", time_to_next_bday)\r\ntime_to_next_birthday(1998,10,1)\r\n\r\n#3\r\n\r\nimport datetime\r\n\r\ndef find_double_day(bday1, bday2):\r\n \"\"\"bday1 is the older person.\r\n both birthdays are entered as tuples in this format:\r\n (year, month, day)\"\"\"\r\n\r\n person1 = datetime.date(*bday1)\r\n person2 = datetime.date(*bday2)\r\n\r\n age_diff = -(person1 - person2)\r\n\r\n p1 = int(age_diff.days)\r\n p2 = 0\r\n\r\n while p2 * 2 != p1:\r\n p1 += 1\r\n p2 += 1\r\n\r\n date_at_twice_age = person2 + datetime.timedelta(days=p2)\r\n print(date_at_twice_age, \"\\n\", \"person 1 was %d days old, and person 2 was %d days old\" % (p1, p2))\r\nbday1 = (1995,10,1)\r\nbday2 = (1998,10,1)\r\nfind_double_day(bday1,bday2)\r\n#4\r\n\r\nimport datetime\r\n\r\ndef find_n_times_day(bday1, bday2, n):\r\n \"\"\"bday1 is the older person.\r\n both birthdays are entered as tuples in this format:\r\n (year, month, day)\"\"\"\r\n\r\n person1 = datetime.date(*bday1)\r\n person2 = datetime.date(*bday2)\r\n\r\n age_diff = -(person1 - person2)\r\n\r\n p1 = int(age_diff.days)\r\n p2 = 0\r\n\r\n while p2 * n != p1:\r\n if p2 * n > p1:\r\n print(\"This never precisely occurred\")\r\n return None\r\n p1 += 1\r\n p2 += 1\r\n\r\n date_at_n_times_age = person2 + datetime.timedelta(days=p2)\r\n\r\n print(date_at_n_times_age, \"\\n\", \"person 1 was %d days old, and person 2 was %d days old\" % (p1, p2))\r\nbday1 = (1995,10,1)\r\nbday2 = (1998,10,1)\r\nfind_n_times_day(bday1,bday2,3)\r\n","sub_path":"Chapter 16/Exercise_16_7.py","file_name":"Exercise_16_7.py","file_ext":"py","file_size_in_byte":3329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"509177385","text":"from setuptools import setup, find_packages\nimport os\n\nversion = '1.0.4'\n\ntests_require = [\n 'zc.testbrowser', \n 'osha.theme', \n 'slc.alertservice', \n ]\n\ndef read(*rnames):\n return open(os.path.join(os.path.dirname(__file__), *rnames)).read()\n\n\nlong_description = (\n read('README.txt')\n + '\\n' +\n 'Change history\\n'\n '**************\\n'\n + '\\n' +\n read('CHANGES.txt')\n + '\\n' +\n 'Detailed Documentation\\n'\n '**********************\\n'\n + '\\n' +\n read('src', 'osha', 'status', 'README.txt')\n + '\\n' +\n 'Contributors\\n'\n '************\\n'\n + '\\n' +\n read('CONTRIBUTORS.txt')\n + '\\n'\n )\n\nsetup(name='osha.status',\n version=version,\n description=\"Small status page\",\n long_description = long_description,\n # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n \"Framework :: Plone\",\n \"Programming Language :: Python\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n keywords='',\n author='Patrick Gerken (syslab.com)',\n author_email='gerken@syslab.com',\n url='http://www.syslab.com',\n license='GPL',\n packages=['osha', 'osha.status'],\n package_dir = {'' : 'src'},\n namespace_packages=['osha'],\n include_package_data=True,\n zip_safe=False,\n tests_require=tests_require,\n extras_require=dict(tests=tests_require),\n install_requires=[\n 'setuptools',\n 'Products.ATCountryWidget',\n 'pytz'\n # -*- Extra requirements: -*-\n ],\n entry_points=\"\"\"\n # -*- Entry points: -*-\n \"\"\",\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"218879839","text":"import pytest\nimport inspect\nimport re\nimport random\nimport shutil\nimport csv\n\nfrom abc import ABCMeta, ABC\nfrom collections.abc import Iterable\nfrom dateutil.parser import parse\nfrom datetime import datetime, timedelta\nfrom pathlib import Path\n\nimport app\nfrom src import database\nfrom src import reminder\ntry:\n from src import deadlined_reminders as dr\n DEADLINED_REMINDERS_IMPORTED = True\nexcept ImportError:\n dr = None\n DEADLINED_REMINDERS_IMPORTED = False\n\nfrom src.external_reminders import EveningReminder\n\n# This is for generality of task of implementation the concrete class\nCONCRETE_CLASS_NAME = 'DateReminder'\nABSTRACT_METHOD_NAME = 'is_due'\n\nclass DummyReminder:\n def __init__(self, *args, **kwargs):\n pass\n\n\n@pytest.fixture\ndef backup_reminders_csv():\n # setup\n src_path = Path('reminders.csv')\n dst_path = Path('reminders.csv.bk')\n\n src_existed = False\n if src_path.exists():\n src_existed = True\n shutil.copy2(src_path, dst_path)\n\n # start the test\n yield None\n\n # teardown\n if src_existed:\n shutil.move(dst_path, src_path)\n else:\n src_path.unlink()\n\n\n# === TASK 1 ========================================================================\n\n@pytest.mark.task_1_regular_class_implementation\ndef test_task_1_regular_class_implementation():\n assert hasattr(reminder, 'PoliteReminder'), \\\n 'You should implement class `PoliteReminder` in reminder.py'\n assert inspect.isclass(reminder.PoliteReminder), \\\n '`PoliteReminder` is not a class'\n assert issubclass(reminder.PoliteReminder, reminder.PrefixedReminder), \\\n '`PoliteReminder` should inherit from `PrefixedReminder`'\n\n polite_reminder = reminder.PoliteReminder('test_string')\n assert hasattr(polite_reminder, 'prefix'), \\\n 'No `prefix` property on `PoliteReminder`. Did you inherit from `PrefixedReminder`?'\n assert 'please' in polite_reminder.prefix.lower(),\\\n '`PoliteReminder` should initiate its parent [super()] with a polite prefix containing \"please\"'\n\n# === TASK 2 ========================================================================\n\n@pytest.mark.task_2_overriding_text\ndef test_task_2_overriding_text():\n test_task_1_regular_class_implementation()\n\n polite_reminder = reminder.PoliteReminder('test_string')\n assert polite_reminder.text != polite_reminder.prefix + '',\\\n 'You should override the `text` property with the concatenation'\n assert polite_reminder.text == polite_reminder.prefix + 'test_string',\\\n '`PoliteReminder` should prefix the passed string with your prefix'\n\n# === TASK 3-4 ======================================================================\n\n@pytest.mark.task_3_DeadlinedMetaReminder\ndef test_task_3_DeadlinedMetaReminder():\n assert DEADLINED_REMINDERS_IMPORTED, \\\n 'Could not find module `deadlined_reminders`. Check the name is correct...'\n\n # this is a vestige of parametrized tests\n class_name = 'DeadlinedMetaReminder'\n assert hasattr(dr, class_name), \\\n f'Could not find class `{class_name}` in `deadlined_reminders.py`'\n\n cls = getattr(dr, class_name)\n assert inspect.isclass(cls), f'`{class_name}` is not a class'\n\n assert inspect.isabstract(cls), f'{class_name} should be abstract'\n assert type(cls) == ABCMeta, f'{class_name} should be an Abstract Base Class'\n assert issubclass(cls, Iterable), f'{class_name} should inherit from `collections.abc.Iterable`'\n\n # --- CHECK METHOD ----------------------------\n assert hasattr(cls, ABSTRACT_METHOD_NAME),\\\n f'Could not find `{ABSTRACT_METHOD_NAME}` in `{class_name}`'\n assert ABSTRACT_METHOD_NAME in cls.__abstractmethods__,\\\n f'Method {ABSTRACT_METHOD_NAME} is not abstract in class {class_name}'\n\n params = inspect.signature(cls.is_due).parameters\n assert 'self' in params,\\\n f'`{ABSTRACT_METHOD_NAME}()` should be a method. Did you forget `self`?'\n\n\n@pytest.mark.task_4_DeadlinedReminder\ndef test_task_4_DeadlinedReminder():\n assert DEADLINED_REMINDERS_IMPORTED, \\\n 'Could not find module `deadlined_reminders`. Check the name is correct...'\n\n class_name = 'DeadlinedReminder'\n assert hasattr(dr, class_name), \\\n f'Could not find class `{class_name}` in `deadlined_reminders.py`'\n\n cls = getattr(dr, class_name)\n assert inspect.isclass(cls), f'`{class_name}` is not a class'\n\n assert inspect.isabstract(cls), f'{class_name} should be abstract'\n assert type(cls) == ABCMeta, f'{class_name} should be an Abstract Base Class'\n assert issubclass(cls, Iterable), f'{class_name} should inherit from `collections.abc.Iterable`'\n\n assert ABC in cls.__mro__, 'Class `DeadlinedReminder` should inherit from `ABC`'\n\n # --- CHECK METHOD ----------------------------\n assert hasattr(cls, ABSTRACT_METHOD_NAME),\\\n f'Could not find `{ABSTRACT_METHOD_NAME}` in `{class_name}`'\n assert ABSTRACT_METHOD_NAME in cls.__abstractmethods__,\\\n f'Method {ABSTRACT_METHOD_NAME} is not abstract in class {class_name}'\n\n params = inspect.signature(cls.is_due).parameters\n assert 'self' in params,\\\n f'`{ABSTRACT_METHOD_NAME}()` should be a method. Did you forget `self`?'\n\n\n# === TASK 5 & 6 & 7 ================================================================\n\n@pytest.mark.task_5_concrete_subclass_stub\ndef test_task_5_concrete_subclass_stub():\n test_task_4_DeadlinedReminder()\n\n assert hasattr(dr, CONCRETE_CLASS_NAME), \\\n f'Could not find class `{CONCRETE_CLASS_NAME}` in `deadlined_reminders.py`'\n\n cls = getattr(dr, CONCRETE_CLASS_NAME)\n assert inspect.isclass(cls), f'`{CONCRETE_CLASS_NAME}` is not a class'\n\n assert issubclass(cls, dr.DeadlinedReminder), \\\n f'{CONCRETE_CLASS_NAME} should subclass `DeadlinedReminder`'\n\n implemented_fcts = inspect.getmembers(cls, inspect.isfunction)\n implemented_fct_names = [name for name, fct in implemented_fcts]\n assert '__init__' in implemented_fct_names,\\\n f'You should implement `__init__` on {CONCRETE_CLASS_NAME}'\n\n init_params = inspect.signature(cls.__init__).parameters\n assert 'text' in init_params,\\\n f'`{CONCRETE_CLASS_NAME}.__init__()` should receive `text` as a parameter'\n assert 'date' in init_params,\\\n f'`{CONCRETE_CLASS_NAME}.__init__()` should receive `date` as a parameter'\n\n class DateReminder(cls):\n def __iter__(self): pass\n def is_due(self): pass\n\n reminder = DateReminder('test_string', '01/01/2020')\n assert reminder.text == 'test_string',\\\n f'Incorrect text set in {CONCRETE_CLASS_NAME}.__init__()'\n assert reminder.date == parse('01/01/2020'),\\\n f'Incorrect date set in {CONCRETE_CLASS_NAME}.__init__(). Did you `parse()` it?'\n\n\n@pytest.mark.task_6_is_due\ndef test_task_6_is_due():\n test_task_5_concrete_subclass_stub()\n\n method_name = 'is_due'\n\n cls = getattr(dr, CONCRETE_CLASS_NAME)\n assert method_name not in cls.__abstractmethods__,\\\n f'You should implement `{method_name}()` on {CONCRETE_CLASS_NAME}'\n\n class DateReminder(cls):\n def __iter__(self): pass\n\n offset = random.randint(3, 100)\n\n date = datetime.now() + timedelta(days=offset)\n reminder = DateReminder('test_string', f'{date:%d/%m/%Y}')\n method = getattr(reminder, method_name)\n assert inspect.ismethod(method),\\\n f'`{method_name}()` is not a method on {CONCRETE_CLASS_NAME}. Did you forget `self` ?'\n\n passed_date = datetime.now() - timedelta(days=offset)\n passed_reminder = DateReminder('test_string', f'{passed_date:%d/%m/%Y}')\n assert passed_reminder.is_due() is True,\\\n f'`{CONCRETE_CLASS_NAME}.is_due()` should return True for a past date'\n\n future_date = datetime.now() + timedelta(days=offset)\n future_reminder = DateReminder('test_string', f'{future_date:%d/%m/%Y}')\n assert future_reminder.is_due() is False,\\\n f'`{CONCRETE_CLASS_NAME}.is_due()` should return False for a future date ({future_date:%d/%m/%Y})'\n\n\n@pytest.mark.task_7_iter\ndef test_task_7_iter():\n test_task_5_concrete_subclass_stub()\n\n method_name = '__iter__'\n\n cls = getattr(dr, CONCRETE_CLASS_NAME)\n assert method_name not in cls.__abstractmethods__,\\\n f'You should implement `{method_name}()` on {CONCRETE_CLASS_NAME}'\n\n # at this point we no longer need to mock it, we should be able to instantiate directly\n assert not cls.__abstractmethods__,\\\n f'{CONCRETE_CLASS_NAME} should implement all virtual methods'\n DateReminder = cls\n\n offset = random.randint(3, 100)\n date = datetime.now() + timedelta(days=offset)\n date_str = f'{date:%d/%m/%Y}'\n formatted_date = parse(date_str, dayfirst=True).isoformat()\n\n reminder = DateReminder('test_string', date_str)\n method = getattr(reminder, method_name)\n assert inspect.ismethod(method),\\\n f'`{method_name}()` is not a method on {CONCRETE_CLASS_NAME}. Did you forget `self` ?'\n\n serialized_reminder = list(reminder)\n assert len(serialized_reminder) == 2,\\\n f'{CONCRETE_CLASS_NAME} should be serialized into an iterable of 2 elements'\n\n assert serialized_reminder[0] == 'test_string',\\\n f'First element of your serialized {CONCRETE_CLASS_NAME} should be its `text`.'\n\n assert serialized_reminder[1] == formatted_date,\\\n f'Second element of your serialized {CONCRETE_CLASS_NAME} should be _formatted_ date.'\n\n\n# === TASK 8 ========================================================================\n\n@pytest.mark.task_8_update_interface\ndef test_task_8_update_interface(backup_reminders_csv):\n add_reminder_params = inspect.signature(database.add_reminder).parameters\n assert len(add_reminder_params) >= 2,\\\n '`database.add_reminder()` should take two parameters'\n\n assert 'text' == list(add_reminder_params)[0],\\\n '`database.add_reminder() should still take the `text` as first parameter'\n assert 'date' == list(add_reminder_params)[1],\\\n '`database.add_reminder() should take the `date` as second parameter'\n assert add_reminder_params['date'].default is inspect.Parameter.empty,\\\n '`date` should not have a default value in `database.add_reminder()`'\n\n if len(add_reminder_params) > 2:\n return\n\n try:\n database.add_reminder('test_string', '1/2/2020')\n except Exception as ex:\n pytest.fail(f'Could not add reminder with text and date. Error: {ex}')\n else:\n with open('reminders.csv', 'r') as f:\n lines = f.readlines()\n reader = csv.reader(lines[-1:])\n try:\n row = next(reader)\n except StopIteration:\n pytest.fail('database.add_reminder() had no effect')\n else:\n assert row[0] == 'test_string',\\\n 'database.add_reminder() did not serialize text correctly. Check your DateReminder text'\n assert row[1] == '2020-02-01T00:00:00',\\\n 'database.add_reminder() did not serialize date correctly. Check your DateReminder date'\n\n# === TASK 9 ========================================================================\n\n@pytest.mark.task_9_accept_class\ndef test_task_9_accept_class(backup_reminders_csv):\n test_task_6_is_due()\n test_task_7_iter()\n\n # --- correct_imports ---------------------------------------------\n assert not hasattr(database, 'PoliteReminder'),\\\n 'You should no longer import `PoliteReminder` in `database`'\n assert not hasattr(database, 'DateReminder'),\\\n 'You should no longer import `DateReminder` in `database`'\n\n assert hasattr(database, 'DeadlinedReminder'),\\\n 'You should import `DeadlinedReminder` in `database`'\n\n # --- add_reminder_third_parameter --------------------------------\n signature = inspect.signature(database.add_reminder)\n params = list(signature.parameters)\n assert len(params) == 3,\\\n 'You should pass a third parameter to `add_reminder`'\n assert params[2] == 'ReminderClass',\\\n 'The third parameter should be `ReminderClass`'\n\n # --- add_reminder_date -------------------------------------------\n database.add_reminder('test_reminder', '1/1/2020', dr.DateReminder)\n\n # --- add_reminder_incorrect --------------------------------------\n # NOTE: pytest.raises(TypeError) does not work here as we want custom message\n # for the other exceptions, which would bubble up otherwise\n error_message = 'You should only allow conforming classes in `add_reminder`.'\\\n ' Did you forget `issubclass()`?'\n try:\n database.add_reminder('test_reminder', '1/1/2020', DummyReminder)\n pytest.fail(error_message)\n except TypeError as e:\n assert str(e) == 'Invalid Reminder Class', error_message\n except Exception:\n pytest.fail(error_message)\n\n# === TASK 10 ========================================================================\n\n@pytest.mark.task_10_subclasshook\ndef test_task_10_subclasshook(backup_reminders_csv):\n test_task_4_DeadlinedReminder()\n\n DeadlinedReminder = dr.DeadlinedReminder\n assert '__subclasshook__' in DeadlinedReminder.__dict__,\\\n 'Could not find `__subclasshook__` onto `DeadlinedReminder`'\n\n # NOTE: we should not getattr, as that one is bound *to the class* and the check fails\n hook = DeadlinedReminder.__dict__['__subclasshook__']\n assert isinstance(hook, classmethod),\\\n '`__subclasshook__` should be a classmethod'\n\n assert issubclass(EveningReminder, DeadlinedReminder),\\\n '`__subclasshook__` gives wrong result for class that'\\\n ' respects the protocol of `DeadlinedReminder`'\n\n assert not issubclass(DummyReminder, DeadlinedReminder),\\\n '`__subclasshook__` gives wrong result for class that '\\\n ' does not respect the protocol of `DeadlinedReminder`'\n\n # --- task_10_add_reminder_evening ---------------------------------\n assert hasattr(app, 'EveningReminder'),\\\n 'You did not import/use `EveningReminder` in `app.py`'\n\n try:\n database.add_reminder('test_reminder', '1/1/2020', EveningReminder)\n except Exception as exc:\n pytest.fail('Could not pass an `EveningReminder` to `add_reminder`')\n\n# === TASK 11 ========================================================================\n\n@pytest.mark.task_11_add_reminder_isinstance\ndef test_task_11_add_reminder_isinstance():\n code_lines, starts_on = inspect.getsourcelines(database.add_reminder)\n EXISTS_LINE_WITH_issubclass = any('issubclass' in line for line in code_lines)\n assert not EXISTS_LINE_WITH_issubclass,\\\n 'You should remove the `issubclass` check'\n\n IDX_LINE_WITH_isinstance = None\n IDX_LINE_WITH_constructor = None\n for idx, line in enumerate(code_lines):\n if re.findall(r'ReminderClass\\(.*\\)', line):\n IDX_LINE_WITH_constructor = idx\n break\n\n for idx, line in enumerate(code_lines):\n if re.findall(r'isinstance\\(.*\\)', line):\n IDX_LINE_WITH_isinstance = idx\n assert 'ReminderClass' not in line,\\\n 'You should call `isinstance` with the instance, not the class'\n break\n\n assert IDX_LINE_WITH_isinstance is not None,\\\n 'You should add a check for `isinstance`'\n assert IDX_LINE_WITH_constructor is not None \\\n and IDX_LINE_WITH_constructor < IDX_LINE_WITH_isinstance,\\\n 'You should construct the `reminder` before checking `isinstance()`'\n\n# === TASK 12 ========================================================================\n\n@pytest.mark.task_12_register_polite_reminder\ndef test_task_12_register_polite_reminder():\n test_task_1_regular_class_implementation()\n\n PoliteReminder = reminder.PoliteReminder\n assert hasattr(PoliteReminder, '__iter__'),\\\n 'You should add `__iter__` on PoliteReminder'\n\n init_params = inspect.signature(PoliteReminder.__init__).parameters\n assert init_params.keys() == {'self', 'text', 'date'},\\\n 'In the last task PoliteReminder.__init__() should also take `date` parameter'\n\n assert init_params['date'].default is None,\\\n 'The `date` parameter of PoliteReminder.__init__() should be `None`'\n\n pr = PoliteReminder('test', '1/1/2020')\n polite_reminder_iter = list(pr.__iter__())\n assert polite_reminder_iter[0] == pr.text,\\\n '`PoliteReminder.__iter__()` should return the `text` as first element'\n\n assert len(polite_reminder_iter) == 1,\\\n '`PoliteReminder.__iter__()` should return only one item in the list'\n\n # --- task_12_registration ------------------------------------------\n assert hasattr(app, 'PoliteReminder'),\\\n 'You should import `PoliteReminder` in `app.py`'\n\n assert hasattr(app, 'DeadlinedReminder'),\\\n 'You should import `DeadlinedReminder` in `app.py`'\n\n assert issubclass(reminder.PoliteReminder, dr.DeadlinedReminder),\\\n 'You should register `PoliteReminder` with `DeadlinedReminder`'\n","sub_path":"tests/test_module1.py","file_name":"test_module1.py","file_ext":"py","file_size_in_byte":16936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"272126696","text":"_author_ = \"Gabe Brown\"\n\n# Program - PigLatin\n# CIS - 125\n# Translates English to PigLatin\n\n\n# Declare Vowels and find out how many letters in word\nvowels = \"aeiou\"\nVowels = \"AEIOU\"\nword = \"\"\npigWord = \"\"\n\n# Get Input and find first letter\nword = input(\"What is the English word that you would like to translate to PigLatin?\")\nfirstLetter = word[0]\n\n\n# Translate word to PigLatin\nif firstLetter in vowels or firstLetter in Vowels:\n pigWord = word[0:len(word)] + \"yay\"\nelse:\n pigWord = word[1:len(word)] + firstLetter + \"ay\"\n \n# Print out answer\nprint(word, \"in PigLatin is:\", pigWord)\n ","sub_path":"PigLatin/pigLatin.py","file_name":"pigLatin.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"223840291","text":"# Mobile Advertising Project\n# RPi/mobileAd.py\n# Built by\n# Vincent Reynard Satyadharma & Natanael Avellino\n# Last updated : 28/05/2019\n# Update notes:\n# - Feature : Added websocket functionality with SocketIO (18, 33-36, 117-123)\n# - Feature : Added placeholder background thread for future use with car OBD (38-49)\n# GitHub link : https://github.com/VincentReynardS/mobile-advertising-BASE\n\n\n\n\n\nimport os\nimport json\nfrom flask import Flask, flash, request, redirect, url_for, render_template, jsonify\nfrom flask_socketio import SocketIO, emit\nfrom werkzeug.utils import secure_filename\nfrom threading import Lock\nfrom random import random # module for generating random numbers\n\n# Set this variable to \"threading\", \"eventlet\" or \"gevent\" to test the\n# different async modes, or leave it set to None for the application to choose\n# the best option based on installed packages.\nasync_mode = None\n\nUPLOAD_FOLDER = 'static/iklan'\nALLOWED_EXTENSIONS = set(['gif', 'mp4', '3gp', 'mkv'])\n\napp = Flask('__name__')\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['SECRET_KEY'] = 'secret!'\nsocketio = SocketIO(app, async_mode=async_mode)\nthread = None\nthread_lock = Lock()\n\n# Function to run in background\ndef background_thread():\n \"\"\"Example of how to send server generated events to clients.\"\"\"\n speed = 0\n rpm = 0\n while True:\n socketio.sleep(2)\n speed += 1\n rpm += 1\n socketio.emit('my_response',\n {'speed': speed, 'rpm': rpm},\n namespace='/test')\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n@app.route('/', methods=['GET', 'POST'])\ndef upload_file():\n videos = os.listdir('static/iklan')\n if request.method == 'POST':\n if 'delete' in request.form:\n filename=request.form['delete']\n os.remove('static/iklan/' + filename)\n return redirect(url_for('deleted_file', filename=filename))\n # check if the post request has the file part\n if 'file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n file = request.files['file']\n # if user does not select file, browser also\n # submit a empty part without filename\n if file.filename == '':\n flash('No selected file')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n return redirect(url_for('uploaded_file', filename=filename))\n return render_template('upload_file.html', videos=videos)\n\n@app.route('/display', methods=['GET', 'POST'])\ndef display():\n videos = []\n for root, dirs, files in os.walk(\"static\\\\iklan\", topdown=False):\n for name in files:\n videos.append(os.path.relpath(os.path.join(root, name), '.'))\n # videoToPlay = videos[0] \n return render_template('display.html', videos=videos[0])\n\n@app.route('/uploaded_file/')\ndef uploaded_file(filename):\n return \"File \" + filename + \" has been uploaded!\"\n\n@app.route('/deleted_file/')\ndef deleted_file(filename):\n return \"File \" + filename + \" has been deleted\"\n\n@app.route('/getVideo', methods=['GET'])\ndef getVideo():\n videos = []\n endedVideo = str(request.args.get('endedVideo')) # get ended video from getNewVideo.js\n # lists all videos in static/iklan folder\n for root, dirs, files in os.walk(\"static\\\\iklan\", topdown=False):\n for name in files:\n videos.append(os.path.relpath(os.path.join(root, name), '.'))\n # check the ended video's index in the list, if it is the last video, start over.\n # Else, continue to the next video. This method enables the display to run newly added video(s)\n # without the need to iterate the entire list first.\n if (videos.index(endedVideo) != len(videos)-1):\n newVideo = videos[videos.index(endedVideo)+1]\n else:\n newVideo = videos[0]\n return jsonify({ 'videoToPlay': newVideo}) # return the next video to getNewVideo.js\n \n@app.route('/blank')\ndef blank():\n return \"blank\"\n\n@socketio.on('connect', namespace='/test')\ndef test_connect():\n global thread\n with thread_lock:\n if thread is None:\n thread = socketio.start_background_task(background_thread)\n emit('my_response', {'speed': 'Connected!', 'rpm': 'Connected!'})\n\nif __name__ == '__main__':\n # app.run(host='0.0.0.0', port='5000')\n socketio.run(app, host='0.0.0.0', port='5000', debug=True)","sub_path":"RPi/mobileAd.py","file_name":"mobileAd.py","file_ext":"py","file_size_in_byte":4656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"186989638","text":"import traceback\r\nimport time\r\nfrom threading import Lock\r\nfrom collections import deque\r\nfrom collections import namedtuple\r\nfrom statistics import mean, stdev\r\nimport copy\r\nfrom lxml import etree as etree_\r\nfrom .. import observableproperties as properties\r\nfrom . import mdibbase\r\nfrom . import msgreader\r\nfrom .. import namespaces\r\nfrom .. import pmtypes\r\nfrom concurrent import futures\r\nfrom .. import loghelper\r\n\r\n_global_nsmap = namespaces.nsmap\r\n\r\nPROFILING = False\r\nif PROFILING:\r\n import cProfile\r\n import pstats\r\n from io import StringIO\r\n\r\n\r\nLOG_WF_AGE_INTERVAL = 30 # how often a log message is written with mean and stdef of waveforms age\r\nAGE_CALC_SAMPLES_COUNT = 100 # amount of data for wf mean age and stdev calculation\r\n\r\nA_NO_LOG = 0\r\nA_OUT_OF_RANGE = 1\r\nA_STILL_OUT_OF_RANGE = 2\r\nA_BACK_IN_RANGE = 3\r\n\r\n\r\nclass DeterminationTimeWarner:\r\n \"\"\"A Helper to reduce log warnings regarding determination time.\"\"\"\r\n ST_IN_RANGE = 0\r\n ST_OUT_OF_RANGE = 1\r\n result_lookup = {\r\n # (last, current) : (action, shall_repeat)\r\n (ST_IN_RANGE, ST_IN_RANGE): (A_NO_LOG, False),\r\n (ST_IN_RANGE, ST_OUT_OF_RANGE): (A_OUT_OF_RANGE, False),\r\n (ST_OUT_OF_RANGE, ST_OUT_OF_RANGE): (A_STILL_OUT_OF_RANGE, True),\r\n (ST_OUT_OF_RANGE, ST_IN_RANGE): (A_BACK_IN_RANGE, False)\r\n }\r\n def __init__(self, repeat_period=30):\r\n self.repeat_period = repeat_period\r\n self._last_log_time = 0\r\n self.last_state = self.ST_IN_RANGE\r\n\r\n def getOutOfDeterminationTimeLogState(self, minAge, maxAge, warn_limit):\r\n '''\r\n @return: one of above constants\r\n '''\r\n now = time.time()\r\n if minAge < -warn_limit or maxAge > warn_limit:\r\n current_state = self.ST_OUT_OF_RANGE\r\n else:\r\n current_state = self.ST_IN_RANGE\r\n action, shall_repeat = self.result_lookup[(self.last_state, current_state)]\r\n if self.last_state != current_state:\r\n # a state transition\r\n self.last_state = current_state\r\n self._last_log_time = now\r\n return action\r\n else:\r\n # no state transition, but might need repeated logging\r\n if shall_repeat and now - self._last_log_time >= self.repeat_period:\r\n self._last_log_time = now\r\n return action\r\n else:\r\n return A_NO_LOG\r\n\r\n_AgeData = namedtuple('_AgeData', 'mean_age stdev min_age max_age')\r\n\r\nclass ClientRtBuffer(object):\r\n '''Collects data of one real time stream.'''\r\n def __init__(self, sample_period, max_samples):\r\n '''\r\n @param sample_period: float value, in seconds. \r\n When an incoming real time sample array is split into single RtSampleContainers, this is used to calculate the individual time stamps.\r\n Value can be zero if correct value is not known. In this case all Containers will have the observation time of the sample array.\r\n @param max_samples: integer, max. length of self.rtdata\r\n '''\r\n self.rt_data = deque(maxlen=max_samples)\r\n self.sample_period = sample_period\r\n self._max_samples = max_samples\r\n self._logger = loghelper.getLoggerAdapter('sdc.client.mdib.rt')\r\n self._lock = Lock()\r\n self.last_sc = None # last statecontainer that was handled\r\n self._age_of_data_list = deque(maxlen=AGE_CALC_SAMPLES_COUNT) # used to calculate average age of samples when received\r\n self._reported_min_age = None\r\n self._reported_max_age = None\r\n\r\n\r\n def mkRtSampleContainers(self, realtimeSampleArrayContainer):\r\n '''\r\n\r\n :param realtimeSampleArrayContainer: a RealTimeSampleArrayMetricStateContainer instance\r\n :return: a list of mdibbase.RtSampleContainer\r\n '''\r\n self.last_sc = realtimeSampleArrayContainer\r\n metricValue = realtimeSampleArrayContainer.metricValue\r\n if metricValue is None:\r\n # this can happen if metric state is not activated.\r\n self._logger.debug('real time sample array \"{} \"has no metric value, ignoring it', realtimeSampleArrayContainer.descriptorHandle)\r\n return []\r\n observationTime = metricValue.DeterminationTime\r\n annotations = metricValue.Annotations\r\n applyAnnotations = metricValue.ApplyAnnotations\r\n rtSampleContainers = []\r\n if metricValue.Samples is not None:\r\n for i, sample in enumerate(metricValue.Samples):\r\n appliedAnnotations = []\r\n if applyAnnotations is not None:\r\n for aa in applyAnnotations:\r\n if aa.SampleIndex == i:\r\n # there is an annotation for this sample:\r\n aIndex = aa.AnnotationIndex\r\n annot = annotations[aIndex] # index is zero-based\r\n appliedAnnotations.append(annot)\r\n t = observationTime + i * self.sample_period\r\n rtSampleContainers.append(mdibbase.RtSampleContainer(sample, t, metricValue.Validity, appliedAnnotations))\r\n return rtSampleContainers\r\n\r\n def addRtSampleContainers(self, sc):\r\n if not sc:\r\n return\r\n with self._lock:\r\n self.rt_data.extend(sc)\r\n self._age_of_data_list.append(time.time() - sc[-1].observationTime) # use time of youngest sample, this is the best value for indication of delays\r\n try:\r\n self._reported_min_age = min(self._age_of_data_list[-1], self._reported_min_age)\r\n except TypeError:\r\n self._reported_min_age = self._age_of_data_list[-1]\r\n try:\r\n self._reported_max_age = max(self._age_of_data_list[-1], self._reported_min_age)\r\n except TypeError:\r\n self._reported_max_age = self._age_of_data_list[-1]\r\n\r\n def readData(self):\r\n ''' This read method consumes all data in buffer.\r\n @return: a list of RtSampleContainer objects''' \r\n with self._lock:\r\n ret = copy.copy(self.rt_data)\r\n self.rt_data.clear()\r\n return ret\r\n\r\n\r\n def get_age_stdev(self):\r\n with self._lock:\r\n min_value, self._reported_min_age = self._reported_min_age, None\r\n max_value, self._reported_max_age = self._reported_max_age, None\r\n mean_data = 0 if len(self._age_of_data_list) == 0 else mean(self._age_of_data_list)\r\n std_deviation = 0 if len(self._age_of_data_list) < 2 else stdev(self._age_of_data_list)\r\n return _AgeData(mean_data, std_deviation, min_value or 0, max_value or 0)\r\n\r\n_BufferedNotification = namedtuple('_BufferedNotification', 'report handler')\r\n\r\nclass ClientMdibContainer(mdibbase.MdibContainer):\r\n ''' This mdib is meant to be read-only.\r\n Only update source is a BICEPSClient.'''\r\n\r\n DETERMINATIONTIME_WARN_LIMIT = 1.0 # in seconds\r\n MDIB_VERSION_CHECK_DISABLED = False # for testing purpose you can disable checking of mdib version, so that every notification is accepted.\r\n INITIAL_NOTIFICATION_BUFFERING = True # if False, the response for the first incoming notification is answered after the getmdib is done.\r\n # if True, first notifications are buffered and the responses are sent immediately.\r\n def __init__(self, sdcClient, maxRealtimeSamples=100):\r\n super(ClientMdibContainer, self).__init__(sdcClient.sdc_definitions)\r\n self._logger = loghelper.getLoggerAdapter('sdc.client.mdib', sdcClient.log_prefix)\r\n self._sdcClient = sdcClient\r\n if self.bicepsSchema is None:\r\n raise RuntimeError('no bicepsSchema instance')\r\n self._isInitialized = False\r\n self.rtBuffers = {} # key is a handle, value is a ClientRtBuffer\r\n self._maxRealtimeSamples = maxRealtimeSamples\r\n self._last_wf_age_log = time.time()\r\n if PROFILING:\r\n self.pr = cProfile.Profile()\r\n \r\n self._contextMdibVersion = None\r\n self._msgReader = msgreader.MessageReader(self)\r\n # a buffer for notifications that are received before initial getmdib is done\r\n self._bufferedNotifications = list()\r\n self._bufferedNotificationsLock = Lock()\r\n self.waveform_time_warner = DeterminationTimeWarner()\r\n self.metric_time_warner = DeterminationTimeWarner()\r\n\r\n def initMdib(self):\r\n if self._isInitialized:\r\n raise RuntimeError('ClientMdibContainer is already initialized')\r\n # first start receiving notifications, then call getMdib.\r\n # Otherwise we might miss notifications.\r\n self._bindToObservables()\r\n \r\n getService = self._sdcClient.client('Get')\r\n self._logger.info('initializing mdib...')\r\n mdibNode = getService.getMdibNode()\r\n self.nsmapper.useDocPrefixes(mdibNode.nsmap)\r\n self._logger.info('creating description containers...')\r\n descriptorContainers = self._msgReader.readMdDescription(mdibNode)\r\n with self.descriptions._lock: #pylint: disable=protected-access\r\n self.descriptions.clear()\r\n self.addDescriptionContainers(descriptorContainers)\r\n self._logger.info('creating state containers...')\r\n self.clearStates()\r\n stateContainers = self._msgReader.readMdState(mdibNode)\r\n self.addStateContainers(stateContainers)\r\n\r\n mdibVersion = mdibNode.get('MdibVersion')\r\n sequenceId = mdibNode.get('SequenceId')\r\n if mdibVersion is not None:\r\n self.mdibVersion = int(mdibVersion)\r\n self._logger.info('setting initial mdib version to {}', mdibVersion)\r\n else:\r\n self._logger.warn('found no mdib version in GetMdib response, assuming \"0\"')\r\n self.mdibVersion = 0\r\n self.sequenceId = sequenceId\r\n self._logger.info('setting sequence Id to {}', sequenceId)\r\n \r\n # retrieve context states only if there were none in mdibNode\r\n if len(self.contextStates.objects) == 0:\r\n self._getContextStates()\r\n else:\r\n self._logger.info('found context states in GetMdib Result, will not call getContextStates')\r\n\r\n # process buffered notifications\r\n with self._bufferedNotificationsLock:\r\n for bufferedReport in self._bufferedNotifications:\r\n bufferedReport.handler(bufferedReport.report, is_buffered_report=True)\r\n del self._bufferedNotifications[:]\r\n self._isInitialized = True\r\n\r\n self._sdcClient._register_mdib(self) #pylint: disable=protected-access\r\n self._logger.info('initializing mdib done')\r\n\r\n\r\n def _bufferNotification(self, report, callable):\r\n '''\r\n write notification to an temporary buffer, as long as mdib is not initialized\r\n :param report: the report\r\n :param callable: the mothod that shall be called later for delayed handling of report\r\n :return: True if buffered, False if report shall be processed immediately\r\n '''\r\n if self._isInitialized:\r\n # no reason to buffer\r\n return False\r\n\r\n if not self.INITIAL_NOTIFICATION_BUFFERING:\r\n self._waitUntilInitialized(callable.__name__)\r\n return False\r\n\r\n # get lock and check if we need to write to buffer\r\n with self._bufferedNotificationsLock:\r\n if not self._isInitialized:\r\n self._bufferedNotifications.append(_BufferedNotification(report, callable))\r\n return True\r\n return False\r\n\r\n def syncContextStates(self):\r\n '''This method requests all context states from device and deletes all local context states that are not\r\n available in response from Device.'''\r\n try:\r\n self._logger.info('syncContextStates called')\r\n contextService = self._sdcClient.client('Context')\r\n responseNode = contextService.getContextStatesNode()\r\n self._logger.info('creating context state containers...')\r\n contextStateContainers = self._msgReader.readContextState(responseNode)\r\n devices_contextStateHandles = [s.Handle for s in contextStateContainers]\r\n with self.contextStates._lock: # pylint: disable=protected-access\r\n for obj in self.contextStates.objects:\r\n if obj.Handle not in devices_contextStateHandles:\r\n self.contextStates.removeObjectNoLock((obj))\r\n except:\r\n self._logger.error(traceback.format_exc())\r\n\r\n\r\n def _getContextStates(self, handles = None):\r\n try:\r\n self._logger.debug('new Query, handles={}', handles)\r\n time.sleep(0.001)\r\n contextService = self._sdcClient.client('Context')\r\n self._logger.info('requesting context states...')\r\n responseNode = contextService.getContextStatesNode(handles)\r\n self._logger.info('creating context state containers...')\r\n contextStateContainers = self._msgReader.readContextState(responseNode)\r\n\r\n self._contextMdibVersion = int(responseNode.get('MdibVersion', '0'))\r\n self._logger.debug('_getContextStates: setting _contextMdibVersion to {}', self._contextMdibVersion)\r\n \r\n self._logger.debug('got {} context states', len(contextStateContainers))\r\n with self.contextStates._lock: #pylint: disable=protected-access\r\n for stateContainer in contextStateContainers:\r\n oldStateContainers = self.contextStates.handle.get(stateContainer.Handle, [])\r\n if len(oldStateContainers) == 0:\r\n self.contextStates.addObjectNoLock(stateContainer)\r\n self._logger.debug('new ContextState {}', stateContainer)\r\n elif len(oldStateContainers) == 1:\r\n oldStateContainer = oldStateContainers[0]\r\n if oldStateContainer.StateVersion != stateContainer.StateVersion:\r\n self._logger.debug('update {} ==> {}', oldStateContainer, stateContainer)\r\n oldStateContainer.updateFromNode(stateContainer.node)\r\n self.contextStates.updateObjectNoLock(oldStateContainer)\r\n else:\r\n old = etree_.tostring(oldStateContainer.node)\r\n new = etree_.tostring(stateContainer.node)\r\n if old == new:\r\n self._logger.debug('no update {}', oldStateContainer.node)\r\n else:\r\n self._logger.error('no update but different!\\n{ \\n{}',\r\n lambda:etree_.tostring(oldStateContainer.node), lambda:etree_.tostring(stateContainer.node)) #pylint: disable=cell-var-from-loop \r\n else:\r\n txt = ', '.join([str(x) for x in oldStateContainers])\r\n self._logger.error('found {} objects: {}', len(oldStateContainers), txt)\r\n \r\n except:\r\n self._logger.error(traceback.format_exc())\r\n finally:\r\n self._logger.info('_getContextStates done')\r\n\r\n\r\n def _bindToObservables(self):\r\n # observe properties of sdcClient\r\n if PROFILING:\r\n properties.bind(self._sdcClient, waveFormReport=self._onWaveformReportProfiled)\r\n else:\r\n properties.bind(self._sdcClient, waveFormReport=self._onWaveformReport)\r\n properties.bind(self._sdcClient, episodicMetricReport=self._onEpisodicMetricReport)\r\n properties.bind(self._sdcClient, episodicAlertReport=self._onEpisodicAlertReport)\r\n properties.bind(self._sdcClient, episodicContextReport=self._onEpisodicContextReport)\r\n properties.bind(self._sdcClient, episodicComponentReport=self._onEpisodicComponentReport)\r\n properties.bind(self._sdcClient, descriptionModificationReport=self._onDescriptionModificationReport)\r\n properties.bind(self._sdcClient, episodicOperationalStateReport=self._onOperationalStateReport)\r\n\r\n\r\n def _canAcceptMdibVersion(self, log_prefix, newMdibVersion):\r\n if self.MDIB_VERSION_CHECK_DISABLED:\r\n return True\r\n if newMdibVersion is None:\r\n self._logger.error('{}: could not check MdibVersion!', log_prefix)\r\n else:\r\n # log deviations from expected mdib versionb\r\n if newMdibVersion < self.mdibVersion:\r\n self._logger.warn('{}: ignoring too old Mdib version, have {}, got {}', log_prefix, self.mdibVersion, newMdibVersion)\r\n elif (newMdibVersion - self.mdibVersion) > 1:\r\n if self._sdcClient.all_subscribed:\r\n self._logger.warn('{}: expect mdibVersion {}, got {}', log_prefix, self.mdibVersion+1, newMdibVersion)\r\n # it is possible to receive multiple notifications with the same mdib version => compare \">=\"\r\n if newMdibVersion >= self.mdibVersion:\r\n return True\r\n return False\r\n\r\n\r\n def _updateSequenceId(self, reportNode):\r\n sequenceId = reportNode.get('SequenceId')\r\n if sequenceId != self.sequenceId:\r\n self.sequenceId = sequenceId\r\n\r\n\r\n def _waitUntilInitialized(self, log_prefix):\r\n showsuccesslog = False\r\n started = time.monotonic()\r\n while not self._isInitialized:\r\n delay = time.monotonic() - started\r\n if 3 >= delay > 1:\r\n showsuccesslog = True\r\n self._logger.warn('{}: _waitUntilInitialized takes long...', log_prefix)\r\n elif delay > 10:\r\n raise RuntimeError('_waitUntilInitialized failed')\r\n time.sleep(1)\r\n delay = time.monotonic() - started\r\n if showsuccesslog:\r\n self._logger.info('{}: _waitUntilInitialized took {} seconds', log_prefix, delay)\r\n\r\n\r\n def _onEpisodicMetricReport(self, reportNode, is_buffered_report=False):\r\n if not is_buffered_report and self._bufferNotification(reportNode, self._onEpisodicMetricReport):\r\n return\r\n newMdibVersion = int(reportNode.get('MdibVersion', '1'))\r\n if not self._canAcceptMdibVersion('_onEpisodicMetricReport', newMdibVersion):\r\n return\r\n\r\n now = time.time()\r\n metricsByHandle = {}\r\n maxAge = 0\r\n minAge = 0\r\n statecontainers = self._msgReader.readEpisodicMetricReport(reportNode)\r\n try:\r\n with self.mdibLock:\r\n self.mdibVersion = newMdibVersion\r\n self._updateSequenceId(reportNode)\r\n for sc in statecontainers:\r\n if sc.descriptorContainer is not None and sc.descriptorContainer.DescriptorVersion != sc.DescriptorVersion:\r\n self._logger.warn(\r\n '_onEpisodicMetricReport: metric \"{}\": descriptor version expect \"{}\", found \"{}\"',\r\n sc.descriptorHandle, sc.DescriptorVersion, sc.descriptorContainer.DescriptorVersion)\r\n sc.descriptorContainer = None\r\n try:\r\n oldStateContainer = self.states.descriptorHandle.getOne(sc.descriptorHandle, allowNone=True)\r\n except RuntimeError as ex:\r\n self._logger.error('_onEpisodicMetricReport, getOne on states: {}', ex)\r\n continue\r\n desc_h = sc.descriptorHandle\r\n metricsByHandle[desc_h] = sc # metric\r\n if oldStateContainer is not None:\r\n if self._hasNewStateUsableStateVersion(oldStateContainer, sc, 'EpisodicMetricReport', is_buffered_report):\r\n oldStateContainer.updateFromOtherContainer(sc)\r\n self.states.updateObject(oldStateContainer)\r\n else:\r\n self.states.addObject(sc)\r\n\r\n if sc.metricValue is not None:\r\n observationTime = sc.metricValue.DeterminationTime\r\n if observationTime is None:\r\n self._logger.warn(\r\n '_onEpisodicMetricReport: metric {} version {} has no DeterminationTime',\r\n desc_h, sc.StateVersion)\r\n else:\r\n age = now - observationTime\r\n minAge = min(minAge, age)\r\n maxAge = max(maxAge, age)\r\n shall_log = self.metric_time_warner.getOutOfDeterminationTimeLogState(minAge, maxAge, self.DETERMINATIONTIME_WARN_LIMIT)\r\n if shall_log == A_OUT_OF_RANGE:\r\n self._logger.warn(\r\n '_onEpisodicMetricReport mdibVersion {}: age of metrics outside limit of {} sec.: max, min = {:03f}, {:03f}',\r\n newMdibVersion, self.DETERMINATIONTIME_WARN_LIMIT, maxAge, minAge)\r\n elif shall_log == A_STILL_OUT_OF_RANGE:\r\n self._logger.warn(\r\n '_onEpisodicMetricReport mdibVersion {}: age of metrics still outside limit of {} sec.: max, min = {:03f}, {:03f}',\r\n newMdibVersion, self.DETERMINATIONTIME_WARN_LIMIT, maxAge, minAge)\r\n elif shall_log == A_BACK_IN_RANGE:\r\n self._logger.info(\r\n '_onEpisodicMetricReport mdibVersion {}: age of metrics back in limit of {} sec.: max, min = {:03f}, {:03f}',\r\n newMdibVersion, self.DETERMINATIONTIME_WARN_LIMIT, maxAge, minAge)\r\n finally:\r\n self.metricsByHandle = metricsByHandle # used by waitMetricMatches method\r\n\r\n\r\n def _onEpisodicAlertReport(self, reportNode, is_buffered_report=False):\r\n if not is_buffered_report and self._bufferNotification(reportNode, self._onEpisodicAlertReport):\r\n return\r\n newMdibVersion = int(reportNode.get('MdibVersion', '1'))\r\n if not self._canAcceptMdibVersion('_onEpisodicAlertReport', newMdibVersion):\r\n return\r\n\r\n alertByHandle = {}\r\n allAlertContainers = self._msgReader.readEpisodicAlertReport(reportNode)\r\n self._logger.debug('_onEpisodicAlertReport: received {} alerts', len(allAlertContainers))\r\n try:\r\n with self.mdibLock:\r\n self.mdibVersion = newMdibVersion\r\n self._updateSequenceId(reportNode)\r\n for sc in allAlertContainers:\r\n if sc.descriptorContainer is not None and sc.descriptorContainer.DescriptorVersion != sc.DescriptorVersion:\r\n self._logger.warn(\r\n '_onEpisodicAlertReport: alert \"{}\": descriptor version expect \"{}\", found \"{}\"',\r\n sc.descriptorHandle, sc.DescriptorVersion, sc.descriptorContainer.DescriptorVersion)\r\n sc.descriptorContainer = None\r\n try:\r\n oldStateContainer = self.states.descriptorHandle.getOne(sc.descriptorHandle, allowNone=True)\r\n except RuntimeError as ex:\r\n self._logger.error('_onEpisodicAlertReport, getOne on states: {}', ex)\r\n continue\r\n desc_h = sc.descriptorHandle\r\n\r\n if oldStateContainer is not None:\r\n if self._hasNewStateUsableStateVersion(oldStateContainer, sc, 'EpisodicAlertReport', is_buffered_report):\r\n oldStateContainer.updateFromOtherContainer(sc)\r\n self.states.updateObject(oldStateContainer)\r\n alertByHandle[oldStateContainer.descriptorHandle] = oldStateContainer\r\n else:\r\n self.states.addObject(sc)\r\n alertByHandle[sc.descriptorHandle] = sc\r\n finally:\r\n self.alertByHandle = alertByHandle # update observable\r\n\r\n def _onOperationalStateReport(self, reportNode, is_buffered_report=False):\r\n if not is_buffered_report and self._bufferNotification(reportNode, self._onOperationalStateReport):\r\n return\r\n newMdibVersion = int(reportNode.get('MdibVersion', '1'))\r\n if not self._canAcceptMdibVersion('_onOperationalStateReport', newMdibVersion):\r\n return\r\n operationByHandle = {}\r\n self._logger.info('_onOperationalStateReport: report={}', lambda:etree_.tostring(reportNode))\r\n allOperationStateContainers = self._msgReader.readOperationalStateReport(reportNode)\r\n try:\r\n with self.mdibLock:\r\n self.mdibVersion = newMdibVersion\r\n self._updateSequenceId(reportNode)\r\n for sc in allOperationStateContainers:\r\n if sc.descriptorContainer is not None and sc.descriptorContainer.DescriptorVersion != sc.DescriptorVersion:\r\n self._logger.warn('_onOperationalStateReport: OperationState \"{}\": descriptor version expect \"{}\", found \"{}\"',\r\n sc.descriptorHandle, sc.DescriptorVersion, sc.descriptorContainer.DescriptorVersion)\r\n sc.descriptorContainer = None\r\n try:\r\n oldStateContainer = self.states.descriptorHandle.getOne(sc.descriptorHandle, allowNone=True)\r\n except RuntimeError as ex:\r\n self._logger.error('_onOperationalStateReport, getOne on states: {}', ex)\r\n continue\r\n desc_h = sc.descriptorHandle\r\n\r\n if oldStateContainer is not None:\r\n if self._hasNewStateUsableStateVersion(oldStateContainer, sc, 'OperationalStateReport', is_buffered_report):\r\n oldStateContainer.updateFromOtherContainer(sc)\r\n self.states.updateObject(oldStateContainer)\r\n operationByHandle[oldStateContainer.descriptorHandle] = oldStateContainer\r\n else:\r\n self.states.addObject(sc)\r\n operationByHandle[sc.descriptorHandle] = sc\r\n finally:\r\n self.operationByHandle = operationByHandle\r\n\r\n\r\n\r\n def _onWaveformReportProfiled(self, reportNode):\r\n self.pr.enable()\r\n self._onWaveformReport(reportNode)\r\n self.pr.disable()\r\n s = StringIO()\r\n ps = pstats.Stats(self.pr, stream=s).sort_stats('cumulative')\r\n ps.print_stats(30)\r\n print (s.getvalue())\r\n print ('total number of states: {}'.format(len(self.states._objects))) #pylint:disable=protected-access\r\n print ('total number of objIds: {}'.format(len(self.states._objectIDs))) #pylint:disable=protected-access\r\n for name, l in self.states._objectIDs.items(): #pylint:disable=protected-access\r\n if len(l) > 50:\r\n print ('object {} has {} idx references, {}'.format(name, len(l), l))\r\n\r\n\r\n def _onWaveformReport(self, reportNode, is_buffered_report=False):\r\n #pylint:disable=too-many-locals\r\n # reportNode contains a list of msg:State nodes\r\n if not is_buffered_report and self._bufferNotification(reportNode, self._onWaveformReport):\r\n return\r\n newMdibVersion = int(reportNode.get('MdibVersion', '1'))\r\n if not self._canAcceptMdibVersion('_onWaveformReport', newMdibVersion):\r\n return\r\n waveformByHandle = {}\r\n waveformAge = {} # collect age of all waveforms in this report, and make one report if age is above warn limit (instead of multiple)\r\n allRtSampleArrayContainers = self._msgReader.readWaveformReport(reportNode)\r\n self._logger.debug('_onWaveformReport: {} waveforms received', len(allRtSampleArrayContainers))\r\n try:\r\n with self.mdibLock:\r\n self.mdibVersion = newMdibVersion\r\n self._updateSequenceId(reportNode)\r\n for new_sac in allRtSampleArrayContainers:\r\n d_handle = new_sac.descriptorHandle\r\n descriptorContainer = new_sac.descriptorContainer\r\n if descriptorContainer is None:\r\n self._logger.warn('_onWaveformReport: No Descriptor found for handle \"{}\"', d_handle)\r\n\r\n oldStateContainer = self.states.descriptorHandle.getOne(d_handle, allowNone=True)\r\n if oldStateContainer is None:\r\n self.states.addObject(new_sac)\r\n current_sc = new_sac\r\n else:\r\n if self._hasNewStateUsableStateVersion(oldStateContainer, new_sac, 'WaveformReport', is_buffered_report):\r\n # update old state container from new one\r\n oldStateContainer.updateFromOtherContainer(new_sac)\r\n self.states.updateObject(oldStateContainer)\r\n current_sc = oldStateContainer # we will need it later\r\n waveformByHandle[d_handle] = current_sc\r\n # add to Waveform Buffer\r\n rtBuffer = self.rtBuffers.get(d_handle)\r\n if rtBuffer is None:\r\n if descriptorContainer is not None:\r\n # read sample period\r\n try:\r\n sample_period = descriptorContainer.SamplePeriod or 0\r\n except AttributeError:\r\n sample_period = 0 # default\r\n rtBuffer = ClientRtBuffer(sample_period=sample_period, max_samples=self._maxRealtimeSamples)\r\n self.rtBuffers[d_handle] = rtBuffer\r\n last_sc = rtBuffer.last_sc\r\n rtSampleContainers = rtBuffer.mkRtSampleContainers(new_sac)\r\n rtBuffer.addRtSampleContainers(rtSampleContainers)\r\n\r\n # check age\r\n if len(rtSampleContainers) > 0:\r\n waveformAge[d_handle] = rtSampleContainers[-1].age\r\n\r\n # check descriptor version\r\n if descriptorContainer.DescriptorVersion != new_sac.DescriptorVersion:\r\n self._logger.error('_onWaveformReport: descriptor {}: expect version \"{}\", found \"{}\"',\r\n d_handle, new_sac.DescriptorVersion, descriptorContainer.DescriptorVersion)\r\n\r\n if len(waveformAge) > 0:\r\n minAge = min(waveformAge.values())\r\n maxAge = max(waveformAge.values())\r\n shall_log = self.waveform_time_warner.getOutOfDeterminationTimeLogState(minAge, maxAge, self.DETERMINATIONTIME_WARN_LIMIT)\r\n if shall_log != A_NO_LOG:\r\n tmp = ', '.join('\"{}\":{:.3f}sec.'.format(k, v) for k,v in waveformAge.items())\r\n if shall_log == A_OUT_OF_RANGE:\r\n self._logger.warn('_onWaveformReport mdibVersion {}: age of samples outside limit of {} sec.: age={}!',\r\n newMdibVersion, self.DETERMINATIONTIME_WARN_LIMIT, tmp)\r\n elif shall_log == A_STILL_OUT_OF_RANGE:\r\n self._logger.warn('_onWaveformReport mdibVersion {}: age of samples still outside limit of {} sec.: age={}!',\r\n newMdibVersion, self.DETERMINATIONTIME_WARN_LIMIT, tmp)\r\n elif shall_log == A_BACK_IN_RANGE:\r\n self._logger.info('_onWaveformReport mdibVersion {}: age of samples back in limit of {} sec.: age={}',\r\n newMdibVersion, self.DETERMINATIONTIME_WARN_LIMIT, tmp)\r\n if LOG_WF_AGE_INTERVAL:\r\n now = time.time()\r\n if now - self._last_wf_age_log >= LOG_WF_AGE_INTERVAL:\r\n age_data = self.get_wf_age_stdev()\r\n self._logger.info('waveform mean age={:.1f}ms., stdev={:.2f}ms. min={:.1f}ms., max={}',\r\n age_data.mean_age*1000., age_data.stdev*1000.,\r\n age_data.min_age*1000., age_data.max_age*1000.)\r\n self._last_wf_age_log = now\r\n finally:\r\n self.waveformByHandle = waveformByHandle\r\n\r\n\r\n def _onEpisodicContextReport(self, reportNode, is_buffered_report=False):\r\n if not is_buffered_report and self._bufferNotification(reportNode, self._onEpisodicContextReport):\r\n return\r\n newMdibVersion = int(reportNode.get('MdibVersion', '1'))\r\n if not self._canAcceptMdibVersion('_onEpisodicContextReport', newMdibVersion):\r\n return\r\n contextByHandle = {}\r\n stateContainers = self._msgReader.readEpisodicContextReport(reportNode)\r\n try:\r\n with self.mdibLock:\r\n self.mdibVersion = newMdibVersion\r\n self._updateSequenceId(reportNode)\r\n for sc in stateContainers:\r\n try:\r\n oldStateContainer = self.contextStates.handle.getOne(sc.Handle, allowNone=True)\r\n except RuntimeError as ex:\r\n self._logger.error('_onEpisodicContextReport, getOne on contextStates: {}', ex)\r\n continue\r\n\r\n if oldStateContainer is None:\r\n self.contextStates.addObject(sc)\r\n self._logger.info(\r\n '_onEpisodicContextReport: new context state handle = {} Descriptor Handle={} Assoc={}, Validators={}',\r\n sc.Handle, sc.descriptorHandle, sc.ContextAssociation, sc.Validator)\r\n contextByHandle[sc.Handle] = sc\r\n else:\r\n if self._hasNewStateUsableStateVersion(oldStateContainer, sc, 'EpisodicContextReport', is_buffered_report):\r\n self._logger.info(\r\n '_onEpisodicContextReport: updated context state handle = {} Descriptor Handle={} Assoc={}, Validators={}',\r\n sc.Handle, sc.descriptorHandle, sc.ContextAssociation, sc.Validator)\r\n oldStateContainer.updateFromOtherContainer(sc)\r\n self.contextStates.updateObject(oldStateContainer)\r\n contextByHandle[oldStateContainer.Handle] = oldStateContainer\r\n finally:\r\n self.contextByHandle = contextByHandle\r\n\r\n\r\n def _onEpisodicComponentReport(self, reportNode, is_buffered_report=False):\r\n '''The EpisodicComponentReport is sent if at least one property of at least one component state has changed \r\n and SHOULD contain only the changed component states.\r\n Components are MDSs, VMDs, Channels. Not metrics and alarms\r\n '''\r\n if not is_buffered_report and self._bufferNotification(reportNode, self._onEpisodicComponentReport):\r\n return\r\n newMdibVersion = int(reportNode.get('MdibVersion', '1'))\r\n if not self._canAcceptMdibVersion('_onEpisodicComponentReport', newMdibVersion):\r\n return\r\n componentByHandle = {}\r\n statecontainers = self._msgReader.readEpisodicComponentReport(reportNode)\r\n try:\r\n with self.mdibLock:\r\n self.mdibVersion = newMdibVersion\r\n self._updateSequenceId(reportNode)\r\n for sc in statecontainers:\r\n desc_h = sc.descriptorHandle\r\n if desc_h is None:\r\n self._logger.error('_onEpisodicComponentReport: missing descriptor handle in {}!',\r\n lambda: etree_.tostring(sc.node)) # pylint: disable=cell-var-from-loop\r\n else:\r\n try:\r\n oldStateContainer = self.states.descriptorHandle.getOne(desc_h, allowNone=True)\r\n except RuntimeError as ex:\r\n self._logger.error('_onEpisodicComponentReport, getOne on states: {}', ex)\r\n continue\r\n\r\n if oldStateContainer is None:\r\n self.states.addObject(sc)\r\n self._logger.info(\r\n '_onEpisodicComponentReport: new component state handle = {} DescriptorVersion={}',\r\n desc_h, sc.DescriptorVersion)\r\n componentByHandle[sc.descriptorHandle] = sc\r\n else:\r\n if self._hasNewStateUsableStateVersion(oldStateContainer, sc, 'EpisodicComponentReport', is_buffered_report):\r\n self._logger.info(\r\n '_onEpisodicComponentReport: updated component state, handle=\"{}\" DescriptorVersion={}',\r\n desc_h, sc.DescriptorVersion)\r\n oldStateContainer.updateFromOtherContainer(sc)\r\n self.states.updateObject(oldStateContainer)\r\n componentByHandle[oldStateContainer.descriptorHandle] = oldStateContainer\r\n finally:\r\n self.componentByHandle = componentByHandle\r\n\r\n\r\n def _onDescriptionModificationReport(self, reportNode, is_buffered_report=False):\r\n '''The DescriptionModificationReport is sent if at least one Descriptor has been created, updated or deleted during runtime.\r\n It consists of 1...n DescriptionModificationReportParts.\r\n '''\r\n if not is_buffered_report and self._bufferNotification(reportNode, self._onDescriptionModificationReport):\r\n return\r\n newMdibVersion = int(reportNode.get('MdibVersion', '1'))\r\n if not self._canAcceptMdibVersion('_onDescriptionModificationReport', newMdibVersion):\r\n return\r\n descriptions_lookup_list = self._msgReader.readDescriptionModificationReport(reportNode)\r\n with self.mdibLock:\r\n self.mdibVersion = newMdibVersion\r\n self._updateSequenceId(reportNode)\r\n for descriptions_lookup in descriptions_lookup_list:\r\n newDescriptorByHandle = {}\r\n updatedDescriptorByHandle = {}\r\n\r\n # -- new --\r\n newDescriptorContainers, stateContainers = descriptions_lookup[pmtypes.DescriptionModificationTypes.CREATE]\r\n for dc in newDescriptorContainers:\r\n self.descriptions.addObject(dc)\r\n self._logger.debug('_onDescriptionModificationReport: created description \"{}\" (parent=\"{}\")',\r\n dc.handle, dc.parentHandle)\r\n newDescriptorByHandle[dc.handle] = dc\r\n for sc in stateContainers:\r\n # determine multikey\r\n if sc.isContextState:\r\n multikey = self.contextStates\r\n else:\r\n multikey = self.states\r\n multikey.addObject(sc)\r\n\r\n # -- deleted --\r\n deletedDescriptorContainers, stateContainers = descriptions_lookup[pmtypes.DescriptionModificationTypes.DELETE]\r\n for dc in deletedDescriptorContainers:\r\n self._logger.debug('_onDescriptionModificationReport: remove descriptor \"{}\" (parent=\"{}\")',\r\n dc.handle, dc.parentHandle)\r\n self.rmDescriptorHandleAll(dc.handle) # handling of self.deletedDescriptorByHandle inside called method\r\n\r\n # -- updated --\r\n updatedDescriptorContainers, stateContainers = descriptions_lookup[pmtypes.DescriptionModificationTypes.UPDATE]\r\n for dc in updatedDescriptorContainers:\r\n self._logger.info('_onDescriptionModificationReport: update descriptor \"{}\" (parent=\"{}\")',\r\n dc.handle, dc.parentHandle)\r\n container = self.descriptions.handle.getOne(dc.handle, allowNone=True)\r\n if container is None:\r\n pass\r\n else:\r\n container.updateDescrFromNode(dc.node)\r\n updatedDescriptorByHandle[dc.handle] = dc\r\n # if this is a context descriptor, delete all associated states that are not in\r\n # state_containers list\r\n if dc.isContextDescriptor:\r\n updated_handles = set([s.Handle for s in stateContainers if s.descriptorHandle == dc.handle])\r\n my_handles = set([s.Handle for s in self.contextStates.descriptorHandle.get(dc.handle, [])])\r\n to_be_deleted = my_handles - updated_handles\r\n for handle in to_be_deleted:\r\n st = multikey.handle.getOne(handle)\r\n self.contextStates.removeObjectNoLock(st)\r\n for sc in stateContainers:\r\n # determine multikey\r\n if sc.isContextState:\r\n multikey = self.contextStates\r\n oldstateContainer = multikey.handle.getOne(sc.Handle, allowNone=True)\r\n else:\r\n multikey = self.states\r\n oldstateContainer = multikey.descriptorHandle.getOne(sc.descriptorHandle, allowNone=True)\r\n if oldstateContainer is not None:\r\n oldstateContainer.updateFromOtherContainer(sc)\r\n multikey.updateObject(oldstateContainer)\r\n\r\n # write observables for every report part separately\r\n if newDescriptorByHandle:\r\n self.newDescriptorByHandle = newDescriptorByHandle\r\n if updatedDescriptorByHandle:\r\n self.updatedDescriptorByHandle = updatedDescriptorByHandle\r\n\r\n\r\n def _hasNewStateUsableStateVersion(self, oldStateContainer, newStateContainer, reportName, is_buffered_report):\r\n '''\r\n compare state versions old vs new\r\n :param oldStateContainer:\r\n :param newStateContainer:\r\n :param reportName: used for logging\r\n :return: True if new state is ok for mdib , otherwise False\r\n '''\r\n diff = int(newStateContainer.StateVersion) - int(oldStateContainer.StateVersion)\r\n # diff == 0 can happen if there is only a descriptor version update\r\n if diff == 1: # this is the perfect version\r\n return True\r\n elif diff > 1:\r\n self._logger.error('{}: missed {} states for state DescriptorHandle={} ({}->{})',\r\n reportName,\r\n diff - 1, oldStateContainer.descriptorHandle,\r\n oldStateContainer.StateVersion, newStateContainer.StateVersion)\r\n return True # the new version is newer, therefore it can be added to mdib\r\n elif diff < 0:\r\n if not is_buffered_report:\r\n self._logger.error(\r\n '{}: reduced state version for state DescriptorHandle={} ({}->{}) ',\r\n reportName, oldStateContainer.descriptorHandle,\r\n oldStateContainer.StateVersion, newStateContainer.StateVersion)\r\n return False\r\n else: # diff == 0:\r\n diffs = oldStateContainer.diff(newStateContainer) # compares all xml attributes\r\n if diffs:\r\n self._logger.error(\r\n '{}: repeated state version {} for state {}, DescriptorHandle={}, but states have different data:{}',\r\n reportName, oldStateContainer.StateVersion, oldStateContainer.__class__.__name__,\r\n oldStateContainer.descriptorHandle, diffs)\r\n return False\r\n\r\n\r\n def waitMetricMatches(self, handle, matchesfunc, timeout):\r\n ''' wait until a matching metric has been received. The matching is defined by the handle of the metric and the result of a matching function.\r\n If the matching function returns true, this function returns.\r\n @param handle: The handle string of the metric of interest.\r\n @param matchesfunc: a callable, argument is the current state with matching handle. Can be None, in that case every state matches\r\n Example:\r\n expected = 42\r\n def isMatchingValue(state):\r\n found = state.xpath('dom:MetricValue/@Value', namespaces=nsmap) # returns a list of values, empty if nothing matches\r\n if found:\r\n found[0] = int(found[0])\r\n return [expected] == found\r\n @param timeout: timeout in seconds\r\n @return: the matching state. In cas of a timeout it raises a TimeoutError exception.\r\n ''' \r\n fut = futures.Future()\r\n # define a callback function that sets value of fut\r\n def onMetricsByHandle(metricsByHandle):\r\n metric = metricsByHandle.get(handle)\r\n if metric is not None:\r\n if matchesfunc is None or matchesfunc(metric):\r\n fut.set_result(metric)\r\n try:\r\n properties.bind(self, metricsByHandle = onMetricsByHandle)\r\n begin = time.monotonic()\r\n ret = fut.result(timeout)\r\n self._logger.debug('waitMetricMatches: got result after {:.2f} seconds', time.monotonic() - begin)\r\n return ret\r\n finally:\r\n properties.unbind(self, metricsByHandle = onMetricsByHandle)\r\n\r\n\r\n def mkProposedState(self, descriptorHandle, copyCurrentState=True, handle=None):\r\n ''' Create a new state that can be used as proposed state in according operations.\r\n The new state is not part of mdib!\r\n\r\n :param descriptorHandle: the descriptor\r\n :param copyCurrentState: if True, all members of existing state will be copied to new state\r\n :param handle: if this is a multi state class, then this is the handle of the existing state that shall be used for copy.\r\n :return:\r\n '''\r\n descr = self.descriptions.handle.getOne(descriptorHandle)\r\n new_state = self.mkStateContainerFromDescriptor(descr)\r\n if copyCurrentState:\r\n lookup = self.contextStates if new_state.isContextState else self.states\r\n if new_state.isMultiState:\r\n if handle is None: # new state\r\n return new_state\r\n else:\r\n old_state = lookup.handle.getOne(handle)\r\n else:\r\n old_state = lookup.descriptorHandle.getOne(descriptorHandle)\r\n new_state.updateFromOtherContainer(old_state)\r\n return new_state\r\n\r\n def get_wf_age_stdev(self):\r\n means = []\r\n stdevs = []\r\n mins = []\r\n maxs = []\r\n for buf in self.rtBuffers.values():\r\n age_data = buf.get_age_stdev()\r\n means.append(age_data.mean_age)\r\n stdevs.append(age_data.stdev)\r\n mins.append(age_data.min_age)\r\n maxs.append(age_data.max_age)\r\n return _AgeData(mean(means), mean(stdevs), min(mins), max(maxs))\r\n","sub_path":"sdc11073/mdib/clientmdib.py","file_name":"clientmdib.py","file_ext":"py","file_size_in_byte":47641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"624096416","text":"import glob\nimport pickle\nimport os\nimport sys\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nimport persistent_homology\n\n\n\ndef load_data(pik_file):\n '''\n '''\n with open(pik_file, \"rb\") as IN:\n data = pickle.load(IN)\n\n return data\n\n\n\ndef make_latex_table(data):\n '''\n '''\n table = \"\"\" \\\\begin{center}\n \\\\begin{tabular}{|| c c c ||}\n \\\\hline\n Birth & Death & Basis \\\\\\\\\n \\\\hline\\\\hline\n \"\"\"\n for row in data:\n table += \" & \".join(row)\n table += \" \\\\\\\\\"\n table += \"\\n\"\n table += \"\\\\hline\"\n table += \"\\n\"\n table += \"\\\\end{tabular}\\n\"\n table += \"\\\\end{center}\"\n\n return table\n\n\ndef birth_death_plot_many(many_intervals):\n ''' Birth Death Plots\n '''\n\n fig, axs = plt.subplots(3, 4, figsize = (15, 15))\n\n labels = [\"H0\", \"H1\", \"H2\"]\n row = 0\n col = 0\n lims = [\n -1, # min of both axes\n 12, # max of both axes\n ]\n for title, intervals in many_intervals:\n max_weight = 0\n for key in intervals:\n birth = [e[0] for e in intervals[key]]\n death = [e[1] for e in intervals[key]]\n max_weight = max(max_weight, max(death))\n axs[row, col].scatter(birth, death, alpha = 0.5, s = 20, label = labels[key])\n axs[row, col].set_xlabel(\"Birth\")\n axs[row, col].set_ylabel(\"Death\")\n # now plot both limits against each other\n axs[row, col].plot(lims, lims, 'k-', alpha=0.75, zorder=0)\n axs[row, col].set_aspect('equal')\n axs[row, col].set_xlim(lims)\n axs[row, col].set_ylim(lims)\n axs[row, col].set_title(\"{}\".format(title) , fontweight = \"bold\")\n axs[row, col].legend(loc = \"lower right\")\n # max weight\n axs[row, col].axhline(y = max_weight)\n axs[row, col].axvline(x = max_weight)\n\n col += 1\n if col == 4:\n row += 1\n col = 0\n if row == 3:\n row = 0\n\n plt.suptitle(\"Birth Death Diagram\", fontweight = \"bold\")\n plt.tight_layout()\n plt.savefig(\"birth_death.png\")\n\n\n\ndef main(out_dir):\n '''\n '''\n\n all_intervals = []\n ## load picked data from disk\n for f in sorted(glob.glob(os.path.join(out_dir, \"*.data\"))):\n print(f)\n data = load_data(f)\n ## retrieve important datastructures\n fname, vr_complex, pivots, pivots_idx = data\n\n intervals, homol_ranks, homol = persistent_homology.persistence(\n pivots, pivots_idx,\n vr_complex.simplices_for_lookup,\n vr_complex.weights)\n\n sample = os.path.basename(fname).replace(\".csv\", \"\")\n all_intervals.append((sample, intervals))\n\n birth_death_plot_many(all_intervals)\n\n for sample, intervals in all_intervals:\n print(sample)\n persistent_homologies = persistent_homology.check_for_persistent_homologies(intervals, 10)\n homologies = list(((str(round(p[1], 2)), str(round(p[2], 2)), str(p[3])) for p in persistent_homologies))\n print(len(homologies))\n print(make_latex_table(homologies))\n print(\"-------------------------------\")\n\nif __name__ == '__main__':\n main(sys.argv[1])\n","sub_path":"assignment11.py","file_name":"assignment11.py","file_ext":"py","file_size_in_byte":3188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"35386758","text":"import os\n#import unittest\nimport sys\nsys.path.append(os.path.dirname(os.path.realpath(\n '/home/andreas/Documents/Internship/ncOrtho_to_distribute/ncortho_python'\n '/ncortho-python/ncortho/blastparser.py'))\n)\nfrom blastparser import BlastParser\n\ndef main():\n sample_genome = '/home/andreas/Documents/Internship/M.musculus_root/cm_retry/root/genome/Mus_musculus.chromosomes.fa'\n #sample_genome = '/share/project/andreas/miRNA_project/genomes/yeast/Saccharomyces_cerevisiae.R64-1-1.dna.chromosome.I.fa'\n hitlist = [('mmu-mir-574_c1', '2', '1', '78', '+', '107.4')]\n hitlist.append(('mmu-mir-574_c2', '2', '78', '1', '-', '107.4'))\n #hitlist = []\n #hitlist.append(('mir-1_c1', 'II', '2', '50', '+', '50.5'))\n print(hitlist)\n #hitlist.append(('mir-1_c2', 'VII', '526072', '526147', '+'))\n gp = GenomeParser(sample_genome, hitlist)\n hits = gp.extract_sequences()\n print(hits)\n\n# II - rna_aln - cm 1 77 73402 73326 - no 1 0.31 0.0 77.3 8.3e-16 ! dna:genescaffold genescaffold:vicPac1:GeneScaffold_587:1:293948:1 REF\n#VII - rna_aln - cm 1 77 526072 526147 + no 1 0.46 0.0 63.5 1.2e-11 ! dna:genescaffold genescaffold:vicPac1:GeneScaffold_2748:1:649003:1 REF\n \nif __name__ == '__main__':\n main()\n","sub_path":"ncortho/test/functional_test_blastparser.py","file_name":"functional_test_blastparser.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"196986653","text":"from requests import request as http_request\nimport json\n\n# api: https://apidocs.imgur.com/\n\nclass Imgur(object):\n client_id = '0e3018f09a810e1'\n client_secret = '6c34c57b9b1a0aac1b79f516b2f2908ecc0b0e80'\n username = 'pullupcz'\n refresh_token = '0f11739d6876349efa78960fcb3e4ee3110331d9' # nutná autorizace pro získání refresh_token\n access_token = '54235d35006443061c54158f2e13e6327fd5a778' # ručně zadané AT - možná bude potřeba reload, ale psali tam platnost na 3650 dnů ... :)\n _form = '------WebKitFormBoundary'\n _hash = '7MA4YWxkTrZu0gW'\n url = 'https://api.imgur.com/3/'\n\n def get_payload(self, **kwargs):\n \"\"\" složí payload - aby ty stringy nebyly tak dlouhý ... a nečitený \"\"\"\n item = self._form + self._hash + \"\\r\\nContent-Disposition: form-data; name=\\\"{name}\\\"\\r\\n\\r\\n{value}\\r\\n\"\n payload = \"\".join([item.format(name=key, value=value) for key, value in kwargs.items()])\n return payload + self._form + self._hash + \"--\"\n\n def request(self, method, url, headers, data=None):\n response = http_request(method, url, headers=headers, data=data)\n return response.json()\n\n def get_access_token(self):\n if self.access_token: return self.access_token # pokud mám access token tak jej použiju\n\n payload = self.get_payload(\n refresh_token=self.refresh_token,\n client_id=self.client_id,\n client_secret=self.client_secret,\n grant_type='refresh_token',\n )\n headers = {'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'}\n return self.request(\"POST\", \"https://api.imgur.com/oauth2/token\", headers, payload)\n\n def album_list(self):\n \"\"\"list ids of albums\"\"\"\n url = self.url + \"account/{username}/albums/ids/\".format(username=self.username)\n headers = {'Authorization': \"Bearer {accessToken}\".format(accessToken=self.get_access_token())}\n return self.request(\"GET\", url, headers)\n\n def album_create(self, nazev, popis, privacy='hidden'):\n \"\"\"Create a new album\"\"\"\n url = self.url + \"album\"\n payload = self.get_payload(title=nazev, description=popis, privacy=privacy)\n headers = {\n 'content-type': \"multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW\",\n 'Authorization': \"Bearer {accessToken}\".format(accessToken=self.get_access_token())\n }\n return self.request(\"POST\", url, headers, payload)\n\n def album_images(self, album_hash):\n \"\"\"Gets images from album\"\"\"\n url = self.url + \"album/{albumHash}/images\".format(albumHash=album_hash)\n headers = {'Authorization': 'Client-ID {clientId}'.format(clientId=self.client_id)}\n return self.request(\"GET\", url, headers)\n\n def image_upload(self, image, name, album):\n \"\"\"\n\n :param image: url or binary file or base64 (max size 10MB)\n :param name:\n :param album:\n :return:\n \"\"\"\n url = self.url + \"image\"\n payload = self.get_payload(image=image, name=name, album=album)\n headers = {\n 'content-type': \"multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW\",\n 'Authorization': \"Bearer {accessToken}\".format(accessToken=self.get_access_token())\n }\n return self.request(\"POST\", url, headers, payload)\n\n\nif __name__ == '__main__':\n client = Imgur()\n print(client.album_list())\n print(client.image_upload('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'test image 1', 'OKgmZlx'))\n ##################### integrovat do djanga a do třídy Media","sub_path":"_project/pullup/_/imgur.py","file_name":"imgur.py","file_ext":"py","file_size_in_byte":3431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"273451632","text":"from munkres import Munkres, print_matrix\nimport requests\nimport json\nimport math\n\ndef Hungarian(matrix,i):\n m = Munkres()\n indexes = m.compute(matrix)\n #print_matrix(matrix, msg='Minimum distance through this matrix:')\n total = 0\n for row, column in indexes:\n value = matrix[row][column]\n total += value\n y=cnos[column]\n z=i[row][column]\n print ('Agent %d will go to the customer %d at address no. %d and have to travel %d kms' % (row, y ,z, value))\n lax[row] = lcxs[column][i[row][column]]\n lay[row] = lcys[column][i[row][column]]\n print ('Minimum distance: %d kms' % total)\ndef URL(a,b,c,d): #https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=40.6655101,-73.89188969999998&destinations=40.6905615%2C-73.9976592&key=\n basic_link ='https://maps.googleapis.com/maps/api/distancematrix/'\n file_type='json?' #can use xml also\n units='units=metric&' #can also be imperial\n start_point='origins=%s,%s'%(a,b)\n end_point='&destinations=%s,%s&key='% (c,d)\n key=input(\"please enter your unique key\")\n URL= '%s%s%s%s%s%s'%(basic_link,file_type,units,start_point,end_point,key)\n return URL\ndef location():\n '''locationax= [float(x) for x in input(\"Please provide x coordinates of the agents:\\n\").split()]\n locationay=[float(x) for x in input(\"Please provide y coordinates of the agents:\\n\").split()]\n no_of_customers=int(input(\"How many customers do we have?\\n\"))\n locationcx=[]\n locationcy=[]\n rank=[]'''\n cno=[]\n locationax = [12.9716, 26.9124, 18.960]\n locationay = [77.5946, 75.7873, 72.820]\n\n locationcx = [[13.090, 23.030, 17.4, 18.53], [19.95, 28.6353, 22.570, 13.090],\n [19.95, 28.6353, 22.570, 13.090, 23.030, 17.4, 18.53], [19.076, 19.95]]\n locationcy = [[80.270, 72.580, 78.480, 73.840], [79.3, 77.225, 88.360, 80.270],\n [79.3, 77.225, 88.360, 80.270, 72.580, 78.480, 73.840], [72.8777, 79.3]]\n no_of_customers=4\n rank=[3,2,4,1]\n for x in range(no_of_customers):\n '''r = int(input(\"What is the priority of customer %d?\\n\" %(x)))\n lx = [float(x) for x in input(\"Please provide x coordinates of customer %d:\\n\" % (x)).split()]\n ly = [float(x) for x in input(\"Please provide y coordinates of customer %d:\\n\" % (x)).split()]\n rank.append(r)\n locationcx.append(lx)\n locationcy.append(ly)'''\n cno.append(x)\n\n return locationax,locationay,locationcx,locationcy, no_of_customers,rank,cno\ndef distance(i, j):\n l=[]\n for k in range(len(lcxs[j])):\n link=URL(lax[i],lay[i],lcxs[j][k],lcys[j][k])\n result = requests.get(link)\n data = (result.json())\n dist = data[\"rows\"][0][\"elements\"][0][\"distance\"][\"text\"]\n k = dist.split()\n m=float(k[0].replace(',', ''))\n l.append(m)\n #print(l)\n #print(min(l))\n return min(l), l.index(min(l))\ndef ordered(lcx, lcy,cno, rank):\n sorted_y_idx_list = sorted(range(len(rank)), key=lambda x: rank[x])\n lcxs = [lcx[i] for i in sorted_y_idx_list]\n lcys = [lcy[i] for i in sorted_y_idx_list]\n cnos=[cno[i] for i in sorted_y_idx_list]\n #print(lcxs)\n #print(lcys)\n #print(cnos)\n return lcxs, lcys, cnos\ndef update_everything():\n for j in range(len(lax)):\n del lcxs[0]\n del lcys[0]\n del cnos[0]\n\nlax, lay, lcx, lcy, noc, rank,cno= location()\nlcxs, lcys, cnos = ordered(lcx, lcy, cno, rank)\n\ndef run():\n Matrix = []\n shortest_address = []\n for f in range(len(lax)):\n r=[]\n i=[]\n for j in range(len(lax)):\n u,v=distance(f,j)\n k=float(u)\n r.append(k)\n i.append(v)\n Matrix.append(r)\n shortest_address.append(i)\n print (Matrix)\n Hungarian(Matrix,shortest_address)\n\nwhile len(lax)= 0.7)\n for pt in zip(*loc[::-1]):\n cv2.rectangle(frame, pt, (pt[0] + w, pt[1] + h), (0, 255, 0), 3)\n cv2.imshow(\"Frame\", frame)\n\n key = cv2.waitKey(1)\n if key == 27:\n break\n\nvideo.release()\ncv2.destroyAllWindows()\n","sub_path":"template_matching.py","file_name":"template_matching.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"516216864","text":"# -*- coding: utf-8 -*-\nimport spold2_reader as spold2\nimport utils, MasterData, excel_template_utils, os, shutil\ntemplate_folder = r'C:\\Dropbox (ecoinvent)\\ei-int\\technical\\external\\SRI\\data collection\\SRI_refinery\\Technical\\conversion'\ntemplate_filename = 'all_with_GLO_validated.xlsx'\ndf = utils.read_excel(template_folder, template_filename, None)\ntab = 'meta'\nc = df[tab]['geography'] == 'GLO'\nc = list(c.index)\ndf[tab].loc[c, 'technologyComment'] = 'The technology represents a weighted average. See geography comment for more details.'\ndfs = []\nfor tab in df:\n if tab in MasterData.excel_columns:\n df[tab] = utils.add_empty_columns(df[tab], MasterData.excel_columns[tab])\n dfs.append((df[tab], tab, MasterData.excel_columns[tab]))\n elif tab in excel_template_utils.columns_for_excel:\n dfs.append((df[tab], tab, excel_template_utils.columns_for_excel[tab]))\ntemplate_filename = 'all_with_GLO_validated_corrected.xlsx'\nutils.dataframe_to_excel(template_folder, template_filename, dfs, feedback = True)\n#template_filename = 'all_validated.xlsx'\nresult_folder = r'C:\\Dropbox (ecoinvent)\\ei-int\\technical\\external\\SRI\\data collection\\SRI_refinery\\Technical\\conversion\\spold'\nrestricted = False\nfs = spold2.template_to_spold2(template_folder, template_filename, \n result_folder, restricted = restricted)\nfilelist = utils.build_file_list(result_folder, 'spold')\nfor filename in filelist:\n f = spold2.Dataset(result_folder, filename)\n s = os.path.join(result_folder, filename)\n for i in range(1, 7):\n folder = os.path.join(result_folder, 'batch{}'.format(str(i)))\n d = os.path.join(folder, filename)\n if os.path.exists(d):\n shutil.copy(s, d)\n os.remove(s)\n break","sub_path":"projects/refinery/03_to_spold.py","file_name":"03_to_spold.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"254833813","text":"#!/usr/bin/env python3i\n#\n# srt - stable rt tooling\n#\n# Copyright (c) Siemens AG, 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE\n\nimport argparse\nfrom unittest import TestCase\n\nfrom stable_rt_tools.srt_util_context import SrtContext\n\n\ndef make_args(old_tag=None, new_tag=None):\n return argparse.Namespace(OLD_TAG=old_tag, NEW_TAG=new_tag)\n\n\nclass TestSrtContext(TestCase):\n def test_tag(self):\n ctx = SrtContext(make_args('v4.4.114-rt37', 'v4.4.115-rt38'), '/tmp')\n path = '/tmp/patches/v4.4.115-rt38'\n self.assertEqual(str(ctx.new_tag), 'v4.4.115-rt38')\n self.assertEqual(ctx.new_short_tag, '4.4.115-rt38')\n self.assertEqual(ctx.new_dir_patches, path)\n self.assertEqual(ctx.new_dir_series, path + '/patches')\n self.assertEqual(ctx.new_dir_mails, path + '/mails')\n self.assertEqual(ctx.new_fln_patch,\n path + '/patch-4.4.115-rt38.patch.xz')\n self.assertEqual(ctx.new_fln_tar,\n path + '/patches-4.4.115-rt38.tar.xz')\n\n def test_is_rc(self):\n ctx = SrtContext(\n make_args('v4.4.115-rt38', 'v4.4.115-rt39-rc1'), '/tmp')\n path = '/tmp/patches/v4.4.115-rt39-rc1/'\n files = [path + 'patch-4.4.115-rt39-rc1.patch.xz',\n path + 'patches-4.4.115-rt39-rc1.tar.xz']\n self.assertEqual(ctx.get_files(), files)\n\n def test_get_files(self):\n ctx = SrtContext(make_args('v4.4.115-rt38', 'v4.4.115-rt39'), '/tmp')\n\n path = '/tmp/patches/v4.4.115-rt39/'\n files = [path + 'patch-4.4.115-rt39.patch.xz',\n path + 'patches-4.4.115-rt39.tar.xz']\n self.assertEqual(ctx.get_files(), files)\n","sub_path":"stable_rt_tools/tests/test_srt_util_context.py","file_name":"test_srt_util_context.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"652361841","text":"from django.shortcuts import render,redirect,get_object_or_404\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.http import HttpResponseRedirect,HttpResponse, Http404\nfrom django.contrib.auth import login, authenticate\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom .forms import SignUpForm,ProjectForm,UpdateUserProfileForm,RateForm\nfrom rest_framework import status,viewsets\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom .models import Profile,Project,Rate\nfrom .serializer import ProfileSerializer,ProjectSerializer\nfrom django.urls import reverse\n\n# Create your views here.\ndef home(request):\n projects = Project.objects.all()\n rates = Rate.objects.all()\n users = User.objects.exclude(id=request.user.id)\n form = ProjectForm(request.POST or None, files=request.FILES) \n if form.is_valid():\n project=form.save(commit=False)\n project.user = request.user.profile\n project.save()\n return redirect('home')\n context = {\n 'projects': projects,\n 'form': form,\n 'users':users,\n 'rates':rates,\n }\n return render(request, 'home.html', context)\n\n return render(request,'home.html')\n\ndef signup(request):\n if request.method == 'POST':\n form = SignUpForm(request.POST)\n if form.is_valid():\n name = form.cleaned_data['username']\n email = form.cleaned_data['email']\n form.save()\n return redirect(\"/\")\n else:\n form = SignUpForm()\n return render(request, 'register/register.html', {'form': form}) \n\ndef search_project(request):\n rates = Rate.objects.all()\n if 'searchproject' in request.GET and request.GET[\"searchproject\"]:\n search_term = request.GET.get(\"searchproject\")\n searched_project = Project.search_by_name(search_term)\n message = f\"{search_term}\"\n context = {'projects':searched_project,'message': message}\n\n return render(request, \"search.html\",context)\n else:\n message = \"You haven't searched for any term\"\n return render(request, 'search.html',{\"message\":message}) \n\n@login_required(login_url='login')\ndef profile(request, username):\n projects = request.user.profile.projects.all()\n if request.method == 'POST':\n prof_form = UpdateUserProfileForm(request.POST, request.FILES, instance=request.user.profile)\n if prof_form.is_valid():\n prof_form.save()\n return redirect(request.path_info)\n else:\n prof_form = UpdateUserProfileForm(instance=request.user.profile)\n if request.method == \"POST\":\n form = ProjectForm(request.POST or None, files=request.FILES)\n if form.is_valid():\n project = form.save(commit=False)\n project.user = request.user.profile\n project.save()\n else:\n form = ProjectForm()\n\n context = {\n 'prof_form': prof_form,\n 'projects': projects,\n 'form':form,\n\n }\n return render(request, 'profile.html', context)\n\n@login_required(login_url='login')\ndef project(request,id):\n project = Project.objects.get(id =id)\n rates = Rate.objects.order_by('-date')\n current_user = request.user\n if request.method == 'POST':\n form = RateForm(request.POST)\n if form.is_valid():\n design = form.cleaned_data['design']\n usability = form.cleaned_data['usability']\n content = form.cleaned_data['content']\n rate = Rate()\n rate.project = project\n rate.user = current_user\n rate.design = design\n rate.usability = usability\n rate.content = content\n rate.average = (rate.design + rate.usability + rate.content)/3\n rate.save()\n return HttpResponseRedirect(reverse('project', args=(project.id,)))\n else:\n form = RateForm()\n context={\"project\":project,\"rates\":rates,\"form\":form}\n \n return render(request, 'project.html',context) \n\nclass ProfileList(APIView):\n def get(self, request, format=None):\n all_profiles = Profile.objects.all()\n serializers = ProfileSerializer(all_profiles, many=True)\n return Response(serializers.data)\n\n def post(self, request, format=None):\n serializers = ProfileSerializer(data=request.data)\n if serializers.is_valid():\n serializers.save()\n return Response(serializers.data, status=status.HTTP_201_CREATED)\n return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST) \n\nclass ProjectList(APIView):\n def get(self, request, format=None):\n all_projects = Project.objects.all()\n serializers = ProjectSerializer(all_projects, many=True)\n return Response(serializers.data)\n\n def post(self, request, format=None):\n serializers = ProjectSerializer(data=request.data)\n if serializers.is_valid():\n serializers.save()\n return Response(serializers.data, status=status.HTTP_201_CREATED)\n return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST) \n","sub_path":"projectapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"355449975","text":"import os, sys\n\ndef getHeader(w=160):\n return '''\\n\\n
    {day}
    {d}
    \\n'''.format(w)\n\ndef getFooter():\n return '''
    \\n\\n'''\n\ndef dealFile(f, path):\n if f[-4:].lower() == \".txt\":\n return ''' {0}\\n'''.format(open(os.path.join(path, f)).read().strip())\n else:\n return ''' \\n'''.format(f)\n\ndef generalHtml(w, smil, path):\n ret = getHeader(w)\n for e in smil:\n ret += dealFile(e, path)\n return ret + getFooter()\n\ndef decodeSmil(f):\n ret = []\n a = open(f).read()\n f1 = 'src=\"'\n f2 = '\"'\n f3 = 'width=\"'\n t1 = t2 = 0\n while t1 >= 0:\n t1 = a.find(f1, t1)\n if t1 > 0:\n t2 = a.find(f2, t1+len(f1))\n if t2 > 0:\n ret.append(a[t1+len(f1):t2])\n t1 = t2\n\n t1 = a.find(f3)\n t2 = a.find(f2, t1+len(f3))\n\n return int(a[t1+len(f3):t2]), ret\n\ndef makeHtml(f):\n width, smil = decodeSmil(f)\n html = generalHtml(width, smil, os.path.split(f)[0])\n open(\"/tmp/mobile/b.html\", \"w\").write(html)\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n makeHtml(sys.argv[1])\n","sub_path":"py/mms-smil.py","file_name":"mms-smil.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"554048889","text":"#!/usr/bin/python\n\n# python -W ignore main.py -c ./sample.txt -p Jaccard -a k-means -g ./sample-base.txt\n# python -W ignore main.py -c oryx.csv -p Jaccard -a k-means -g oryx-golden-label.csv -o ./proba/oryx\n\n\nimport argument_parser\nimport clustering\nimport coverage\nimport projection\nimport golden_standard\n\n\n\nprint(\"Start\")\narguments = argument_parser.arg_parser()\ncoverage_file = arguments[0]\nproj_type = arguments[1]\nalg_type = arguments[2]\ngolden_standard_path = arguments[3]\noutput_file = arguments[4]\nheatmap_rajzol = arguments[5] # default = False\n\n\n\n\n# matrix beolvasasa / feldolgozasa\ncov_matrix = coverage.CoverageMatrix(matrix_path=coverage_file)\ncov_matrix.matrix_parser()\ncov_matrix.graph_attribures(output_file)\n\n\n\n\n# a package alapu eredmeny beolvasasa\ngs = golden_standard.GoldenStandardHierarchy(golden_standard_path, cov_matrix.not_cevered_element)\ngs.heatmap_create(cov_matrix, output_file, bongeszo_rajzol_e=heatmap_rajzol)\n\n\n\n# projekciok vegrehajtasa\nprojections = projection.Projections(proj_type, cov_matrix)\nprojections.projections(cov_matrix)\n\n\n\n# klaszterezesek vegrehajtasa es az eredmenyek osszehasonlitasa\ncl_result = clustering.Clustering(alg_type, projections, cov_matrix, output_file+\"_\"+proj_type, gs.num_of_cluster)\ncl_result.clustering_and_compare(gs.golden_standard_results, heatmap_rajzol)\n\n\"\"\"\nalgorithms = ['louvain', 'louvain-with-projection', 'k-means', 'agglomerative', 'dbscan', 'birch',\n 'miniBatch', 'feature-agglomerative', 'affinity-propagation', 'meanShift']\n\nfor a in range(len(algorithms)):\n # klaszterezesek vegrehajtasa es az eredmenyek osszehasonlitasa\n cl_result = clustering.Clustering(algorithms[a], projections, cov_matrix, output_file+\"_\"+proj_type, gs.num_of_cluster)\n cl_result.clustering_and_compare(gs.golden_standard_results, heatmap_rajzol)\n\"\"\"\n\nprint(\"End\")\n\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"547777387","text":"from collections import defaultdict\nfrom operator import itemgetter\n\n# from pudb import set_trace; set_trace()\n\nfrom transduce import transduce\n\ndef translate(tr, rules):\n intext = \" \".join(tr.leaves())\n print(\"** Translating:\", intext)\n\n theresults = transduce(tr, rules)\n output_triples = set()\n string_weights = defaultdict(float)\n print('Finished transducing.')\n if not theresults:\n print(\" FAILED TO TRANSLATE O NOES.\")\n\n for (tree, weight) in theresults:\n treestr = tree.pprint(margin=1000)\n outtext = \" \".join(tree.leaves())\n string_weights[outtext] += float(weight)\n output_triples.add((treestr, outtext, float(weight)))\n \"\"\"\n for result in theresults:\n treestr = result.tree.pprint(margin=1000)\n outtext = \" \".join(result.tree.leaves())\n w = result.weight\n output_triples.add((treestr,outtext,w))\n \"\"\"\n\n inorder = sorted(string_weights.items(), key=itemgetter(1), reverse = True)\n return inorder\n","sub_path":"training/translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"630189381","text":"#!/usr/bin/env python\n# vim: set fileencoding=utf-8 :\n# Andre Anjos \n# Sun Jul 24 16:57:47 2011 +0200\n#\n# Copyright (C) 2011-2013 Idiap Research Institute, Martigny, Switzerland\n\n\"\"\"Tests bindings to the Visioner face detection framework.\n\"\"\"\n\nimport os\nimport nose.tools\nfrom ...test import utils\nfrom ... import io, ip\nfrom ...ip import test as iptest\nfrom ...io import test as iotest\n\nTEST_VIDEO = utils.datafile(\"test.mov\", iotest.__name__)\nIMAGE = utils.datafile('test-faces.jpg', iptest.__name__, os.path.join('data', 'faceextract'))\n\n@utils.visioner_available\ndef test_single():\n\n from .. import MaxDetector\n processor = MaxDetector(scanning_levels=10)\n locdata = processor(ip.rgb_to_gray(io.load(IMAGE)))\n assert locdata is not None\n\n@utils.visioner_available\n@utils.ffmpeg_found()\ndef test_faster():\n\n from .. import MaxDetector\n video = io.VideoReader(TEST_VIDEO)\n images = [ip.rgb_to_gray(k) for k in video[:20]]\n processor = MaxDetector(scanning_levels=10)\n\n # find faces on the video\n for image in images:\n locdata = processor(image)\n assert locdata is not None\n\n@utils.visioner_available\n@utils.ffmpeg_found()\n@nose.tools.nottest\ndef test_fast():\n\n from .. import MaxDetector\n video = io.VideoReader(TEST_VIDEO)\n images = [ip.rgb_to_gray(k) for k in video[:10]]\n processor = MaxDetector(scanning_levels=5)\n\n # find faces on the video\n for image in images:\n locdata = processor(image)\n assert locdata is not None\n\n@utils.visioner_available\n@utils.ffmpeg_found()\n@nose.tools.nottest\ndef test_thourough():\n\n from .. import MaxDetector\n video = io.VideoReader(TEST_VIDEO)\n images = [ip.rgb_to_gray(k) for k in video[:2]]\n processor = MaxDetector()\n\n # find faces on the video\n for image in images:\n locdata = processor(image)\n assert locdata is not None\n","sub_path":"python/bob/visioner/test/test_detection.py","file_name":"test_detection.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"30840353","text":"\nHEADER_CORE_METRICS = \"Core Metrics\"\nHEADER_TOTAL_COUNT = \"Total Count\"\n\nMETA_HEADERS = [HEADER_CORE_METRICS, HEADER_TOTAL_COUNT]\n\nCHARACTERS = \"Characters\"\nWORDS = \"Words\"\nSENTENCES = \"Sentences\"\nSYLLABLES = \"Syllables\"\nEASY_WORDS = \"Easy Words\"\nCOMPLEX_WORDS = \"Complex Words\"\n\nHEADER_ALGORITHM = \"Algorithm\"\nHEADER_SCORE = \"Score\"\nHEADER_DESCRIPTION = \"Description\"\n\nMETRICS_HEADERS = [HEADER_ALGORITHM, HEADER_SCORE, HEADER_DESCRIPTION]\n\nFRES = \"Flesch Reading Ease Score\"\nFKGL = \"Flesch-Kincaid Grade Level\"\nGFI = \"Gunning Fog Index\"\nARI = \"Automated Readability Index\"\nSMOG = \"Simple Measure of Gobbledygook\"\nCLI = \"Coleman-Liau Index\"\nLWS = \"Linsear Write Score\"\nFRY = \"Fry Readability Formula\"\n","sub_path":"code/common/Constants.py","file_name":"Constants.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"405179362","text":"\"\"\"\nUrl router for the administration site\n\"\"\"\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.urls import re_path\n\nfrom core_dashboard_common_app import constants as dashboard_constants\nfrom core_dashboard_common_app.views.common import views as common_views\nfrom core_explore_common_app.views.user import ajax as user_ajax\nfrom core_main_app.admin import core_admin_site\nfrom core_main_registry_app.settings import ENABLE_BLOB_ENDPOINTS\nfrom core_dashboard_registry_app.views.common import (\n views as registry_common_views,\n)\nfrom core_dashboard_registry_app.views.common.ajax import EditDataView\n\n\nadmin_urls = [\n # Admin\n re_path(\n r\"^records$\",\n staff_member_required(\n registry_common_views.DashboardRegistryRecords.as_view(\n allow_change_workspace_if_public=False,\n administration=True,\n template=dashboard_constants.ADMIN_DASHBOARD_TEMPLATE,\n )\n ),\n name=\"core_dashboard_records\",\n ),\n re_path(\n r\"^forms$\",\n staff_member_required(\n registry_common_views.DashboardRegistryForms.as_view(\n document=dashboard_constants.FUNCTIONAL_OBJECT_ENUM.FORM.value,\n administration=True,\n template=dashboard_constants.ADMIN_DASHBOARD_TEMPLATE,\n )\n ),\n name=\"core_dashboard_forms\",\n ),\n re_path(\n r\"^workspaces$\",\n staff_member_required(\n common_views.DashboardWorkspaces.as_view(\n administration=True,\n template=dashboard_constants.ADMIN_DASHBOARD_TEMPLATE,\n )\n ),\n name=\"core_dashboard_workspaces\",\n ),\n re_path(\n r\"^queries\",\n staff_member_required(\n common_views.DashboardQueries.as_view(\n administration=True,\n template=dashboard_constants.ADMIN_DASHBOARD_TEMPLATE,\n )\n ),\n name=\"core_dashboard_queries\",\n ),\n re_path(\n r\"^query/(?P\\w+)/(?P\\w+)\",\n staff_member_required(\n user_ajax.ContentPersistentQueryView.as_view(\n administration=True,\n template=\"core_explore_common_app/admin/persistent_query/view_query_content.html\",\n )\n ),\n name=\"core_explore_common_persistent_query_content\",\n ),\n re_path(\n r\"^workspace-list-records/(?P\\w+)$\",\n staff_member_required(\n registry_common_views.DashboardRegistryWorkspaceRecords.as_view(\n administration=True,\n template=dashboard_constants.ADMIN_DASHBOARD_TEMPLATE,\n )\n ),\n name=\"core_dashboard_workspace_list\",\n ),\n re_path(\n r\"^dashboard-data/(?P[\\w-]+)/edit/$\",\n staff_member_required(EditDataView.as_view()),\n name=\"core_dashboard_app_edit_data\",\n ),\n]\n\nif ENABLE_BLOB_ENDPOINTS:\n admin_urls.append(\n re_path(\n r\"^files$\",\n staff_member_required(\n common_views.DashboardFiles.as_view(\n administration=True,\n template=dashboard_constants.ADMIN_DASHBOARD_TEMPLATE,\n )\n ),\n name=\"core_dashboard_files\",\n ),\n )\n\nurls = core_admin_site.get_urls()\ncore_admin_site.get_urls = lambda: admin_urls + urls\n","sub_path":"core_dashboard_registry_app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"253308845","text":"import hmac\nimport hashlib\nimport base64\n\n\ndef compute_signature(message: str, api_secret: str) -> str:\n signature = hmac.new(\n key=api_secret.encode('utf-8'),\n msg=message.encode('utf-8'),\n digestmod=hashlib.sha256\n ).digest()\n return 'sha256=' + base64.b64encode(signature).decode('utf-8')\n","sub_path":"pypeform/hash.py","file_name":"hash.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"225463392","text":"from flask import Flask, render_template, request, send_file\nfrom io import BytesIO\nfrom werkzeug import FileStorage\n\nfrom src.bit import convert_int_into_bytes\nfrom src.block import get_blocks\nfrom src.conjugation import conjugate_blocks, get_conjugation_map\nfrom src.image import Image\nfrom src.psnr import calculate_psnr\nfrom src.vigenere import vigenere_pad, vigenere_cipher, vigenere_decipher\n\nBLOCK_SIZE = 8\n\napp = Flask(__name__)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n return render_template('index.html')\n\n\n@app.route('/insert', methods=['GET', 'POST'])\ndef insert():\n if request.method == 'GET':\n return render_template('insert.html')\n\n image = Image(request.files['image'])\n\n message = request.files['message'].read()\n length = len(message)\n name = request.files['message'].filename\n threshold = float(request.form['threshold'])\n\n if request.form.get('encrypt'):\n key = request.form['key']\n message = vigenere_pad(message)\n message = vigenere_cipher(message, key)\n\n if len(message) > image.get_payload(threshold):\n return 'The message is too long'\n\n blocks = get_blocks(message)\n conjugation_map = get_conjugation_map(blocks, threshold)\n conjugate_blocks(blocks, threshold, conjugation_map)\n\n image.concatenate_into_header(name.encode())\n image.concatenate_into_header(conjugation_map)\n image.concatenate_into_header(convert_int_into_bytes(length))\n\n if request.form.get('random'):\n seed = 0\n key = request.form['key']\n for char in key:\n seed += ord(char)\n image.insert_message_random(blocks, threshold, seed)\n else:\n image.insert_message(blocks, threshold)\n\n image.prepare_to_save()\n image.save()\n\n psnr = calculate_psnr(image.pixels, image.original_pixels, image.bpp)\n\n return render_template('result.html', filename=image.filename, psnr=psnr)\n\n\n@app.route('/extract', methods=['GET', 'POST'])\ndef extract():\n if request.method == 'GET':\n return render_template('extract.html')\n\n image = Image(request.files['image'])\n threshold = float(request.form['threshold'])\n\n filename, conjugation_map, length = image.parse_header()\n\n message = None\n if request.form.get('random'):\n seed = 0\n key = request.form['key']\n for char in key:\n seed += ord(char)\n message = image.extract_message_random(conjugation_map, threshold, seed)\n else:\n message = image.extract_message(conjugation_map, threshold)\n\n if request.form.get('encrypt'):\n key = request.form['key']\n message = vigenere_decipher(message, key)\n\n text_file = FileStorage(stream=BytesIO(message[:length]), filename=filename)\n return send_file(\n text_file, attachment_filename=filename, as_attachment=True)\n\n\n@app.route('/download/')\ndef download(filename):\n return send_file(\n 'static/' + filename, attachment_filename=filename, as_attachment=True)\n\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0')\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"69306847","text":"# -*- coding:utf-8 -*-\n\nfrom django.conf.urls import url\nfrom .views import *\n\nurlpatterns = [\n #入库迁移1.0 url\n url(r'^web1/', ftpln_web1, name='web1'),\n url(r'^data_processing/', data_processing, name='data_processing'),\n url(r'^parity/', parity, name='parity'),\n url(r'^delsfile/', del_sourse_file, name='delsfile'),\n url(r'^deldfile/', del_target_file, name='deldfile'),\n url(r'^reset/', reset, name='reset'),\n url(r'^logout/', logout, name='logout'),\n]","sub_path":"ftpln/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"162941744","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/4/21 11:24\n# @Author : Lwq\n# @File : 6-1.py\n# @Software: PyCharm\n\"\"\"\n更小的空间创建大量实例\n\"\"\"\nimport tracemalloc\n\n\nclass People1:\n def __init__(self, id, name, level):\n self.id = id\n self.name = name\n self.level = level\n\n\nclass People2:\n __slots__ = ['id', 'name', 'level']\n\n def __init__(self, id, name, level):\n self.id = id\n self.name = name\n self.level = level\n\n\n# p1 = People1(1, 'jim', 20)\n# p2 = People2(1, 'jim', 20)\n# print(p1.__dict__)\n# print('p1:', sys.getsizeof(p1.__dict__))\n# p1.x = 'x1231231231231'\n# print(p1.x)\n# p1.__dict__.pop('x')\n# print(p1.__dict__)\n# print('p1(x):', sys.getsizeof(p1.__dict__))\n\ntracemalloc.start()\n# f1 = [People1(1,2,3) for _ in range(100000)]\nf2 = [People2(1,2,3) for _ in range(100000)]\nsnapshot = tracemalloc.take_snapshot()\ntop_stats = snapshot.statistics('filename')\nfor stat in top_stats[:10]:\n print(stat)","sub_path":"unit6/6-2.py","file_name":"6-2.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"455315350","text":"# -*- coding: UTF-8 -*-\n\n\"\"\"\nurls.py:\nControlador especifico de la aplicacion api. Declaramos un enrutador en el cual metemos las urls a las\nvistas(viewsets) de nuestra api.\n\"\"\"\n\n# Importamos utilidades de patrones y urls\nfrom django.conf.urls import patterns, include, url\n# Importamos el DefaultRouter de RestFramework\nfrom rest_framework.routers import DefaultRouter\n# Importamos las vistas de nuestra api\nfrom api import views\n# Importamos las vistas para las fotos\nfrom api.views import FotoDetail, FotoList\n\nrouter = DefaultRouter()\nrouter.register(r'categorias', views.CategoriaViewSet)\nrouter.register(r'medicamentos', views.MedicamentoViewSet)\nrouter.register(r'entradas', views.EntradaViewSet)\nrouter.register(r'farmacias', views.FarmaciaViewSet)\nrouter.register(r'salidas', views.SalidaViewSet)\nrouter.register(r'noticias', views.NoticiaViewSet)\nrouter.register(r'noticiasRecientes', views.NoticiaRecienteViewSet)\n\nurlpatterns = patterns('',\n url(r'^', include(router.urls)),\n url(r'^fotos/(?P\\d+)$', FotoDetail.as_view(), name='foto-detail'),\n url(r'^fotos/$', FotoList.as_view(), name='foto-list'),\n)","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"179633478","text":"\nfrom ..base_loader import DataSetLoader\nfrom ...core.dataset import DataSet\nfrom ...core.instance import Instance\nfrom ...core.const import Const\n\n\nclass PeopleDailyCorpusLoader(DataSetLoader):\n \"\"\"\n 别名::class:`fastNLP.io.PeopleDailyCorpusLoader` :class:`fastNLP.io.data_loader.PeopleDailyCorpusLoader`\n\n 读取人民日报数据集\n \"\"\"\n\n def __init__(self, pos=True, ner=True):\n super(PeopleDailyCorpusLoader, self).__init__()\n self.pos = pos\n self.ner = ner\n\n def _load(self, data_path):\n with open(data_path, \"r\", encoding=\"utf-8\") as f:\n sents = f.readlines()\n examples = []\n for sent in sents:\n if len(sent) <= 2:\n continue\n inside_ne = False\n sent_pos_tag = []\n sent_words = []\n sent_ner = []\n words = sent.strip().split()[1:]\n for word in words:\n if \"[\" in word and \"]\" in word:\n ner_tag = \"U\"\n print(word)\n elif \"[\" in word:\n inside_ne = True\n ner_tag = \"B\"\n word = word[1:]\n elif \"]\" in word:\n ner_tag = \"L\"\n word = word[:word.index(\"]\")]\n if inside_ne is True:\n inside_ne = False\n else:\n raise RuntimeError(\"only ] appears!\")\n else:\n if inside_ne is True:\n ner_tag = \"I\"\n else:\n ner_tag = \"O\"\n tmp = word.split(\"/\")\n token, pos = tmp[0], tmp[1]\n sent_ner.append(ner_tag)\n sent_pos_tag.append(pos)\n sent_words.append(token)\n example = [sent_words]\n if self.pos is True:\n example.append(sent_pos_tag)\n if self.ner is True:\n example.append(sent_ner)\n examples.append(example)\n return self.convert(examples)\n\n def convert(self, data):\n \"\"\"\n\n :param data: python 内置对象\n :return: 一个 :class:`~fastNLP.DataSet` 类型的对象\n \"\"\"\n data_set = DataSet()\n for item in data:\n sent_words = item[0]\n if self.pos is True and self.ner is True:\n instance = Instance(\n words=sent_words, pos_tags=item[1], ner=item[2])\n elif self.pos is True:\n instance = Instance(words=sent_words, pos_tags=item[1])\n elif self.ner is True:\n instance = Instance(words=sent_words, ner=item[1])\n else:\n instance = Instance(words=sent_words)\n data_set.append(instance)\n data_set.apply(lambda ins: len(ins[Const.INPUT]), new_field_name=Const.INPUT_LEN)\n return data_set\n","sub_path":"fastNLP/io/data_loader/people_daily.py","file_name":"people_daily.py","file_ext":"py","file_size_in_byte":2945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"604134250","text":"import json\nimport datetime\n\nimport numpy as np\nfrom slugify import slugify\n\nimport constants\n\n\ndef read_player_data(season=None):\n with open('./data/players-by-team.json') as json_file:\n data = json.load(json_file)\n\n data = assign_guids(data)\n\n for _, player in data.items():\n player['general position'] = assign_general_position(player['position'])\n player['season'] = assign_season_to_player(player['url'])\n\n if season is not None:\n data = {guid: player_details for guid, player_details in data.items() if player_details['season'] == season}\n\n assert data, \"No match lineups to return, have you selected a valid season?\"\n\n return data\n\n\ndef read_match_data(season=None, sort=True):\n with open('./data/match-lineups-with-odds.json') as json_file:\n data = json.load(json_file)\n\n for match in data:\n match['info']['season'] = assign_season_to_match(match['info']['date'])\n\n for match in data:\n match['info']['season'] = assign_season_to_match(match['info']['date'])\n\n if season is not None:\n data = [match for match in data if match['info']['season'] == season]\n\n if sort:\n for match in data:\n match['info']['datetime'] = convert_date_to_datetime_object(match['info']['date'])\n data = sorted(data, key=lambda x: x['info']['datetime'])\n\n assert data, \"No match lineups to return, have you selected a valid season?\"\n\n return data\n\n\ndef read_fixtures_data():\n with open('./crawler/fixtures.json') as jsonfile:\n fixtures = json.load(jsonfile)\n\n for fixture in fixtures:\n fixture['datetime'] = convert_date_to_datetime_object(fixture['date'], string_format='%d.%m.%Y')\n\n fixtures = sorted(fixtures, key=lambda x: x['datetime'])\n\n return fixtures\n\n\ndef normalise_features(vector):\n assert isinstance(vector, np.ndarray)\n return ((vector - 50) / (100 - 50)).clip(min=0)\n\n\ndef convert_date_to_datetime_object(date, string_format='%d %B %Y'):\n return datetime.datetime.strptime(date, string_format)\n\n\ndef assign_season_to_match(date):\n\n date = convert_date_to_datetime_object(date)\n\n year = date.year\n month = date.month\n if month in [7, 8, 9, 10, 11, 12]:\n season = str(year) + '-' + str(year + 1)\n else:\n season = str(year - 1) + '-' + str(year)\n return season\n\n\ndef assign_season_to_player(url):\n url = url.split('/')[-2]\n season = constants.PLAYER_URL_TO_SEASON.get(url, '2017-2018')\n return season\n\n\ndef assign_guids(data):\n for i, player in enumerate(data):\n player['guid'] = i\n guid_conversion = {player['guid']: player for player in data}\n return guid_conversion\n\n\ndef assign_general_position(position):\n return constants.EXACT_TO_GENERIC[position]\n\n\ndef assign_odds_to_match(matchlineups, fd):\n for match in matchlineups:\n for index, row in fd.iterrows():\n try:\n home_team = constants.FOOTBALL_DATA_TEAM_MAPPINGS['2014-2015'][match['info']['home team']]\n away_team = constants.FOOTBALL_DATA_TEAM_MAPPINGS['2014-2015'][match['info']['away team']]\n\n except KeyError:\n home_team = None\n away_team = None\n\n if home_team == slugify(row['HomeTeam']) and away_team == slugify(row['AwayTeam']):\n if datetime.datetime.strptime(match['info']['date'], '%d %B %Y') == datetime.datetime.strptime(row['Date'], '%d/%m/%y'):\n match['info']['home odds'] = row['PSH']\n match['info']['draw odds'] = row['PSD']\n match['info']['away odds'] = row['PSA']\n\n return matchlineups\n\n\ndef get_goals(match):\n return match['info']['home goals'], match['info']['away goals']\n\n\ndef get_season(match):\n return match['info']['season']\n\n\ndef get_lineup_names(match):\n return match['info']['home lineup names'], match['info']['away lineup names']\n\n\ndef get_teams(match):\n return constants.LINEUP_TO_PLAYER_TEAM_MAPPINGS['ALL'][match['info']['home team']], \\\n constants.LINEUP_TO_PLAYER_TEAM_MAPPINGS['ALL'][match['info']['away team']]\n\n\ndef get_lineup_numbers(match):\n return match['info']['home lineup numbers'], match['info']['away lineup numbers']\n\n\ndef get_lineup_nationalities(match):\n return match['info']['home lineup nationalities'], match['info']['away lineup nationalities']\n\n\ndef get_match_odds(match):\n return match['info']['home odds'], match['info']['draw odds'], match['info']['away odds']","sub_path":"data_methods.py","file_name":"data_methods.py","file_ext":"py","file_size_in_byte":4471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"199179578","text":"import tkinter as tk\nimport random\nfrom settings import *\n\nroot = tk.Tk()\nheight = 700\nwidth = 700\nc = tk.Canvas(root, height = height, width = width)\n\ndef drawGrid():\n root.mainloop()\n\ndef createGrid():\n w_const = (width - 10) / DIM\n h_const = (height - 10) / DIM\n x1 = 5\n y1 = 5\n x2 = w_const + 5\n y2 = h_const + 5\n for i in range(DIM):\n for j in range(DIM):\n rect = c.create_rectangle(x1, y1, x2, y2, fill=\"white\", outline = 'black')\n x1 = x2\n x2 += h_const\n y1 += h_const\n y2 += h_const\n x2 = w_const + 5\n x1 = 5\n c.pack()\n root.title(\"Maze World\")\n","sub_path":"HW1/draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"10123142","text":"from django.urls import path\nfrom products.views import (\n product_detail_view,\n product_create_view,\n dynamic_lookup_view,\n product_delete_view,\n product_list_view,\n )\n\napp_name = \"products\"\nurlpatterns = [\n\n path('create', product_create_view, name='create'),\n path('product', product_detail_view, name='product'),\n path('', product_list_view, name='products'),\n \n path('/', dynamic_lookup_view, name='one_product'),\n path('/delete', product_delete_view, name='delete'),\n]","sub_path":"src/products/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"452148812","text":"import glob\nimport os\nimport re\nimport sys\n\nfrom ..core import BaseApp\n\n\nclass Maya(BaseApp):\n\n name = 'maya'\n\n @classmethod\n def iter_installed(cls):\n if sys.platform == 'darwin':\n for path in glob.glob('/Applications/Autodesk/maya20*/Maya.app'):\n app = cls.app_from_path(path)\n if app:\n yield app\n elif sys.platform == 'linux2':\n for path in glob.glob('/usr/autodesk/maya20*'):\n app = cls.app_from_path(path)\n if app:\n yield app\n else:\n pass #raise NotImplementedError(sys.platform)\n\n @classmethod\n def app_from_path(cls, path):\n if sys.platform == 'darwin':\n m = re.match(r'^/Applications/Autodesk/maya(\\d{4}(?:\\.\\d+)?)/Maya.app($|/)', path)\n if m:\n return cls(m.group(0), m.group(1))\n if sys.platform == 'linux2':\n m = re.search(r'maya(\\d{4}(?:\\.\\d+)?)(/|$)', path)\n if m:\n return cls(path, m.group(1))\n\n @classmethod\n def get_running_app(cls):\n try:\n import maya.cmds\n import maya.utils\n except ImportError:\n return\n return cls.app_from_path(maya.utils.__file__)\n\n def export(self, environ):\n environ.add('PYTHONPATH', os.path.abspath(os.path.join(\n __file__, '..', 'sandbox'\n )))\n\n def get_command(self):\n if sys.platform == 'darwin':\n return ['%s/Contents/MacOS/Maya' % self.path]\n elif sys.platform == 'linux2':\n return ['%s/bin/maya%s' % (self.path, self.version)]\n else:\n raise NotImplementedError(sys.platform)\n\n def get_python(self):\n if sys.platform == 'darwin':\n return '%s/Contents/bin/mayapy' % self.path\n elif sys.platform == 'linux2':\n return '%s/bin/mayapy' % self.path\n raise NotImplementedError(sys.platform)\n\n def get_site_packages(self):\n if sys.platform == 'darwin':\n return '%s/Contents/Frameworks/Python.framework/Versions/Current/lib/python2.7/site-packages' % self.path\n elif sys.platform.startswith('linux'):\n return '%s/lib/python2.7/site-packages' % self.path\n\n\n\ndef standalone_initialize():\n \"\"\"Called during Maya startup to initialize standalone mode.\"\"\"\n # NOTE: Initializing before the GUI is setup will segfault it, so we have to\n # be a little careful to not do that.\n # OS X Maya.app -> /Applications/Autodesk/maya2015/Maya.app/Contents/MacOS/Maya\n # OS X Python -> /Applications/Autodesk/maya2015/Maya.app/Contents/bin/../Frameworks/Python.framework/Versions/Current/Resources/Python.app/Contents/MacOS/Python\n if os.path.basename(sys.executable).lower().startswith('python'):\n\n # Don't initialize again; it causes problems sometimes.\n # I don't really know how you could get here without running initialize\n # already, because how else would the userSetup.py get imported?\n from maya import cmds, standalone\n if hasattr(cmds, 'ls'):\n return\n\n standalone.initialize()\n\ndef gui_initialize():\n if not os.path.basename(sys.executable).lower().startswith('python'):\n from ... import init\n init('maya.gui')","sub_path":"appinit/apps/maya/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"45291630","text":"from blanc import BlancHelp\nimport pandas as pd\nimport random\nimport nltk\nimport argparse\nfrom utils import Defaults\nnltk.download('punkt')\nnltk.download('words')\nfrom nltk.corpus import words\n\nrandom.seed(1)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n '--type', type=str,\n default='standard',\n help='Type of analysis'\n )\nparser.add_argument(\n '--gap',\n type=int,\n help='distance between words to mask during inference',\n default=Defaults.gap,\n )\nparser.add_argument(\n '--min_token_length_normal',\n type=int,\n help=(\n 'minimum number of chars in normal tokens to mask, where a normal token is '\n 'a whole word'\n ),\n default=Defaults.min_token_length_normal,\n )\nparser.add_argument(\n '--min_token_length_lead',\n type=int,\n help='minimum number of chars in lead token to mask, where a lead token begins a word',\n default=Defaults.min_token_length_lead,\n )\nparser.add_argument(\n '--min_token_length_followup',\n type=int,\n help=(\n 'minimum number of chars in followup token to mask, where a followup token '\n 'continues a word'\n ),\n default=Defaults.min_token_length_followup,\n )\nparser.add_argument(\n '--device',\n type=str,\n help='cpu or cuda device',\n default=Defaults.device,\n )\nparser.add_argument(\n '--model_name',\n type=str,\n help='Select model cased or uncased',\n default=Defaults.model_name\n )\nparser.add_argument(\n '--n_tokens',\n type=int,\n help='Number of replaced words in translation',\n default=1\n )\nparser.add_argument(\n '--output_name',\n type=str,\n default=\"ru_en_blanc\",\n help='Output file name')\n\nparser.add_argument(\n '--base',\n type=int,\n help='Base model or your pritrained',\n default=Defaults.base,\n )\n\nargs = parser.parse_args()\n\n\nru_en_train = pd.read_csv('train.ruen.df.short.tsv', sep='\\t', header=0)\n# ru_en_train = ru_en_train.sample(100)\n# ru_en_train = ru_en_train.reset_index(drop=True)\n\nprint(ru_en_train.head())\n\nblanc_help = BlancHelp(gap=args.gap,\n base=args.base,\n model_name=args.model_name,\n min_token_length_normal=args.min_token_length_normal,\n min_token_length_lead=args.min_token_length_lead,\n min_token_length_followup=args.min_token_length_followup,\n device=args.device\n )\n\nif args.type == 'standard':\n\n score, total_unks = blanc_help.eval_pairs(ru_en_train.original, ru_en_train.translation)\n\n print(\"Total number of UNKs: \", total_unks)\n\n ru_en_train['score'] = score\n\n ru_en_train.to_csv(args.output_name + \".csv\", sep=',', index=False)\n\n\n# For random shuffle\nelif args.type == 'shuffle':\n t_unks = 0\n for i in range(len(ru_en_train)):\n\n # shuffle words in a sentences\n en_words = ru_en_train.translation[i].split()\n random.shuffle(en_words)\n new_translation = ' '.join(en_words)\n summary = new_translation\n\n document = ru_en_train.original[i]\n\n blanc_score, total_unks = blanc_help.eval_once(document, summary)\n ru_en_train.loc[i, 'score'] = blanc_score\n t_unks += total_unks\n print(\"Total number of UNKs: \", t_unks)\n ru_en_train.to_csv(args.output_name + \".csv\", sep=',', index=False)\n\n# For random words replacement\nelif args.type == 'replace':\n\n word_list = words.words()\n t_unks = 0\n for i in range(len(ru_en_train)):\n\n # shuffle words in a sentences\n print(ru_en_train.translation[i])\n sen_words = ru_en_train.translation[i].split()\n\n cnt = 0\n attempt = 0\n status = True\n\n while cnt < args.n_tokens:\n\n random.shuffle(word_list)\n n = random.randint(0, len(sen_words)-1)\n attempt += 1\n # print(sen_words[n])\n if attempt < 100:\n if len(sen_words[n]) > 3:\n\n for ran_word in word_list:\n\n if len(ran_word) != len(sen_words[n]):\n continue\n\n sen_words[n] = ran_word\n\n # print(sen_words[n])\n cnt += 1\n break\n else:\n break\n\n new_translation = ' '.join(sen_words)\n\n print(new_translation)\n\n summary = new_translation\n\n document = ru_en_train.original[i]\n\n blanc_score, total_unks = blanc_help.eval_once(document, summary)\n t_unks += total_unks\n print(\"Blanc score: \", blanc_score)\n ru_en_train.loc[i, 'score'] = blanc_score\n print(\"Total number of UNKs: \", t_unks)\n ru_en_train.to_csv(args.output_name + \".csv\", sep=',', index=False)\n\n# Set translation as document\nelif args.type == 'oposite':\n score, total_unks = blanc_help.eval_pairs(ru_en_train.translation, ru_en_train.original)\n\n ru_en_train['score'] = score\n\n ru_en_train.to_csv(args.output_name + \".csv\", sep=',', index=False)\n print(\"Total number of UNKs: \", total_unks)\nelse:\n print('Uknown option. Please read documentation')\n","sub_path":"blanc_mt/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":6027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"376040819","text":"from django import forms\nfrom django.contrib.auth.models import User\n\n\nclass EmailRegistrationForm(forms.Form):\n\n email = forms.EmailField(label=(\"E-mail\"))\n\n def save(self):\n \"\"\"\n Save this form's self.instance object if commit=True. Otherwise, add\n a save_m2m() method to the form which can be called after the instance\n is saved manually at a later time. Return the model instance.\n \"\"\"\n if self.errors:\n raise ValueError(\n (\"The User could not be created because the data didn't\"\n \" validate.\")\n )\n try:\n return User.objects.get(username=self.cleaned_data['email'])\n except User.DoesNotExist:\n return User.objects.create_user(\n self.cleaned_data['email'], self.cleaned_data['email']\n )\n","sub_path":"main/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"295803449","text":"#An irrational decimal fraction is created by concatenating the positive integers:\n\n#0.123456789101112131415161718192021...\n\n#It can be seen that the 12th digit of the fractional part is 1.\n\n#If dn represents the nth digit of the fractional part, find the value of the following expression.\n\n#d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000\n\nimport timeit\nNumbers = [1,10,100,1000,10000,100000,1000000]\nanswers=[]\ndef get(i):\n if i <= 8:\n answers.append(i+1)\n if i > 8 and i <= 188:\n number = int(10+((i-8)/2))\n _index = ((i-8)%2)\n if _index == 0:\n answers.append(int(str(number-1)[-1]))\n else:\n answers.append(int(str(number)[_index-1]))\n \n if i > 188 and i <= 2888:\n number = int(100+((i-188)/3))\n _index = ((i-188)%3)\n if _index == 0:\n answers.append(int(str(number-1)[-1]))\n else:\n answers.append(int(str(number)[_index-1]))\n\n if i > 2888 and i <=38888:\n number = int(1000+((i-2888)/4))\n _index = ((i-2888)%4)\n if _index ==0:\n answers.append(int(str(number-1)[-1]))\n else: \n answers.append(int(str(number)[_index-1]))\n if i >38888 and i <=488888:\n number = int(10000+((i-38888)/5))\n _index = ((i-38888)%5)\n if _index == 0: \n answers.append(int(str(number-1)[-1]))\n else:\n answers.append(int(str(number)[_index-1]))\n if i >488888 and i <=5888888:\n number = int(100000 + ((i-488888)/6))\n _index = ((i-488888)%6)\n if _index == 0:\n answers.append(int(str(number-1)[-1]))\n else:\n answers.append(int(str(number)[_index-1]))\n elif i>5888888:\n print('ERROR','requested value out of known range the final value of the known length of the decimal is ...1000000')\n\ndef Problem40():\n for i in Numbers:\n get(i)\n print(answers)\n answer = 0\n for a in answers:\n answer += int(a)\n print(answer)\n\nelapsed_time = timeit.timeit(Problem40, number=1)\n\nprint(elapsed_time)\n#answer = numbers[0], numbers[9], numbers[99], numbers[999], numbers[9999],numbers[99999],numbers[999999]\n#print(answer)\n","sub_path":"Project Euler/Complete/040_Champernowne's_constant.py","file_name":"040_Champernowne's_constant.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"76070769","text":"##########################################################################\n#\n# Copyright (c) 2014, Esteban Tovagliari. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# * Redistributions of source code must retain the above\n# copyright notice, this list of conditions and the following\n# disclaimer.\n#\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided with\n# the distribution.\n#\n# * Neither the name of John Haddon nor the names of\n# any other contributors to this software may be used to endorse or\n# promote products derived from this software without specific prior\n# written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n# IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n##########################################################################\n\nimport functools\n\nimport appleseed\n\nimport IECore\n\nimport GafferUI\nimport GafferAppleseed\n\ndef appendLights( menuDefinition, prefix=\"/Appleseed\" ) :\n\n\t__addToMenu( menuDefinition, prefix + \"/Environment/\", \"latlong_map_environment_edf\", \"Skydome\" )\n\t__addToMenu( menuDefinition, prefix + \"/Environment/\", \"hosek_environment_edf\", \"Physical Sky\" )\n\n\tlightModelsToExpose = [ \"point_light\", \"directional_light\", \"spot_light\" ]\n\n\tfor model in appleseed.Light.get_input_metadata() :\n\t\tif model in lightModelsToExpose :\n\t\t\t__addToMenu( menuDefinition, prefix + \"/Light/\", model )\n\n\tedfModelsToExpose = [ \"diffuse_edf\" ]\n\n\tfor model in appleseed.EDF.get_input_metadata() :\n\t\tif model in edfModelsToExpose :\n\t\t\t__addToMenu( menuDefinition, prefix + \"/Light/\", model )\n\ndef __lightCreator( name ) :\n\n\tlight = GafferAppleseed.AppleseedLight( name )\n\tlight.loadShader( name )\n\treturn light\n\ndef __addToMenu( menuDefinition, prefix, model, displayName = None ) :\n\n\tif displayName == None :\n\t\tdisplayName = __displayName( model )\n\n\tmenuPath = prefix + displayName\n\tmenuDefinition.append(\n\t\tmenuPath,\n\t\t{\n\t\t\t\"command\" : GafferUI.NodeMenu.nodeCreatorWrapper( functools.partial( __lightCreator, model ) ),\n\t\t\t\"searchText\" : \"as\" + displayName.replace( \" \", \"\" ),\n\t\t}\n\t)\n\ndef __displayName( model ) :\n\n\tif model == \"diffuse_edf\":\n\t\treturn \"Rect\"\n\n\tdisplayName = \" \".join( [ IECore.CamelCase.toSpaced( x ) for x in model.split( \"_\" ) ] )\n\tdisplayName = displayName.replace(\" Light\", \"\" )\n\tdisplayName = displayName.replace(\" Environment Edf\", \"\" )\n\treturn displayName\n","sub_path":"python/GafferAppleseedUI/LightMenu.py","file_name":"LightMenu.py","file_ext":"py","file_size_in_byte":3348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"399892185","text":"import socket\nfrom thread import *\n\n# crating the socket\ns = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\nhost = '127.0.0.1'\nport = 5000\n\n#connecting to the server\ntry:\n\ts.connect((host,port))\nexcept:\n\tprint(\"[log]: Cant connect to the server\")\n\texit()\n\nrecv_thread = ClientThread(s)\nrecv_thread.daemon = True\nrecv_thread.start()\n\nwhile True:\n\tx = input(\">\")\n\ttry:\n\t\trecv_thread.send(x)\n\texcept:\n\t\tprint(\"[log]: Cant connect to the server\")\n\t\texit()\n\t\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"393599548","text":"\n\ndef make_averager():\n count = 0\n sum = 0\n\n def averager(new_value):\n nonlocal count, sum\n count += 1\n sum += new_value\n return sum/count\n\n return averager\n\navg = make_averager()\nprint(avg(10))\nprint(avg(11))\nprint(avg(12))","sub_path":"07-closure-deco/average_2.py","file_name":"average_2.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"545360640","text":"from sklearn.preprocessing import RobustScaler\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.decomposition import PCA\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.pipeline import Pipeline, FeatureUnion\nfrom xgboost import XGBClassifier\nTARGET='binary_bin'\nPARAMETER_GRID = {\n 'f__pca__n_components':[2, 3, 4, 8],\n 'f__kbest__k':[10, 20],\n 'c__n_estimators': [10, 100, 500],\n 'c__objective': ['binary:logistic'],\n 'c__eval_metric': ['aucpr'], # Evaluation metrics for validation data during tree building\n 'c__subsample': [1], # Subsample ratio of the training instances. Setting it to 0.5 means that XGBoost would randomly sample half of the training data prior to growing trees.\n 'c__colsample_bytree': [1, 0.8, 0.5], # Subsample ratio of columns when constructing each tree. Subsampling occurs once for every tree constructed.\n 'c__colsample_bylevel': [1, 0.8, 0.5], # Subsample ratio of columns for each level. Subsampling occurs once for every new depth level reached in a tree. Columns are subsampled from the set of columns chosen for the current tree.\n 'c__colsample_bynode': [1, 0.8, 0.4],# Subsample ratio of columns for each node (split). Subsampling occurs once every time a new split is evaluated. Columns are subsampled from the set of columns chosen for the current level.\n 'c__num_parallel_tree': [1, 2], # Number of parallel trees constructed during each iteration. This option is used to support boosted random forest.\n 'c__max_depth': [1, 2, 3], # Maximum depth of a tree. Increasing this value will make the model more complex and more likely to overfit.\n 'c__reg_alpha': [0], # L1 regularization term on weights. Increasing this value will make model more conservative.\n 'c__reg_lambda': [1], # L2 regularization term on weights. Increasing this value will make model more conservative.\n 'c__learning_rate': [0.001, 0.005], # 0.3 Step size shrinkage used in update to prevents overfitting. Shrinks the feature weights to make the boosting process more conservative.\n 'c__scale_pos_weight': [1] # should be negative_samples_count / positive_samples_count\n}\n\nestimator = Pipeline([\n ('i', SimpleImputer()), # Replace nan's with the median value between previous and next observation\n ('s', RobustScaler()), # Scale data in order to center it and increase robustness against noise and outliers\n ('f', FeatureUnion([\n ('pca', PCA()),\n ('kbest', SelectKBest())\n ])),\n ('c', XGBClassifier()),\n])","sub_path":"pipelines/pca_kbest_xgboost.py","file_name":"pca_kbest_xgboost.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"111353899","text":"__author__ = \"Rustam Safin\"\nfrom chaco.tools.api import LineInspector\nfrom traits.api import Any, Bool\n\n\nclass ValueInspector(LineInspector):\n \"\"\"\n Value Inspector only for BaseXYPlots\n \"\"\"\n\n on_move = Any\n cross = Bool(False)\n\n def __init__(self, *args, **kwargs):\n super(ValueInspector, self).__init__(*args, **kwargs)\n\n assert self.on_move, kwargs\n\n def draw(self, gc, view_bounds=None):\n plot = self.component\n if plot is None:\n return\n\n if self.is_listener:\n tmp = self._get_screen_pts()\n elif self.is_interactive:\n tmp = self._last_position\n\n if tmp:\n sy, sx = tmp\n self._draw_vertical_line(gc, sx)\n if self.cross:\n self._draw_horizontal_line(gc, sy)\n\n def normal_mouse_move(self, event):\n plot = self.component\n if plot is not None and self.is_interactive:\n self._last_position = (event.y, event.x)\n index_coord, value_coord = self._map_to_data(event.y, event.x)\n plot.index.metadata[self.metadata_name] = index_coord\n plot.value.metadata[self.metadata_name] = value_coord\n\n plot.request_redraw()\n self.on_move(index_coord, value_coord)\n\n\nclass ManyValuesInspector(ValueInspector):\n def __init__(self, *args, **kwargs):\n super(ManyValuesInspector, self).__init__(*args, **kwargs)\n\n def _map_to_data_many(self, x, y):\n plot = self.component\n index = plot.index_mapper.map_data(x)\n value = plot.value_mapper.map_data(y)\n values = []\n\n #indexData = list(plot.index.get_data())\n indexData = plot.all_idx.get_data()\n\n if index < indexData[0]:\n drive_id = indexData[0]\n elif index > indexData[-1]:\n drive_id = indexData[-1]\n else:\n for i, d in enumerate(indexData):\n if round(index) == d:\n drive_id = d\n break\n\n for p in plot.container.components[-1:]:\n values.append(p.info.get_data(drive_id, value))\n\n return index, value, values\n\n def normal_mouse_move(self, event):\n plot = self.component\n self._last_position = (event.y, event.x)\n index, value, values = self._map_to_data_many(event.y, event.x)\n\n plot.index.metadata[self.metadata_name] = index\n plot.value.metadata[self.metadata_name] = value\n\n plot.request_redraw()\n self.on_move(index, value, values)\n","sub_path":"src/core/chaco/line_inspector.py","file_name":"line_inspector.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"323900213","text":"import unittest\n\nfrom app import app, db\nfrom app.models import Note\nfrom counter import count_unique_words\n\n\nclass TestNoteModel(unittest.TestCase):\n\n def setUp(self):\n # database in memory\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'\n db.create_all()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n\n def test_validation(self):\n with self.assertRaises(ValueError):\n Note(text=None, unique_count=None)\n with self.assertRaises(ValueError):\n Note(text='', unique_count=0)\n with self.assertRaises(ValueError):\n Note(text=' ', unique_count=0)\n with self.assertRaises(ValueError):\n Note(text='a ' * 900, unique_count=1) # long string\n\n # success\n self.assertTrue(Note(text='text', unique_count=1))\n\n def test_all_ordered(self):\n strings = [' three,, words here', 'one', 'lol lol lol lol kek',\n ' ....??... ', 'the biggest note in this test']\n\n for string in strings:\n db.session.add(Note(\n text=string,\n unique_count=count_unique_words(string)\n ))\n db.session.commit()\n\n notes_db = [\n (note.text, note.unique_count) for note in Note.ordered_all()\n ]\n\n # sort original notes\n notes_original = sorted(\n ((s, count_unique_words(s)) for s in strings),\n key=lambda item: item[1], # by count\n reverse=True\n )\n\n self.assertEqual(notes_db, notes_original)\n","sub_path":"tests/test_note_model.py","file_name":"test_note_model.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"101486051","text":"from random import randint\r\nfrom time import sleep\r\nimport Error as err\r\nimport sujet as suj\r\nclass Orydie:\r\n\r\n\tdef __init__(self,name, ammo, damage):\r\n\t\tself.name = name\r\n\t\tself.ammo = ammo\r\n\t\tself.damage = damage\r\n\tdef vistrel(self, ammo,damage, target):\r\n\t\tif ammo > 0:\r\n\t\t\tprint(\"Вы выстрелили в\",target.name)\r\n\t\t\ttarget.healght -= damage\r\n\t\t\tammo -= 1\r\n\t\telse:\r\n\t\t\tprint(\"У вас закончились патроны\")\r\nclass Human:\r\n\tdef __init__(self,name, healght, damage):\r\n\t\tself.healght = healght\r\n\t\tself.damage = damage\r\n\t\tself.name = name\r\nclass Hero(Human):\r\n\tdef __init__(self, name, healght, damage, medical_box, orydie, money):\r\n\t\tsuper().__init__(name, healght, damage)\r\n\t\tself.medical_box = medical_box\r\n\t\tself.orydie = orydie\r\n\t\tself.money = money\r\n\tdef attack(self,target):\r\n\t\twhile True:\r\n\t\t\ttry:\r\n\t\t\t\tanswer = int(input('1 - Стреляем, 2 - бьем?\\n'))\r\n\t\t\t\tif answer != 1 and answer != 2:\r\n\t\t\t\t\traise err.NumberError('Введите 1 или 2')\r\n\t\t\texcept err.NumberError as e:\r\n\t\t\t\tprint(e)\r\n\t\t\texcept ValueError:\r\n\t\t\t\tprint('Введите число!!!')\r\n\t\t\telse:\r\n\t\t\t\tbreak\r\n\t\t\tfinally:\r\n\t\t\t\tsleep(2)\t\t\t\r\n\t\t\t\r\n\t\tif answer == 1:\r\n\t\t\tself.orydie.vistrel(self.orydie.ammo,self.orydie.damage, target)\r\n\t\telif answer == 2:\r\n\t\t\tprint(self.name,\"ударил\",target.name)\r\n\t\t\ttarget.healght -= self.damage\r\nclass Zombie(Human):\r\n\tdef __init__(self,name,healght,damage,moneyPeople, kolvo):\r\n\t\tsuper().__init__(name, healght, damage)\r\n\t\tself.moneyPeople = moneyPeople\r\n\t\tself.kolvo = kolvo\r\n\tdef attack(self, target):\r\n\t\tprint(self.name,\"ударил\",target.name)\r\n\t\ttarget.healght -= self.damage\r\ndef battle(player,zombie_leg,zombie_sr,rezer_sr, res_leg):\r\n\tkolvoMoney = 0\r\n\twhile True:\r\n\t\tif player.healght > 0:\r\n\t\t\tprint(player.name,\"Хотите воспользоваться аптечкой?\")\r\n\t\t\ttry:\r\n\t\t\t\ti = int(input(\"1 - да\\n2 - нет\\n\"))\r\n\t\t\t\tif i < 1 or i > 2:\r\n\t\t\t\t\traise err.NumberError(\"Необходимо ввести число от 1 до 2\")\r\n\t\t\texcept err.NumberError as e:\r\n\t\t\t\tprint(e)\r\n\t\t\t\tcontinue\r\n\t\t\texcept ValueError:\r\n\t\t\t\tprint(\"Введите число\")\r\n\t\t\telse:\r\n\t\t\t\tsleep(1)\r\n\t\t\t\tif i == 1:\r\n\t\t\t\t\tif player.medical_box > 0:\r\n\t\t\t\t\t\tprint(\"Вы воспользовались аптечкой\")\r\n\t\t\t\t\t\tplayer.healght += 20\r\n\t\t\t\t\t\tplayer.medical_box -= 1\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tprint(\"Аптечек больше нет!\")\r\n\t\t\t\t\tsleep(1)\r\n\t\t\t\t\tprint(\"А теперь вы атакуете\")\r\n\t\t\t\telse:\r\n\t\t\t\t\tprint(\"Вы атакуете\")\r\n\t\t\t\tplayer.attack(zombie)\r\n\t\t\t\tif zombie.healght <= 0:\r\n\t\t\t\t\tzombie.kolvo -= 1\r\n\t\t\t\t\tprint(\"Вы убили противника\")\r\n\t\t\t\t\tzombie.healght = rezer_sr.healght\r\n\t\t\t\t\tprint(\"Осталось\",zombie.kolvo,\"зомби\")\r\n\t\t\t\t\tplayer.money += zombie.moneyPeople\r\n\t\t\t\t\tkolvoMoney += zombie.moneyPeople\r\n\t\t\t\t\tprint(\"Теперь у тебя \",player.money,\"битконов\")\r\n\t\t\t\tzombie.attack(player)\r\n\t\t\tfinally:\r\n\t\t\t\tsleep(2)\r\n\t\tif player.healght <= 0:\r\n\t\t\tprint(\"Игра окончена\")\r\n\t\t\tprint(player.name,\"успел порубить\",count_kill,zombie.name,\"и заработать\", kolvoMoney,\"биткоинов\")\r\n\r\n\t\t\tbreak\r\n\t\tif zombie.kolvo == 0:\r\n\t\t\tprint(\"Игра окончена\")\r\n\t\t\tprint(\"Вы победили!!! и заработали\", kolvoMoney, \"биткоинов\")\r\n\t\t\tzombie.healght = rezer_sr.healght + 5\r\n\t\t\trezer_sr.healght += 5\r\n\t\t\tzombie.damage = rezer_sr.damage + 3\r\n\t\t\trezer_sr.damage += 3\t\r\n\t\t\tzombie.moneyPeople += rezer_sr.moneyPeople + 5\r\n\t\t\trezer_sr.moneyPeople += 5\r\n\t\t\tzombie.kolvo = rezer_sr.kolvo + 1\r\n\t\t\trezer_sr.kolvo += 1\r\n\t\t\tbreak\r\n\t\tprint(\"У вас осталось\", player.healght,\"жизней и\",player.medical_box,\"аптечек\")\r\n\t\tprint('У',zombie.name,\"осталось\",zombie.healght+'/'+rezer_sr.healght)\r\n\tprint('Вы вернулись в подземелье')\r\n\tmenuLocation(player,zombie_leg,zombie_sr,rezer_sr, res_leg)\r\ndef menuLocation(player,zombie_leg,zombie_sr,rezer_sr, res_leg):\r\n\tglobal shetchik\r\n\tif shetchik == 0:\r\n\t\ttext = \"Ладно ты осваивайся а я пошел в свой магаз.\"\r\n\t\tprint(\"Ты в укрытии.\")\r\n\t\tsleep(1)\r\n\t\tprint(\"Тут не подалеку есть магазин оружий и аптечек их продаю я,\")\r\n\t\tsleep(1.5)\r\n\t\tprint(\"многие люди зомбировались с кошельками, так как не знали о наступлении апокалипсиса,\")\r\n\t\tsleep(2)\r\n\t\tprint(\"значит денег ты найдешь много,\")\r\n\t\tsleep(1)\r\n\t\tprint(text)\r\n\t\tshetchik += 1\r\n\ttext = \"1 - пойти в магазин\\n2 - пойти наверх\\n\"\r\n\twhile True:\r\n\t\ttry:\r\n\t\t\tdeistvia = int(input(text))\r\n\t\t\tif deistvia > 2 or deistvia < 1:\r\n\t\t\t\traise err.NumberError(\"Вы должны ввести число от 1 до 2 не больше и не меньше!!!\")\r\n\t\texcept ValueError:\r\n\t\t\tprint(\"Введите число 1 или 2!!!\")\r\n\t\t\tcontinue\r\n\t\texcept err.NumberError as e:\r\n\t\t\tprint(e)\r\n\t\t\tcontinue\r\n\t\telse:\r\n\t\t\tbreak\r\n\tif deistvia == 1:\r\n\t\tsleep(1.5)\r\n\t\tmagaz(player,zombie_leg,zombie_sr,rezer_sr, res_leg)\r\n\telif deistvia == 2:\r\n\t\tgo_up(player,zombie_leg,zombie_sr,rezer_sr, res_leg)\r\ndef vijivanie(player,zombie_leg,zombie_sr,rezer_sr, res_leg):\r\n\tkolvoMoney = 0\r\n\twhile True:\r\n\t\tif player.healght > 0:\r\n\t\t\tprint(player.name,\"Хотите воспользоваться аптечкой?\")\r\n\t\t\ttry:\r\n\t\t\t\ti = int(input(\"1 - да\\n2 - нет\\n\"))\r\n\t\t\t\tif i < 1 or i > 2:\r\n\t\t\t\t\traise err.NumberError(\"Необходимо ввести число от 1 до 2\")\r\n\t\t\texcept err.NumberError as e:\r\n\t\t\t\tprint(e)\r\n\t\t\t\tcontinue\r\n\t\t\texcept ValueError:\r\n\t\t\t\tprint(\"Введите число\")\r\n\t\t\telse:\r\n\t\t\t\tsleep(1)\r\n\t\t\t\tif i == 1:\r\n\t\t\t\t\tif player.medical_box > 0:\r\n\t\t\t\t\t\tprint(\"Вы воспользовались аптечкой\")\r\n\t\t\t\t\t\tplayer.healght += 20\r\n\t\t\t\t\t\tplayer.medical_box -= 1\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tprint(\"Аптечек больше нет!\")\r\n\t\t\t\t\tsleep(1)\r\n\t\t\t\t\tprint(\"А теперь вы атакуете\")\r\n\t\t\t\telse:\r\n\t\t\t\t\tprint(\"Вы атакуете\")\r\n\t\t\t\tplayer.attack(zombie)\r\n\t\t\t\tif zombie.healght <= 0:\r\n\t\t\t\t\tzombie.kolvo += 1\r\n\t\t\t\t\tprint(\"Вы убили противника\")\r\n\t\t\t\t\tzombie.healght = res_leg.healght\r\n\t\t\t\t\tplayer.money += zombie.moneyPeople\r\n\t\t\t\t\tkolvoMoney += zombie.moneyPeople\r\n\t\t\t\t\tprint(\"Теперь у тебя \",player.money,\"битконов\")\r\n\t\t\t\tzombie.attack(player)\r\n\t\t\tfinally:\r\n\t\t\t\tsleep(2)\r\n\t\tif player.healght <= 0:\r\n\t\t\tprint(\"Игра окончена\")\r\n\t\t\tprint(player.name,\"успел порубить\",count_kill,zombie.name,\"и заработать\", kolvoMoney,\"биткоинов\")\r\n\t\t\tbreak\r\n\t\tif zombie.kolvo >= 15:\r\n\t\t\tzombie.healght = res_leg.healght + 5\r\n\t\t\tres_leg.healght += 5\r\n\t\t\tzombie.damage = res_leg.damage + 3\r\n\t\t\tres_leg.damage += 3\t\r\n\t\t\tzombie.moneyPeople += res_leg.moneyPeople + 5\r\n\t\t\tres_leg.moneyPeople += 5\r\n\t\t\tzombie.kolvo = res_leg.kolvo + 1\r\n\t\t\tres_leg.kolvo += 1\r\n\t\tprint(\"У вас осталось\", player.healght,\"жизней и\",player.medical_box,\"аптечек\")\r\n\t\tprint('У',zombie.name,\"осталось\",zombie.healght+'/'+res_leg.healght)\t\t\r\ndef go_up(player,zombie_leg,zombie_sr,rezer_sr, res_leg):\r\n\tprint(\"Вы поднялись из подземелья наверх, и увидели 3 таблички и 3 пути\")\r\n\tsleep(1)\r\n\tprint(\"1 - Выживание(уровень зомби слабый),\")\r\n\tsleep(2)\r\n\tprint(\"2 - Отряды зомби(уровень зомби средний),\")\r\n\tsleep(2)\r\n\tprint(\"3 - Сражение на територии зомби(уровень зомби сильный),\")\r\n\tsleep(2)\r\n\tprint(\"4 - вернуться назад. Куда идем?\")\r\n\twhile True:\r\n\t\ttry:\r\n\t\t\tanswer = int(input())\r\n\t\t\tif answer < 1 or answer > 4:\r\n\t\t\t\traise err.NumberError(\"Вы должны ввести число от 1 до 4 не больше и не меньше!!!\")\r\n\t\texcept err.NumberError as e:\r\n\t\t\tprint(e)\r\n\t\t\tcontinue\r\n\t\texcept ValueError:\r\n\t\t\tprint(\"Введите число!!!\")\r\n\t\t\tcontinue\r\n\t\telse:\r\n\t\t\tbreak\r\n\t\tfinally:\r\n\t\t\tsleep(1)\r\n\t\r\n\tif answer == 1:\r\n\t\tvijivanie(player,zombie_leg,zombie_sr,rezer_sr, res_leg)\r\n\tif answer == 2:\r\n\t\tbattle(player,zombie_leg,zombie_sr,rezer_sr, res_leg)\r\n\telif answer == 3:\r\n\t\tmap(player)\r\n\telif answer == 4:\r\n\t\tprint(\"Вы вернулись назад.\")\r\n\t\tmenuLocation(player,zombie_leg,zombie_sr,rezer_sr,res_leg)\r\ndef magaz(player,zombie_leg,zombie_sr,rezer_sr, res_leg):\r\n\ttovars = {\r\n\t\t1 : {\"Номер\": 1, \"Название\":\"Аптечка\",\"стоимость\": 100,},\r\n\t\t2 : {\"Номер\": 2, \"Название\": \"Кастет\",\"стоимость\": 110,\"урон\": 15},\r\n\t\t3 : {\"Номер\": 3, \"Название\": \"Мачете\",\"стоимость\": 130,\"урон\": 20},\r\n\t\t4 : {\"Номер\": 4, \"Название\": \"Катана\",\"стоимость\": 150,\"урон\": 30},\r\n\t\t5 : {\"Номер\": 5, \"Название\": \"Revolver\", \"стоимость\": 300, \"патронов\": 8,\"урон\": 70},\r\n\t\t6 : {\"Номер\": 6, \"Название\": \"Deseart Eagle\",\"стоимость\":250,\"патронов\": 8,\"урон\": 60},\r\n\t\t7 : {\"Номер\": 7, \"Название\": \"Ak-47\",\"стоимость\": 400,\"патронов\": 23,\"урон\": 60}}\r\n\r\n\tprint(\"Привет\",player.name,\"решил посетить магазин. Хочешь посмотреть товары и их функции?\")\r\n\twhile True:\r\n\t\ttry:\r\n\t\t\tanswer = int(input(\"1 - товары и их функции\\n2 - уйти из магазина\\n\"))\r\n\t\t\tif answer > 2 or answer < 1:\r\n\t\t\t\traise err.NumberError(\"Вы должны ввести число от 1 до 2 не больше и не меньше!!!\")\r\n\t\texcept ValueError:\r\n\t\t\tprint(\"Введите число 1 или 2!!!\")\r\n\t\t\tcontinue\r\n\t\texcept err.NumberError as e:\r\n\t\t\tprint(e)\r\n\t\t\tcontinue\r\n\t\telse:\r\n\t\t\tbreak\r\n\t\tfinally:\r\n\t\t\tsleep(2)\r\n\tif answer == 1:\r\n\t\tfor i in tovars:\r\n\t\t\tprint(tovars[i].items())\r\n\t\t\tsleep(2)\r\n\t\twhile True:\r\n\t\t\ttry:\r\n\t\t\t\tanswer = int(input(\"Брать будешь?\\n 1 - да\\n2 - нет\\n\"))\r\n\t\t\t\tif answer > 2 or answer < 1:\r\n\t\t\t\t\traise err.NumberError(\"Вы должны ввести число от 1 до 2 не больше и не меньше!!!\")\r\n\t\t\texcept ValueError:\r\n\t\t\t\tprint(\"Введите число!!!\")\r\n\t\t\t\tcontinue\r\n\t\t\texcept err.NumberError as e:\r\n\t\t\t\tprint(e)\r\n\t\t\telse:\r\n\t\t\t\tbreak\r\n\t\t\tfinally:\r\n\t\t\t\tsleep(2)\t\t\t\r\n\t\tif answer == 1:\r\n\t\t\tviborPokypki(player,zombie_leg,zombie_sr,rezer_sr, res_leg)\r\n\t\telse:\r\n\t\t\tprint(\"Не хочешь - как хочешь\")\r\n\telif answer == 2:\r\n\t\tprint(\"Ладно удачи!\")\r\n\t\tmenuLocation(player,zombie_leg,zombie_sr,rezer_sr,res_leg)\r\ndef viborPokypki(player,zombie_leg,zombie_sr,rezer_sr, res_leg):\r\n\ttovars = {\r\n\t\t1 : {\"Номер\": 1, \"Название\":\"Аптечка\",\"стоимость\": 100,},\r\n\t\t2 : {\"Номер\": 2, \"Название\": \"Кастет\",\"стоимость\": 110,\"урон\": 15},\r\n\t\t3 : {\"Номер\": 3, \"Название\": \"Мачете\",\"стоимость\": 130,\"урон\": 20},\r\n\t\t4 : {\"Номер\": 4, \"Название\": \"Катана\",\"стоимость\": 150,\"урон\": 30},\r\n\t\t5 : {\"Номер\": 5, \"Название\": \"Revolver\", \"стоимость\": 300, \"патронов\": 8,\"урон\": 70},\r\n\t\t6 : {\"Номер\": 6, \"Название\": \"Deseart Eagle\",\"стоимость\":250,\"патронов\": 8,\"урон\": 60},\r\n\t\t7 : {\"Номер\": 7, \"Название\": \"Ak-47\",\"стоимость\": 400,\"патронов\": 23,\"урон\": 60}}\r\n\tprint(\"Выбери что хочешь купить\")\r\n\twhile True:\r\n\t\tprint(\"У тебя\",player.money,\"биткоинов\")\r\n\t\ttry:\r\n\t\t\tanswer = int(input(\"Введи номер оружия(он указан в функции товара),\\n8 - если снова хочешь посмотреть функции товаров,\\nи 9 - если хочешь уйти из магазина\\n\"))\r\n\t\t\tif answer > 9 or answer < 1:\r\n\t\t\t\traise err.NumberError(\"Вы должны ввести число от 1 до 9 не больше и не меньше!!!\")\r\n\t\texcept ValueError:\r\n\t\t\tprint(\"Введити число!!!!!\")\r\n\t\t\tcontinue\r\n\t\texcept err.NumberError as e:\r\n\t\t\tprint(e)\r\n\t\t\tcontinue\r\n\t\telse:\r\n\t\t\tbreak\r\n\t\tfinally:\r\n\t\t\tsleep(2)\r\n\tif answer in range(1,8):\r\n\t\tpokypka(player,zombie_leg,zombie_sr,rezer_sr, res_leg,answer)\r\n\telif answer == 8:\r\n\t\tfor i in tovars:\r\n\t\t\tprint(tovars[i].items())\r\n\t\t\tsleep(2)\r\n\t\tviborPokypki(player,zombie_leg,zombie_sr,rezer_sr, res_leg)\r\n\telif answer == 9:\r\n\t\tprint(\"Ок! Удачи\")\r\n\t\tmenuLocation(player,zombie_leg,zombie_sr,rezer_sr, res_leg)\r\ndef pokypka(player,zombie_leg,zombie_sr,rezer_sr, res_leg,number):\r\n\tglobal shetchik\r\n\ttovars = {\r\n\t\t1 : {\"Номер\": 1, \"Название\":\"Аптечка\",\"стоимость\": 100,},\r\n\t\t2 : {\"Номер\": 2, \"Название\": \"Кастет\",\"стоимость\": 110,\"урон\": 15},\r\n\t\t3 : {\"Номер\": 3, \"Название\": \"Мачете\",\"стоимость\": 130,\"урон\": 20},\r\n\t\t4 : {\"Номер\": 4, \"Название\": \"Катана\",\"стоимость\": 150,\"урон\": 30},\r\n\t\t5 : {\"Номер\": 5, \"Название\": \"Revolver\", \"стоимость\": 300, \"патронов\": 8,\"урон\": 70},\r\n\t\t6 : {\"Номер\": 6, \"Название\": \"Deseart Eagle\",\"стоимость\":250,\"патронов\": 8,\"урон\": 60},\r\n\t\t7 : {\"Номер\": 7, \"Название\": \"Ak-47\",\"стоимость\": 400,\"патронов\": 23,\"урон\": 60}}\r\n\tif number == 1:\r\n\t\tif player.money - tovars[number][\"стоимость\"] >= 0: \r\n\t\t\tplayer.medical_box += 1\r\n\t\t\tplayer.money -= tovars[number][\"стоимость\"]\r\n\t\t\tprint(\"Поздравляю с покупкой!!! теперь у тебя\", player.medical_box,\"аптечки\")\r\n\t\telse:\r\n\t\t\tprint(\"У вас недостаточно средств для покупки\")\r\n\t\t\tsleep(1)\r\n\t\t\tviborPokypki(player,zombie_leg,zombie_sr,rezer_sr, res_leg)\r\n\telif number in range(2,5):\r\n\t\tif shetchik == 1:\t\r\n\t\t\tif player.money - tovars[number][\"стоимость\"] > 0: \r\n\t\t\t\tplayer.blijBoi = tovars[number][\"урон\"]\r\n\t\t\t\tplayer.damage += player.blijBoi\r\n\t\t\t\tplayer.money -= tovars[number][\"стоимость\"]\r\n\t\t\t\tprint(\"Поздровляю с покупкой!!! теперь у тебя\",player.damage,\"урона и\",tovars[number][\"Название\"],)\r\n\t\t\telse:\r\n\t\t\t\tprint(\"У вас недостаточно средств для покупки\")\r\n\t\t\t\tviborPokypki(player,zombie_leg,zombie_sr,rezer_sr, res_leg)\r\n\t\t\tshetchik += 1\r\n\t\telse:\r\n\t\t\tif player.money - tovars[number][\"стоимость\"] > 0: \r\n\t\t\t\tplayer.damage -= player.blijBoi \r\n\t\t\t\tplayer.blijBoi = tovars[number][\"урон\"]\r\n\t\t\t\tplayer.damage += player.blijBoi\r\n\t\t\t\tplayer.money -= tovars[number][\"стоимость\"]\r\n\t\t\t\tprint(\"Поздровляю с покупкой!!! теперь у тебя\",player.damage,\"урона и\",tovars[number][\"Название\"],)\r\n\t\t\telse:\r\n\t\t\t\tprint(\"У вас недостаточно средств для покупки\")\r\n\t\t\t\tviborPokypki(player,zombie_leg,zombie_sr,rezer_sr, res_leg)\r\n\telse:\r\n\t\tif player.money - tovars[number][\"стоимость\"] > 0: \r\n\t\t\tplayer.orydie.damage = tovars[number][\"урон\"]\r\n\t\t\tplayer.orydie.ammo = tovars[number][\"патронов\"]\r\n\t\t\tplayer.orydie.name = tovars[number][\"Название\"]\r\n\t\t\tplayer.money -= tovars[number][\"стоимость\"]\r\n\t\t\tprint('Поздровляю с новым',player.orydie.name,'!!!')\r\n\t\telse:\r\n\t\t\tprint(\"У вас недостаточно средств для покупки\")\r\n\t\t\tviborPokypki(player,zombie_leg,zombie_sr,rezer_sr, res_leg)\r\n\twhile True:\r\n\t\ttry:\r\n\t\t\tanswer = int(input('Хочешь что нибудь еще?\\n1 - да\\n2 - нет'))\r\n\t\t\tif answer != 1 and answer != 2:\r\n\t\t\t\traise err.NumberError(\"Введите 1 или 2!!!\")\r\n\t\texcept err.NumberError as e:\r\n\t\t\tprint(e)\r\n\t\texcept ValueError:\r\n\t\t\tprint(\"Ввелите число\")\r\n\t\telse:\r\n\t\t\tbreak\r\n\t\tfinally:\r\n\t\t\tsleep(1.5)\r\n\tif answer == 1:\r\n\t\tviborPokypki(player,zombie_leg,zombie_sr,rezer_sr, res_leg)\r\n\telif answer == 2:\r\n\t\tprint('Ок')\r\n\t\tsleep(2)\r\n\t\tmenuLocation(player,zombie_leg,zombie_sr,rezer_sr, res_leg)\r\n#suj.sydjet()\r\norydie = Orydie(\"Травмат\",5,10)\r\neldar = Hero(input(\"Кстати как тебя зовут?\\n\"), 150, 15, 3, orydie, 100)\r\neldar.name = eldar.name.capitalize().strip()\r\nif eldar.name == 'Султан' or eldar.name == \"Мурад\" or eldar.name == \"Султанмурад\" or eldar.name == \"Sultan\" or eldar.name == \"Murad\" or eldar.name == \"Sultanmurad\" or eldar.name == \"Myrad\" or eldar.name == \"Sultanmyrad\":\r\n\tprint(\"Султанмурад вы проверяете мою домашку.\\nТут есть магазин и чтоб вы могли проверить его у вас будет много денег\")\r\n\tsleep(2)\r\n\teldar.money = 100000\r\nsred_zombo = Zombie(\"Зомбарь\", 25, 30, 15, 10)\r\nleg_zombo = Zombie(\"Ватник\", 15, 20, 10, 0)\r\nrezLeg = Zombie(\"Ватник\", 15, 20, 10, 0)\r\nreserv = Zombie(\"Резерв\", 25, 30, 15, 10)\r\nshetchik = 0\r\nmenuLocation(eldar, leg_zombo, sred_zombo,reserv,rezLeg)","sub_path":"pitonozavr/Lessons/L15/game/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":17167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"197214794","text":"import numpy as np\nfrom tools.ListGiant import ListInsert\n\ndef mot_tracklets_concat(init_tracklet,window_tracklet,cr_fr,param):\n concat_fr = cr_fr\n ListInsert(init_tracklet.state,concat_fr,window_tracklet.state[concat_fr],[])\n ListInsert(init_tracklet.hyp.score,concat_fr,window_tracklet.hyp.score[concat_fr],0)\n ListInsert(init_tracklet.hyp.ystate,concat_fr,window_tracklet.hyp.ystate[concat_fr],[])\n #ListInsert(init_tracklet.hyp.ystates_ids,concat_fr,window_tracklet.hyp.ystates_ids[concat_fr],[])\n init_tracklet.FMotion.X = np.c_[init_tracklet.FMotion.X,window_tracklet.FMotion.X[:,concat_fr]]\n init_tracklet.FMotion.P = np.concatenate((init_tracklet.FMotion.P,window_tracklet.FMotion.P[:,:,concat_fr][:,:,np.newaxis]),axis = 2)\n init_tracklet.A_Model = param.alpha*window_tracklet.A_Model + (1 - param.alpha)*init_tracklet.A_Model\n init_tracklet.last_update = concat_fr\n ListInsert(init_tracklet.A_model_list,concat_fr,window_tracklet.A_model_list,None)\n ListInsert(init_tracklet.hyp.ystates_id,concat_fr,window_tracklet.hyp.ystates_id,-1)\n if len(window_tracklet.state[concat_fr]) > 0:\n window_tracklet.ifr = concat_fr + 1\n \n #remove the detections which is already concat with existing init tracklets\n window_tracklet.state[concat_fr] = []\n window_tracklet.FMotion.X[:,concat_fr] = 0\n window_tracklet.FMotion.P[:,:,concat_fr] = 0\n window_tracklet.hyp.score[concat_fr] = 0\n window_tracklet.hyp.ystate[concat_fr] = []\n","sub_path":"mot_func/mot_tracklets_concat.py","file_name":"mot_tracklets_concat.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"441493921","text":"from numpy import *\nfrom pylab import *\nfrom numpy.random import *\n\n## ESTIMATION BOUNDS\n\nclass Bounds(object):\n\n def __init__(self,signal_model,name=\"CRB\"):\n self.signal_model = signal_model\n self.name=name\n\n def __str__(self):\n return self.name\n\nclass Exact_Bounds(Bounds):\n\n def compute(self,method=0):\n \n \"\"\" Compute the Cramer Rao bound \"\"\"\n CRB=zeros(10)\n \n # extract parameter\n N=self.signal_model.N\n w0=self.signal_model.w0\n c=self.signal_model.c\n sigma2=self.signal_model.sigma2\n\n if method==0:\n #Closed form inversion of the Fisher Inversion Matrix\n \n #precompute values\n n_vect=arange(N)\n n_vect2=n_vect**2\n q=sum(exp(2j*w0*n_vect))\n beta=1/((N**2)-(abs(q)**2))\n \n den=0;\n for num_phase in range(0,3):\n ck=c[num_phase]\n ak=abs(ck)\n phik=angle(ck)\n \n f1k=sum(n_vect*(1-exp(2j*(n_vect*w0+phik))))\n f2k=sum(n_vect2*(1-exp(2j*(n_vect*w0+phik))))\n \n den=den+(ak**2)*real(f2k-N*beta*(abs(f1k)**2)-beta*conj(q)*(f1k**2)*exp(-2j*phik)) # angular frequency\n CRB[2*num_phase]=(beta**2)*imag((N-conj(q))*f1k*conj(ck))**2 # real part of phasor\n CRB[2*num_phase+1]=(beta**2)*real((N+conj(q))*f1k*conj(ck))**2 # imag part of phasor\n \n CRB[6]=2*sigma2/den # Need to be computed first\n CRB[:6:2]=2*beta*sigma2*(N-real(q))+CRB[6]*CRB[:6:2]\n CRB[1:6:2]=2*beta*sigma2*(N+real(q))+CRB[6]*CRB[1:6:2]\n \n \n else:\n #Numerical inversion of the Fisher Inversion Matrix using numpy\n C=vstack((real(c),imag(c)))\n c_vect=matrix(ravel(C.T)).T\n n_vect=arange(0,N)\n n_vect2=n_vect**2\n \n #construct matrix A and Q\n a=matrix(exp(1j*w0*n_vect)).T\n b=matrix(n_vect*exp(1j*w0*n_vect)).T\n A=hstack((real(a),-imag(a)))\n Q=hstack((-imag(b),-real(b)))\n \n #construct Fisher Information Matrix\n F1=kron(eye(3),A)\n f2=kron(eye(3),Q)*c_vect\n F=(1/sigma2)*bmat([[F1.T*F1, F1.T*f2], [f2.T*F1, f2.T*f2]])\n CRB[:7]=diag(linalg.inv(F)) #Computation of the CRB\n\n\n # compute TVE2\n a_vect=abs(c)\n CRB[7:]=(CRB[:6:2]+CRB[1:6:2])/(a_vect**2)\n\n return CRB\n\n\nclass Approximated_Bounds(Bounds):\n\n def compute(self):\n \n \"\"\" Compute the CRB approximation when N>>1\"\"\"\n CRB=zeros(10)\n \n # extract parameter\n N=self.signal_model.N\n c=self.signal_model.c\n sigma2=self.signal_model.sigma2\n \n a_vect=abs(c)\n eta=sum(a_vect**2)/(6*sigma2)\n \n #Compute CRB\n for num_phase in range(0,3):\n ck=c[num_phase]\n CRB[2*num_phase]=2*(sigma2/N)+(imag(ck)**2)/(eta*N)\n CRB[2*num_phase+1]=2*(sigma2/N)+(real(ck)**2)/(eta*N)\n\n CRB[6]=4/(eta*(N**3))\n \n # Compute TVE2\n etak=(a_vect**2)/(2*sigma2)\n CRB[7:]=(1/N)*((2/etak)+(1/eta))\n \n return CRB\n\n\n\n","sub_path":"three_phase_signal/bounds.py","file_name":"bounds.py","file_ext":"py","file_size_in_byte":3338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"294434198","text":"class SymTable(object):\n\n\tid = 1\n\tdef __init__(self, name=\"main\", parent=None):\n\n\t\tself.id = SymTable.id\n\n\t\tSymTable.id+=1\n\t\tself.nested_scopes=[] #List of all symbol tables whose scope are within this symbol table\n\t\tself.symbols = {}\t #Dictionary to hold the attributes and names of all symbols\n\t\tself.functions = {}\t\t#Dictionary to hold functions name and attributes\n\t\tself.offset = 0\t\t\t# Byte Storage offset for this scope\n\n\t\tself.parent = parent\n\t\t\n\t\tif self.parent != None:\n\t\t\tself.parent.nested_scopes.append(self)\n\n\n\tdef add_function(self, function_name, function_attr):\n\n\t\tself.functions[function_name] = function_attr\n\n\tdef add_symbol(self, sym_name, sym_attr):\n\n\t\tself.symbols[sym_name] = sym_attr\n\n\tdef find_var_decl(self, var):\n\t\ttemp = self\n\t\tflag = 0\n\t\t\n\t\twhile(temp is not None):\n\t\t\tif var in temp.symbols:\n\t\t\t\tflag = 1\n\t\t\t\tbreak\n\t\t\ttemp = temp.parent\n\n\t\treturn (flag,temp)\n\n\tdef find_func_decl(self, function):\n\t\ttemp = self\n\t\tflag = 0\n\t\t\n\t\twhile(temp is not None):\n\t\t\tif function in temp.function:\n\t\t\t\tflag = 1\n\t\t\t\tbreak\n\t\t\ttemp = temp.parent\n\n\t\treturn (flag,temp)","sub_path":"asgn4_main/bin/Scope_SymTab.py","file_name":"Scope_SymTab.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"393575091","text":"import os\nimport _mylib\nimport community\nimport pickle\nimport log\nimport numpy as np\nimport argparse\nimport networkx as nx\nfrom scipy import stats\n\ndef get_community(G, fname):\n com_fname = fname + '_com'\n if os.path.isfile(com_fname):\n partition = pickle.load(open(com_fname, 'rb'))\n else:\n partition = community.best_partition(G)\n pickle.dump(partition, open(com_fname, 'wb'))\n\n return partition\n\n\ndef _getCommunity(partition):\n com = {}\n\n for n in partition:\n p = partition[n]\n if p not in com:\n com[p] = set()\n com[p].update(set([n]))\n\n com = {c: com[c] for c in com if len(com[c]) > 1}\n\n # Make sure we do not consider the singleton nodes\n return com\n\n\ndef partitionDistance(part1, part2, nodes=None):\n \"\"\"\n Compute the partiton distance between communities c1 and c2\n \"\"\"\n\n c1 = _getCommunity(part1)\n c2 = _getCommunity(part2)\n\n if nodes is None:\n n1 = set([])\n n2 = set([])\n for c in c1:\n n1.update(c1[c])\n for c in c2:\n n2.update(c2[c])\n nodes = n1.intersection(n2)\n\n c1 = {c: c1[c].intersection(nodes) for c in c1}\n c2 = {c: c2[c].intersection(nodes) for c in c2}\n\n m = max(len(c1), len(c2))\n m = range(0, m)\n\n mat = {i: {j: 0 for j in c2} for i in c1}\n\n total = 0\n for i in c1:\n for j in c2:\n if i in c1 and j in c2:\n mat[i][j] = len(c1[i].intersection(c2[j]))\n total += mat[i][j]\n\n if total <= 1:\n return 1.0\n\n assignment = []\n rows = c1.keys()\n cols = c2.keys()\n\n while len(rows) > 0 and len(cols) > 0:\n mval = 0\n r = -1\n c = -1\n for i in rows:\n for j in cols:\n if mat[i][j] >= mval:\n mval = mat[i][j]\n r = i\n c = j\n rows.remove(r)\n cols.remove(c)\n assignment.append(mval)\n\n dist = total - np.sum(assignment)\n\n if np.isnan(dist / total):\n return 0\n\n return 1.*dist / total\n\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('dataset', help='dataset name', type=str)\n args = parser.parse_args()\n\n dataset = args.dataset\n directory = './data-adv/rand_edge/'\n # dataset = 'socfb-Amherst41'\n log_file = './log/' + dataset\n\n MAX_GEN = 10\n ad_p_remove = \"0\"\n crawler_list = ['med', 'mod', 'rw', 'bfs', 'rand']\n # crawler_list = ['mod']\n\n for crawler_type in crawler_list:\n for i in range(0, MAX_GEN):\n fname = directory + str(ad_p_remove) + '/' + \\\n dataset + '/' + crawler_type + '/' + \\\n dataset + '_' + str(i+1) + '_1'\n G = _mylib.read_file(fname)\n node_count = G.number_of_nodes()\n\n com_G = get_community(G, fname)\n node_G = G.nodes()\n deg_hist_G = nx.degree_histogram(G)\n\n for j in range(0, MAX_GEN):\n if i == j:\n continue\n\n fname = directory + str(ad_p_remove) + '/' + \\\n dataset + '/' + crawler_type + '/' + \\\n dataset + '_' + str(j + 1) + '_1'\n\n G = _mylib.read_file(fname)\n com_adv = get_community(G, fname)\n node_adv = G.nodes()\n deg_hist_adv = nx.degree_histogram(G)\n d, p = stats.ks_2samp(deg_hist_G, deg_hist_adv)\n\n int_ = len(set(node_G).intersection(set(node_adv)))\n union_ = len(set(node_G).union(set(node_adv)))\n\n jaccard = 1.*int_ / union_\n # node_cov_size = 1.*len(node_adv) / len(node_G)\n coverage_dist = 1.*(abs(len(node_adv) - len(node_G))) / (abs(len(node_adv)) + abs(len(node_G)))\n node_cov_sim = 1. - coverage_dist\n partition_sim = 1. - partitionDistance(com_G, com_adv)\n degree_dist, p_val = stats.ks_2samp(deg_hist_G, deg_hist_adv)\n\n print('Type {} \\t i-j:{}-{} \\t p:{} \\t '\n 'Coverage:{} \\t'\n ' Node sim:{} \\t '\n 'Partiton sim:{} \\t '\n 'Deg: {} p:{}'.format(\n crawler_type, i, j,\n ad_p_remove,\n node_cov_sim,\n jaccard,\n partition_sim,\n degree_dist,\n p_val))\n\n log.save_to_file_line(log_file + '_0_measure.txt', [ad_p_remove, crawler_type, \"Node Sim\", jaccard])\n log.save_to_file_line(log_file + '_0_measure.txt', [ad_p_remove, crawler_type, \"Node Coverage\", node_cov_sim])\n log.save_to_file_line(log_file + '_0_measure.txt', [ad_p_remove, crawler_type, \"Partition Sim\", partition_sim])\n log.save_to_file_line(log_file + '_0_measure.txt', [ad_p_remove, crawler_type, \"Degree Dist.\", degree_dist])\n log.save_to_file_line(log_file + '_0_measure.txt', [ad_p_remove, crawler_type, \"p\", p_val])\n","sub_path":"adversary_sample_zero_check.py","file_name":"adversary_sample_zero_check.py","file_ext":"py","file_size_in_byte":5109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"609846640","text":"\"\"\"Sentry integration to Muffin framework.\"\"\"\nfrom __future__ import annotations\n\nfrom contextvars import ContextVar\nfrom functools import partial\nfrom typing import TYPE_CHECKING, Callable, ClassVar, Dict, List, Optional, TypeVar\n\nfrom muffin import Application, Request, ResponseError, ResponseRedirect\nfrom muffin.plugins import BasePlugin\nfrom sentry_sdk import Hub\nfrom sentry_sdk import Scope as SentryScope\nfrom sentry_sdk import init as sentry_init\nfrom sentry_sdk.tracing import Transaction\n\nif TYPE_CHECKING:\n from asgi_tools.types import TASGIApp, TASGIReceive, TASGISend\n\nTProcess = Callable[[Dict, Dict, Request], Dict]\nTVProcess = TypeVar(\"TVProcess\", bound=TProcess)\n\n\nclass Plugin(BasePlugin):\n\n \"\"\"Setup Sentry and send exceptions and messages.\"\"\"\n\n name = \"sentry\"\n client = None\n defaults: ClassVar[Dict] = {\n \"dsn\": \"\", # Sentry DSN\n \"sdk_options\": {}, # See https://docs.sentry.io/platforms/python/configuration/options/\n \"ignore_errors\": (ResponseError, ResponseRedirect),\n }\n current_scope: ContextVar[Optional[SentryScope]] = ContextVar(\n \"sentry_scope\",\n default=None,\n )\n processors: List[TProcess]\n\n def __init__(self, *args, **kwargs):\n \"\"\"Initialize the plugin.\"\"\"\n super(Plugin, self).__init__(*args, **kwargs)\n self.processors = []\n\n def setup(self, app: Application, **options):\n \"\"\"Initialize Sentry Client.\"\"\"\n super().setup(app, **options)\n\n # Setup Sentry\n dsn = self.cfg.dsn\n if dsn:\n sentry_init(dsn=dsn, **self.cfg.sdk_options)\n\n async def middleware( # type: ignore[override]\n self,\n handler: TASGIApp,\n request: Request,\n receive: TASGIReceive,\n send: TASGISend,\n ):\n \"\"\"Capture exceptions to Sentry.\"\"\"\n hub = Hub(Hub.current)\n with hub.configure_scope() as scope:\n scope.clear_breadcrumbs()\n scope._name = \"muffin\"\n self.current_scope.set(scope)\n scope.add_event_processor(partial(self.process_data, request=request))\n\n with hub.start_transaction(\n Transaction.continue_from_headers(\n request.headers,\n op=f\"{request.scope['type']}.muffin\",\n ),\n custom_sampling_context={\"asgi_scope\": scope},\n ):\n try:\n return await handler(request, receive, send)\n\n except Exception as exc:\n if type(exc) not in self.cfg.ignore_errors:\n hub.capture_exception(exc)\n raise exc from None\n\n def processor(self, fn: TVProcess) -> TVProcess:\n \"\"\"Register a custom processor.\"\"\"\n self.processors.append(fn)\n return fn\n\n def process_data(self, event: Dict, hint: Dict, request: Request) -> Dict:\n \"\"\"Prepare data before send it to Sentry.\"\"\"\n if request:\n url = request.url\n event[\"request\"] = {\n \"url\": f\"{url.scheme}://{url.host}{url.path}\",\n \"query_string\": request.url.query_string,\n \"method\": request.method,\n \"headers\": dict(request.headers),\n }\n\n if request.get(\"client\"):\n event[\"request\"][\"env\"] = {\"REMOTE_ADDR\": request.client[0]}\n\n for processor in self.processors:\n event = processor(event, hint, request)\n\n return event\n\n def capture_exception(self, *args, **kwargs):\n \"\"\"Capture exception.\"\"\"\n if self.cfg.dsn:\n with Hub(Hub.current, self.current_scope.get()) as hub:\n return hub.capture_exception(*args, **kwargs)\n\n def capture_message(self, *args, **kwargs):\n \"\"\"Capture message.\"\"\"\n if self.cfg.dsn:\n with Hub(Hub.current, self.current_scope.get()) as hub:\n return hub.capture_message(*args, **kwargs)\n","sub_path":"muffin_sentry/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"516243098","text":"import pygame as pg\n\nfrom data.load import *\nfrom data.scripts.state_machine import State\nfrom data.scripts.timer import Countdown\n\n\nclass Splash(State):\n _alpha = 0\n _rate = 10\n\n def __init__(self):\n super().__init__()\n self.background = WHITE\n self.ticks = 0\n self.splash = BIG_FONT.render(TITLE, 0, BLACK)\n self.any_key = SMALL_FONT.render(\"Press any key...\", 0, BLACK)\n self.next = \"GAME\"\n\n self.timer = Countdown()\n self.timer.setup_countdown(1)\n\n def cleanup(self):\n self.done = False\n self.timer.reset_timer()\n\n return self.persistent\n\n def set_rect(self):\n self.splash_rect = self.splash.get_rect()\n self.splash_rect.center = CENTER\n self.any_key_rect = self.any_key.get_rect()\n self.any_key_rect.midtop = self.splash_rect.midbottom\n\n def update(self, tick, keys, mkeys, mouse_pos):\n self.set_rect()\n self.ticks += tick\n if not 0 <= self._alpha <= 255:\n self._rate = self._rate * -1\n self._alpha += self._rate\n self.any_key.set_alpha(self._alpha)\n if not self.timer.done:\n self.timer.tick_timer(tick)\n if (any(keys) or any(mkeys)) and self.timer.done:\n self.done = True\n\n def draw(self, surface):\n surface.fill(self.background)\n surface.blit(self.splash, self.splash_rect)\n surface.blit(self.any_key, self.any_key_rect)\n","sub_path":"data/states/splash.py","file_name":"splash.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"553624060","text":"print(\"\\nLab 0 written by JLorio\\n\\n\")\n\ninitiallist = [\"JJJJJJJJJJJJ\",\" CCC\",\" L\",\n \" J\", \" C C\",\" L\",\n \" J\", \" C\",\" L\",\n \" J\", \" C\",\" L\",\n \"J J\",\" C C\",\" L\",\n \" JJJ\",\" CCC\",\" LLLLLLLLL\"]\n\ncounter = 0\nfor i in initiallist:\n if counter + 1 % 3 == 0:\n counter += 1\n elif(counter < 16):\n print(initiallist[counter], initiallist[counter+1], initiallist[counter + 2])\n counter += 3","sub_path":"initials.py","file_name":"initials.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"14065554","text":"# coding=utf-8\n\nimport socket\n\n_dnscache = {}\n\n\ndef _setDNSCache():\n def igetaddrinfo(*args, **kwargs):\n if args in _dnscache:\n return _dnscache[args]\n else:\n _dnscache[args] = socket.igetaddrinfo(*args, **kwargs)\n return _dnscache[args]\n if not hasattr(socket, 'igetaddrinfo'):\n socket.igetaddrinfo = socket.getaddrinfo\n socket.getaddrinfo = igetaddrinfo\n\n\ndef test():\n _setDNSCache()\n import requests\n r1 = requests.get('http://www.baidu.com')\n print('第一次没有命中缓存时间: ' + str(r1.elapsed.microseconds))\n # print(_dnscache)\n r2 = requests.get('http://www.baidu.com')\n print('第二次命中缓存时间: ' + str(r2.elapsed.microseconds))\n\n\nif __name__ == '__main__':\n test()","sub_path":"unit_testing/test_dns.py","file_name":"test_dns.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"92638055","text":"import pygame\nimport sys\n\nfrom pygame.math import Vector2\n\nfrom settings import Settings\n\n\n\nclass Snake:\n def __init__(self, screen):\n self.settings = Settings()\n self.screen = screen\n\n # the snake has a starting length of 3 cells\n self.body = [Vector2(5, 10), Vector2(4, 10), Vector2(3, 10)]\n # the snake moves to the right initially\n self.direction = Vector2(1, 0)\n self.new_block = False\n\n # load all the snake blocks to be displayed later\n self.head_up = pygame.image.load(\n 'graphics/head_up.png').convert_alpha()\n self.head_down = pygame.image.load(\n 'graphics/head_down.png').convert_alpha()\n self.head_right = pygame.image.load(\n 'graphics/head_right.png').convert_alpha()\n self.head_left = pygame.image.load(\n 'graphics/head_left.png').convert_alpha()\n\n self.tail_up = pygame.image.load(\n 'graphics/tail_up.png').convert_alpha()\n self.tail_down = pygame.image.load(\n 'graphics/tail_down.png').convert_alpha()\n self.tail_right = pygame.image.load(\n 'graphics/tail_right.png').convert_alpha()\n self.tail_left = pygame.image.load(\n 'graphics/tail_left.png').convert_alpha()\n\n self.body_vertical = pygame.image.load(\n 'graphics/body_vertical.png').convert_alpha()\n self.body_horizontal = pygame.image.load(\n 'graphics/body_horizontal.png').convert_alpha()\n\n self.body_tr = pygame.image.load(\n 'graphics/body_tr.png').convert_alpha()\n self.body_tl = pygame.image.load(\n 'graphics/body_tl.png').convert_alpha()\n self.body_br = pygame.image.load(\n 'graphics/body_br.png').convert_alpha()\n self.body_bl = pygame.image.load(\n 'graphics/body_bl.png').convert_alpha()\n\n # load the sound to be played when the snake gets a reward\n self.crunch_sound = pygame.mixer.Sound('sound/crunch.wav')\n\n # find the direction in which the head is pointing\n def update_head_graphics(self):\n head_relation = self.body[1] - self.body[0]\n if head_relation == Vector2(1, 0):\n self.head = self.head_left\n\n elif head_relation == Vector2(-1, 0):\n self.head = self.head_right\n\n elif head_relation == Vector2(0, 1):\n self.head = self.head_up\n\n elif head_relation == Vector2(0, -1):\n self.head = self.head_down\n\n # find the direction in which the tail is pointing\n def update_tail_graphics(self):\n tail_relation = self.body[-2] - self.body[-1]\n if tail_relation == Vector2(1, 0):\n self.tail = self.tail_left\n\n elif tail_relation == Vector2(-1, 0):\n self.tail = self.tail_right\n\n elif tail_relation == Vector2(0, 1):\n self.tail = self.tail_up\n\n elif tail_relation == Vector2(0, -1):\n self.tail = self.tail_down\n\n def draw_snake(self):\n self.update_head_graphics()\n self.update_tail_graphics()\n\n for index, block in enumerate(self.body):\n # create a rect for postioning\n x_pos = int(block.x * self.settings.cell_size)\n y_pos = int(block.y * self.settings.cell_size)\n block_rect = pygame.Rect(\n x_pos, y_pos, self.settings.cell_size, self.settings.cell_size)\n\n # draw the head of the snake\n if index == 0:\n self.screen.blit(self.head, block_rect)\n\n # draw the tail of the snake\n elif index == len(self.body) - 1:\n self.screen.blit(self.tail, block_rect)\n\n # draw the remaining blocks of the snake\n else:\n # check the relative positioning of the next and previous block\n previous_block = self.body[index + 1] - block\n next_block = self.body[index - 1] - block\n\n # the blocks are on the same vertical line\n if previous_block.x == next_block.x:\n self.screen.blit(self.body_vertical, block_rect)\n\n # the blocks are on the same horizontal line\n elif previous_block.y == next_block.y:\n self.screen.blit(self.body_horizontal, block_rect)\n\n # handling blocks at a turn\n else:\n if previous_block.x == -1 and next_block.y == -1 or previous_block.y == -1 and next_block.x == -1:\n self.screen.blit(self.body_tl, block_rect)\n\n elif previous_block.x == -1 and next_block.y == 1 or previous_block.y == 1 and next_block.x == -1:\n self.screen.blit(self.body_bl, block_rect)\n\n elif previous_block.x == 1 and next_block.y == -1 or previous_block.y == -1 and next_block.x == 1:\n self.screen.blit(self.body_tr, block_rect)\n\n elif previous_block.x == 1 and next_block.y == 1 or previous_block.y == 1 and next_block.x == 1:\n self.screen.blit(self.body_br, block_rect)\n\n def move_snake(self):\n # if the snake ate an apple, increase it's length by one and update\n if self.new_block == True:\n body_copy = self.body[:]\n body_copy.insert(0, body_copy[0] + self.direction)\n self.body = body_copy[:]\n self.new_block = False\n else:\n body_copy = self.body[:-1]\n body_copy.insert(0, body_copy[0] + self.direction)\n self.body = body_copy[:]\n\n def add_block(self):\n self.new_block = True\n\n def play_crunch_sound(self):\n self.crunch_sound.play()\n\n def reset(self):\n self.body = [Vector2(5, 10), Vector2(4, 10), Vector2(3, 10)]\n self.direction = Vector2(1, 0)\n","sub_path":"main-game/snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":5846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"479803461","text":"from django.urls import path\n\nfrom .views import TodoView,TododetailView,TodoDeleteView,TodoCreateView,TodoUpdateView\n\nurlpatterns = [\n path('list/', TodoView.as_view(), name='list'),\n path('detail//', TododetailView.as_view(), name='detail'),\n path('create/', TodoCreateView.as_view(), name='create'),\n path('delete//', TodoDeleteView.as_view(), name='delete'),\n path('update//', TodoUpdateView.as_view(), name='update'),\n]","sub_path":"todo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"70904949","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.externals import joblib\n\nfrom sklearn.metrics import confusion_matrix, classification_report, accuracy_score, roc_curve, auc\n\nfrom preprocessing import (validate_input, preprocess_surname,\n preprocess_census, preprocess_voter,\n create_location_ethnic_prob,\n transform_output, create_name_predictor)\n\n\ndef predict_ethnic(lastname, cbg2000, name_prob, location_ethnic_prob, verbose_prob=False, verbose_all=False):\n \"\"\"\n Predicting ethnicity given surname(lastname), location code(cbg2000),\n name probability(name_prob), location probability conditioned on ethnicity(location_ethnic_prob)\n :param lastname: list, containing people's lastname\n :param cbg2000: list, containing people's geolocation code\n :param name_prob: DataFrame, output from preprocess_surname()\n :param location_ethnic_prob: DataFrame, output from create_location_ethnic_prob()\n :param verbose_prob: Boolean, if True, will return probability for predicted ethnic\n :param verbose_all: Boolean, if True and verbose_prob is True, will return probability for all ethnic\n (useful when drawing roc curve)\n :return: ethnic_pred_race: list, containing predicted ethnic\n ethnic_pred_prob: list, containing probability of predicted ethnic\n \"\"\"\n lastname, cbg2000 = validate_input(lastname, cbg2000)\n name_p = name_prob.loc[lastname][\n ['white', 'black', 'asian', 'other', 'hispanic']]\n if len(cbg2000) != 0:\n location_ethnic_p = location_ethnic_prob.loc[cbg2000][\n ['white', 'black', 'asian', 'other', 'hispanic']]\n name_p = name_p.reset_index().drop('name', axis=1)\n location_ethnic_p = location_ethnic_p.reset_index().drop('GISJOIN', axis=1)\n numerator = location_ethnic_p * name_p\n denominator = numerator.sum(axis=1)\n ans = numerator.div(denominator, axis='index').fillna(0)\n\n ethnic_pred_race = ans.idxmax(axis=1).tolist()\n ethnic_pred_prob = ans.max(axis=1).tolist()\n else:\n ethnic_pred_race = name_p.idxmax(axis=1).tolist()\n ethnic_pred_prob = name_p.max(axis=1).tolist()\n ans = name_p.fillna(0)\n if verbose_prob:\n if verbose_all:\n return ethnic_pred_race, ans\n else:\n return ethnic_pred_race, ethnic_pred_prob\n else:\n return ethnic_pred_race\n\n\ndef main():\n \"\"\"\n Usage: 1. Use preprocess_surname() to get name_prob\n 2. Use preprocess_census() to get cleaned census\n 3. Use create_location_ethnic_prob() to get location_ethnic_prob\n and ethnic_perc\n 4. Use preprocess_voter() to get cleaned voter's file\n 5. Specify the column containing surname and geolocation code.\n eg, 'lastname' and 'gisjoin00'\n Please note that geolocation code in voter's file should match\n with census file.\n 6. Put all of data described above into predict_ethnic() to get\n the predicted ethnic\n 7. Use metric to measure the performance if needed.\n Note: If cbg2000 is an empty list, it will only use name to do prediction\n \"\"\"\n print('READ SURNAME LIST')\n name_prob = preprocess_surname('./data/surname_list/app_c.csv')\n\n print('READ CENSUS FILE')\n census = preprocess_census(\n './data/Census2000_BG/nhgis0062_ds172_2010_block.csv',\n transform=False, census_type='block')\n\n print('CREATE PROBABILITY MATRIX BASED ON CENSUS FILE')\n location_ethnic_prob, ethnic_perc = create_location_ethnic_prob(\n census, True)\n\n print('READ VOTER FILE')\n # If remove_flag == True, it will remove voters whose surname are not in census surname list\n # \n # If remove_flag == False, it will keep those voters and use n-gram + logistic regression\n # to predict their ethnicity based on surname\n remove_flag = False\n voter_file = preprocess_voter('./data/FL1_voters_geo_covariates.csv', census_type='block', sample=0, remove_name=remove_flag)\n\n if not remove_flag:\n print('USE N-GRAM TO PREDICT VOTER NOT ON THE NAME LIST')\n notinlistname = np.setdiff1d(voter_file['lastname'], name_prob.index)\n try:\n n_gram_model = joblib.load('./model/n_gram.pkl')\n classifier = joblib.load('./model/classifier.pkl')\n except:\n n_gram_model, classifier = create_name_predictor('./data/surname_list/app_c.csv')\n notinname_prob = classifier.predict_proba(n_gram_model.transform(notinlistname))\n notinname_df = pd.DataFrame(notinname_prob, columns=classifier.classes_,index=notinlistname)\n notinname_df.index.name = 'name'\n name_prob = name_prob.append(notinname_df)\n print('Sample size %d' % len(voter_file))\n\n print('START PREDICTING')\n surname = voter_file['lastname']\n cbg2000 = voter_file['gisjoin10']\n predict = predict_ethnic(\n surname, cbg2000, name_prob, location_ethnic_prob, False)\n predict = pd.Series(predict).apply(transform_output)\n predict.to_pickle('./out_blk.pkl')\n print(accuracy_score(predict, voter_file['race']))\n print(np.sum(predict == voter_file['race']) / float(len(predict)))\n print(classification_report(predict, voter_file['race']))\n print(confusion_matrix(predict, voter_file['race']))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ethnic_predict.py","file_name":"ethnic_predict.py","file_ext":"py","file_size_in_byte":5427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"183982671","text":"\"\"\"\n Digitando algo pelo teclado e armazenando na mesma variável\n\"\"\"\n\nfrase = input('Digite algo: ')\n\n\"\"\"\n Somando dois números\n\"\"\"\n\nn1 = int(input('Digite o primeiro número: '))\nn2 = int(input('Digite o segundo número: '))\nsoma = n1 + n2\nprint(f'A soam de {n1} e {n2} é: {soma}')\n\n\"\"\"\n Tipos de dados:\n\n int: inteiro\n float: ponto flutuante, real\n bool: booleano\n str: string\n\"\"\"\n\n# Formatação: print|(\".....\".format(variável))\n#...........: print|(f\".....{variável}\")\n\n\"\"\"\n Tipos:\n type(variável)\n\"\"\"","sub_path":"Arquivos em PYTHON/Resumo/Curso em vídeo/Tipos_Primitivos_e_Saída_de_dados.py","file_name":"Tipos_Primitivos_e_Saída_de_dados.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"211744351","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.template import loader\nfrom django.http import JsonResponse\nfrom data_scraping.models import State, County, StatePop, CountyPop, Indicator\nimport json\nfrom analyze_visual.models import Visual, StateInfo\n# Create your views here.\n\ndef index(request):\n template = loader.get_template('analyze_visual/home.html')\n visual = Visual.objects.all().order_by('order')\n context = {\n 'visual': visual,\n 'geo_type':'all_state',\n 'states':State.objects.all().order_by(\"state_name\")\n }\n return HttpResponse(template.render(context, request))\n\ndef state(request, state_short_name):\n template = loader.get_template('analyze_visual/state.html')\n context = {\n 'visual': Visual.objects.all().exclude(chart_type=\"PNG\").order_by('order'),\n 'states':State.objects.all().order_by(\"state_name\"),\n 'state':State.objects.filter(state_short_name=state_short_name).first(),\n 'stateinfo': StateInfo.objects.filter(state__state_short_name=state_short_name),\n 'counties': County.objects.filter(state__state_short_name=state_short_name)\n }\n return HttpResponse(template.render(context, request))\n\ndef jing(request):\n return HttpResponse(\"

    I'm Jing

    \")\n \ndef geo_api(request):\n if request.method == 'GET':\n geo_type = request.GET.get(\"geo_type\", None) # all_state, all_county, state, county\n geo_state_id = request.GET.get(\"geo_state_id\", None)\n geo_county_id = request.GET.get(\"geo_county_id\", None)\n if geo_type == \"all_state\":\n result = {\"type\":\"FeatureCollection\", \"features\":[]}\n for state in State.objects.all():\n i = {\"type\":\"Feature\", \"id\":\"USA-%s\"%state.state_short_name,\n \"properties\":{\"state_id\":state.state_id,\"name\":state.state_name},\n \"geometry\": json.loads(state.geometry.replace(\"'\",'\"'))}\n result[\"features\"].append(i)\n return JsonResponse(result)\n if geo_type == \"all_county\" and geo_state_id != None:\n state = State.objects.filter(state_id=geo_state_id).first()\n result = {\"type\":\"FeatureCollection\", \n \"properties\":{\"kind\":\"state\", \"state\":state.state_short_name},\n \"features\":[]}\n for county in County.objects.filter(state = state):\n i = {\"type\":\"Feature\",\n \"properties\":{\"kind\":\"county\",\"county_id\":county.county_id, \"name\":county.county_name, \"state\":state.state_short_name},\n \"geometry\": json.loads(county.geometry.replace(\"'\",'\"'))\n }\n result[\"features\"].append(i)\n return JsonResponse(result)\n if geo_type == \"state\" and geo_state_id != None:\n state = State.objects.filter(state_id=geo_state_id).first()\n result = {\"type\":\"FeatureCollection\", \n \"properties\":{\"kind\":\"state\", \"state\":state.state_short_name},\n \"features\":[{\"type\":\"Feature\", \"id\":\"USA-%s\"%state.state_short_name,\n \"properties\":{\"state_id\":state.state_id,\"name\":state.state_name},\n \"geometry\": json.loads(state.geometry.replace(\"'\",'\"'))}]}\n return JsonResponse(result)\n if geo_type == \"county\" and geo_state_id != None and geo_county_id != None:\n state = State.objects.filter(state_id=geo_state_id).first()\n county = County.objects.filter(state=state, county_id=geo_county_id).first()\n result = {\"type\":\"FeatureCollection\", \n \"properties\":{\"kind\":\"state\", \"state\":state.state_short_name},\n \"features\":[{\"type\":\"Feature\",\n \"properties\":{\"kind\":\"county\",\"county_id\":county.county_id, \"name\":county.county_name, \"state\":state.state_short_name},\n \"geometry\": json.loads(county.geometry.replace(\"'\",'\"'))\n }]}\n return JsonResponse(result)\n if geo_type == \"all_county\":\n result = {\"type\":\"FeatureCollection\", \n \"properties\":{\"kind\":\"state\"},\n \"features\":[]}\n for county in County.objects.all():\n i = {\"type\":\"Feature\",\n \"properties\":{\"kind\":\"county\",\"county_id\":county.county_id, \"name\":county.county_name, \"state\":county.state.state_short_name},\n \"geometry\": json.loads(county.geometry.replace(\"'\",'\"'))\n }\n result[\"features\"].append(i)\n return JsonResponse(result)\n \n return JsonResponse({'message':'error'})\n ","sub_path":"analyze_visual/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"577183391","text":"import memory_normal # DON'T import as *\r\nimport EXEC_data_normal\r\nimport register_file\r\n\r\ndef hex_to_binary(char):\r\n if char == '0': return '0000'\r\n elif char == '1': return '0001'\r\n elif char == '2': return '0010'\r\n elif char == '3': return '0011'\r\n elif char == '4': return '0100'\r\n elif char == '5': return '0101'\r\n elif char == '6': return '0110'\r\n elif char == '7': return '0111'\r\n elif char == '8': return '1000'\r\n elif char == '9': return '1001'\r\n elif char == 'a': return '1010'\r\n elif char == 'b': return '1011'\r\n elif char == 'c': return '1100'\r\n elif char == 'd': return '1101'\r\n elif char == 'e': return '1110'\r\n elif char == 'f': return '1111'\r\n\r\nfile_object = open(\"MachineCode.txt\", \"r\")\r\nmc_code = file_object.readlines()\r\n\r\nfor i in range(len(mc_code)):\r\n if (mc_code[i])[-1] == '\\n': mc_code[i] = mc_code[i][:-1]\r\n# print(mc_code)\r\n\r\ni = 0\r\nfor i in range(len(mc_code)):\r\n if mc_code[i] == '': break\r\n\r\n value = \"\"\r\n j = mc_code[i].find(' ')\r\n address = int(mc_code[i][:j],16)\r\n if mc_code[i][j+1] == '\"':\r\n type = 0 # str\r\n value = (mc_code[i])[j+2:-1]\r\n elif mc_code[i][j+1] == 'b':\r\n type = 1 # byte\r\n value = mc_code[i][j+3:-1]+' '\r\n # length = 0\r\n # for f in range(j+4,len(mc_code[i])):\r\n # if mc_code[i][f] == ' ': length += 1\r\n elif mc_code[i][j+1] == 'w':\r\n type = 2 # word\r\n value = mc_code[i][j+3:-1] + ' '\r\n elif mc_code[i][j+1] == 'h':\r\n type = 3 # half-word\r\n value = mc_code[i][j+3:-1] + ' '\r\n elif mc_code[i][j+1] == 'd':\r\n type = 4 # double word\r\n value = mc_code[i][j+3:-1] + ' '\r\n\r\n EXEC_data_normal.execute_data(value,type,address)\r\n\r\nfor i in range(i+2,len(mc_code)):\r\n j = mc_code[i].find(' ')\r\n address = (mc_code[i])[:j]\r\n k = (mc_code[i])[j+1:]\r\n binary_equivalent = hex_to_binary(k[2]) + hex_to_binary(k[3]) + hex_to_binary(k[4]) + hex_to_binary(k[5]) + hex_to_binary(k[6]) + hex_to_binary(k[7]) + hex_to_binary(k[8]) + hex_to_binary(k[9])\r\n # print(binary_equivalent)\r\n memory_normal.write_code_line_to_mem(int(address,16), binary_equivalent)\r\n\r\n\r\n\r\n# register_file.print_register(0)\r\n# memory_normal.print_all_memory()\r\n# print(memory_normal.code_stop)\r\n# print(hex(memory_normal.data_stop))\r\n# print(memory_normal.read_byte_from_mem(int(\"0x0\",16)))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Source Code/parent_normal.py","file_name":"parent_normal.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"375358904","text":"import numpy as np\r\n\r\n# This script transforms csv-files into a 2D-matrix\r\n# of rows x columns, which is lines x columns in the csv file..\r\n# This is not the best way, it's just for illustration.\r\n\r\n# Create an empty list to hold the matrix\r\nX = []\r\n\r\ninput_filepath = \"inputfilepathhere\"\r\n\r\nfor line in open(input_filepath):\r\n\r\n # For each line in the file, split on the commas\r\n row = line.split(',')\r\n\r\n # Remove any line break characters\r\n # need not be done since we are casting to float,\r\n # but good to know. Although this doesn't work as is,\r\n # need to change it a bit and not just lift it out of print statement\r\n\r\n # print([s.replace('\\n', '') for s in row])\r\n #\r\n # print(row)\r\n\r\n # This yields strings, so we want to cast them into floats\r\n # Note that the map function returns a map, so we need to pass it\r\n # to the list()-function.\r\n sample = list(map(float, row))\r\n\r\n # Append to our list\r\n X.append(sample)\r\n\r\n\r\n# Convert the list into an numpy array\r\nX = np.array(X)\r\n\r\nprint(X)\r\n\r\n# Check the shape\r\nprint(X.shape)\r\n\r\n\r\n","sub_path":"utils/CSVtoMatrix.py","file_name":"CSVtoMatrix.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"567963548","text":"from tunezagg.base import MethodMetaclass\n\n\n\"\"\"\nBase class for data structures in which response data is dumped\n\"\"\"\n\nclass ServiceMethod(object):\n __metaclass__ = MethodMetaclass\n\n def __init__(self, **values):\n self._data = {}\n\n for key in self._fields.keys():\n try:\n setattr(self, key, values.pop(key))\n except AttributeError:\n pass\n\n @classmethod\n def from_object(cls, obj):\n values = {}\n\n for field_name, field in cls._fields.items():\n field_key = field.object_key or field_name\n\n bits = field_key.split('.')\n root_attr = bits.pop(0)\n value = obj.get(root_attr)\n\n while bits:\n bit = bits.pop(0)\n\n try:\n bit = int(bit)\n value = value[bit]\n except IndexError:\n value = None\n break\n except ValueError:\n if isinstance(value, dict):\n value = value[bit]\n else:\n value = getattr(value, bit, None)\n if callable(value):\n value = value()\n\n if value is not None:\n value = field.to_python(value)\n values[field_name] = value\n\n return cls(**values)\n\n @classmethod\n def from_response(cls, obj):\n return cls.from_object(obj)\n","sub_path":"models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"357805298","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 17 09:57:00 2019\n\n@author: jmat\n\"\"\"\n\n\nimport pandas\nimport folium\n\ndata= pandas.read_csv(\"Volcanoes_USA.txt\")\n\ndef color_producer(elevation):\n if elevation <1000:\n return \"green\"\n elif 1000<= elevation <3000:\n return \"orange\"\n else:\n return \"red\"\n \nmap=folium.Map(location=[38.58,-99.09],zoom_start=6)\n\nfg=folium.FeatureGroup(name=\"My Map\")\nx=list(data[\"LAT\"])\ny=list(data[\"LON\"])\nz=list(data[\"NAME\"])\ne=list(data[\"ELEV\"])\nfor lat,lon,name,elev in zip(x,y,z,e):\n map.add_child(folium.CircleMarker(location=[lat,lon] ,radius=6,popup =name+\" Elev:\"+str(elev)+ \" meters\" ,fill_color=color_producer(elev),color=\"grey\",fill_opacity=0.7))\n\nfg.add_child(folium.GeoJson(data=(open(\"world.json\",\"r\",encoding=\"utf-8-sig\")).read(),\n style_function=lambda x : {\"fillColor\":\"green\" if x['properties']['POP2005'] <10000000\n else \"orange\" if 10000000<= x['properties']['POP2005'] <=20000000\n else \"red\"\n }\n ) )\n\nmap.add_child(fg)\n\n## Can be used for marking with CSV data of markers\nmap.save(\"Coloring_GeoJSON_Layer.html\")","sub_path":"Web Map/Coloring_GeoJSON_Layer.py","file_name":"Coloring_GeoJSON_Layer.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"336372255","text":"#!/usr/bin/env python\nimport rospy\nimport math\n\nfrom std_msgs.msg import Float64\nfrom gazebo_msgs.msg import ContactsState\nfrom sensor_msgs.msg import Imu\nfrom nav_msgs.msg import Odometry\nfrom geometry_msgs.msg import Point, Quaternion, Vector3\nfrom sensor_msgs.msg import JointState\n\nfrom gazebo_connection import GazeboConnection\nfrom biped_inverse_kinematics import BipedKinematics\n\n\nclass BipedRobot(object):\n def __init__(self):\n self.gazebo = GazeboConnection\n\n # publisher\n self.publishers = []\n self._L_haa_joint_pub = rospy.Publisher(\n '/biped/L_haa_joint_position_controller/command', Float64, queue_size=1)\n self._L_hfe_joint_pub = rospy.Publisher(\n '/biped/L_hfe_joint_position_controller/command', Float64, queue_size=1)\n self._L_kfe_joint_pub = rospy.Publisher(\n '/biped/L_kfe_joint_position_controller/command', Float64, queue_size=1)\n self._R_haa_joint_pub = rospy.Publisher(\n '/biped/R_haa_joint_position_controller/command', Float64, queue_size=1)\n self._R_hfe_joint_pub = rospy.Publisher(\n '/biped/R_hfe_joint_position_controller/command', Float64, queue_size=1)\n self._R_kfe_joint_pub = rospy.Publisher(\n '/biped/R_kfe_joint_position_controller/command', Float64, queue_size=1)\n\n self.publishers.append(self._L_haa_joint_pub)\n self.publishers.append(self._L_hfe_joint_pub)\n self.publishers.append(self._L_kfe_joint_pub)\n self.publishers.append(self._R_haa_joint_pub)\n self.publishers.append(self._R_hfe_joint_pub)\n self.publishers.append(self._R_kfe_joint_pub)\n\n # subscriber\n self.base_position = Point()\n self.base_orientation = Quaternion()\n self.base_angular_velocity = Vector3()\n self.base_linear_acceleration = Vector3()\n self.L_contact_force = Vector3()\n self.R_contact_force = Vector3()\n self.joints_state = JointState()\n\n rospy.Subscriber(\"/odom\", Odometry, self.odom_callback)\n rospy.Subscriber(\"/biped/imu/data\", Imu, self.imu_callback)\n rospy.Subscriber(\"/L_lowerleg_contactsensor_state\",\n ContactsState, self.L_contact_callback)\n rospy.Subscriber(\"/R_lowerleg_contactsensor_state\",\n ContactsState, self.R_contact_callback)\n rospy.Subscriber(\"/biped/joint_states\", JointState,\n self.joints_state_callback)\n\n self.initial_pos()\n\n def initial_pos(self):\n pos = [-0.8, 1.57, -1.57, 0.8, 1.57, -1.57]\n pos = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n self.move_joints(pos)\n\n def odom_callback(self, msg):\n self.base_position = msg.pose.pose.position\n\n def imu_callback(self, msg):\n self.base_orientation = msg.orientation\n self.base_angular_velocity = msg.angular_velocity\n self.base_linear_acceleration = msg.linear_acceleration\n\n def L_contact_callback(self, msg):\n for state in msg.states:\n self.L_contact_force = state.total_wrench.force\n\n def R_contact_callback(self, msg):\n for state in msg.states:\n self.R_contact_force = state.total_wrench.force\n\n def joints_state_callback(self, msg):\n self.joints_state = msg\n\n def move_joints(self, joints_array):\n\n for i, publisher_object in enumerate(self.publishers):\n joint_value = Float64()\n joint_value.data = joints_array[i]\n rospy.loginfo(str(joint_value))\n publisher_object.publish(joint_value)\n\n def start_loop(self, rate_value=0.5):\n rospy.loginfo(\"Start Loop\")\n pos1 = [-0.0, 0.8, -0.0, 0.0, 0.8, -0.0]\n pos2 = [0.0, -0.8, 0.0, 0.0, -0.8, 0.0]\n position = \"pos1\"\n rate = rospy.Rate(rate_value)\n while not rospy.is_shutdown():\n if position == \"pos1\":\n self.move_joints(pos1)\n position = \"pos2\"\n else:\n self.move_joints(pos2)\n position = \"pos1\"\n rate.sleep()\n\n # def move_leg(self, x_pos, y_pos, z_pos):\n\ndef clip(value, max_value = 0.5):\n if(value>max_value):\n return max_value\n elif(value<-1*max_value):\n return -1*max_value\n else:\n return value\n\nif __name__ == \"__main__\":\n rospy.init_node('joint_publisher_node')\n my_robot = BipedRobot()\n rate_value = 50\n rate = rospy.Rate(rate_value)\n # my_robot.start_loop()\n\n target_angle = 0\n kp = 10\n kd = 1\n angle_diff = 0\n pre_angle_diff = 0\n leg_angle = 0\n while not rospy.is_shutdown():\n \n # pos = [0.0, -0.5, 0.0, 0.0, -0.5, 0.0]\n\n # my_robot.move_joints(pos)\n\n body_angle = my_robot.base_position.x/(my_robot.base_position.z+10e-8)\n body_angle = math.atan(body_angle)\n # angle = math.degrees(angle)\n angle_diff = body_angle-target_angle\n \n # if(my_robot.L_contact_force.z < 0 or my_robot.R_contact_force.z < 0):\n # leg_angle = -1 * (kp*angle_diff - kd*(angle_diff-pre_angle_diff))\n # leg_angle = clip(leg_angle, 0.8)\n # pos = [0.0, leg_angle, 0.0, 0.0, leg_angle, 0.0]\n # my_robot.move_joints(pos)\n # else:\n # my_robot.initial_pos()\n leg_angle = 1 * (kp*angle_diff - kd*(angle_diff-pre_angle_diff))\n leg_angle = clip(leg_angle, 1.0)\n pos = [0.0, leg_angle, 0.0, 0.0, leg_angle, 0.0]\n my_robot.move_joints(pos)\n \n pre_angle_diff = angle_diff\n print(angle_diff)\n print(leg_angle)\n \n rate.sleep()\n # my_robot.start_loop(rate_value)\n","sub_path":"ros/src/my_biped_robot_sims/scripts/BipedRobot.py","file_name":"BipedRobot.py","file_ext":"py","file_size_in_byte":5663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"417303753","text":"import json\n\nfrom django import template\nfrom django.template.exceptions import TemplateDoesNotExist\nfrom django.template.loader import render_to_string\nfrom django.utils.safestring import mark_safe\n\nfrom envergo.geodata.utils import to_geojson as convert_to_geojson\n\nregister = template.Library()\n\n\n@register.simple_tag\ndef to_geojson(obj, geometry_field=\"geometry\"):\n json_obj = convert_to_geojson(obj)\n return mark_safe(json.dumps(json_obj))\n\n\n@register.simple_tag(takes_context=True)\ndef show_regulation_body(context, regulation):\n template_name = f\"moulinette/{regulation.slug}/result_{regulation.result}.html\"\n try:\n content = render_to_string(template_name, context=context.flatten())\n except TemplateDoesNotExist:\n content = \"\"\n\n return content\n\n\n@register.simple_tag(takes_context=True)\ndef show_criterion_body(context, regulation, criterion):\n template_name = (\n f\"moulinette/{regulation.slug}/{criterion.slug}_{criterion.result_code}.html\"\n )\n context_data = context.flatten()\n context_data.update({\"regulation\": regulation, \"criterion\": criterion})\n try:\n content = render_to_string(template_name, context_data)\n except TemplateDoesNotExist:\n content = \"\"\n\n return content\n\n\n@register.simple_tag\ndef criterion_value(config, criterion, field):\n \"\"\"Display a criterion static value.\n\n If this value is overriden in the MoulinetteConfig instance,\n display the config value instead.\n \"\"\"\n values = config.criteria_values\n key = f\"{criterion.unique_slug}__{field}\"\n default = getattr(criterion, field, \"\")\n return mark_safe(values.get(key, default))\n\n\n@register.simple_tag()\ndef debug(stuff):\n raise 0\n","sub_path":"envergo/moulinette/templatetags/moulinette.py","file_name":"moulinette.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"58707333","text":"# -*- coding: utf8 -*-\nimport pytest\n\nfrom nest.repository.location import DatabaseLocationRepository\nfrom nest.repository.plan import DatabasePlanRepository\nfrom nest.repository.task import DatabaseTaskRepository\nfrom nest.repository.user import DatabaseUserRepository\nfrom nest.web import main\nfrom .user_helper import register_user\nfrom tests.web.helper import mysql_connection\n\n_plan_ids = []\n_task_id = None\nlocation_repository = DatabaseLocationRepository(\n connection=mysql_connection,\n)\nplan_repository = DatabasePlanRepository(\n connection=mysql_connection,\n)\ntask_repository = DatabaseTaskRepository(\n connection=mysql_connection,\n)\nuser_repository = DatabaseUserRepository(\n connection=mysql_connection,\n)\n\n\ndef clear_database():\n plan_repository.clear()\n task_repository.clear()\n user_repository.clear()\n\n\n# 写法来自这里:https://docs.pytest.org/en/stable/xunit_setup.html\ndef setup_module():\n clear_database()\n register_user(location_repository, user_repository)\n print('初始化完毕')\n\n\ndef teardown_module():\n clear_database()\n print('清理数据库')\n\n\n@pytest.fixture\ndef client():\n with main.app.test_client() as client:\n client.post('/user/login', json={\n 'email': 'foobar.bef@gmail.com',\n 'password': 'def',\n })\n yield client\n\n\ndef test_create_task(client):\n # 创建任务以便联表查询\n rv = client.post('/task', json={\n 'brief': 'test',\n })\n json_data = rv.get_json()\n global _task_id\n _task_id = json_data['result']['id']\n\n\ndef test_create_plan(client):\n rv = client.post('/plan', json={\n 'repeat_type': 'hourly',\n 'task_id': _task_id,\n 'trigger_time': '2021-02-20 17:39:00',\n })\n json_data = rv.get_json()\n assert json_data['result']['id']\n assert isinstance(json_data['result']['id'], int)\n global _plan_ids\n _plan_ids.append(json_data['result']['id'])\n\n\ndef test_get_plan(client):\n rv = client.get('/plan/{}'.format(_plan_ids[0]))\n assert rv.get_json()['status'] == 'success'\n result = rv.get_json()['result']\n assert result['id'] == _plan_ids[0]\n assert result['task_id'] == _task_id\n","sub_path":"tests/web/test_get_plan.py","file_name":"test_get_plan.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"470464965","text":"# -*- coding: utf-8 -*-\n\nimport math\nimport os\nimport xc_base\nimport geom\nimport xc\n# Macros\nfrom materials.sections.fiber_section import defSimpleRCSection\nfrom postprocess import RC_material_distribution\n\n\n\nfrom materials.sia262 import SIA262_materials\nfrom materials.sia262 import SIA262_limit_state_checking\n\nfrom postprocess import limit_state_data as lsd\nfrom postprocess import element_section_map\n\n#Thickness of the elements\ndeckThickness= 0.35\nparapetBodyThickness= 0.38\nparapetHeadThickness= 0.5\n\n\n\nconcrete= SIA262_materials.c30_37\nreinfSteel= SIA262_materials.B500A\n\nreinfConcreteSectionDistribution= RC_material_distribution.RCMaterialDistribution()\nsections= reinfConcreteSectionDistribution.sectionDefinition\n\nexecfile('generic_layers_aux.py')\n\n#instances of defSimpleRCSection.RecordRCSlabBeamSection that defines the\n#variables that make up THE TWO reinforced concrete sections in the two\n#reinforcement directions of a slab or the front and back ending sections\n#of a beam element\n\ndeckRCSects= defSimpleRCSection.RecordRCSlabBeamSection(name='deckRCSects',sectionDescr='slab of shell elements',concrType=concrete, reinfSteelType=reinfSteel,depth=deckThickness) \ndeckLong= defSimpleRCSection.MainReinfLayer(rebarsDiam=16e-3,areaRebar= areaFi16,rebarsSpacing=0.150,width=1.0,nominalCover=0.040)\ndeckRCSects.dir1PositvRebarRows=[deckLong] #long. sup.\ndeckRCSects.dir1NegatvRebarRows=[deckLong] #long. inf.\ndeckTransv= defSimpleRCSection.MainReinfLayer(rebarsDiam=13e-3,areaRebar= (areaFi12+areaFi14)/2.0,rebarsSpacing=0.150,width=1.0,nominalCover=0.040)\ndeckRCSects.dir2PositvRebarRows=[deckTransv] #transv. sup.\ndeckRCSects.dir2NegatvRebarRows=[deckTransv] #transv. inf.\ndeckRCSects.creaTwoSections() \nsections.append(deckRCSects)\n\nparapetBodyRCSects= defSimpleRCSection.RecordRCSlabBeamSection(name='parapetBodyRCSects',sectionDescr='slab of shell elements',concrType=concrete, reinfSteelType=reinfSteel,depth=parapetBodyThickness) \nparapetBodyHoriz= defSimpleRCSection.MainReinfLayer(rebarsDiam=16e-3,areaRebar= areaFi16,rebarsSpacing=0.150,width=1.0,nominalCover=0.040)\nparapetBodyRCSects.dir1PositvRebarRows=[parapetBodyHoriz] #horiz. sup.\nparapetBodyRCSects.dir1NegatvRebarRows=[parapetBodyHoriz] #horiz. inf.\nparapetBodyVert= defSimpleRCSection.MainReinfLayer(rebarsDiam=13e-3,areaRebar= (areaFi12+areaFi14)/2.0,rebarsSpacing=0.150,width=1.0,nominalCover=0.040)\nparapetBodyRCSects.dir2PositvRebarRows=[parapetBodyVert] #vert. sup.\nparapetBodyRCSects.dir2NegatvRebarRows=[parapetBodyVert] #vert. inf.\nparapetBodyRCSects.creaTwoSections() \nsections.append(parapetBodyRCSects)\n\nparapetHeadRCSects= defSimpleRCSection.RecordRCSlabBeamSection(name='parapetHeadRCSects',sectionDescr='slab of shell elements',concrType=concrete, reinfSteelType=reinfSteel,depth=parapetHeadThickness) \nparapetHeadHoriz= defSimpleRCSection.MainReinfLayer(rebarsDiam=18e-3,areaRebar= areaFi18,rebarsSpacing=0.150,width=1.0,nominalCover=0.040)\nparapetHeadRCSects.dir1PositvRebarRows=[parapetHeadHoriz] #horiz. sup.\nparapetHeadRCSects.dir1NegatvRebarRows=[parapetHeadHoriz] #horiz. inf.\nparapetHeadVert= defSimpleRCSection.MainReinfLayer(rebarsDiam=13e-3,areaRebar= (areaFi12+areaFi14)/2.0,rebarsSpacing=0.150,width=1.0,nominalCover=0.040)\nparapetHeadRCSects.dir2PositvRebarRows=[parapetHeadVert] #vert. sup.\nparapetHeadRCSects.dir2NegatvRebarRows=[parapetHeadVert] #vert. inf.\nparapetHeadRCSects.creaTwoSections() \nsections.append(parapetHeadRCSects)\n\n\n\n\n","sub_path":"ps_bole_calculs_statiques/xc_model_impact/sectionsDef.py","file_name":"sectionsDef.py","file_ext":"py","file_size_in_byte":3465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"418728981","text":"def vecvel(x,y,sampling_rate):\n \"\"\"\n ----------------------------------------------------------------------\n vecvel(x,y,sampling_rate)\n ----------------------------------------------------------------------\n Goal of the function :\n Compute eye velocity\n ----------------------------------------------------------------------\n Input(s) :\n x: raw data, horizontal components of the time series\n y: raw data, vertical components of the time series\n samplign_rate: eye tracking sampling rate\n ----------------------------------------------------------------------\n Output(s) :\n vx: velocity, horizontal component\n vy: velocity, vertical component\n ----------------------------------------------------------------------\n Function created by Martin Rolfs\n adapted by Martin SZINTE (mail@martinszinte.net)\n ----------------------------------------------------------------------\n \"\"\"\n import numpy as np\n\n n = x.size\n\n vx = np.zeros_like(x)\n vy = np.zeros_like(y)\n\n vx[2:n-3] = sampling_rate/6 * (x[4:-1] + x[3:-2] - x[1:-4] - x[0:-5])\n vx[1] = sampling_rate/2*(x[2] - x[0]);\n vx[n-2] = sampling_rate/2*(x[-1]-x[-3])\n\n vy[2:n-3] = sampling_rate/6 * (y[4:-1] + y[3:-2] - y[1:-4] - y[0:-5])\n vy[1] = sampling_rate/2*(y[2] - y[0]);\n vy[n-2] = sampling_rate/2*(y[-1]-y[-3])\n\n return vx,vy\n\ndef microsacc_merge(x,y,vx,vy,velocity_th,min_dur,merge_interval):\n \"\"\"\n ----------------------------------------------------------------------\n microsacc_merge(x,y,vx,vy,velocity_th,min_duration,merge_interval)\n ----------------------------------------------------------------------\n Goal of the function :\n Detection of monocular candidates for microsaccades\n ----------------------------------------------------------------------\n Input(s) :\n x: raw data, horizontal components of the time series\n y: raw data, vertical components of the time series\n vx: velocity horizontal components of the time series\n vy: velocity vertical components of the time series\n velocity_th: velocity threshold\n min_dur: saccade minimum duration\n merge_interval: merge interval for subsequent saccade candidates\n ----------------------------------------------------------------------\n Output(s):\n out_val(0:num,0) onset of saccade\n out_val(0:num,1) end of saccade\n out_val(1:num,2) peak velocity of saccade (vpeak)\n out_val(1:num,3) saccade vector horizontal component\n out_val(1:num,4) saccade vector vertical component\n out_val(1:num,5) saccade horizontal amplitude whole sequence\n out_val(1:num,6) saccade vertical amplitude whole sequence\n ----------------------------------------------------------------------\n Function created by Martin Rolfs\n adapted by Martin SZINTE (mail@martinszinte.net)\n ----------------------------------------------------------------------\n \"\"\"\n import numpy as np\n import os\n\n\n # compute threshold\n msdx = np.sqrt(np.median(vx**2) - (np.median(vx))**2)\n msdy = np.sqrt(np.median(vy**2) - (np.median(vy))**2)\n\n if np.isnan(msdx):\n msdx = np.sqrt(np.mean(vx**2) - (np.mean(vx))**2)\n if msdx < np.nextafter(0,1):\n os.error('msdx < realmin')\n\n if np.isnan(msdy):\n msdy = np.sqrt(np.mean(vy**2) - (np.mean(vy))**2 )\n if msdy < np.nextafter(0,1):\n os.error('msdy < realmin')\n\n radiusx = velocity_th*msdx;\n radiusy = velocity_th*msdy;\n\n # compute test criterion: ellipse equation\n test = (vx/radiusx)**2 + (vy/radiusy)**2;\n indx = np.where(test>1)[0];\n\n # determine saccades\n N, nsac, dur, a, k = indx.shape[0], 0, 0, 0, 0\n\n while k < N-1:\n if indx[k+1]-indx[k]==1:\n dur += 1\n else:\n if dur >= min_dur:\n nsac += 1\n b = k\n if nsac == 1:\n sac = np.array([indx[a],indx[b]])\n else:\n sac = np.vstack((sac, np.array([indx[a],indx[b]])))\n a = k+1\n dur = 1\n\n k += 1\n\n # check for minimum duration\n if dur >= min_dur:\n nsac += 1;\n b = k;\n if nsac == 1:\n sac = np.array([indx[a],indx[b]])\n else:\n sac = np.vstack((sac, np.array([indx[a],indx[b]])))\n\n # merge saccades\n if nsac > 0:\n msac = np.copy(sac)\n s = 0\n sss = True\n nsac = 1\n while s < nsac-1:\n if sss == False:\n nsac += 1\n msac[nsac,:] = sac[s,:]\n if sac[s+1,0]-sac[s,1] <= merge_interval:\n msac[1] = sac[s+1,1]\n sss = True\n else:\n sss = False\n s += 1\n if sss == False:\n nsac += 1\n msac[nsac,:] = sac[s,:]\n else:\n msac = []\n nsac = 0\n\n # compute peak velocity, horizonal and vertical components\n\n msac = np.matrix(msac)\n out_val = np.matrix(np.zeros((msac.shape[0],7))*np.nan)\n\n if msac.shape[1]>0:\n for s in np.arange(0,msac.shape[0],1):\n\n # onset and offset\n out_val[s,0],a = msac[s,0], msac[s,0]\n out_val[s,1],b = msac[s,1], msac[s,1]\n\n # saccade peak velocity (vpeak)\n vpeak = np.max(np.sqrt(vx[a:b]**2 + vy[a:b]**2))\n out_val[s,2] = vpeak\n\n # saccade vector (dx,dy)\n dx = x[b]-x[a]\n dy = y[b]-y[a]\n out_val[s,3] = dx\n out_val[s,4] = dy\n\n # saccade amplitude (dX,dY)\n minx, maxx = np.min(x[a:b]),np.max(x[a:b])\n minix, maxix = np.where(x == minx)[0][0], np.where(x == maxx)[0][0]\n miny, maxy = np.min(y[a:b]),np.max(y[a:b])\n miniy, maxiy = np.where(y == miny)[0][0], np.where(y == maxy)[0][0]\n dX = np.sign(maxix-minix)*(maxx-minx);\n dY = np.sign(maxiy-miniy)*(maxy-miny);\n out_val[s,5] = dX\n out_val[s,6] = dY\n\n\n return out_val\n\ndef saccpar(sac):\n \"\"\"\n ----------------------------------------------------------------------\n saccpar(sac)\n ----------------------------------------------------------------------\n Goal of the function :\n Arange data from microsaccade detection\n ----------------------------------------------------------------------\n Input(s) :\n sac: monocular microsaccades matrix (from microsacc_merge)\n ----------------------------------------------------------------------\n Output(s):\n out_val(0:num,0) saccade onset\n out_val(0:num,1) saccade offset\n out_val(1:num,2) saccade duration\n out_val(1:num,3) saccade velocity peak\n out_val(1:num,4) saccade vector distance\n out_val(1:num,5) saccade vector angle\n out_val(1:num,6) saccade whole sequence amplitude\n out_val(1:num,7) saccade whole sequence angle\n ----------------------------------------------------------------------\n Function created by Martin Rolfs\n adapted by Martin SZINTE (mail@martinszinte.net)\n ----------------------------------------------------------------------\n \"\"\"\n import numpy as np\n\n if sac.shape[0] > 0:\n # 0. Saccade onset\n sac_onset = np.array(sac[:,0])\n\n # 1. Saccade offset\n sac_offset = np.array(sac[:,1])\n\n # 2. Saccade duration\n sac_dur = np.array(sac[:,1] - sac[:,0])\n\n # 3. Saccade peak velocity\n sac_pvel = np.array(sac[:,2])\n\n # 4. Saccade vector distance and angle\n sac_dist = np.sqrt(np.array(sac[:,3])**2 + np.array(sac[:,4])**2)\n\n # 5. Saccade vector angle\n sac_angd = np.arctan2(np.array(sac[:,4]),np.array(sac[:,3]))\n\n # 6. Saccade whole sequence amplitude\n sac_ampl = np.sqrt(np.array(sac[:,5])**2 + np.array(sac[:,6])**2)\n\n # 7. Saccade whole sequence amplitude\n sac_anga = np.arctan2(np.array(sac[:,6]),np.array(sac[:,5]))\n\n # make matrix\n out_val = np.matrix(np.hstack((sac_onset,sac_offset,sac_dur,sac_pvel,sac_dist,sac_angd,sac_ampl,sac_anga)))\n else:\n out_val = np.matrix([]);\n\n return out_val\n\n\ndef isincircle(x,y,xc,yc,rad):\n \"\"\"\n ----------------------------------------------------------------------\n isincircle(x,y,xc,yc,rad)\n ----------------------------------------------------------------------\n Goal of the function :\n Check if coordinate in circle\n ----------------------------------------------------------------------\n Input(s) :\n x: x coordinate\n y: y coordinate\n xc: x coordinate of circle\n yc: y coordinate of circle\n rad: radius of circle\n ----------------------------------------------------------------------\n Output(s):\n incircle: (True) = yes, (False) = no\n ----------------------------------------------------------------------\n Function created by Martin Rolfs\n adapted by Martin SZINTE (mail@martinszinte.net)\n ----------------------------------------------------------------------\n \"\"\"\n import numpy as np\n\n if np.sqrt((x-xc)**2 + (y-yc)**2) < rad:\n incircle = True\n else:\n incircle = False\n\n return incircle\n\ndef draw_bg_trial(analysis_info,draw_cbar = False):\n \"\"\"\n ----------------------------------------------------------------------\n draw_bg_trial(analysis_info,draw_cbar = False)\n ----------------------------------------------------------------------\n Goal of the function :\n Draw eye traces figure background\n ----------------------------------------------------------------------\n Input(s) :\n analysis_info: analysis settings\n draw_cbar: draw color circle (True) or not (False)\n ----------------------------------------------------------------------\n Output(s):\n incircle: (True) = yes, (False) = no\n ----------------------------------------------------------------------\n Function created by Martin Rolfs\n adapted by Martin SZINTE (mail@martinszinte.net)\n ----------------------------------------------------------------------\n \"\"\"\n import numpy as np\n import cortex\n import matplotlib.pyplot as plt\n import matplotlib.gridspec as gridspec\n from matplotlib.ticker import FormatStrFormatter\n import matplotlib.colors as colors\n import ipdb\n deb = ipdb.set_trace\n\n # Saccade analysis per run and sequence\n # Define figure\n title_font = {'loc':'left', 'fontsize':14, 'fontweight':'bold'}\n axis_label_font = {'fontsize':14}\n bg_col = (0.9, 0.9, 0.9)\n axis_width = 0.75\n line_width_corr = 1.5\n\n # Horizontal eye trace\n screen_val = 12.5\n ymin1,ymax1,y_tick_num1 = -screen_val,screen_val,11\n y_tick1 = np.linspace(ymin1,ymax1,y_tick_num1)\n xmin1,xmax1,x_tick_num1 = 0,1,5\n x_tick1 = np.linspace(xmin1,xmax1,x_tick_num1)\n\n # Vertical eye trace\n ymin2,ymax2,y_tick_num2 = -screen_val,screen_val,11\n y_tick2 = np.linspace(ymin2,ymax2,y_tick_num2)\n xmin2,xmax2,x_tick_num2 = 0,1,5\n x_tick2 = np.linspace(xmin2,xmax2,x_tick_num2)\n\n cmap = 'hsv'\n cmap_steps = 16\n col_offset = 0#1/14.0\n base = cortex.utils.get_cmap(cmap)\n val = np.linspace(0, 1,cmap_steps+1,endpoint=False)\n colmap = colors.LinearSegmentedColormap.from_list('my_colmap',base(val), N = cmap_steps)\n\n pursuit_polar_ang = np.deg2rad(np.arange(0,360,22.5))\n pursuit_ang_norm = (pursuit_polar_ang + np.pi) / (np.pi * 2.0)\n pursuit_ang_norm = (np.fmod(pursuit_ang_norm + col_offset,1))*cmap_steps\n\n pursuit_col_mat = colmap(pursuit_ang_norm.astype(int))\n pursuit_col_mat[:,3]=0.2\n\n saccade_polar_ang = np.deg2rad(np.arange(0,360,22.5)+180)\n saccade_ang_norm = (saccade_polar_ang + np.pi) / (np.pi * 2.0)\n saccade_ang_norm = (np.fmod(saccade_ang_norm + col_offset,1))*cmap_steps\n\n saccade_col_mat = colmap(saccade_ang_norm.astype(int))\n saccade_col_mat[:,3] = 0.8\n\n\n polar_ang = np.deg2rad(np.arange(0,360,22.5))\n\n fig = plt.figure(figsize = (15, 7))\n gridspec.GridSpec(2,8)\n\n # Horizontal eye trace\n ax1 = plt.subplot2grid((2,8),(0,0),rowspan= 1, colspan = 4)\n ax1.set_ylabel('Hor. coord. (dva)',axis_label_font,labelpad = 0)\n ax1.set_ylim(bottom = ymin1, top = ymax1)\n ax1.set_yticks(y_tick1)\n ax1.set_xlabel('Time (%)',axis_label_font,labelpad = 10)\n ax1.set_xlim(left = xmin1, right = xmax1)\n ax1.set_xticks(x_tick1)\n ax1.set_facecolor(bg_col)\n ax1.set_title('Horizontal eye position',**title_font)\n ax1.xaxis.set_major_formatter(FormatStrFormatter('%.2g'))\n for rad in analysis_info['rads']:\n ax1.plot(x_tick1,x_tick1*0+rad, color = [1,1,1], linewidth = axis_width*2)\n ax1.plot(x_tick1,x_tick1*0-rad, color = [1,1,1], linewidth = axis_width*2)\n\n # Vertical eye trace\n ax2 = plt.subplot2grid((2,8),(1,0),rowspan= 1, colspan = 4)\n ax2.set_ylabel('Ver. coord. (dva)',axis_label_font, labelpad = 0)\n ax2.set_ylim(bottom = ymin2, top = ymax2)\n ax2.set_yticks(y_tick2)\n ax2.set_xlabel('Time (%)',axis_label_font, labelpad = 10)\n ax2.set_xlim(left = xmin2, right = xmax2)\n ax2.set_xticks(x_tick2)\n ax2.set_facecolor(bg_col)\n ax2.set_title('Vertical eye position',**title_font)\n ax2.xaxis.set_major_formatter(FormatStrFormatter('%.2g'))\n for rad in analysis_info['rads']:\n ax2.plot(x_tick2,x_tick2*0+rad, color = [1,1,1], linewidth = axis_width*2)\n ax2.plot(x_tick2,x_tick2*0-rad, color = [1,1,1], linewidth = axis_width*2)\n\n # Screen eye trace\n ax3 = plt.subplot2grid((2,8),(0,4),rowspan= 2, colspan = 4)\n ax3.set_xlabel('Horizontal coordinates (dva)', axis_label_font, labelpad = 10)\n ax3.set_ylabel('Vertical coordinates (dva)', axis_label_font, labelpad = 0)\n ax3.set_xlim(left = ymin1, right = ymax1)\n ax3.set_xticks(y_tick1)\n ax3.set_ylim(bottom = ymin2, top = ymax2)\n ax3.set_yticks(y_tick2)\n ax3.set_facecolor(bg_col)\n ax3.set_title('Screen view',**title_font)\n ax3.set_aspect('equal')\n\n theta = np.linspace(0, 2*np.pi, 100)\n for rad in analysis_info['rads']:\n ax3.plot(rad*np.cos(theta), rad*np.sin(theta),color = [1,1,1],linewidth = axis_width*3)\n\n plt.subplots_adjust(wspace = 1.4,hspace = 0.4)\n\n # color legend\n if draw_cbar == True:\n cbar_axis = fig.add_axes([0.47, 0.77, 0.8, 0.1], projection='polar')\n norm = colors.Normalize(0, 2*np.pi)\n t = np.linspace(0,2*np.pi,200,endpoint=True)\n r = [0,1]\n rg, tg = np.meshgrid(r,t)\n im = cbar_axis.pcolormesh(t, r, tg.T,norm= norm, cmap = colmap)\n cbar_axis.set_yticklabels([])\n cbar_axis.set_xticklabels([])\n cbar_axis.set_theta_zero_location(\"W\",offset = -360/cmap_steps/2)\n cbar_axis.spines['polar'].set_visible(False)\n else:\n cbar_axis = []\n\n return ax1, ax2, ax3, cbar_axis\n\n","sub_path":"stats/behav_analysis/sac_utils.py","file_name":"sac_utils.py","file_ext":"py","file_size_in_byte":14789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"20865635","text":"\"\"\"\nReviews and Reports\n\"\"\"\nclass Reviews():\n\tdef __init__(self,review_id,content,like_dislike,rid,uid):\n\t\tself.review_id = \"\".join([\"review\",str(review_id)])\n\t\tself.content = content\n\t\tself.like_dislike = like_dislike\n\t\tself.rid = rid\n\t\tself.uid = uid\n\n\tdef insertReviews(self):\n\t\tinsert_reviews = \"INSERT INTO Reviews VALUES (\\'{}\\',\\'{}\\', {});\".format(self.review_id,self.content,self.like_dislike)\n\t\treturn insert_reviews\n\n\tdef insertRates(self):\n\t\tinsert_rate = \"INSERT INTO rates VALUES (\\'{}\\',\\'{}\\', \\'{}\\');\".format(self.review_id,self.rid,self.uid)\n\t\treturn insert_rate\t\t\n\nclass Reports():\n\tdef __init__(self,report_id,content,rating,rid,uid):\n\t\tself.report_id = \"\".join([\"report\",str(report_id)])\n\t\tself.content = content\n\t\tself.rating = rating\n\t\tself.rid = rid\n\t\tself.uid = uid\n\n\tdef insertReports(self):\n\t\tinsert_reports = \"INSERT INTO Reports VALUES (\\'{}\\',\\'{}\\', {});\".format(self.report_id,self.content,self.rating)\n\t\treturn insert_reports\n\n\tdef insertWriteAbout(self):\n\t\tinsert_write_about = \"INSERT INTO write_about VALUES (\\'{}\\',\\'{}\\', \\'{}\\');\".format(self.report_id,self.uid,self.rid)\n\t\treturn insert_write_about\t\t\n\n\n\n\n\nif __name__ == \"__main__\":\n\tr = Reviews(1,\"good food\",True,\"restaurant1\",\"foodie19\")\n\tprint(r.insertReviews())\n\tprint(r.insertRates())\n\n\tp = Reports(1,\"good food\",True,\"restaurant1\",\"foodie19\")\n\tprint(p.insertReports())\n\tprint(p.insertWriteAbout())\n\n\n\n\n\n","sub_path":"Reviews.py","file_name":"Reviews.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"494667293","text":"from flask_wtf import FlaskForm\r\nfrom wtforms import SubmitField, StringField, validators, TextAreaField, \\\r\n SelectMultipleField\r\n\r\n\r\nclass CreateArticleForm(FlaskForm):\r\n title = StringField('Title', [validators.DataRequired()])\r\n text = TextAreaField('Text', [validators.DataRequired()])\r\n tags = SelectMultipleField('Tags', coerce=int)\r\n submit = SubmitField('Create Article')\r\n","sub_path":"blog/forms/article.py","file_name":"article.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"39912943","text":"import numpy as np\nimport pandas as pd\ndef clean():\n df_clean = None\n df = pd.read_csv(\"earthquake.csv\")\n col_n = ['time','latitude','longitude','depth','mag','place']\n a = pd.DataFrame(df,columns=col_n)\n b=pd.DataFrame(a['place'].str.split(',',1).tolist(),columns=['loc','region'])\n col_clean = ['time','latitude','longitude','depth','mag','region']\n result = a.join(b)\n df_clean = pd.DataFrame(result,columns=col_clean)\n df_clean = df_clean.dropna()\n df_clean = df_clean.drop_duplicates()\n return df_clean\nprint(clean())\n","sub_path":"data_week2-2/earthquake.py","file_name":"earthquake.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"209438849","text":"# _*_ coding:utf-8 _*_\n#文件作者: ZHMing123\n#开发时间:2019/11/1 21:47\n#文件名称:MaoyanSpider.py\n#开发工具:PyCharm\n\nimport re\nfrom scrapy.spiders import Rule, CrawlSpider\nfrom scrapy.selector import Selector\nfrom scrapy.linkextractors import LinkExtractor\nfrom maoyan.items import MaoyanItem\nfrom data_decrytion import data_decrytion\n\nclass MaoyanSpider(CrawlSpider):\n name = \"maoyan\"\n start_urls = [\"https://maoyan.com/films\"]\n rules = (\n Rule(LinkExtractor(allow=(r'https://maoyan.com/films\\?showType=3&offset=\\d{0,3}'))),\n Rule(LinkExtractor(allow=(r'https://maoyan.com/films/\\d+')), callback=\"parse_item\")\n )\n\n def parse_item(self, response):\n # print(response.body)\n # sel = Selector(response)\n movie_name = response.css(\"div.movie-brief-container h3.name::text\").extract_first()\n movie_English_name = response.css(\"div.movie-brief-container div[class='ename ellipsis']::text\").extract_first()\n movie_type = response.css(\"div.movie-brief-container li.ellipsis::text\")[0].extract()\n movie_release = response.css(\"div.movie-brief-container li.ellipsis::text\")[2].extract()\n movie_total_time = response.css(\"div.movie-brief-container li.ellipsis::text\")[1].extract().split('/')[-1].strip()\n # movie_rate = float(response.css(\"div.star-on::attr(style)\").extract_first().strip(\";%\").split(\":\")[1])/10\n # movie_rate = response.css(\"span.stonefont::text\").extract()[0]\n # movie_comment_num = response.css(\"span.stonefont::text\").extract()[1]\n # movie_box_office = response.css(\"span.stonefont::text\").extract()[2] + '亿'\n\n # print(response.css(\"span.stonefont::text\").extract())\n\n # cmp = re.compile(r\"(&#x.*;)\")\n # data = cmp.findall(response.text)\n\n # 解析字体\n data_decryted = data_decrytion(response)\n if len(data_decryted) == 3:\n movie_rate, movie_comment_num, movie_box_office = data_decryted[0], data_decryted[1], data_decryted[2]\n else:\n movie_rate, movie_comment_num, movie_box_office = None, None, None\n\n\n\n item = MaoyanItem()\n item['movie_name'] = movie_name\n item['movie_English_name'] = movie_English_name\n item['movie_type'] = movie_type\n item['movie_release'] = movie_release\n item['movie_total_time'] = movie_total_time\n item['movie_rate'] = movie_rate\n item['movie_comment_num'] = movie_comment_num\n item['movie_box_office'] = movie_box_office\n\n yield item","sub_path":"maoyan/maoyan/spiders/MaoyanSpider.py","file_name":"MaoyanSpider.py","file_ext":"py","file_size_in_byte":2545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"93548781","text":"import requests, os, re\nimport lxml.html as ET\n#import xml.etree.ElementTree as ET\n\nfrom .item import Item\nfrom . import _settings\n\n\n\n\n\n\n\ndef translateTypeInverse(type_,subtype):\n if type_ == 'anime':\n if subtype == 'TV':\n return 1\n elif subtype == 'OVA':\n return 2\n elif subtype == 'Movie':\n return 3\n elif subtype == 'Special':\n return 4\n elif subtype == 'ONA':\n return 5\n elif subtype == 'Music':\n return 6\n else:\n return None\n\n if type_ == 'manga':\n if subtype == 'Manga':\n return 1\n elif subtype == 'Novel':\n return 2\n elif subtype == 'One Shot':\n return 3\n elif subtype == 'Doujin':\n return 4\n elif subtype == 'Manhwa':\n return 5\n elif subtype == 'Manhua':\n return 6\n elif subtype == 'OEL':\n return 7\n else:\n return None\n\n\n\ndef getList(user,type_):\n\n h = {'User-agent': 'api-indiv-9F93C52A963974CF674325391990191C'}\n\n r = requests.get('http://myanimelist.net/malappinfo.php?u=' + user + '&status=all&type=' + type_, headers=h)\n\n root = ET.fromstring(r.text.encode(\"utf-8\")) \n \n items = []\n for anime in root.findall(type_):\n item = Item()\n if anime.find('series_'+type_+'db_id') is not None:\n item['malid'] = int(anime.find('series_'+type_+'db_id').text)\n if anime.find('series_title') is not None:\n item['title'] = anime.find('series_title').text\n if anime.find('series_synonyms') is not None:\n item['synonyms'] = anime.find('series_synonyms').text\n if anime.find('series_type') is not None:\n item['type'] = anime.find('series_type').text\n if anime.find('series_episodes') is not None:\n item['episodes'] = anime.find('series_episodes').text\n if anime.find('series_chapters') is not None:\n item['chapters'] = anime.find('series_chapters').text\n if anime.find('series_volumes') is not None:\n item['volumes'] = anime.find('series_volumes').text\n if anime.find('series_status') is not None:\n item['status'] = anime.find('series_status').text\n if anime.find('series_start') is not None:\n item['start'] = anime.find('series_start').text\n if anime.find('series_end') is not None:\n item['end'] = anime.find('series_end').text\n if anime.find('series_image') is not None:\n item['image'] = anime.find('series_image').text\n if anime.find('my_watched_episodes') is not None:\n item['my_watched_episodes'] = anime.find('my_watched_episodes').text\n if anime.find('my_read_chapters') is not None:\n item['my_read_chapters'] = anime.find('my_read_chapters').text\n if anime.find('my_read_volumes') is not None:\n item['my_read_volumes'] = anime.find('my_read_volumes').text\n if anime.find('my_start_date') is not None:\n item['my_start_date'] = anime.find('my_start_date').text\n if anime.find('my_finish_date') is not None:\n item['my_finish_date'] = anime.find('my_finish_date').text\n if anime.find('my_score') is not None:\n item['my_score'] = anime.find('my_score').text\n if anime.find('my_status') is not None:\n item['my_status'] = anime.find('my_status').text\n if anime.find('my_rewatching') is not None:\n item['my_rewatching'] = anime.find('my_rewatching').text\n if anime.find('my_rewatching_ep') is not None:\n item['my_rewatching_ep'] = anime.find('my_rewatching_ep').text\n if anime.find('my_last_updated') is not None:\n item['my_last_updated'] = anime.find('my_last_updated').text\n\n\n items.append(item)\n \n return items\n\ndef getItemData(type_,id_):\n h = {'User-agent': 'api-indiv-9F93C52A963974CF674325391990191C'}\n\n r = requests.get('http://myanimelist.net/' + type_ + '/' + str(id_), headers=h)\n\n item = parse_anime_response(r.text)\n\n newitem = Item()\n newitem['malid'] = item['id']\n newitem['synopsis'] = item['synopsis']\n\n return (newitem,)\n\n\n\ndef getItemImage(url):\n h = {'User-agent': 'api-indiv-9F93C52A963974CF674325391990191C'}\n path = '.' + url.split('.net')[1]\n\n r = requests.get(url, headers=h)\n\n if r.status_code == 200:\n\n if not os.path.exists(os.path.dirname(path)):\n os.makedirs(os.path.dirname(path))\n with open(path, 'wb') as f:\n for chunk in r.iter_content(1024):\n f.write(chunk)\n\ndef dateToMAL(date):\n return date[5:7] + date[8:10] + date[0:4]\n\n\ndef updateItem(type_,item):\n\n xml = ''\n\n for k,v in item.items():\n if k == 'my_watched_episodes':\n xml += '' + str(item['my_watched_episodes']) + ''\n if k == 'my_read_chapters':\n xml += '' + str(item['my_read_chapters']) + ''\n if k == 'my_read_volumes':\n xml += '' + str(item['my_read_volumes']) + ''\n elif k == 'my_status':\n xml += '' + str(item['my_status']) + ''\n elif k == 'my_score':\n xml += '' + str(item['my_score']) + ''\n elif k == 'my_start_date':\n xml += '' + dateToMAL(item['my_start_date']) + ''\n elif k == 'my_finish_date':\n xml += '' + dateToMAL(item['my_finish_date']) + ''\n xml += '' \n\n data = {'id': str(item['malid']), 'data': xml }\n\n url = 'http://myanimelist.net/api/' + type_ + 'list/update/' + str(item['malid']) + '.xml'\n requests.post(url,data=data,auth=requests.auth.HTTPBasicAuth(_settings.user, _settings.password))\n\n\ndef search(type_,word):\n url = 'http://myanimelist.net/api/' + type_ + '/search.xml?q=' + word.replace(' ','+')\n r = requests.get(url,auth=requests.auth.HTTPBasicAuth(_settings.user, _settings.password))\n\n\n root = ET.fromstring(r.text.encode(\"utf-8\")) \n \n items = []\n for anime in root.findall(\"entry\"):\n item = Item()\n if anime.find('id') is not None:\n item['malid'] = int(anime.find('id').text)\n if anime.find('title') is not None:\n item['title'] = anime.find('title').text\n if anime.find('episodes') is not None:\n item['episodes'] = anime.find('episodes').text\n if anime.find('status') is not None:\n item['status'] = anime.find('status').text\n if anime.find('type') is not None:\n if translateTypeInverse(type_,anime.find('type').text) is not None:\n item['type'] = translateTypeInverse(type_,anime.find('type').text) \n #if anime.find('score') is not None:\n # item['score'] = anime.find('score').text\n if anime.find('start_date') is not None:\n item['start'] = anime.find('start_date').text\n if anime.find('end_date') is not None:\n item['end'] = anime.find('end_date').text\n if anime.find('synopsis') is not None:\n try:\n item['synopsis'] = anime.find('synopsis').text\n except:\n pass\n if anime.find('image') is not None:\n item['image'] = anime.find('image').text\n\n items.append(item)\n\n return items\n\n\n\ndef parse_anime_response(html):\n\n html = ET.fromstring(html)\n\n anime = {}\n\n # Anime ID\n details_link = html.xpath('//a[text()=\"Details\"]')[0].get('href')\n anime['id'] = int(re.findall(r'.*/(anime|manga)/(\\d+)/.*?', details_link)[0][1])\n\n # Title and rank\n h1 = html.xpath('//h1/div')[0]\n anime['title'] = h1.tail\n anime['rank'] = int(re.findall('\\d+', h1.text)[0])\n \n # Extract from sections on the left column\n left_column = html.xpath('//div[@id=\"content\"]/table/tr/td[@class=\"borderClass\"]')[0]\n\n node = left_column.xpath('//img')\n if node:\n anime['image_url'] = node[0].get('src')\n\n # Alternative titles\n other_titles = {}\n\n node = left_column.xpath('//span[text()=\"English:\"]')\n if node:\n other_titles['english'] = node[0].tail.strip().split(', ')\n\n node = left_column.xpath('//span[text()=\"Synonyms:\"]')\n if node:\n other_titles['synonyms'] = node[0].tail.strip().split(', ')\n\n node = left_column.xpath('//span[text()=\"Japanese:\"]')\n if node:\n other_titles['japanese'] = node[0].tail.strip().split(', ')\n\n if other_titles:\n anime['other_titles'] = other_titles\n\n # Information section\n node = left_column.xpath('//span[text()=\"Type:\"]')\n if node:\n anime['type'] = node[0].tail.strip()\n\n node = left_column.xpath('//span[text()=\"Episodes:\"]')\n if node:\n try:\n anime['episodes'] = int(node[0].tail.strip().replace(',', ''))\n except:\n anime['episodes'] = 0\n node = left_column.xpath('//span[text()=\"Status:\"]')\n if node:\n anime['status'] = node[0].tail.strip().replace(',', '')\n\n node = left_column.xpath('//span[text()=\"Aired:\"]')\n if node:\n anime['air_dates'] = node[0].tail.strip().replace(',', '')\n #TODO parse air dates\n\n node = left_column.xpath('//span[text()=\"Genres:\"]')\n if node:\n genres = []\n for a in node[0].getparent()[1:]:\n genres.append(a.text.strip())\n\n anime['genres'] = genres\n \n node = left_column.xpath('//span[text()=\"Rating:\"]')\n if node:\n anime['classification'] = node[0].tail.strip()\n\n node = left_column.xpath('//span[text()=\"Score:\"]')\n if node:\n anime['members_score'] = float(node[0].tail.strip())\n\n node = left_column.xpath('//span[text()=\"Popularity:\"]')\n if node:\n anime['popularity_rank'] = int(node[0].tail.strip().replace('#', '', 1).replace(',', ''))\n\n node = left_column.xpath('//span[text()=\"Members:\"]')\n if node:\n anime['members_count'] = int(node[0].tail.strip().replace(',', ''))\n\n node = left_column.xpath('//span[text()=\"Favorites:\"]')\n if node:\n anime['favorited_count'] = int(node[0].tail.strip().replace(',', ''))\n\n # Popular tags\n node = left_column.xpath('//span[preceding-sibling::h2[text()=\"Popular Tags\"]]')\n if node:\n tags = []\n for a in node[0]:\n tags.append(a.text)\n\n anime['tags'] = tags\n\n # Extract from sections on the rigth column\n right_column = html.xpath('//div[@id=\"content\"]/table/tr/td/div/table')[1]\n\n # TEST IF IT WORKS FINE\n synopsis = right_column.xpath('//h2[text()=\"Synopsis\"]')\n if synopsis:\n anime['synopsis'] = ''\n for element in synopsis[0].getparent():\n try:\n anime['synopsis'] += element.tail\n except:\n pass\n\n # Related anime TEST IF IT WORKS FINE\n related_anime = right_column.xpath('//h2[text()=\"Related Anime\"]')\n if related_anime:\n\n kind = make_related_key(related_anime[0])\n related_list = []\n\n node = related_anime[0].getnext()\n while node.tag != 'h2':\n \n if node.tag == 'br':\n if related_list:\n anime[kind] = related_list\n\n kind = make_related_key(node)\n related_list = []\n \n else:\n item = {}\n match = re.findall('/(anime|manga)/(\\d+)', node.get('href'))\n if match:\n item['%s_id' % match[0][0]] = int(match[0][1])\n item['title'] = node.text\n item['url'] = node.get('href')\n\n related_list.append(item)\n\n node = node.getnext()\n \n\n return anime\n\n\ndef make_related_key(node):\n return node.tail.split(':')[0].replace(' ', '_').lower()\n\n","sub_path":"shurmal/myanimelist.py","file_name":"myanimelist.py","file_ext":"py","file_size_in_byte":11918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"84550036","text":"# dependency sqlalchemy\n# pip install sqlalchemy for installation\n\nimport socket\nimport threading\nimport time\nimport datetime\nfrom sqlalchemy import *\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\n\n# SQL Alchemy setup\nBase = declarative_base()\nengine = create_engine('sqlite:///db.sqlite3')\n\n\n# ORM model\nclass Account(Base):\n __tablename__ = \"account\"\n account_nr = Column(Integer, primary_key=True)\n name = Column(String)\n balance = Column(Float)\n last_updated = Column(DateTime, default=datetime.datetime.now(), onupdate=datetime.datetime.now)\n\n\nsession = sessionmaker()\nsession.configure(bind=engine)\nBase.metadata.create_all(engine)\n\n# Socket setup:\nPORT = 3030\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind((socket.gethostname(), PORT))\ns.listen(5)\nprint(f\"Server is running, listening on port {PORT}\")\n\n\ndef clients():\n while True:\n # now our endpoint knows about the OTHER endpoint.\n clientsocket, address = s.accept()\n print(f\"Connection from {address} has been established.\")\n clientsocket.send(bytes(welcome, \"utf-8\"))\n while True:\n try:\n data = clientsocket.recv(2048)\n dataStr = data.decode(\"utf-8\")\n\n if not data:\n break\n\n print(\"Client Says: \" + dataStr)\n commands = dataStr.split(\" \", 100)\n\n msg = \"Invalid syntax! Type help for commands\"\n\n if commands[0] == \"create\":\n msg = create(commands[1], commands[2])\n elif commands[0] == \"withdraw\" and len(commands) == 5:\n if commands[3] == \"safe\":\n msg = withdraw(commands[1], commands[2], commands[4])\n elif commands[3] == \"unsafe\":\n msg = unsafe_withdraw(commands[1], commands[2], commands[4])\n elif commands[0] == \"withdraw\":\n msg = withdraw(commands[1], commands[2], 0)\n elif commands[0] == \"deposit\":\n msg = deposit(commands[1], commands[2])\n elif commands[0] == \"edit\":\n msg = edit(commands[1], commands[2])\n elif commands[0] == \"accounts\" and len(commands) == 3:\n msg = accounts_by_balance(commands[2])\n elif commands[0] == \"accounts\":\n msg = accounts()\n elif commands[0] == \"help\":\n msg = help\n\n clientsocket.sendall(bytes(msg, \"utf-8\"))\n\n except socket.error:\n print(\"Error Occured.\")\n break\n\n\ndef create(name, balance):\n session_instant = session()\n account = Account(name=name, balance=balance)\n session_instant.add(account)\n session_instant.commit()\n return f'Created account, account number: {account.account_nr}'\n\n\ndef withdraw(amount, name, seconds):\n session_instant = session()\n while True:\n\n tmp_account_balance = session_instant.query(Account).filter(Account.name == name).first().balance\n tmp_account_balance -= float(amount)\n tmp_account_last_updated = session_instant.query(Account).filter(Account.name == name).first().last_updated\n\n # sleep\n time.sleep(float(seconds))\n\n if tmp_account_balance >= 0:\n account = session_instant.query(Account).filter(Account.name == name).first()\n\n #Optimistic lock\n if tmp_account_last_updated == account.last_updated:\n account.balance = tmp_account_balance\n session_instant.commit()\n data = f'Withdrew {amount} from account nr: {account.account_nr}. Remaining balance is: {account.balance}'\n break\n else:\n print(\"wrong timestamp, trying again\")\n else:\n data = \"Insufficient funds\"\n break\n return data\n\n\ndef unsafe_withdraw(amount, name, seconds):\n session_instant = session()\n\n account_balance = session_instant.query(Account).filter(Account.name == name).first().balance\n\n # sleep for 10 seconds, to invoke transaction error\n time.sleep(float(seconds))\n\n account = session_instant.query(Account).filter(Account.name == name).first()\n\n if account_balance >= float(amount):\n account.balance = account_balance - float(account_balance)\n\n #No lock = unsafe\n session_instant.commit()\n return f'Withdrew {amount} from account nr: {account.account_nr}. Remaining balance is: {account.balance}'\n else:\n return \"Insufficient funds\"\n\n\ndef deposit(amount, name):\n session_instant = session()\n account = session_instant.query(Account).filter(Account.name == name).first()\n account.balance += float(amount)\n session_instant.commit()\n return f'Deposited {amount} to account nr: {account.account_nr}. New balance is: {account.balance}'\n\n\ndef accounts():\n session_instant = session()\n accounts = session_instant.query(Account).all()\n data = \"Accounts in the database:\\n\\naccount_nr:\\tname:\\t\\tbalance:\\t\\tlast_updated:\\n\"\n\n for account in accounts:\n data += f'{account.account_nr}\\t\\t{account.name}\\t\\t{account.balance}\\t\\t{account.last_updated}\\n'\n return data\n\n\ndef accounts_by_balance(balance):\n session_instant = session()\n accounts = session_instant.query(Account).filter(Account.balance > balance)\n data = f\"Accounts in the database with balance greater than {balance}:\\n\\naccount_nr:\\tname:\\t\\tbalance:\\t\\tlast_updated\\n\"\n\n for account in accounts:\n data += f'{account.account_nr}\\t\\t{account.name}\\t\\t{account.balance}\\t\\t{account.last_updated}\\n'\n return data\n\n\ndef edit(name, new_name):\n session_instant = session()\n account = session_instant.query(Account).filter(Account.name == name).first()\n account.name = new_name\n session_instant.commit()\n return f'Account nr: {account.account_nr} has changed name to {new_name}'\n\n\nthreads = []\nfor i in range(5):\n threads.append(threading.Thread(target=clients))\n threads[i].start()\n\n# Messages\nhelp = \"Commands\\n\" \\\n \"Create account: create [name] [initial balance]\\n\" \\\n \"Withdraw money: withdraw [amount] [from name], optional [safe|unsafe] [seconds]. Sleeps before editing safe or unsafe transaction\\n\" \\\n \"Deposit money: deposit [amount] [to name]\\n\" \\\n \"Edit name: edit [old_name] [new_name]\\n\" \\\n \"Show accounts: accounts\\n\" \\\n \"Show accounts with balance greater than x: accounts -gt [x]\\n\" \\\n \"Show commands: help\"\n\nwelcome = \"Welcome to the bank cli\\n\" + help\n","sub_path":"o6/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"481497324","text":"# Copyright 2020 Huawei Technologies Co., Ltd.All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Define pytorch tracer context manager.\"\"\"\nimport importlib\n\nfrom torch.nn import Module\nfrom torch.onnx.utils import _trace\nfrom torch.onnx.utils import _node_getitem\nfrom torch.onnx.symbolic_helper import _set_opset_version\n\n\nSCRIPT_METHOD = getattr(importlib.import_module(\"torch._C\"),\n \"ScriptMethod\")\nonnx_tracer = _trace\ngetitem_of_node = _node_getitem\nset_opset_version = _set_opset_version\n\n\ndef unique_state_dict(model):\n \"\"\"\n Wrapper of torch.jit._unique_state_dict.\n\n Args:\n model (Module): Torch model.\n\n Returns:\n dict, params.\n \"\"\"\n from torch.jit import _unique_state_dict\n\n return _unique_state_dict(model)\n\n\ndef create_autograd_variable(tensor):\n \"\"\"\n Create autograd variable to trace the whole graph.\n\n Args:\n tensor (torch.Tensor): Tensor.\n\n Returns:\n torch.autograd.Variable, variable.\n \"\"\"\n variable = getattr(importlib.import_module(\"torch.autograd\"), \"Variable\")\n return variable(tensor, requires_grad=False)\n\n\nclass OverloadTorchModuleTemporarily:\n \"\"\"\n Fix bugs in new version of pytorch.\n PyTorch official solution.\n \"\"\"\n\n def __init__(self):\n self.backup = None\n\n def __enter__(self):\n def _tracing_name(traced_module, tracing_state):\n traced_module_stack = getattr(tracing_state, \"_traced_module_stack\")\n if not traced_module_stack:\n return None\n module = traced_module_stack[-1]\n for name, child in module.named_children():\n if child is traced_module:\n return name\n return None\n\n def _slow_forward(self_, *inputs, **kwargs):\n tracing_state = getattr(importlib.import_module(\"torch._C\"),\n \"_get_tracing_state\")()\n if not tracing_state or isinstance(self_.forward, SCRIPT_METHOD):\n return self_.forward(*inputs, **kwargs)\n if not hasattr(tracing_state, '_traced_module_stack'):\n tracing_state._traced_module_stack = []\n name = _tracing_name(self_, tracing_state)\n get_name_func = getattr(self_, \"_get_name\")\n if name:\n tracing_state.push_scope('%s[%s]' % (get_name_func(), name))\n else:\n tracing_state.push_scope(get_name_func())\n tracing_state._traced_module_stack.append(self_)\n try:\n result = self_.forward(*inputs, **kwargs)\n finally:\n tracing_state.pop_scope()\n tracing_state._traced_module_stack.pop()\n return result\n\n self.backup = getattr(Module, \"_slow_forward\")\n setattr(Module, '_slow_forward', _slow_forward)\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n setattr(Module, '_slow_forward', self.backup)\n","sub_path":"mindinsight/mindconverter/graph_based_converter/third_party_graph/torch_utils.py","file_name":"torch_utils.py","file_ext":"py","file_size_in_byte":3562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"571582654","text":"from django.http import HttpResponse\nfrom Twitter.models import TwitterAccess\nfrom twython import Twython\nfrom IGeLU2014BE.settings import APP_KEY, APP_SECRET\nimport json\n\n\ndef home(request):\n try:\n access_object = TwitterAccess.objects.get()\n except:\n connection = Twython(APP_KEY, APP_SECRET, oauth_version=2)\n access_token = connection.obtain_access_token()\n ta = TwitterAccess(token=access_token)\n ta.save()\n else:\n access_token = access_object.token\n stream = []\n twitter = Twython(APP_KEY, access_token=access_token)\n tweets = twitter.search(q=\"#eluna15 OR #eluna2015\", count=100)\n\n for tweet in tweets['statuses']:\n data = {}\n data['text'] = tweet['text']\n if tweet['entities']['urls']:\n data['url'] = tweet['entities']['urls'][0]['url']\n data['created_at'] = tweet['created_at']\n # data['url'] = tweet['entities']['urls']['url']\n data['screen_name'] = tweet['user']['screen_name']\n data['profile_image_url_https'] = tweet['user']['profile_image_url_https']\n stream.append(data)\n return HttpResponse(json.dumps(stream), content_type=\"application/json\")\n","sub_path":"Twitter/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"244441948","text":"#!/usr/bin/env python\n'''\nFile: shows.py\nAuthor: George Ang \nDescription:\n'''\n\nfrom db import db\n\ndef insert(showname, **kwargs):\n kwargs.update(dict(showname=showname))\n\n\n if 'callback' in kwargs:\n callback = kwargs.pop('callback')\n else:\n callback = None\n\n def _on_found(response, error):\n if error:\n if callback:\n callback(None, error)\n if not response:\n db.new_shows.insert(kwargs, callback=callback)\n else :\n db.new_shows.update(response, kwargs, callback=callback)\n\n db.new_shows.find_one(dict(showname=showname), callback=_on_found)\n\ndef find(*args, **kwargs):\n db.new_shows.find(*args, **kwargs)\n\ndef remove(*args, **kwargs):\n db.new_shows.remove(*args, **kwargs)\n\n","sub_path":"app/amodel/new_shows.py","file_name":"new_shows.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"553795873","text":"#!/usr/bin/env python\n#\n# Copyright 2011 MiuMeet AG\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom google.appengine.api import datastore_types\nfrom google.appengine.ext import db\n\ntry:\n import json\nexcept:\n from django.utils import simplejson as json\n\nclass JSONProperty(db.TextProperty):\n \"\"\"An a jsonizable object that gets jsonized when stored\"\"\"\n\n def default_value(self):\n \"\"\"Returns the default value\n\n :return: str\n \"\"\"\n if self.default != None: \n return json.loads(json.dumps(self.default))\n\n def validate(self, value):\n \"\"\"Validates the property. No-op\n\n :param value: Value to validate\n :return: value\n \"\"\"\n return value\n\n def get_value_for_datastore(self, model_instance):\n \"\"\"Returns the values for datastore\n\n :param model_instance: The model instance\n :return: db.Text\n \"\"\"\n result = super(JSONProperty, self).get_value_for_datastore(model_instance)\n result = json.dumps(result)\n return db.Text(result)\n\n def make_value_from_datastore(self, value):\n \"\"\"Creates value from datastore value\n\n :param value: Datastore value\n :return: JSON object\n \"\"\"\n try:\n value = json.loads(str(value))\n except:\n pass\n return super(JSONProperty, self).make_value_from_datastore(value)","sub_path":"appengine-python/datastore/json_property.py","file_name":"json_property.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"509757849","text":"# Copyright 2013 – present by the SalishSeaCast Project contributors\n# and The University of British Columbia\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"SalishSeaCast release management script that tags NEMO code and model\nconfiguration repos for a production release.\n\"\"\"\nimport argparse\nimport logging\nfrom pathlib import Path\n\nimport coloredlogs\nimport hglib\nimport verboselogs\nimport yaml\n\nNAME = \"tag_release\"\nCOMMIT_AUTHOR = f\"SalishSeaNowcast.release_mgmt.{NAME}\"\nverboselogs.install()\nlogger = logging.getLogger(NAME)\ncoloredlogs.install(fmt=\"%(asctime)s %(hostname)s %(name)s %(levelname)s %(message)s\")\n\n\ndef main():\n parsed_args = _command_line_interface()\n repos = _load_repos_list(parsed_args.repos_file)\n for repo in repos:\n _tag_repo(repo, parsed_args.tag)\n\n\ndef _command_line_interface():\n parser = argparse.ArgumentParser(\n description=\"\"\"\n Tag NEMO code and model configuration repos for a production release.\n \"\"\"\n )\n parser.prog = f\"python -m release_mgmt.{NAME}\"\n parser.add_argument(\n \"repos_file\",\n type=Path,\n help=\"\"\"\n Path/name of YAML file containing the list of repository paths to tag.\n The list is unique for each user and machine combination.\n \"\"\",\n )\n parser.add_argument(\n \"tag\",\n help=\"\"\"\n Tag to mark the most recently committed repo changesets with.\n Format: PROD-run-type-hypenated-description\n Examples: PROD-hindcast-201806-v2-2017, PROD-nowcast-green-201702v2\n \"\"\",\n )\n return parser.parse_args()\n\n\ndef _load_repos_list(repos_file):\n \"\"\"\n :param pathlib.Path repos_file:\n :rtype: dict\n \"\"\"\n with repos_file.open(\"rt\") as f:\n repos_info = yaml.safe_load(f)\n logger.info(f\"read list of repos to tag from {repos_file}\")\n return (repo for repo in repos_info[\"repos\"])\n\n\ndef _tag_repo(repo, tag):\n logger.info(f\"processing repo: {repo}\")\n if not Path(repo).exists():\n logger.error(f\"repo does not exist: {repo}\")\n raise SystemExit(2)\n try:\n with hglib.open(repo) as hg:\n status = hg.status(\n modified=True, added=True, removed=True, deleted=True, copies=True\n )\n except hglib.error.ServerError:\n logger.error(f\"unable to find Mercurial repo root in: {repo}\")\n raise SystemExit(2)\n if status:\n logger.error(f\"uncommitted changes in repo: {repo}\")\n raise SystemExit(2)\n with hglib.open(repo) as hg:\n incoming_changes = hg.incoming()\n if incoming_changes:\n logger.warning(\n f\"found incoming changes from Bitbucket that you need to \"\n f\"deal with in repo: {repo}\"\n )\n raise SystemExit(2)\n tags = hg.tags()\n if tag in [existing_tag[0].decode() for existing_tag in tags]:\n logger.warning(f\"tag '{tag}' already exists in repo: {repo}\")\n return\n for _, key, value in hg.config(\"ui\".encode()):\n if key.decode() == \"username\":\n username = value.decode()\n break\n for existing_tag in tags[1:]:\n if existing_tag[0].decode().startswith(\"PROD-\"):\n prev_prod_tag_name = existing_tag[0].decode()\n tip_rev = hg.tip()\n if all(\n (\n tip_rev.author.decode().startswith(COMMIT_AUTHOR),\n tip_rev.desc.decode()\n == f\"Tag production release {prev_prod_tag_name}.\",\n )\n ):\n hg.tag(\n tag.encode(),\n rev=prev_prod_tag_name,\n message=f\"Tag production release {tag}.\",\n user=f\"{COMMIT_AUTHOR} for {username}\",\n )\n break\n else:\n hg.tag(\n tag.encode(),\n message=f\"Tag production release {tag}.\",\n user=f\"{COMMIT_AUTHOR} for {username}\",\n )\n logger.success(f\"added {tag} to repo: {repo}\")\n hg.push()\n logger.success(f\"pushed {tag} tag to Bitbucket from repo: {repo}\")\n\n\nif __name__ == \"__main__\":\n main() # pragma: no cover\n","sub_path":"release_mgmt/tag_release.py","file_name":"tag_release.py","file_ext":"py","file_size_in_byte":4815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"193217954","text":"import sys\nimport logging\nimport requests\nimport json\n\nif sys.version_info >= (2,7):\n logging.captureWarnings(True)\nelse:\n from requests.packages.urllib3.exceptions import InsecureRequestWarning\n requests.packages.urllib3.disable_warnings()\n \nclass FmgFlatuiProxyApi():\n def __init__(self):\n self._proto = 'https'\n self._host = None\n self._port = None\n self._base_url = None \n self._web_session = requests.Session()\n self._debug = None\n self._debug_cookie = None\n self._debug_header = None\n\n def debug(self, value):\n if value == 'on':\n self._debug = True\n else:\n self._debug = False\n\n return self._debug\n\n def debug_cookie(self, value):\n if value == 'on':\n self._debug_cookie = True\n else:\n self._debug_cookie = False\n\n return self._debug_cookie\n\n def debug_header(self, value):\n if value == 'on':\n self._debug_header = True\n else:\n self._debug_header = False\n\n return self._debug_header\n\n def debug_print(self, response):\n if self._debug:\n # REQUEST\n method = response.request.method\n url = response.request.url\n body = response.request.body\n\n print('>>>')\n print('{} {}'.format(method, url))\n\n if body:\n print('\\n{}'.format(json.dumps(json.loads(body), indent=4)))\n\n if self._debug_header:\n print('>>> [headers]')\n for header in self._web_session.headers:\n print('{}: {}'.format(header, self._web_session.headers[header]))\n\n if self._debug_cookie:\n print('>>> [cookies]')\n for cookie in self._web_session.cookies:\n print(cookie)\n\n # RESPONSE\n status_code = response.status_code\n content_type = response.headers.get('content-type')\n\n print('<<<')\n print('{}'.format(status_code))\n\n if content_type == 'application/json':\n print('\\n{}'.format(json.dumps(json.loads(response.text), indent=4)))\n else:\n print('\\n{}'.format(response.text))\n\n if self._debug_cookie:\n print('<<< [cookies]')\n for cookie in response.cookies:\n print(cookie)\n\n def set_headers_from_cookies(self, response):\n x_csrftoken = {\n 'X-CSRFToken': self._web_session.cookies['csrftoken']\n }\n #self._web_session.headers.update(x_csrftoken)\n\n xsrf_token = {\n 'XSRF-TOKEN': self._web_session.cookies['XSRF-TOKEN']\n }\n self._web_session.headers.update(xsrf_token) \n\n #self._web_session.headers.update(x_xsrf_token) \n\n def login(self, host, login, password, port=443):\n '''\n According to Mantis #0643655, we have to set Content-Type to application/json\n '''\n self._web_session.headers.update({'Content-Type': 'application/json'})\n\n self._host = host\n self._port = port\n self._base_url = '{}://{}:{}'.format(self._proto,\n self._host,\n self._port)\n\n login_url1 = '{}/cgi-bin/module/flatui_auth'.format(self._base_url)\n login_url2 = '{}/p/app/'.format(self._base_url)\n\n request_body = {\n 'url': '/gui/userauth',\n 'method': 'login',\n 'params': {\n 'username': login,\n 'secretkey': password,\n 'logintype': 0,\n },\n }\n\n ## This request will retrieve the CURRENT_SESSION and HTTP_CSRF_TOKEN cookies \n response = self._web_session.post(login_url1, json=request_body, verify=False)\n self.debug_print(response)\n\n ## This request will retrieve the XSRF-TOKEN and csrftoken cookies\n response = self._web_session.get(login_url2, verify=False)\n self.debug_print(response)\n\n ## Set X-CSRFToken, XSR-TOKEN and X-XSRF-TOKEN\n self.set_headers_from_cookies(response)\n\n def flatui_proxy(self, method, params=None, json=None):\n url = '{}/cgi-bin/module/flatui_proxy'.format(self._base_url)\n\n if method == 'get':\n response = self._web_session.get(url, params=params)\n\n elif method == 'post':\n response = self._web_session.post(url, params=params, json=json)\n self.debug_print(response)","sub_path":"ftntlib/fmg_flatui_proxy_api.py","file_name":"fmg_flatui_proxy_api.py","file_ext":"py","file_size_in_byte":4588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"132002000","text":"import os\n\nos.system('clear')\n\nfrutas = []\n\nwhile True:\n nome_fruta = input('Informe o nome da fruta (para sair digite EXIT): ')\n if nome_fruta.upper() == 'EXIT': break\n\n try:\n estoque_fruta = int(input('Informe o estoque da fruta: '))\n valor_fruta = float(input('Informe o valor de venda da fruta: '))\n except ValueError:\n print('Um dos valores não é um valor válido!!!!')\n else:\n #lista_aux = []\n #lista_aux.append(nome_fruta)\n #lista_aux.append(estoque_fruta)\n #lista_aux.append(valor_fruta)\n frutas.append([nome_fruta, estoque_fruta, valor_fruta])\n\nprint(frutas)\n","sub_path":"20181206 - Dicionários/exemplo_04_criando_lista_v2.py","file_name":"exemplo_04_criando_lista_v2.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"457063680","text":"#! /usr/bin/env python3\n#\n#\n# Pre-setup specific test parameters\n#\n#\n# Pedro Peixoto \n#\n#\n#---------------------------------------------------\n\nimport os\nimport sys\nimport stat\nimport math\n\nclass EarthMKSDimensions:\n\tname = \"EarthMKSDimensions\"\n\tday = 86400\n\tg = 9.80616\n\tf = 0.00014584\t#2 omega\n\tomega = 0.00007292\n\terad = 6371220\n\t\n\t\ndef CompileSWEPlane(p):\n\tp.compile.program = 'swe_plane'\n\tp.compile.plane_or_sphere = 'plane'\n\tp.compile.plane_spectral_space = 'enable'\n\tp.compile.plane_spectral_dealiasing = 'enable'\n\tp.compile.sphere_spectral_space = 'disable'\n\tp.compile.sphere_spectral_dealiasing = 'disable'\n\tp.compile.compiler = 'gnu'\n\tp.compile.threading = 'omp'\n\treturn p\t\n\n\ndef RuntimeSWEPlaneNondimParameters(p):\n\tp.runtime.g = 1\n\tp.runtime.f = 1\n\tp.runtime.h = 1\n\tp.runtime.domain_size = 1\n\treturn p\t\n\ndef RuntimeSWEPlaneEarthParam(p):\n\ts = EarthMKSDimensions()\n\tp.runtime.g = s.g\n\tp.runtime.f = s.f\n\tp.runtime.h = 10000\n\tp.runtime.domain_size = 2.0*math.pi*s.erad # 40031555.8928087\n\treturn p\t\n\n\t\ndef EnableGUI(p):\n\tp.runtime.gui = 'enable'\n\tp.compile.gui = 'enable'\n\treturn p\t\n\n\ndef DisableGUI(p):\n\tp.runtime.gui = 'disable'\n\tp.compile.gui = 'disable'\n\treturn p\t\n\n\ndef SetupFDCMethods(p):\n\tp.runtime.staggering = 1\n\tp.runtime.spectralderiv = 0\n\n\t#p.compile.plane_spectral_space = 'disable'\n\tp.compile.plane_spectral_dealiasing = 'disable'\n\tp.compile.libfft = 'enable'\n\treturn p\n\n\ndef SetupSpectralMethods(p):\n\tp.runtime.staggering = 0\n\tp.runtime.spectralderiv = 1\n\n\tp.compile.plane_spectral_space = 'enable'\n\tp.compile.plane_spectral_dealiasing = 'enable'\n\treturn p\n\n\n\n\n\n\n\n\n# ---old code ----\n\n#from SWEETJobGeneration import *\n\n#class SWEETSpecificTest(SWEETJobGeneration):\n#\n#\tdef __init__(self): \n#\t\tself.p = SWEETJobGeneration() #For some odd reason, I need self.p, not just self :-(\n#\t\tself.p.compile.program=\"test\"\n\n\n\n#class SWEETEditTests(SWEETSpecificTest):\n\n#\tdef __init__(self, p): \n#\t\tself.p.compile.program=\"test2\"\n#\t\tself = p\n","sub_path":"python_mods/SWEETParameters.py","file_name":"SWEETParameters.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"516833611","text":"#!/usr/bin/env python\n\n\"\"\"\n设计接口自动化测试框架的步骤\n1、整体构思-中心思想和提纲(不考虑具体的实现,即作文内容--和写作文的类比)\n 比如:流程图 结构图 文字 (听的时候,思考少;写的时候,思考多)\n2、目录规划\n3、伪代码\n4、写代码(硬编码,先能跑起来,小步迭代 比如:参数写死,功能最少demo)\n\n一、整体构思\n1主入口--2遍历接���--3发送请求--4得到返回--5对比结果--6测试报告--7发送邮件\n\n二、目录结构\n1、主入口的py文件--main\n2、核心代码py文件夹--src\n 遍历接口\n 发送请求-得到返回\n 对比结果\n\n3、存放接口测试用例的文件夹--case\n 存放形式:excel(推荐)或者数据库\n 推荐excel的原因:\n 1、维护excel简单\n 2、数据库学习成本稍高\n 3、简便性上excel占优\n\n excel的字段设计:\n 1、url\n 2、请求报文\n 3、请求方式post还是get\n 4、实际返回报文\n 5、期望结果\n 6、通过状态\n 7、备注\n\n4、存在公共函数的文件夹--commons\n 公共函数:已经封装好的,比较独立的实现一个小功能,且不依赖别的部分\n 例如:http的请求类\n 发送邮件的类\n 发日志的类\n\n5、存放测试报告的文件夹--reports\n excel形式的报告(推荐)优于html的报告\n 原因:\n 1、excel的统计功能\n\n6、放插件的文件夹--others\n7、存放日志文件的文件夹--logs\n\n三、课上练习\n1、目前先把所有的py文件全不放在src核心文件夹\n 等代码调通后,最后将py文件分发到其他目录中,从而避免开始就出现导包错误\n2、http请求类就绪\n3、接口请求类的编写:class Interface_test:\n 调用请求类并对结果进行对比判断\n 不用unittest的断言,而是使用re.search完成\n 所有参数全部写死(不从excel进行读取)\n4、保证上面的代码可以正常运行并且测试通过\n\n四、课上练习伪代码\n class Interface_test:\n def __init__(self,参数列表):\n self.url = url\n self.params1 = params1\n self.headers1 = headers\n\n def 方法名(self):\n http请求类的调用\n 发送请求\n 获取响应\n\n if self.method1 = \"post\":\n if 数据类型是Form:\n re = http.post_form(参数列表)\n elif 数据类型是Json:\n header = {\"Content-Type\":\"application/json;charset=utf8\"}\n re =http.post_json(参数列表)\n elif self.method1 =\"get\":\n 接收响应数据\n re =http.get1(参数列表)\n else:#主要是异常处理\n # 记录日志文件\n print(\"请求失败,请检查用例里的数据是否正确\")\n\n re.search(检查点,响应内容)\n if re.search(error_code=\"0\",请求类的整个返回r):\n if re.search(\"0\",str(字典([\"error_code\"])))): #参数1是检查点\n #如果这个正则忘了-不会,不写出来,后面的代码无法运行,\n 就可以把正则直接写成1-True,先让代码继续,回头再来完善这个正则,就不会卡在这里了\n print(\"请求成功\")\n else:\n print(\"请求失败\")\n\n#search函数 匹配字符串的全部,并且返回第一个符合条件的字符串(从左到右)\nprint(re.search(\"www\",\"22wwwcom\").group()) #www 扫描字符串全部\n# 参数1是正则表达式,参数2是待匹配的字符串 group()是显示匹配后的结果,可视化\n\n五、\n1、从读取一条记录,然后遍历多行\n 一、读取一条请求\n 1、打开excel(工作簿文件xls,当前工作表sheet)\n 2、读取单元格\n 二、遍历多行\n 1、打开excel(工作簿文件xls,当前工作表sheet)\n 2、遍历多行for--获取总行数\n 3、每循环一次,就调用一次请求\n\n2、先完成post请求,再完成判断,如果post请求,就如何,如果get 请求就如何--ok\n\n\"\"\"\nimport re\nfrom http_class2 import Requests_Post1 #导入http请求文件的类-post类\nfrom http_class2 import Requests_Get1 #导入http请求文件的类--get类\nimport openpyxl\n\nclass Interface_test:\n def __init__(self,url,param1,headers,check_point1,method1,data_type1):\n self.url = url\n self.params1 = params1\n self.headers1 = headers #传入参数,成员变量用于方法间调用\n self.check_point1 = check_point1 #检查点(期望结果 比如 error_code = \"0\"# )\n self.method1 = method1 #post还是get方法\n self.data_type = data_type1\n\n def test(self):\n # 2新建对象\n if self.method1 == \"POST\" and self.data_type == \"Form\":\n requests1 = Requests_Post1(self.url, self.params1,self.headers1) # 传入实际参数\n # 3通过对象调方法\n result1 = requests1.requests_post2()\n print(\"post请求-form获取响应结果(python-字典类型)=\", result1) # 5输出整个返回内容(字典类型)\n elif self.method1 == \"POST\" and self.data_type == \"Json\":\n requests1 = Requests_Post1(self.url, self.params1, self.headers1) # 传入实际参数\n # 3通过���象调方法\n result1 = requests1.requests_post2()\n print(\"post请求-json获取响应结果(python-字典类型)=\", result1) # 5输出整个返回内容(字典类型)\n elif self.method1 == \"GET\":\n requests1 = Requests_Get1(self.url, self.params1, self.headers1) # 传入实际参数\n # 3通过对象调方法\n result1 = requests1.requests_get2()\n print(\"get请求获取响应结果(python-字典类型)=\", result1) # 5输出整个返回内容(字典类型)\n else:\n #记录日志文件,异常处理\n print(\"请求失败,请检查用例里的数据是否正确\")\n\n #二,前面先做分支判断,得到响应数据,这里统一进行正则匹配\n print(\"错误码error_code是:\", result1[\"error_code\"]) # 6输出错误码error_code\n result2 = str(result1[\"error_code\"])\n print(result2)\n result = re.search(self.check_point1, result2).group()\n if result:\n print(\"post请求返回的error_code是'0',测试通过\")\n else:\n print(\"返回的error_code不是'0',测试不通过\")\n\n #定义参数(参数在类的外面写死--下一步把这个写死的参数弄活--从excel中读取出来--从读取一条记录,然后遍历多行)\nurl = \"http://v.juhe.cn/laohuangli/d\" #1地址前缀+请求地址 拼接\nparams1 = {\"key\": \"e711bc6362b3179f5a28de7fd3ee4ace\", #2请求数据body\n \"date\": \"2016-5-14\"} # 拼写错误,date而不是data 这个key是固定的,申请好的\nheaders1 = {} #请求头,暂时写死\n# header1 = {\"Content-Type\":\"application/json;charset=utf8\"}\ncheck_point1 = \"0\" #3检查点 期望结果\nmethod1 = \"post\" #4请求方式-方法 post or get\ndata_type1 = \"Form\" #请求数据类型 Form or Json\n\n# #二、把参数写活,从excel读取\n# path1 = r\"D:\\PycharmProjects\\xiaoqiang\\base_181027\\a1接口层框架设计1-0326\\testcase.xlsx\"\n#\n# #1 打开工作簿文件\n# wb1 = openpyxl.load_workbook(path1) #1打开excel文件(类似打开文件对象)\n# # print(\"获取excel文件-工作簿的所有工作表名字\",wb1.get_sheet_names()) #2返回工作表的名字作为列表的元素\n#\n# #2 获取指定工作表\n# sh1 = wb1.get_sheet_by_name(\"Sheet1\") #3指定要操作的工作表sheet1\n# # print(\"获取指定工作表的名字\",sh1.title) #3获取指定工作表的名字 Sheet1\n#\n# #3 操作单元格\n# #001 读取单元格数据\n# # print(\"获取指定工作表的A1单元格的值\",sh1[\"A1\"].value) #方法1\n# # print(\"获取指定工作表的A1单元格的值\",sh1.cell(row=1,column=1).value) #方法2 方便for循环取值--推荐\n#\n# #01 获取url前缀\n# url1=sh1.cell(row=2,column=3).value\n#\n# #02 获取url后缀\n# url2=sh1.cell(row=2,column=4).value\n#\n# #03拼接完整url\n# url = url1 + url2\n# # print(url) #http://v.juhe.cn/laohuangli/d\n#\n# #02获取请求方法\n# method1 = sh1.cell(row=2,column=5).value\n# # print(method1) #POST\n#\n# #03获取请求数据类型\n# data_type1 = sh1.cell(row=2,column=6).value\n# # print(data_type1) #Form\n#\n# #04获取请求数据--入参\n# # params1 = sh1.cell(row=2,column=7).value\n# # print(params1) #{\"key\": \"e711bc6362b3179f5a28de7fd3ee4ace\", \"date\": \"2016-5-14\"}\n# params1 = {\"key\": \"e711bc6362b3179f5a28de7fd3ee4ace\", #2请求数据body\n# \"date\": \"2016-5-14\"}\n#\n# #05获取检查点--期望结果\n# check_point1 = sh1.cell(row=2,column=8).value\n# # print(check_point1) #\"0\"\n#\n# headers1 = {}\n\n\n# #003 获取最大的列数和最大的行数\n# print(\"获取最大列数\",sh1.max_column) #12\n# print(\"获取最大行数\",sh1.max_row) #3\n\n\n#新建对象\ntest1 = Interface_test(url,params1,headers1,check_point1,method1,data_type1) #自动执行构造方法,传入参数\n\n#对象调方法\ntest1.test()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"other/a1接口层框架设计1-0326/a1接口层框架设计2-3 读取excel.py","file_name":"a1接口层框架设计2-3 读取excel.py","file_ext":"py","file_size_in_byte":9293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"339428255","text":"\"\"\"\r\nCopyright (C) 2017 NVIDIA Corporation. All rights reserved.\r\nLicensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).\r\n\"\"\"\r\nfrom networks import AdaINGen, MsImageDis, Dis_content, VAEGen\r\nfrom utils import weights_init, get_model_list, vgg_preprocess, load_vgg19, get_scheduler\r\nfrom torch.autograd import Variable\r\nimport torch\r\nimport torch.nn as nn\r\nfrom torch.nn import functional as F\r\nfrom GaussianSmoothLayer import GaussionSmoothLayer, GradientLoss\r\nimport os\r\n\r\nclass UNIT_Trainer(nn.Module):\r\n def __init__(self, hyperparameters):\r\n super(UNIT_Trainer, self).__init__()\r\n lr = hyperparameters['lr']\r\n # Initiate the networks\r\n self.gen_a = VAEGen(hyperparameters['input_dim_a'], hyperparameters['gen']) # auto-encoder for domain a\r\n self.dis_cont = MsImageDis(256, hyperparameters['dis']) # discriminator for domain a\r\n self.dis_a = Dis_content()\r\n self.gpuid = hyperparameters['gpuID']\r\n # @ add backgound discriminator for each domain\r\n self.instancenorm = nn.InstanceNorm2d(512, affine=False)\r\n # Setup the optimizers\r\n beta1 = hyperparameters['beta1']\r\n beta2 = hyperparameters['beta2']\r\n dis_params = list(self.dis_a.parameters())\r\n gen_params = list(self.gen_a.parameters())\r\n self.dis_opt = torch.optim.Adam([p for p in dis_params if p.requires_grad],\r\n lr=lr, betas=(beta1, beta2), weight_decay=hyperparameters['weight_decay'])\r\n self.gen_opt = torch.optim.Adam([p for p in gen_params if p.requires_grad],\r\n lr=lr, betas=(beta1, beta2), weight_decay=hyperparameters['weight_decay'])\r\n\r\n self.content_opt = torch.optim.Adam(self.dis_cont.parameters(), lr= lr / 2., betas=(beta1, beta2), weight_decay=hyperparameters['weight_decay'])\r\n self.dis_scheduler = get_scheduler(self.dis_opt, hyperparameters)\r\n self.gen_scheduler = get_scheduler(self.gen_opt, hyperparameters)\r\n self.content_scheduler = get_scheduler(self.content_opt, hyperparameters)\r\n\r\n # Network weight initialization\r\n self.gen_a.apply(weights_init(hyperparameters['init']))\r\n self.dis_a.apply(weights_init('gaussian'))\r\n self.dis_cont.apply(weights_init('gaussian'))\r\n\r\n # initialize the blur network\r\n self.BGBlur_kernel = [5, 9, 15]\r\n self.BlurNet = [GaussionSmoothLayer(3, k_size, 25).cuda(self.gpuid) for k_size in self.BGBlur_kernel]\r\n self.BlurWeight = [0.25, 0.5, 1.]\r\n # self.Gradient = GradientLoss(3, 3)\r\n\r\n # Load VGG model if needed for test\r\n if 'vgg_w' in hyperparameters.keys() and hyperparameters['vgg_w'] > 0:\r\n self.vgg = load_vgg19()\r\n if torch.cuda.is_available():\r\n self.vgg.cuda(self.gpuid)\r\n self.vgg.eval()\r\n for param in self.vgg.parameters():\r\n param.requires_grad = False\r\n\r\n def recon_criterion(self, input, target):\r\n return torch.mean(torch.abs(input - target))\r\n\r\n def forward(self, x_a, x_b):\r\n self.eval()\r\n h_a = self.gen_a.encode_cont(x_a)\r\n output = self.gen_a.dec_cont(h_a)\r\n return output\r\n\r\n def __compute_kl(self, mu):\r\n mu_2 = torch.pow(mu, 2)\r\n encoding_loss = torch.mean(mu_2)\r\n return encoding_loss\r\n\r\n def gen_update(self, x_a, hyperparameters):\r\n self.gen_opt.zero_grad()\r\n self.content_opt.zero_grad()\r\n # encode\r\n h_c = self.gen_a.encode_cont(x_a)\r\n h_a = self.gen_a.encode_sty(x_a)\r\n noise_a = torch.randn(h_c.size()).cuda(h_c.data.get_device())\r\n h_r = self.gen_a.decode_cont(h_c + noise_a)\r\n # second encode\r\n h_cr = self.gen_a.encode_cont(h_r)\r\n h_a_cont = torch.cat((h_a, h_cr), 1)\r\n noise_c = torch.randn(h_a_cont.size()).cuda(h_a_cont.data.get_device())\r\n x_a_recon = self.gen_a.decode_recs(h_a_cont + noise_c)\r\n\r\n # update the content discriminator\r\n self.loss_ContentD = self.dis_cont.calc_gen_loss(h_c)\r\n self.loss_gen_adv_a = 0\r\n # add domain adverisal loss for generator \r\n out_a = self.dis_a(h_r)\r\n \r\n if hyperparameters['gan_type'] == 'lsgan':\r\n self.loss_gen_adv_a += torch.mean((out_a - 1)**2)\r\n elif hyperparameters['gan_type'] == 'nsgan':\r\n all1 = Variable(torch.ones_like(out_b.data).cuda(self.gpuid), requires_grad=False)\r\n self.loss_gen_adv_a += torch.mean(F.binary_cross_entropy(F.sigmoid(out_a), all1))\r\n else:\r\n assert 0, \"Unsupported GAN type: {}\".format(hyperparameters['gan_type'])\r\n\r\n # reconstruction loss\r\n self.loss_gen_recon_x_a = self.recon_criterion(x_a_recon, x_a)\r\n self.loss_gen_recon_kl_c = self.__compute_kl(h_c)\r\n self.loss_gen_recon_kl_sty = self.__compute_kl(h_a)\r\n\r\n self.loss_gen_recon_kl_cyc = self.__compute_kl(h_cr)\r\n # GAN loss\r\n \r\n\r\n # domain-invariant perceptual loss\r\n self.loss_gen_vgg_a = self.compute_vgg_loss(self.vgg, h_r, x_a) if hyperparameters['vgg_w'] > 0 else 0\r\n \r\n # add background guide loss\r\n self.loss_bgm = 0\r\n if hyperparameters['BGM'] != 0: \r\n for index, weight in enumerate(self.BlurWeight):\r\n out_a = self.BlurNet[index](h_r)\r\n out_real_a = self.BlurNet[index](x_a)\r\n grad_loss_a = self.recon_criterion(out_a, out_real_a)\r\n self.loss_bgm += weight * grad_loss_a # total loss\r\n self.loss_gen_total = hyperparameters['gan_w'] * self.loss_gen_adv_a + \\\r\n hyperparameters['recon_x_w'] * self.loss_gen_recon_x_a + \\\r\n hyperparameters['vgg_w'] * self.loss_gen_vgg_a + \\\r\n hyperparameters['recon_kl_w'] * (self.loss_gen_recon_kl_sty + self.loss_gen_recon_kl_c + self.loss_gen_recon_kl_cyc) + \\\r\n hyperparameters['BGM'] * self.loss_bgm + \\\r\n hyperparameters['gan_w'] * self.loss_ContentD \r\n self.loss_gen_total.backward()\r\n self.gen_opt.step()\r\n self.content_opt.step()\r\n\r\n def compute_vgg_loss(self, vgg, img, target):\r\n img_vgg = vgg_preprocess(img)\r\n target_vgg = vgg_preprocess(target)\r\n img_fea = vgg(img_vgg)\r\n target_fea = vgg(target_vgg)\r\n return torch.mean((self.instancenorm(img_fea) - self.instancenorm(target_fea)) ** 2)\r\n\r\n def sample(self, x_a, x_b):\r\n if x_a is None or x_b is None:\r\n return None\r\n self.eval()\r\n x_a_recon, x_ab = [], []\r\n for i in range(x_a.size(0)):\r\n h_a = self.gen_a.encode_cont(x_a[i].unsqueeze(0))\r\n h_a_sty = self.gen_a.encode_sty(x_a[i].unsqueeze(0))\r\n xab = self.gen_a.decode_cont(h_a)\r\n x_ab.append(xab)\r\n hac = self.gen_a.encode_cont(xab)\r\n h_ba_cont = torch.cat((hac, h_a_sty), 1)\r\n x_a_recon.append(self.gen_a.decode_recs(h_ba_cont))\r\n x_a_recon = torch.cat(x_a_recon)\r\n x_ab = torch.cat(x_ab)\r\n self.train()\r\n return x_a, x_a_recon, x_ab, x_b\r\n\r\n def dis_update(self, x_a, x_b, hyperparameters):\r\n self.dis_opt.zero_grad()\r\n self.content_opt.zero_grad()\r\n \r\n # first encode\r\n h_cont = self.gen_a.encode_cont(x_a)\r\n h_t_sty = self.gen_a.encode_sty(x_a)\r\n noise_c = torch.randn(h_cont.size()).cuda(h_cont.data.get_device())\r\n h_trans = self.gen_a.decode_cont(h_cont + noise_c)\r\n # seconde encode\r\n ht_c = self.gen_a.encode_cont(h_trans)\r\n h_cat = torch.cat((ht_c, h_t_sty), 1)\r\n noise_h = torch.randn(h_cat.size()).cuda(h_cat.data.get_device())\r\n h_rec = self.gen_a.dec_recs(h_cat + noise_h)\r\n \r\n \r\n # # @ add content adversial\r\n self.loss_ContentD = self.dis_cont.calc_dis_loss(h_c, ht_c)\r\n \r\n self.loss_dis = 0\r\n # decode (cross domain)\r\n out_fake = self.dis_a(h_cr.detach())\r\n out_real = self.dis_a(x_b)\r\n \r\n \r\n if hyperparameters['gan_type'] == 'lsgan':\r\n self.loss_dis += torch.mean((out_fake - 0)**2) + torch.mean((out_real - 1)**2)\r\n elif hyperparameters['gan_type'] == 'nsgan':\r\n all0 = Variable(torch.zeros_like(out_fake.data).cuda(self.gpuid), requires_grad=False)\r\n all1 = Variable(torch.ones_like(out_real.data).cuda(self.gpuid), requires_grad=False)\r\n self.loss_dis += torch.mean(F.binary_cross_entropy(F.sigmoid(out_fake), all0) +\r\n F.binary_cross_entropy(F.sigmoid(out_real), all1))\r\n else:\r\n assert 0, \"Unsupported GAN type: {}\".format(hyperparameters['gan_type'])\r\n \r\n \r\n\r\n self.loss_dis_total = hyperparameters['gan_w'] * self.loss_dis + 0.5 * hyperparameters['gan_w'] * self.loss_ContentD\r\n self.loss_dis_total.backward() \r\n # nn.utils.clip_grad_norm_(self.loss_dis.parameters(), 5) # dis_content update\r\n self.dis_opt.step()\r\n self.content_opt.step()\r\n\r\n def update_learning_rate(self):\r\n if self.dis_scheduler is not None:\r\n self.dis_scheduler.step()\r\n if self.gen_scheduler is not None:\r\n self.gen_scheduler.step()\r\n if self.content_scheduler is not None:\r\n self.content_scheduler.step()\r\n\r\n def resume(self, checkpoint_dir, hyperparameters):\r\n # Load generators\r\n last_model_name = get_model_list(checkpoint_dir, \"gen\")\r\n state_dict = torch.load(last_model_name)\r\n self.gen_a.load_state_dict(state_dict['a'])\r\n iterations = int(last_model_name[-11:-3])\r\n # Load discriminators\r\n last_model_name = get_model_list(checkpoint_dir, \"dis\")\r\n state_dict = torch.load(last_model_name)\r\n self.dis_a.load_state_dict(state_dict['a'])\r\n \r\n # load discontent discriminator\r\n last_model_name = get_model_list(checkpoint_dir, \"dis_Content\")\r\n state_dict = torch.load(last_model_name)\r\n self.dis_cont.load_state_dict(state_dict['dis_c'])\r\n\r\n\r\n # Load optimizers\r\n state_dict = torch.load(os.path.join(checkpoint_dir, 'optimizer.pt'))\r\n self.dis_opt.load_state_dict(state_dict['dis'])\r\n self.gen_opt.load_state_dict(state_dict['gen'])\r\n self.content_opt.load_state_dict(state_dict['dis_content'])\r\n # Reinitilize schedulers\r\n self.dis_scheduler = get_scheduler(self.dis_opt, hyperparameters, iterations)\r\n self.gen_scheduler = get_scheduler(self.gen_opt, hyperparameters, iterations)\r\n self.content_scheduler = get_scheduler(self.content_opt, hyperparameters, iterations)\r\n print('Resume from iteration %d' % iterations)\r\n return iterations\r\n\r\n def save(self, snapshot_dir, iterations):\r\n # Save generators, discriminators, and optimizers\r\n gen_name = os.path.join(snapshot_dir, 'gen_%08d.pt' % (iterations + 1))\r\n dis_name = os.path.join(snapshot_dir, 'dis_%08d.pt' % (iterations + 1))\r\n dis_Con_name = os.path.join(snapshot_dir, 'dis_Content_%08d.pt' % (iterations + 1))\r\n opt_name = os.path.join(snapshot_dir, 'optimizer.pt')\r\n torch.save({'a': self.gen_a.state_dict()}, gen_name)\r\n torch.save({'a': self.dis_a.state_dict()}, dis_name)\r\n torch.save({'dis_c':self.dis_cont.state_dict()}, dis_Con_name)\r\n # opt state 'dis_content':self.content_opt.state_dict()\r\n torch.save({'gen': self.gen_opt.state_dict(), 'dis': self.dis_opt.state_dict()}, opt_name)","sub_path":"trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":11785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"309999319","text":"import ROOT\nimport os\nimport numpy as np\n\nROOT.gSystem.Load(os.environ['WCSIMDIR'] + \"/libWCSimRoot.so\")\n\n\nclass WCSim:\n def __init__(self, tree):\n print(\"number of entries in the geometry tree: \" + str(self.geotree.GetEntries()))\n self.geotree.GetEntry(0)\n self.geo = self.geotree.wcsimrootgeom\n self.num_pmts = self.geo.GetWCNumPMT()\n self.tree = tree\n self.nevent = self.tree.GetEntries()\n print(\"number of entries in the tree: \" + str(self.nevent))\n # Get first event and trigger to prevent segfault when later deleting trigger to prevent memory leak\n self.tree.GetEvent(0)\n self.current_event = 0\n self.event = self.tree.wcsimrootevent\n self.ntrigger = self.event.GetNumberOfEvents()\n self.trigger = self.event.GetTrigger(0)\n self.current_trigger = 0\n\n def get_event(self, ev):\n # Delete previous triggers to prevent memory leak (only if file does not change)\n triggers = [self.event.GetTrigger(i) for i in range(self.ntrigger)]\n oldfile = self.tree.GetCurrentFile()\n self.tree.GetEvent(ev)\n if self.tree.GetCurrentFile() == oldfile:\n [t.Delete() for t in triggers]\n self.current_event = ev\n self.event = self.tree.wcsimrootevent\n self.ntrigger = self.event.GetNumberOfEvents()\n\n def get_trigger(self, trig):\n self.trigger = self.event.GetTrigger(trig)\n self.current_trigger = trig\n return self.trigger\n\n def get_first_trigger(self):\n first_trigger = 0\n first_trigger_time = 9999999.0\n for index in range(self.ntrigger):\n self.get_trigger(index)\n trigger_time = self.trigger.GetHeader().GetDate()\n if trigger_time < first_trigger_time:\n first_trigger_time = trigger_time\n first_trigger = index\n return self.get_trigger(first_trigger)\n\n def get_truth_info(self): # deprecated: should now use get_event_info instead, leaving here for use with old files\n self.get_trigger(0)\n tracks = self.trigger.GetTracks()\n energy = []\n position = []\n direction = []\n pid = []\n for i in range(self.trigger.GetNtrack()):\n if tracks[i].GetParenttype() == 0 and tracks[i].GetFlag() == 0 and tracks[i].GetIpnu() in [22, 11, -11, 13,\n -13, 111]:\n pid.append(tracks[i].GetIpnu())\n position.append([tracks[i].GetStart(0), tracks[i].GetStart(1), tracks[i].GetStart(2)])\n direction.append([tracks[i].GetDir(0), tracks[i].GetDir(1), tracks[i].GetDir(2)])\n energy.append(tracks[i].GetE())\n return direction, energy, pid, position\n\n def get_event_info(self):\n self.get_trigger(0)\n tracks = self.trigger.GetTracks()\n # Primary particles with no parent are the initial simulation\n particles = [t for t in tracks if t.GetFlag() == 0 and t.GetParenttype() == 0]\n # Check there is exactly one particle with no parent:\n if len(particles) == 1:\n # Only one primary, this is the particle being simulated\n return {\n \"pid\": particles[0].GetIpnu(),\n \"position\": [particles[0].GetStart(i) for i in range(3)],\n \"direction\": [particles[0].GetDir(i) for i in range(3)],\n \"energy\": particles[0].GetE()\n }\n # Particle with flag -1 is the incoming neutrino or 'dummy neutrino' used for gamma\n # WCSim saves the gamma details (except position) in the neutrino track with flag -1\n neutrino = [t for t in tracks if t.GetFlag() == -1]\n # Check for dummy neutrino that actually stores a gamma that converts to e+ / e-\n isConversion = len(particles) == 2 and {p.GetIpnu() for p in particles} == {11, -11}\n if isConversion and len(neutrino) == 1 and neutrino[0].GetIpnu() == 22:\n return {\n \"pid\": 22,\n \"position\": [particles[0].GetStart(i) for i in range(3)], # e+ / e- should have same position\n \"direction\": [neutrino[0].GetDir(i) for i in range(3)],\n \"energy\": neutrino[0].GetE()\n }\n # Check for dummy neutrino from old gamma simulations that didn't save the gamma info\n if isConversion and len(neutrino) == 1 and neutrino[0].GetIpnu() == 12 and neutrino[0].GetE() < 0.0001:\n # Should be a positron/electron pair from a gamma simulation (temporary hack since no gamma truth saved)\n momentum = [sum(p.GetDir(i) * p.GetP() for p in particles) for i in range(3)]\n norm = np.sqrt(sum(p ** 2 for p in momentum))\n return {\n \"pid\": 22,\n \"position\": [particles[0].GetStart(i) for i in range(3)], # e+ / e- should have same position\n \"direction\": [p / norm for p in momentum],\n \"energy\": sum(p.GetE() for p in particles)\n }\n # Otherwise something else is going on... guess info from the primaries\n momentum = [sum(p.GetDir(i) * p.GetP() for p in particles) for i in range(3)]\n norm = np.sqrt(sum(p ** 2 for p in momentum))\n return {\n \"pid\": 0, # there's more than one particle so just use pid 0\n \"position\": [sum(p.GetStart(i) for p in particles)/len(particles) for i in range(3)], # average position\n \"direction\": [p / norm for p in momentum], # direction of sum of momenta\n \"energy\": sum(p.GetE() for p in particles) # sum of energies\n }\n\n def get_digitized_hits(self):\n position = []\n charge = []\n time = []\n pmt = []\n trigger = []\n for t in range(self.ntrigger):\n self.get_trigger(t)\n for hit in self.trigger.GetCherenkovDigiHits():\n pmt_id = hit.GetTubeId() - 1\n position.append([self.geo.GetPMT(pmt_id).GetPosition(j) for j in range(3)])\n charge.append(hit.GetQ())\n time.append(hit.GetT())\n pmt.append(pmt_id)\n trigger.append(t)\n hits = {\n \"position\": np.asarray(position, dtype=np.float32),\n \"charge\": np.asarray(charge, dtype=np.float32),\n \"time\": np.asarray(time, dtype=np.float32),\n \"pmt\": np.asarray(pmt, dtype=np.int32),\n \"trigger\": np.asarray(trigger, dtype=np.int32)\n }\n return hits\n\n def get_true_hits(self):\n position = []\n track = []\n pmt = []\n PE = []\n trigger = []\n for t in range(self.ntrigger):\n self.get_trigger(t)\n for hit in self.trigger.GetCherenkovHits():\n pmt_id = hit.GetTubeID() - 1\n tracks = set()\n for j in range(hit.GetTotalPe(0), hit.GetTotalPe(0)+hit.GetTotalPe(1)):\n pe = self.trigger.GetCherenkovHitTimes().At(j)\n tracks.add(pe.GetParentID())\n position.append([self.geo.GetPMT(pmt_id).GetPosition(k) for k in range(3)])\n track.append(tracks.pop() if len(tracks) == 1 else -2)\n pmt.append(pmt_id)\n PE.append(hit.GetTotalPe(1))\n trigger.append(t)\n hits = {\n \"position\": np.asarray(position, dtype=np.float32),\n \"track\": np.asarray(track, dtype=np.int32),\n \"pmt\": np.asarray(pmt, dtype=np.int32),\n \"PE\": np.asarray(PE, dtype=np.int32),\n \"trigger\": np.asarray(trigger, dtype=np.int32)\n }\n return hits\n\n def get_hit_photons(self):\n start_position = []\n end_position = []\n start_time = []\n end_time = []\n track = []\n pmt = []\n trigger = []\n for t in range(self.ntrigger):\n self.get_trigger(t)\n n_photons = self.trigger.GetNcherenkovhittimes()\n trigger.append(np.full(n_photons, t, dtype=np.int32))\n counts = [h.GetTotalPe(1) for h in self.trigger.GetCherenkovHits()]\n hit_pmts = [h.GetTubeID()-1 for h in self.trigger.GetCherenkovHits()]\n pmt.append(np.repeat(hit_pmts, counts))\n end_time.append(np.zeros(n_photons, dtype=np.float32))\n track.append(np.zeros(n_photons, dtype=np.int32))\n start_time.append(np.zeros(n_photons, dtype=np.float32))\n start_position.append(np.zeros((n_photons, 3), dtype=np.float32))\n end_position.append(np.zeros((n_photons, 3), dtype=np.float32))\n photons = self.trigger.GetCherenkovHitTimes()\n end_time[t][:] = [p.GetTruetime() for p in photons]\n track[t][:] = [p.GetParentID() for p in photons]\n try: # Only works with new tracking branch of WCSim\n start_time[t][:] = [p.GetPhotonStartTime() for p in photons]\n for i in range(3):\n start_position[t][:,i] = [p.GetPhotonStartPos(i)/10 for p in photons]\n end_position[t][:,i] = [p.GetPhotonEndPos(i)/10 for p in photons]\n except AttributeError: # leave as zeros if not using tracking branch\n pass\n photons = {\n \"start_position\": np.concatenate(start_position),\n \"end_position\": np.concatenate(end_position),\n \"start_time\": np.concatenate(start_time),\n \"end_time\": np.concatenate(end_time),\n \"track\": np.concatenate(track),\n \"pmt\": np.concatenate(pmt),\n \"trigger\": np.concatenate(trigger)\n }\n return photons\n\n def get_tracks(self):\n track_id = []\n pid = []\n start_time = []\n energy = []\n start_position = []\n stop_position = []\n parent = []\n flag = []\n for t in range(self.ntrigger):\n self.get_trigger(t)\n for track in self.trigger.GetTracks():\n track_id.append(track.GetId())\n pid.append(track.GetIpnu())\n start_time.append(track.GetTime())\n energy.append(track.GetE())\n start_position.append([track.GetStart(i) for i in range(3)])\n stop_position.append([track.GetStop(i) for i in range(3)])\n parent.append(track.GetParenttype())\n flag.append(track.GetFlag())\n tracks = {\n \"id\": np.asarray(track_id, dtype=np.int32),\n \"pid\": np.asarray(pid, dtype=np.int32),\n \"start_time\": np.asarray(start_time, dtype=np.float32),\n \"energy\": np.asarray(energy, dtype=np.float32),\n \"start_position\": np.asarray(start_position, dtype=np.float32),\n \"stop_position\": np.asarray(stop_position, dtype=np.float32),\n \"parent\": np.asarray(parent, dtype=np.int32),\n \"flag\": np.asarray(flag, dtype=np.int32)\n }\n return tracks\n\n def get_triggers(self):\n trigger_times = np.empty(self.ntrigger, dtype=np.float32)\n trigger_types = np.empty(self.ntrigger, dtype=np.int32)\n for t in range(self.ntrigger):\n self.get_trigger(t)\n trigger_times[t] = self.trigger.GetHeader().GetDate()\n trig_type = self.trigger.GetTriggerType()\n if trig_type > np.iinfo(np.int32).max:\n trig_type = -1;\n trigger_types[t] = trig_type\n triggers = {\n \"time\": trigger_times,\n \"type\": trigger_types\n }\n return triggers\n\n\nclass WCSimFile(WCSim):\n def __init__(self, filename):\n self.file = ROOT.TFile(filename, \"read\")\n tree = self.file.Get(\"wcsimT\")\n self.geotree = self.file.Get(\"wcsimGeoT\")\n super().__init__(tree)\n\n def __del__(self):\n self.file.Close()\n\n\nclass WCSimChain(WCSim):\n def __init__(self, filenames):\n self.chain = ROOT.TChain(\"wcsimT\")\n for file in filenames:\n self.chain.Add(file)\n self.file = self.GetFile()\n self.geotree = self.file.Get(\"wcsimGeoT\")\n super().__init__(self.chain)\n\ndef get_label(infile):\n if \"_gamma\" in infile:\n label = 0\n elif \"_e\" in infile:\n label = 1\n elif \"_mu\" in infile:\n label = 2\n elif \"_pi0\" in infile:\n label = 3\n else:\n print(\"Unknown input file particle type\")\n raise SystemExit\n return label\n","sub_path":"root_utils/root_file_utils.py","file_name":"root_file_utils.py","file_ext":"py","file_size_in_byte":12497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"46238646","text":"favorite_places = {\n\t'user_01': {'nome' : 'philipe',\n\t\t'local_1' : 'ponta negra',\n\t\t'local_2': 'millenium',\n\t\t'local_3' : 'parque dos bilhares',\n\t},\n\t'user_02':{'nome' : 'carolina',\n\t\t'local_1' : 'ponta negra',\n\t\t'local_2' : 'porão do alemão',\n\t\t'local_3' : 'studio 5',\n\t},\n\t'user_03':{'nome': 'joed',\n\t\t'local_1' : 'porão do alemão',\n\t\t'local_2' : 'ponta negra',\n\t\t'local_3' : 'careiro',\n\t},\n}\n\nfor user,user_info in favorite_places.items():\n\tprint('User: '+user)\n\tnome = user_info['nome']\n\tlocal_1 = user_info['local_1']\n\tlocal_2 = user_info['local_2']\n\tlocal_3 = user_info['local_3']\n\n\tprint('Nome: '+nome.title())\n\tprint('Locais Favoritos: '+local_1+','+local_2+','+local_3)\n\n\tprint('')","sub_path":"Curso Intensivo de Python Uma Eric Mat/exercicio/6.9.py","file_name":"6.9.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"633145739","text":"import gym\nimport random\nimport torch\nimport numpy as np\nfrom collections import deque\nimport matplotlib.pyplot as plt\nfrom tqdm import trange\nfrom DQN_agent import Agent\nimport time\n\ndef running_average(x, N):\n ''' Function used to compute the running average\n of the last N elements of a vector x\n '''\n if len(x) >= N:\n y = np.copy(x)\n y[N-1:] = np.convolve(x, np.ones((N, )) / N, mode='valid')\n else:\n y = np.zeros_like(x)\n return y\n\ndef main():\n env = gym.make('LunarLander-v2')\n env.seed(0)\n agent = Agent(state_dim= env.observation_space.shape[0], n_actions=env.action_space.n,seed=0, BUFFER_SIZE = 100000, BATCH_SIZE=64,DISCOUNT=0.99,TAU=1,LR=7e-4,UPDATE_EVERY=4)\n n_ep_running_average = 50\n n_episodes=10\n max_t=1000\n eps_end=0.01\n eps_decay=0.995\n eps = 1.0 # initialize epsilon\n episode_reward_list = [] # this list contains the total reward per episode\n episode_number_of_steps = [] # this list contains the number of steps per episode\n EPISODES = trange(n_episodes, desc='Episode: ', leave=True)\n\n for i in EPISODES:\n state = env.reset()\n total_episode_reward = 0.\n t=0\n for k in range(max_t):\n action = agent.act(state, eps)\n #env.render()\n next_state, reward, done, _ = env.step(action)\n total_episode_reward += reward\n agent.step(state, action, reward, next_state, done)\n state = next_state\n t+=1\n if done:\n break \n episode_reward_list.append(total_episode_reward)\n episode_number_of_steps.append(t)\n eps = max(eps_end, eps_decay*eps) # decrease epsilon\n EPISODES.set_description(\"Episode {} - Reward/Steps: {:.1f}/{} - Avg. Reward/Steps: {:.1f}/{}\".format(i, total_episode_reward, t,\n running_average(episode_reward_list, n_ep_running_average)[-1],\n running_average(episode_number_of_steps, n_ep_running_average)[-1]))\n\n\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"Deep Q-Networks (DQN) - LunarLander discrete/DQN_problem.py","file_name":"DQN_problem.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"420025132","text":"import time\nimport json\nimport sys\nimport requests\nimport logging\nimport argparse\nimport datetime\nimport string\nimport random\nimport os\nfrom ibm_cloud_sdk_core.authenticators import BearerTokenAuthenticator, IAMAuthenticator\nfrom ibm_security_advisor_findings_api_sdk import FindingsApiV1\n\nlogger = logging.getLogger(\"cleanup\")\nlogger.setLevel(logging.INFO)\n\ndef obtain_iam_token(api_key):\n if not api_key:\n raise Exception(\"obtain_iam_token: missing api key\")\n try:\n authenticator = IAMAuthenticator(api_key, url=os.environ['TOKEN_URL'])\n token = authenticator.token_manager.get_token()\n except requests.exceptions.HTTPError as err:\n logger.exception(\"an unexpected error was encountered while obtaining IAM token: \"+str(err))\n sys.exit(1)\n if token:\n return token\n\n\n\ndef get_all_kubebenchnotes(account_id, token, endpoint):\n notes = []\n providers = [\"kubeBenchRedhatOpenshift\", \"kubeBenchRedhatOpenshiftWarnings\", \"kubeBenchRedhatOpenshiftFailures\"]\n notes.extend(get_notes(account_id, token, endpoint, providers))\n return notes\n\n\ndef get_notes(account_id, token, endpoint, providers):\n notes = []\n try:\n findingsAPI = FindingsApiV1(\n authenticator=BearerTokenAuthenticator(token)\n )\n findingsAPI.set_service_url(endpoint)\n for provider in providers:\n response = findingsAPI.list_notes(\n account_id=account_id, \n provider_id=provider\n )\n if response.get_status_code() == 200:\n logger.info(\"got notes by provider: %s\" % provider)\n for note in response.get_result()['notes']:\n notes.append(note)\n else:\n logger.error(\"unable to get notes by provider: %s\" % provider)\n return notes\n except requests.exceptions.HTTPError as err:\n logger.exception(\"an unexpected error was encountered while getting the note: \"+str(err))\n return False\n\n\ndef delete_all_kubenotes(account_id, token, endpoint):\n\tnotes = get_all_kubebenchnotes(account_id, token, endpoint)\n\tdelete_notes(account_id, token, endpoint, notes)\n\t\ndef delete_notes(account_id, token, endpoint, notes):\n try:\n findingsAPI = FindingsApiV1(\n authenticator=BearerTokenAuthenticator(token)\n )\n findingsAPI.set_service_url(endpoint)\n for note in notes:\n response = findingsAPI.delete_note(\n account_id=account_id, \n note_id=note['id'],\n **note\n )\n if response.get_status_code() == 200:\n logger.info(\"deleted note: %s\" % note['id'])\n else:\n logger.error(\"unable to delete note: %s\" % note['id'])\n except:\n logger.exception(\"an unexpected error was encountered while deleting the note: \"+str(err))\n time.sleep(1)\n\n\ndef get_all_kubebenchoccurrences(account_id, token, endpoint):\n occurrences = []\n providers = [\"kubeBenchRedhatOpenshift\", \"kubeBenchRedhatOpenshiftWarnings\", \"kubeBenchRedhatOpenshiftFailures\"]\n occurrences.extend(get_occurrences(account_id, token, endpoint, providers))\n return occurrences\n\n\ndef get_occurrences(account_id, token, endpoint, providers):\n occurrences = []\n try:\n findingsAPI = FindingsApiV1(\n authenticator=BearerTokenAuthenticator(token)\n )\n findingsAPI.set_service_url(endpoint)\n for provider_id in providers:\n response = findingsAPI.list_occurrences(\n account_id=account_id, \n provider_id=provider_id\n )\n if response.get_status_code() == 200:\n logger.info(\"got occurrences by provider: %s\" % provider_id)\n for occurrence in response.get_result()['occurrences']:\n occurrences.append(occurrence)\n else:\n logger.error(\"unable to get occurrences by provider: %s\" % provider_id)\n return occurrences\n except requests.exceptions.HTTPError as err:\n logger.exception(\"an unexpected error was encountered while getting the occurrences: \"+str(err))\n return False\n\n\ndef delete_occurrences(account_id, token, endpoint, occurrences):\n try:\n findingsAPI = FindingsApiV1(\n authenticator=BearerTokenAuthenticator(token)\n )\n findingsAPI.set_service_url(endpoint)\n for occurrence in occurrences:\n response = findingsAPI.delete_occurrence(\n account_id=account_id, \n occurrence_id=occurrence['id'],\n **occurrence\n )\n if response.get_status_code() == 200:\n logger.info(\"deleted occurrence: %s\" % occurrence['id'])\n else:\n logger.error(\"unable to delete occurrence: %s\" % occurrence['id'])\n except requests.exceptions.HTTPError as err:\n logger.exception(\"an unexpected error was encountered while deleting the occurrence: \"+str(err))\n time.sleep(1)\n\ndef cleanup(apikey, account_id, endpoint):\n token = obtain_iam_token(apikey)\n try:\n delete_all_kubenotes(account_id, token, endpoint)\n vulnerabilityOccurrences = get_all_kubebenchoccurrences(account_id, token, endpoint)\n delete_occurrences(account_id, token, endpoint, vulnerabilityOccurrences)\n except:\n logger.exception(\"An unexpected error was encountered while cleanup\")\n\ndef main(args):\n account_id = args[1]\n apikey = args[2]\n endpoint = args[3]\n cleanup(apikey, account_id, endpoint)\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"src/redhat-openshift/kubeBenchCleanup.py","file_name":"kubeBenchCleanup.py","file_ext":"py","file_size_in_byte":5637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"582117974","text":"from django.db import models\nfrom ad_posts.models import Ad\n\n\nclass Pets(Ad):\n BREED_DOG=(\n ('Акита','Акита'),\n ('Аляскинский маламут','Аляскинский маламут'),\n ('Американский бульдог','Американский бульдог'),\n ('Английский бульдог','Английский бульдог'),\n ('Басенджи','Басенджи'),\n ('Бассет','Бассет'),\n ('Бельгийская овчарка','Бельгийская овчарка'),\n ('Бельгийский гриффон','Бельгийский гриффон'),\n ('Бернский зенненхунд','Бернский зенненхунд'),\n ('Бивер','Бивер'),\n ('Бигль','Digma'),\n ('Бишон фризе','Бишон фризе'),\n ('Бобтейл','Бобтейл'),\n ('Боксер','Боксер'),\n ('Болонка','Болонка'),\n ('Бриар','Бриар'),\n ('Брюссельский гриффон','Брюссельский гриффон'),\n ('Бульмастиф','Бульмастиф'),\n ('Бультерьер','Бультерьер'),\n ('Бурбуль','Бурбуль'),\n ('Вельштерьер','Вельштерьер'),\n ('Вест-хайленд-уайт-терьер','Вест-хайленд-уайт-терьер'),\n ('Восточноевропейская овчарка','Восточноевропейская овчарка'),\n ('Далматин','Далматин'),\n ('Джек Рассел терьер','Джек Рассел терьер'),\n ('Доберман','Доберман'),\n ('Дог','Дог'),\n ('Ирландский терьер','Ирландский терьер'),\n ('Йоркширский терьер','Йоркширский терьер'),\n ('Кавказская овчарка','Кавказская овчарка'),\n ('Кане-корсо','Кане-корсо'),\n ('Керн-терьер','Керн-терьер'),\n ('Китайская хохлатая','Китайская хохлатая'),\n ('Кокер-спаниель','Кокер-спаниель'),\n ('Колли','Колли'),\n ('Курцхаар','Курцхаар'),\n ('Лабрадор','ЛабрадорZTE'),\n ('Лайка','Лайка'),\n ('Левретка','Левретка'),\n ('Леонбергер','Леонбергер'),\n ('Лхаса Апсо','Лхаса Апсо'),\n ('Мастиф','Мастиф'),\n ('Миттельшнауцер','Миттельшнауцер'),\n ('Мопс','Мопс'),\n ('Московская сторожевая','Московская сторожевая'),\n ('Немецкая овчарка','Немецкая овчарка'),\n ('Норвич-терьер','Норвич-терьер'),\n ('Ньюфаундленд','Ньюфаундленд'),\n ('Овчарка','Овчарка'),\n ('Папильон','Папильон'),\n ('Пекинес','Пекинес'),\n ('Петербургская орхидея','Петербургская орхидея'),\n ('Питбуль','Питбуль'),\n ('Пойнтер','Пойнтер'),\n ('Пти-брабансон','Пти-брабансон'),\n ('Пудель','Пудель'),\n ('Ретривер','Ретривер'),\n ('Ризеншнауцер','Ризеншнауцер'),\n ('Родезийский риджбек','Родезийский риджбек'),\n ('Ротвейлер','Ротвейлер'),\n ('Русская борзая','Русская борзая'),\n ('Самоедская лайка','Самоедская лайка'),\n ('Сенбернар','Сенбернар'),\n ('Сеттер','Сеттер'),\n ('Сибирский хаски','Сибирский хаски'),\n ('Скотч-терьер','Скотч-терьер'),\n ('Спаниель','Спаниель'),\n ('Среднеазиатская овчарка','Среднеазиатская овчарка'),\n ('Стаффордширский терьер','Стаффордширский терьер'),\n ('Такса','Такса'),\n ('Той-терьер','Той-терьер'),\n ('Той-пудель','Той-пудель'),\n ('Фландрский бувье','Фландрский бувье'),\n ('Фокстерьер','Фокстерьер'),\n ('Французская овчарка','Французская овчарка'),\n ('Французский терьер','Французский терьер'),\n ('Цвергпинчер','Цвергпинчер'),\n ('Цвергшнауцер','Цвергшнауцер'),\n ('Чау-чау','Чау-чау'),\n ('Чихуахуа','Чихуахуа'),\n ('Шарпей','Шарпей'),\n ('Щвейцарская овчарка','Щвейцарская овчарка'),\n ('Шелти','Шелти'),\n ('Ши-тсу','Ши-тсу'),\n ('Шпиц','Шпиц'),\n ('Эрдельтерьер','Эрдельтерьер'),\n ('Ягдтерьер','Ягдтерьер'),\n ('Японский хин','Японский хин'),\n ('Другая','Другая'),\n )\n BREED_CAT=(\n ('Абиссинская','Абиссинская'),\n ('Американский керл','Американский керл'),\n ('Балинез','Балинез'),\n ('Бенгальская','Бенгальская'),\n ('Британская','Британская'),\n ('Бурманская','Бурманская'),\n ('Девон-рекс','Девон-рекс'),\n ('Донской сфинкс','Донской сфинкс'),\n ('Европейская','Европейская'),\n ('Канадский сфинкс','Канадский сфинкс'),\n ('Корниш-рекс','Корниш-рекс'),\n ('Курильский бобтейл','Курильский бобтейл'),\n ('Лаперм','Лаперм'),\n ('Манчкин','Манчкин'),\n ('Мейн-кун','Мейн-кун'),\n ('Меконгский бобтейл','Меконгский бобтейл'),\n ('Невская маскарадная','Невская маскарадная'),\n ('Норвежская лесная','Норвежская лесная'),\n ('Ориентальная','Ориентальная'),\n ('Оцикет','Оцикет'),\n ('Персидская','Персидская'),\n ('Петерболд','Петерболд'),\n ('Русская голубая','Русская голубая'),\n ('Селкирк-рекс','Селкирк-рекс'),\n ('Сиамская','Сиамская'),\n ('Сибирская','Сибирская'),\n ('Сингапурская','Сингапурская'),\n ('Сомалийская','Сомалийская'),\n ('Тайская','Тайская'),\n ('Турецкая ангора','Турецкая ангора'),\n ('Уральский рекс','Уральский рекс'),\n ('Шотландская','Шотландская'),\n ('Экзотическая','Экзотическая'),\n ('Японский бобтейл','Японский бобтейл'),\n ('Другая','Другая'),\n )\n TYPE_BIRD=(\n ('Голуби','Голуби'),\n ('Певчие','Певчие'),\n ('Попугаи','Попугаи'),\n ('С/х птицы','С/х птицы'),\n )\n TYPE_RODENTS=(\n ('Кролики','Кролики'),\n ('Морские свинки','Морские свинки'),\n ('Мыши и крысы','Мыши и крысы'),\n ('Хомяки','Хомяки'),\n ('Хорьки','Хорьки'),\n ('Шиншиллы','Шиншиллы'),\n )\n TYPE_BEAST=(\n ('Козы','Козы'),\n ('Коровы и быки','Коровы и быки'),\n ('Овцы и бараны','Овцы и бараны'),\n ('Лошади','Лошади'),\n ('Свиньи','Свиньи'),\n )\n OTHER=(\n ('Пауки и насекомые','Пауки и насекомые'),\n ('Улитки','Улитки'),\n ('Черепахи и рептилии','Черепахи и рептилии'),\n )\n TYPE_ANIMALS=(\n ('Собаки','Собаки'),\n ('Кошки','Кошки'),\n ('Птицы','Птицы'),\n ('Грызуны','Грызуны'),\n ('Рыбки','Рыбки'),\n ('Лошади','Лошади'),\n ('Рептилии','Рептилии'),\n ('с/х животные','с/х животные'),\n )\n TYPE_GOOD=(\n ('Будки и вольеры','Будки и вольеры'),\n ('Витамины и добавки','Витамины и добавки'),\n ('Игрушки','Игрушки'),\n ('Инструменты для ухода','Инструменты для ухода'),\n ('Клетки и переноски','Клетки и переноски'),\n ('Корма','Корма'),\n ('Косметика и гигиена','Косметика и гигиена'),\n ('Лежаки и домики','Лежаки и домики'),\n ('Миски, кормушки, поилки','Миски, кормушки, поилки'),\n ('Намордники','Намордники'),\n ('Одежда и обувь','Одежда и обувь'),\n ('От блох и клещей','От блох и клещей'),\n ('Ошейники и поводки','Ошейники и поводки'),\n ('Туалет и наполнители','Туалет и наполнители'),\n )\n TYPE_AQUA=(\n ('Аквариумы','Аквариумы'),\n ('Декор и растения','Декор и растения'),\n ('Инвентарь для обслуживания','Инвентарь для обслуживания'),\n ('Обогрев','Обогрев'),\n ('Освещение','Освещение'),\n ('Террариумы','Террариумы'),\n ('Фильтры и аэрация','Фильтры и аэрация'),\n )\n\n breed_dog = models.CharField(max_length=50, blank=True, choices = BREED_DOG, verbose_name=\"Порода собаки\")\n breed_cat = models.CharField(max_length=50, blank=True, choices = BREED_CAT, verbose_name=\"Порода кошки\")\n type_bird = models.CharField(max_length=50, blank=True, choices = TYPE_BIRD, verbose_name=\"Вид птицы\")\n type_rodents = models.CharField(max_length=50, blank=True, choices = TYPE_RODENTS, verbose_name=\"Тип грызуна\")\n type_beast = models.CharField(max_length=50, blank=True, choices = TYPE_BEAST, verbose_name=\"Тип с/х животного\")\n otherss = models.CharField(max_length=50, blank=True, choices = OTHER, verbose_name=\"Другие животные\")\n type_animals = models.CharField(max_length=50, blank=True, choices = TYPE_ANIMALS, verbose_name=\"Тип животного\")\n type_good = models.CharField(max_length=50, blank=True, choices = TYPE_GOOD, verbose_name=\"Тип товара\")\n type_aqua = models.CharField(max_length=50, blank=True, choices = TYPE_AQUA, verbose_name=\"Аквариумистика\")\n\n class Meta:\n verbose_name = \"Животные\"\n verbose_name_plural = \"Животные\"\n","sub_path":"ad_model/pets.py","file_name":"pets.py","file_ext":"py","file_size_in_byte":12045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"384736815","text":"import pyb, time\nfrom pyb import Pin, Timer, ADC, UART\nfrom oled_938 import OLED_938\nfrom mpu6050 import MPU6050\nfrom motor import MOTOR\n\nA1 = Pin('X3', Pin.OUT_PP)\t\t# Control direction of motor A\nA2 = Pin('X4', Pin.OUT_PP)\nPWMA = Pin('X1')\t\t\t\t# Control speed of motor A\n\nB1 = Pin('X7', Pin.OUT_PP)\t\t# Control direction of motor B\nB2 = Pin('X8', Pin.OUT_PP)\nPWMB = Pin('X2')\t\t\t\t# Control speed of motor B\n\ntim = Timer(2, freq = 1000)\nmotorA = tim.channel (1, Timer.PWM, pin = PWMA)\nmotorB = tim.channel (2, Timer.PWM, pin = PWMB)\n\npot = pyb.ADC(Pin('X11'))\nuart = UART(6)\nuart.init(9600, bits=8, parity = None, stop = 2)\n\nimu = MPU6050(1, False)\npitch = 0\n\nrobot = MOTOR()\n\noled = OLED_938(pinout={'sda': 'Y10', 'scl': 'Y9', 'res': 'Y8'}, height=64,\n external_vcc=False, i2c_devid=61)\noled.poweron()\noled.init_display()\n\n\n'''Pitch angle calculation using complementary filter'''\ndef pitch_estimate(pitch, dt, alpha):\n theta = imu.pitch()\n pitch_dot = imu.get_gy()\n pitch = alpha*(pitch + pitch_dot*dt) + (1- alpha)*theta\n return (pitch, pitch_dot)\n\ndef motordrive(w1, w2):\n robot.Aspeed = w1\n robot.Bspeed = w2\n robot.drive()\n\n#Tuning the PID controller - using potentiometer and USR switch to adjust the gain values live\ntrigger = pyb.Switch()\nscale = 20.0\nwhile not trigger():\n time.sleep(0.001)\n offset = pot.read()/4095-0.5\n oled.draw_text(0, 30, 'offset = {:5.2f}'.format(offset))\n oled.display()\n\n\noled.draw_text(0, 20, 'Button pressed. Running.')\noled.display()\n\ndef PID(pitch, pitch_dot, setpoint, pError, dt, total):\n pError = setpoint - pitch\n total = total + pError*dt\n w = Kp*pError - Kd*pitch_dot + Ki*total\n return (w, total)\n\ntotal = 0\npError = 0\nspeed = 0.2\ntic1 = pyb.micros()\nKp = 6\nKi = 80\nKd = 0.6\ntarget = offset\nratio1 = 1\nratio2 = 1\nwhile True:\n dt_micro = pyb.micros() - tic1\n if (dt_micro >= 5000):\n dt = dt_micro*0.000001\n pitch, pitch_dot = pitch_estimate(pitch, dt, 0.95)\n w, total = PID(pitch, pitch_dot, target, pError, dt, total)\n motordrive(w*ratio1, w*ratio2)\n tic1 = pyb.micros()\n elif (uart.any()==5): # wait for 10 chars\n command = uart.read(5)\n if command[2]==ord('5'):\n ratio1 = 1\n ratio2 = 1\n target = offset + speed\n elif command[2]==ord('6'):\n ratio1 = 1\n ratio2 = 1\n target = offset - speed\n elif command[2]==ord('7'):\n ratio1 = 0.5\n ratio2 = 1\n target = offset + speed\n elif command[2]==ord('8'):\n ratio1 = 1\n ratio2 = 0.5\n target = offset + speed\n elif command[2]==ord('1'):\n ratio1 = 1\n ratio2 = 1\n target = offset\n else:\n ratio1 = 1\n ratio2 = 1\n target = offset\n","sub_path":"bdrive.py","file_name":"bdrive.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"525759324","text":"\"\"\"\nCopyright (c) 2013 Shotgun Software, Inc\n----------------------------------------------------\n\n\"\"\"\nimport os\nimport hou\n\nimport tank\nfrom tank import Hook\nfrom tank import TankError\n\n\nclass SceneOperation(Hook):\n \"\"\"\n Hook called to perform an operation with the current scene\n \"\"\"\n def execute(self, operation, file_path, context, **kwargs):\n \"\"\"\n Main hook entry point\n\n :operation: String\n Scene operation to perform\n\n :file_path: String\n File path to use if the operation\n requires it (e.g. open)\n\n :context: Context\n The context the file operation is being\n performed in.\n\n :returns: Depends on operation:\n 'current_path' - Return the current scene\n file path as a String\n 'reset' - True if scene was reset to an empty\n state, otherwise False\n all others - None\n \"\"\"\n if operation == \"current_path\":\n return str(hou.hipFile.name())\n elif operation == \"open\":\n # give houdini forward slashes\n file_path = file_path.replace(os.path.sep, '/')\n hou.hipFile.load(file_path)\n elif operation == \"save\":\n hou.hipFile.save()\n elif operation == \"save_as\":\n # give houdini forward slashes\n file_path = file_path.replace(os.path.sep, '/')\n hou.hipFile.save(str(file_path))\n elif operation == \"reset\":\n hou.hipFile.clear()\n return True\n","sub_path":"tank_dev/install/apps/tk-multi-workfiles/v0.3.3/hooks/scene_operation_tk-houdini.py","file_name":"scene_operation_tk-houdini.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"434060203","text":"cluster = {\n # node names\n 'nodes': {\n # masters\n 'node_1': {'host': '127.0.0.1', 'port': 63791},\n 'node_2': {'host': '127.0.0.1', 'port': 63792},\n # slaves\n 'node_5': {'host': '127.0.0.1', 'port': 63795},\n 'node_6': {'host': '127.0.0.1', 'port': 63796},\n },\n # replication information\n 'master_of': {\n 'node_1': 'node_6', # node_6 slaveof node_1 in redis6.conf\n 'node_2': 'node_5', # node_5 slaveof node_2 in redis5.conf\n },\n\n 'default_node': 'node_1'\n}\n","sub_path":"tests/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"638990210","text":"class Solution(object):\n def twoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n ans = []\n peer2index = {}\n for idx in range(len(nums)):\n if peer2index.has_key(nums[idx]):\n ans.append(peer2index.get(nums[idx]))\n ans.append(idx)\n return ans\n else:\n peer2index[target - nums[idx]] = idx\n","sub_path":"1-100/1. Two Sum.py","file_name":"1. Two Sum.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"476604945","text":"from flask import after_this_request, request\nfrom cStringIO import StringIO as IO\nimport gzip\nimport functools \n\ndef gzipped(f):\n @functools.wraps(f)\n def view_func(*args, **kwargs):\n @after_this_request\n def zipper(response):\n accept_encoding = request.headers.get('Accept-Encoding', '')\n\n if 'gzip' not in accept_encoding.lower():\n return response\n\n response.direct_passthrough = False\n\n if (response.status_code < 200 or\n response.status_code >= 300 or\n 'Content-Encoding' in response.headers):\n return response\n gzip_buffer = IO()\n gzip_file = gzip.GzipFile(mode='wb', \n fileobj=gzip_buffer)\n gzip_file.write(response.data)\n gzip_file.close()\n\n response.data = gzip_buffer.getvalue()\n response.headers['Content-Encoding'] = 'gzip'\n response.headers['Vary'] = 'Accept-Encoding'\n response.headers['Content-Length'] = len(response.data)\n\n return response\n\n return f(*args, **kwargs)\n\n return view_func\n","sub_path":"gzip.py","file_name":"gzip.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"591947480","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 1 11:44:45 2017\n\n@author: Marco\n\"\"\"\nimport sambuca as sb\n\nimport time\nimport multiprocessing as mp\nimport numpy as np\n\n\n\n\ndef sam_com( observed_rrs, objective, siop, result_recorder, image_info, shallow = False):\n #pool = mp.Pool(processes=10)\n pool = None #for serial processing of substrates\n n = 0\n skip_count = 0\n \n #Define a region to process in the image input\n \n #*****Observed data is in band, row(height, x), column(width, y)******\n xstart =0\n xend = image_info['observed_rrs_height']\n xspan = xend - xstart\n ystart = 0\n yend = image_info['observed_rrs_width']\n coordinates=[xstart, xend, ystart, yend]\n num_pixels = xspan * (yend - ystart)\n assert xend <= image_info['observed_rrs_height']\n assert yend <= image_info['observed_rrs_width']\n \n \n # set current starting points as the midpoints of the parameters \n #p0 = (np.array(siop['p_max'])+np.array(siop['p_min']))/2\n p0 = np.array(siop['p_min'])+((np.array(siop['p_max'])-np.array(siop['p_min']))/4)\n t0 = time.time()\n \n # set some relaxed abundance constraints (RASC) after Petit et. al.(2017)******\n \n low_relax = 0.7\n high_relax = 1.3\n \n cons=({'type':'ineq','fun':lambda x:high_relax -(x[4]+x[5]+x[6])},\n {'type':'ineq','fun':lambda x:(x[4]+x[5]+x[6])- low_relax})\n \n #******************************************************************************\n # Return to sum to one constraint\n \n #cons=({'type':'eq','fun':lambda x:1-(x[4]+x[5]+x[6])})\n \n #******************************************************************************\n \n for x in range(xstart, xend):\n for y in range(ystart, yend):\n print ([x,y])\n obs_rrs = observed_rrs[:,x,y]\n \n # Quick and dirty check because we are not masking out the no-data pixels\n if not np.allclose(obs_rrs, 0):\n \n # we need to set the observed rrs for this pixel into the objective, as there is no\n # direct way to get the scipy.minimise function to do it (although there are other ways\n # such as using a closure)\n \n #print(\"sono qui\")\n result = sb.minimize(\n objective,\n p0,\n method='SLSQP',\n bounds=siop['p_bounds'],\n constraints=cons,\n options={'disp':False, 'maxiter':5000},\n obs_rrs=obs_rrs)\n \n #%time result = minimize(objective, p0, method='SLSQP', bounds=p_bounds, options={'disp':False, 'maxiter':500})\n \n # todo: check if the minimiser converged!\n \n # we need to repack the parameter tuple used by scipy.minimize into the sambuca.FreeParameter tuple\n # expected by the pixel result handlers. As the p0 tuple was generated from a FreeParameter tuple in the \n # first place, we know that the order of the values match, so we can simply unpack the result tuple into \n # the FreeParameters constructor.\n #print(result.nit,result.success,*result['x'])\n result_recorder(x, y, obs_rrs, parameters=sb.FreeParameters(*result.x), nit=result.nit, success=result.success)\n #result_recorder(x, y, obs_rrs, parameters=sb.FreeParameters(*result['x']))\n \n # ******GO SHALLOW*****retrieves shallow as possible while SDI remains below 1\n if shallow == True:\n #parameters=sb.FreeParameters(*result.x)\n while result_recorder.sdi[x,y] < 1:\n result.x[3] = result.x[3] - 0.2\n result_recorder(x, y, obs_rrs, parameters=sb.FreeParameters(*result.x), nit=result.nit, success=result.success)\n \n \n else:\n skip_count += 1\n #skip_count_widget.value = 'Pixels skipped (bad input spectra): {0}'.format(skip_count)\n \n # update the progress bar\n n += 1\n #text_widget.value = 'x: {0} y: {1} n: {2}'.format(x, y, n)\n #percentage_widget.value = 'Percentage complete: {0}%'.format(int(100*n/(num_pixels)))\n #progress_bar.value = n\n if pool != None:\n pool.close()\n \n t1 = time.time()\n print(\"Total execution time: {0:.1f} seconds\".format(t1-t0))\n print(\"Average time per pixel: {0:.3f} seconds\".format((t1-t0)/n))\n return result_recorder, coordinates, num_pixels","sub_path":"sen2coral/sambuca_calculations.py","file_name":"sambuca_calculations.py","file_ext":"py","file_size_in_byte":4735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"334488706","text":"import numpy as np\nimport datetime\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport matplotlib.ticker as tick\nfrom scipy.signal import argrelextrema\nimport os\n\n\nfrom Scrapper import getSymbols\n\n\nclass const:\n DateCol = 'Date'\n OpenPriceCol = 'Open'\n HighPriceCol = 'High'\n LowPriceCol = 'Low'\n AdjustedCloseCol = 'Close'\n VolumeCol = 'Volume'\n AdjCloseCol = 'Close'\n\n rounds=2000\n rounds_per_year=252\n years=float(rounds)/rounds_per_year\n\n BOLSA_BAICOM = \"http://bolsa.baicom.com/2\"\n NombreCol = 0\n UltimoCol = 1\n VarDiaCol = 2\n MaxCol = 3\n MinCol = 4\n AperturaCol = 5\n CierreAntCol = 6\n VolumenCol = 7\n CantidadCol = 8\n HoraCol = 9\n\n comision_interes= 0.008\n\ndef clearScreen():\n os.system('cls' if os.name == 'nt' else 'clear')\n\n\ndef compoundYields(yields):\n return np.prod(yields+1)-1\n\ndef getYieldFromTrades(series, trades):\n values=series[trades]\n result=0\n if len(values.shape)>1:\n yields=values[:,1]*(1-const.comision_interes)/(values[:,0]*(1+const.comision_interes))-1\n result=compoundYields(np.asarray(yields))\n elif len(values.shape)==1:\n result=values[1]*(1-const.comision_interes)/(values[0]*(1+const.comision_interes))-1\n\n return result\n\ndef getMaxDrawback(series, trades):\n drawbacks=[0]\n for trade in trades:\n\n period=series[np.arange(trade[0],trade[1]+1)]\n period=period[np.concatenate(([0],np.where(np.diff(period)!=0)[0]+1))]\n maximas=argrelextrema(period,np.greater)[0]\n minimums=argrelextrema(period,np.less)[0]\n if maximas.shape[0]+minimums.shape[0]>1:\n indexes=np.sort(np.concatenate((maximas,minimums)))\n if indexes[0] in minimums:\n indexes=indexes[1:]\n if indexes[-1] in maximas:\n indexes=indexes[:-1]\n if indexes.shape[0]>1:\n maxVals=period[indexes[::2]]\n minVals=period[indexes[1::2]]\n drawbacks.append(np.max((maxVals-minVals)/maxVals))\n\n return max(drawbacks)\n\ndef getTradesFromStrategy(ticker,Strategy,indicators_parameters):\n results=np.array([])\n indicators=Strategy.Indicator(ticker,indicators_parameters)\n trades=np.where(Strategy.Criteria(indicators))[0]\n if trades.shape[0]>0:\n trades_start=np.concatenate(([0],np.where(np.diff(trades) != 1)[0] + 1))\n trades_end=np.concatenate(((trades_start-1)[1:],[trades.shape[0]-1]))\n results=np.empty((trades_start.shape[0],2),dtype=np.int32)\n results[:,0]=trades[trades_start]\n results[:,1]=np.clip(trades[trades_end]+1,0,len(ticker.index)-1) #Ver si le sumo 1 a trades[trades_end]\n\n return results\n\ndef Strategy_Analysis(ticker,Strategy,indicators_parameters):\n series = ticker[const.OpenPriceCol].values\n CARSDDs = {}\n yields = {}\n numberof_trades = {}\n\n winner,trade_yield,ntrades=0,0,0\n\n for parameter in indicators_parameters:\n trades = getTradesFromStrategy(ticker, Strategy, parameter)\n if trades.shape[0]>0:\n trade_yield = getYieldFromTrades(series, trades)\n drawback = getMaxDrawback(series, trades)\n CARSDD = np.exp(trade_yield) / drawback\n dict_index=str(parameter)\n CARSDDs[dict_index] = CARSDD\n yields[dict_index] = trade_yield\n numberof_trades[dict_index] = len(trades)\n if len(CARSDDs)>0:\n winner=sorted(CARSDDs.items(), reverse=True, key=lambda x: x[1])[0][0]\n trade_yield = yields[winner]\n ntrades = int(numberof_trades[winner])\n\n return winner,trade_yield,ntrades\n\n\ndef main():\n provider=\"yahoo\"\n end_date = datetime.datetime.now()\n start_date = end_date - datetime.timedelta(days=365 * const.years)\n symbols=[\"APBR.BA\",\"CTIO.BA\",\"BMA.BA\",\"PAMP.BA\",\"MIRG.BA\",\"FRAN.BA\",\"TRAN.BA\",\"EDN.BA\",\"ERAR.BA\",\"YPFD.BA\",\n \"TS.BA\",\"TECO2.BA\",\"GGAL.BA\",\"ALUA.BA\",\"SAMI.BA\",\"TGNO4.BA\",\"TGSU2.BA\",\"CRES.BA\",\"CELU.BA\",\"LEDE.BA\"]\n #symbols=[\"CECO2.BA\"]\n ###Strategy ad-hoc code###\n\n import StrategyAnalysis.EMA_Crossover_Strategy as EMA_Crossover_Strategy\n Strategy= EMA_Crossover_Strategy.EMA_Crossover_Strategy()\n #import EMA_Crossover_Strategy_MinHold\n #Strategy=EMA_Crossover_Strategy_MinHold.EMA_Crossover_Strategy_MinHold()\n #import UltraADX_Strategy\n #Strategy=UltraADX_Strategy.UltraADX_Strategy()\n #import RSI_Strategy\n #Strategy=RSI_Strategy.RSI_Strategy()\n #import MFI_Strategy\n #Strategy=MFI_Strategy.MFI_Strategy()\n #import Triple_EMA_Crossover_Strategy\n #Strategy=Triple_EMA_Crossover_Strategy.Triple_EMA_Crossover_Strategy()\n #import VWMA_Crossover_Strategy\n #Strategy=VWMA_Crossover_Strategy.VWMA_Crossover_Strategy()\n #import MACD_Strategy\n #Strategy=MACD_Strategy.MACD_Strategy()\n\n ###End of ad-hoc code###\n\n df = pd.DataFrame(data=None, index=None,\n columns=['Stock', 'Parameters', 'Yield %', '# of trades',\n 'Expected yield per trade','Average trade rounds','# Good Trades','# Bad Trades'])\n for symbol in symbols:\n fig=plt.figure()\n ticker = getSymbols(provider, [symbol], None,start_date, end_date)[symbol]\n real_dates = ticker.index\n dates = np.arange(len(real_dates))\n\n def format_date(x, pos=None):\n thisind = np.clip(int(x + 0.5), 0, len(dates) - 1)\n return real_dates[thisind].strftime('%d/%m/%y')\n\n ax_stock=plt.subplot2grid((2,1),(0,0))\n plt.plot(dates,ticker[const.AdjustedCloseCol],color='black')\n ax_stock.xaxis.set_major_locator(tick.AutoLocator())\n ax_stock.xaxis.set_major_formatter(tick.FuncFormatter(format_date))\n\n winner_parameters,trade_yield,ntrades=Strategy_Analysis(ticker,Strategy,Strategy.Parameters)\n expected_yield = 0\n good_trades = 0\n bad_trades = 0\n expected_trade_length = 0\n\n if ntrades>0:\n parameters = tuple([int(x) for x in filter(None,winner_parameters[1:-1].split(','))])\n expected_yield = np.round((trade_yield + 1) ** (1.0 / ntrades) - 1,2)\n trades = getTradesFromStrategy(ticker, Strategy, parameters)\n expected_trade_length=int(np.mean(trades[:,1]-trades[:,0]))\n for trade in trades:\n if getYieldFromTrades(ticker[const.OpenPriceCol].values, [trade]) > 0:\n fill_color = 'green'\n good_trades+=1\n else:\n fill_color = 'red'\n bad_trades+=1\n plt.axvline(dates[trade[0]], color='g', linewidth=1)\n plt.axvline(dates[trade[1]], color='r', linewidth=1)\n dates_fill = [d for d in dates if d >= dates[trade[0]] and d <= dates[trade[1]]]\n plt.fill_between(dates_fill, plt.gca().get_ylim()[0], plt.gca().get_ylim()[1], facecolor=fill_color,\n alpha=0.5)\n\n ax_indicators = plt.subplot2grid((2, 1), (1, 0), sharex=ax_stock)\n Strategy.Plot(ticker, parameters, ax_indicators)\n\n plt.subplots_adjust(wspace=0.01, hspace=0.3, left=0.05, right=0.95, bottom=0.04, top=0.96)\n plt.xlim([dates[0], dates[-1] + 2])\n fig.canvas.set_window_title(symbol + \" - \" + str(len(dates)) + \" rounds\")\n\n data = [symbol, winner_parameters, str(trade_yield*100)+\"%\", ntrades, str(expected_yield*100)+\"%\",expected_trade_length,good_trades,bad_trades]\n currdf = pd.DataFrame(columns=df.columns, index=None)\n currdf.loc[0] = data\n df = df.append(currdf)\n\n print(symbol + \" DONE\")\n\n clearScreen()\n print(df.sort_values('Stock').to_string(index=False))\n plt.show()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"StrategyAnalysis/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"577265156","text":"#\n# DrawingMixin.py -- enable drawing capabilities.\n#\n# Eric Jeschke (eric@naoj.org)\n#\n# Copyright (c) Eric R. Jeschke. All rights reserved.\n# This is open-source software licensed under a BSD license.\n# Please see the file LICENSE.txt for details.\n#\nimport time\nimport math\n\nfrom .CanvasMixin import CanvasMixin\n\nclass DrawingMixin(object):\n \"\"\"The DrawingMixin is a mixin class that adds drawing capability for\n some of the basic CanvasObject-derived types. The setSurface method is\n used to associate a ImageViewCanvas object for layering on.\n \"\"\"\n\n def __init__(self):\n assert isinstance(self, CanvasMixin), \"Missing CanvasMixin class\"\n\n from .CanvasObject import drawCatalog\n # For interactive drawing\n self.candraw = False\n self.drawDict = drawCatalog\n drawtypes = self.drawDict.keys()\n self.drawtypes = []\n for key in ['point', 'line', 'circle', 'ellipse', 'square',\n 'rectangle', 'box', 'polygon', 'freepolygon',\n 'path', 'freepath', 'beziercurve',\n 'triangle', 'righttriangle', 'equilateraltriangle',\n 'ruler', 'compass', 'text']:\n if key in drawtypes:\n self.drawtypes.append(key)\n self.t_drawtype = 'point'\n self.t_drawparams = {}\n self._start_x = 0\n self._start_y = 0\n self._points = []\n\n # For interactive editing\n self.canedit = False\n self._cp_index = None\n self._edit_obj = None\n self._edit_status = False\n\n # For selection\n self._selected = []\n\n # this controls whether an object is automatically selected for\n # editing immediately after being drawn\n self.edit_follows_draw = False\n\n self._processTime = 0.0\n # time delta threshold for deciding whether to update the image\n self._deltaTime = 0.020\n self._draw_obj = None\n self._draw_crdmap = None\n\n # NOTE: must be mixed in with a Callback.Callbacks\n for name in ('draw-event', 'draw-down', 'draw-move', 'draw-up',\n 'draw-scroll', 'keydown-poly_add', 'keydown-poly_del',\n 'keydown-edit_del', 'edit-event', 'edit-down',\n 'edit-move', 'edit-up',\n 'edit-select', 'edit-scroll', 'drag-drop'):\n self.enable_callback(name)\n\n def setSurface(self, viewer):\n self.viewer = viewer\n\n # register this canvas for events of interest\n self.add_callback('draw-down', self.draw_start, viewer)\n self.add_callback('draw-move', self.draw_motion, viewer)\n self.add_callback('draw-up', self.draw_stop, viewer)\n self.add_callback('keydown-poly_add', self.draw_poly_add, viewer)\n self.add_callback('keydown-poly_del', self.draw_poly_delete, viewer)\n self.add_callback('keydown-edit_del', self._edit_delete_cb, viewer)\n\n self.add_callback('edit-down', self.edit_start, viewer)\n self.add_callback('edit-move', self.edit_motion, viewer)\n self.add_callback('edit-up', self.edit_stop, viewer)\n ## self.add_callback('edit-up', self.select_stop, viewer)\n #self.add_callback('edit-scroll', self._edit_scale_cb, viewer)\n self.add_callback('edit-scroll', self._edit_rotate_cb, viewer)\n\n def getSurface(self):\n return self.viewer\n\n def draw(self, viewer):\n super(DrawingMixin, self).draw(viewer)\n if self._draw_obj:\n self._draw_obj.draw(viewer)\n\n ##### DRAWING LOGIC #####\n\n def _draw_update(self, data_x, data_y, viewer):\n\n klass = self.drawDict[self.t_drawtype]\n obj = None\n x, y = self._draw_crdmap.data_to(data_x, data_y)\n\n if self.t_drawtype == 'point':\n radius = max(abs(self._start_x - x),\n abs(self._start_y - y))\n obj = klass(self._start_x, self._start_y, radius,\n **self.t_drawparams)\n\n elif self.t_drawtype == 'compass':\n radius = max(abs(self._start_x - x),\n abs(self._start_y - y))\n obj = klass(self._start_x, self._start_y,\n radius, **self.t_drawparams)\n\n elif self.t_drawtype == 'rectangle':\n obj = klass(self._start_x, self._start_y,\n x, y, **self.t_drawparams)\n\n elif self.t_drawtype == 'square':\n len_x = self._start_x - x\n len_y = self._start_y - y\n length = max(abs(len_x), abs(len_y))\n len_x = cmp(len_x, 0) * length\n len_y = cmp(len_y, 0) * length\n obj = klass(self._start_x, self._start_y,\n self._start_x-len_x, self._start_y-len_y,\n **self.t_drawparams)\n\n elif self.t_drawtype == 'equilateraltriangle':\n len_x = self._start_x - x\n len_y = self._start_y - y\n length = max(abs(len_x), abs(len_y))\n obj = klass(self._start_x, self._start_y,\n length, length, **self.t_drawparams)\n\n elif self.t_drawtype in ('box', 'ellipse', 'triangle'):\n xradius = abs(self._start_x - x)\n yradius = abs(self._start_y - y)\n obj = klass(self._start_x, self._start_y, xradius, yradius,\n **self.t_drawparams)\n\n elif self.t_drawtype == 'circle':\n radius = math.sqrt(abs(self._start_x - x)**2 +\n abs(self._start_y - y)**2 )\n obj = klass(self._start_x, self._start_y, radius,\n **self.t_drawparams)\n\n elif self.t_drawtype == 'line':\n obj = klass(self._start_x, self._start_y, x, y,\n **self.t_drawparams)\n\n elif self.t_drawtype == 'righttriangle':\n obj = klass(self._start_x, self._start_y, x, y,\n **self.t_drawparams)\n\n elif self.t_drawtype in ('polygon', 'path', 'beziercurve'):\n points = list(self._points)\n points.append((x, y))\n obj = klass(points, **self.t_drawparams)\n\n elif self.t_drawtype in ('freepolygon', 'freepath'):\n self._points.append((x, y))\n points = list(self._points)\n obj = klass(points, **self.t_drawparams)\n\n elif self.t_drawtype == 'text':\n obj = klass(self._start_x, self._start_y, **self.t_drawparams)\n\n elif self.t_drawtype == 'ruler':\n obj = klass(self._start_x, self._start_y, x, y,\n **self.t_drawparams)\n\n if obj is not None:\n obj.initialize(None, viewer, self.logger)\n #obj.initialize(None, viewer, viewer.logger)\n self._draw_obj = obj\n if time.time() - self._processTime > self._deltaTime:\n self.process_drawing(viewer)\n\n return True\n\n def draw_start(self, canvas, event, data_x, data_y, viewer):\n if not self.candraw or (viewer != event.viewer):\n return False\n\n self._draw_obj = None\n # get the drawing coordinate type (default 'data')\n crdtype = self.t_drawparams.get('coord', 'data')\n self._draw_crdmap = viewer.get_coordmap(crdtype)\n # record the start point\n x, y = self._draw_crdmap.data_to(data_x, data_y)\n self._points = [(x, y)]\n self._start_x, self._start_y = x, y\n self._draw_update(x, y, viewer)\n\n self.process_drawing(viewer)\n return True\n\n def draw_stop(self, canvas, event, data_x, data_y, viewer):\n if not self.candraw or (viewer != event.viewer):\n return False\n\n self._draw_update(data_x, data_y, viewer)\n obj, self._draw_obj = self._draw_obj, None\n self._points = []\n\n if obj:\n objtag = self.add(obj, redraw=True)\n self.make_callback('draw-event', objtag)\n\n if self.edit_follows_draw:\n self.clear_selected()\n self.edit_select(obj)\n self.make_callback('edit-select', self._edit_obj)\n return True\n else:\n self.process_drawing(viewer)\n\n def draw_motion(self, canvas, event, data_x, data_y, viewer):\n if not self.candraw or (viewer != event.viewer):\n return False\n self._draw_update(data_x, data_y, viewer)\n return True\n\n def draw_poly_add(self, canvas, event, data_x, data_y, viewer):\n if not self.candraw or (viewer != event.viewer):\n return False\n if self._draw_obj is None:\n return self.edit_poly_add(canvas, event, data_x, data_y, viewer)\n if self.t_drawtype in ('polygon', 'path'):\n x, y = self._draw_crdmap.data_to(data_x, data_y)\n self._points.append((x, y))\n elif self.t_drawtype == 'beziercurve' and len(self._points) < 3:\n x, y = self._draw_crdmap.data_to(data_x, data_y)\n self._points.append((x, y))\n return True\n\n def draw_poly_delete(self, canvas, event, data_x, data_y, viewer):\n if not self.candraw or (viewer != event.viewer):\n return False\n if self._draw_obj is None:\n return self.edit_poly_del(canvas, event, data_x, data_y, viewer)\n if self.t_drawtype in ('polygon', 'path', 'beziercurve'):\n if len(self._points) > 0:\n self._points.pop()\n return True\n\n def is_drawing(self):\n return self._draw_obj is not None\n\n def enable_draw(self, tf):\n self.candraw = tf\n\n def set_drawcolor(self, colorname):\n self.t_drawparams['color'] = colorname\n\n def set_drawtype(self, drawtype, **drawparams):\n drawtype = drawtype.lower()\n assert drawtype in self.drawtypes, \\\n ValueError(\"Bad drawing type '%s': must be one of %s\" % (\n drawtype, self.drawtypes))\n self.t_drawtype = drawtype\n self.t_drawparams = drawparams.copy()\n\n def get_drawtypes(self):\n return self.drawtypes\n\n def get_drawtype(self):\n return self.t_drawtype\n\n def getDrawClass(self, drawtype):\n drawtype = drawtype.lower()\n klass = self.drawDict[drawtype]\n return klass\n\n def get_drawparams(self):\n return self.t_drawparams.copy()\n\n def process_drawing(self, viewer):\n self._processTime = time.time()\n #viewer.redraw(whence=3)\n #self.redraw(whence=3)\n self.update_canvas()\n\n ##### EDITING LOGIC #####\n\n def get_edit_object(self):\n return self._edit_obj\n\n def is_editing(self):\n return self.get_edit_obj() is not None\n\n def enable_edit(self, tf):\n self.canedit = tf\n\n def _edit_update(self, data_x, data_y, viewer):\n if (not self.canedit) or (self._cp_index is None):\n return False\n\n x, y = self._edit_obj.crdmap.data_to(data_x, data_y)\n\n if self._cp_index < 0:\n self._edit_obj.move_to(x - self._start_x,\n y - self._start_y)\n else:\n # special hack for objects that have rot_deg attribute\n if hasattr(self._edit_obj, 'rot_deg') and (self._cp_index > 0):\n rot_deg = - self._edit_obj.rot_deg\n xoff, yoff = self._edit_obj.get_center_pt()\n x, y = self._edit_obj.crdmap.rotate_pt(x, y, rot_deg,\n xoff=xoff, yoff=yoff)\n\n self._edit_obj.set_edit_point(self._cp_index, (x, y))\n\n if time.time() - self._processTime > self._deltaTime:\n self.process_drawing(viewer)\n return True\n\n def _is_editable(self, obj, x, y, is_inside):\n return is_inside and obj.editable\n\n def _prepare_to_move(self, obj, data_x, data_y):\n #print(\"moving an object\")\n self.edit_select(obj)\n self._cp_index = -1\n ref_x, ref_y = self._edit_obj.get_reference_pt()\n x, y = obj.crdmap.data_to(data_x, data_y)\n self._start_x, self._start_y = x - ref_x, y - ref_y\n\n def edit_start(self, canvas, event, data_x, data_y, viewer):\n if not self.canedit or (viewer != event.viewer):\n return False\n\n self._edit_tmp = self._edit_obj\n self._edit_status = False\n self._cp_index = None\n #shift_held = 'shift' in event.modifiers\n shift_held = False\n\n selects = self.get_selected()\n if len(selects) == 0:\n # <-- no objects already selected\n\n # check for objects at this location\n #print(\"getting items\")\n objs = canvas.select_items_at(viewer, data_x, data_y,\n test=self._is_editable)\n #print(\"items: %s\" % (str(objs)))\n\n if len(objs) == 0:\n # <-- no objects under cursor\n return False\n\n # pick top object\n obj = objs[-1]\n self._prepare_to_move(obj, data_x, data_y)\n\n else:\n self._edit_status = True\n\n # Ugh. Check each selected object's control points\n # for a match\n contains = []\n for obj in selects:\n #print(\"editing: checking for cp\")\n #edit_pts = self._edit_obj.get_edit_points()\n edit_pts = list(map(lambda pt: obj.crdmap.to_data(*pt),\n obj.get_edit_points()))\n #print((self._edit_obj, dir(self._edit_obj)))\n #print(edit_pts)\n i = obj.get_pt(viewer, edit_pts, data_x, data_y,\n obj.cap_radius)\n if i is not None:\n #print(\"editing cp #%d\" % (i))\n # editing a control point from an existing object\n self._edit_obj = obj\n self._cp_index = i\n self._edit_update(data_x, data_y, viewer)\n return True\n\n if obj.contains(data_x, data_y):\n contains.append(obj)\n\n # <-- no control points match, is there an object that contains\n # this point?\n if len(contains) > 0:\n # TODO?: make a compound object of contains and move it?\n obj = contains[-1]\n if self.is_selected(obj) and shift_held:\n # deselecting object\n self.select_clear(obj)\n else:\n self._prepare_to_move(obj, data_x, data_y)\n ## Compound = self.getDrawClass('compoundobject')\n ## c_obj = Compound(*self.get_selected())\n ## c_obj.inherit_from(obj)\n ## self._prepare_to_move(c_obj, data_x, data_y)\n\n else:\n # <-- user clicked outside any selected item's control pt\n # and outside any selected item\n if not shift_held:\n self.clear_selected()\n\n # see now if there is an unselected item at this location\n objs = canvas.select_items_at(viewer, data_x, data_y,\n test=self._is_editable)\n #print(\"items: %s\" % (str(objs)))\n if len(objs) > 0:\n # pick top object\n obj = objs[-1]\n if self.num_selected() > 0:\n # if there are already some selected items, then\n # add this object to the selection, make a compound\n # object\n self.edit_select(obj)\n Compound = self.getDrawClass('compoundobject')\n c_obj = Compound(*self.get_selected())\n c_obj.inherit_from(obj)\n self._prepare_to_move(c_obj, data_x, data_y)\n else:\n # otherwise just start over with this new object\n self._prepare_to_move(obj, data_x, data_y)\n\n self.process_drawing(viewer)\n return True\n\n def edit_stop(self, canvas, event, data_x, data_y, viewer):\n if not self.canedit or (viewer != event.viewer):\n return False\n\n if (self._edit_tmp != self._edit_obj) or (\n (self._edit_obj is not None) and\n (self._edit_status != self._edit_obj.is_editing())):\n # <-- editing status has changed\n #print(\"making edit-select callback\")\n self.make_callback('edit-select', self._edit_obj)\n\n if (self._edit_obj is not None) and (self._cp_index is not None):\n # <-- an object has been edited\n self._edit_update(data_x, data_y, viewer)\n self._cp_index = None\n self.make_callback('edit-event', self._edit_obj)\n\n return True\n\n def edit_motion(self, canvas, event, data_x, data_y, viewer):\n if not self.canedit or (viewer != event.viewer):\n return False\n\n if (self._edit_obj is not None) and (self._cp_index is not None):\n self._edit_update(data_x, data_y, viewer)\n return True\n\n return False\n\n def edit_poly_add(self, canvas, event, data_x, data_y, viewer):\n if not self.canedit or (viewer != event.viewer):\n return False\n obj = self._edit_obj\n if (obj is not None) and obj.is_editing() and \\\n (obj.kind in ('polygon', 'path')):\n self.logger.debug(\"checking points\")\n # determine which line we are adding a point to\n points = list(obj.get_points())\n if obj.kind == 'polygon':\n points = points + [points[0]]\n x0, y0 = obj.crdmap.to_data(*points[0])\n insert = None\n for i in range(1, len(points[1:])):\n x1, y1 = obj.crdmap.to_data(*points[i])\n self.logger.debug(\"checking line %d\" % (i))\n if obj.within_line(viewer, data_x, data_y, x0, y0, x1, y1,\n 8):\n insert = i\n break\n x0, y0 = x1, y1\n if insert is not None:\n self.logger.debug(\"inserting point\")\n # Point near a line\n x, y = obj.crdmap.data_to(data_x, data_y)\n points.insert(insert, (x, y))\n obj.points = points\n self.process_drawing(viewer)\n else:\n self.logger.debug(\"cursor not near a line\")\n\n return True\n\n def edit_poly_del(self, canvas, event, data_x, data_y, viewer):\n if not self.canedit or (viewer != event.viewer):\n return False\n obj = self._edit_obj\n if (obj is not None) and obj.is_editing() and \\\n (obj.kind in ('polygon', 'path')):\n self.logger.debug(\"checking points\")\n # determine which point we are deleting\n points = list(obj.get_points())\n delete = None\n for i in range(len(points)):\n x1, y1 = obj.crdmap.to_data(*points[i])\n self.logger.debug(\"checking line %d\" % (i))\n if obj.within_radius(viewer, data_x, data_y, x1, y1,\n 8):\n delete = i\n break\n if delete is not None:\n self.logger.debug(\"deleting point\")\n points.pop(delete)\n obj.points = points\n self.process_drawing(viewer)\n else:\n self.logger.debug(\"cursor not near a point\")\n\n return True\n\n def edit_rotate(self, delta_deg, viewer):\n if self._edit_obj is None:\n return False\n self._edit_obj.rotate_by(delta_deg)\n self.process_drawing(viewer)\n self.make_callback('edit-event', self._edit_obj)\n return True\n\n def _edit_rotate_cb(self, canvas, event, viewer, msg=True):\n if not self.canedit or (viewer != event.viewer):\n return False\n bd = viewer.get_bindings()\n amount = event.amount\n if bd.get_direction(event.direction) == 'down':\n amount = - amount\n return self.edit_rotate(amount)\n\n def edit_scale(self, delta_x, delta_y, viewer):\n if self._edit_obj is None:\n return False\n self._edit_obj.scale_by(delta_x, delta_y)\n self.process_drawing(viewer)\n self.make_callback('edit-event', self._edit_obj)\n return True\n\n def _edit_scale_cb(self, canvas, event, viewer, msg=True):\n if not self.canedit or (viewer != event.viewer):\n return False\n bd = viewer.get_bindings()\n if bd.get_direction(event.direction) == 'down':\n amount = 0.9\n else:\n amount = 1.1\n return self.edit_scale(amount, amount)\n\n def edit_delete(self):\n if (self._edit_obj is not None) and self._edit_obj.is_editing():\n obj, self._edit_obj = self._edit_obj, None\n self.deleteObject(obj)\n self.make_callback('edit-event', self._edit_obj)\n return True\n\n def _edit_delete_cb(self, canvas, event, data_x, data_y, viewer):\n if not self.canedit or (viewer != event.viewer):\n return False\n return self.edit_delete()\n\n def edit_select(self, newobj):\n if not self.canedit:\n return False\n\n # add new object to selection\n self.select_add(newobj)\n self._edit_obj = newobj\n return True\n\n ##### SELECTION LOGIC #####\n\n def _is_selectable(self, obj, x, y, is_inside):\n return is_inside and obj.editable\n #return is_inside\n\n def is_selected(self, obj):\n return obj in self._selected\n\n def get_selected(self):\n return self._selected\n\n def num_selected(self):\n return len(self._selected)\n\n def clear_selected(self):\n for obj in list(self._selected):\n self.select_clear(obj)\n\n def select_clear(self, obj):\n if obj in self._selected:\n self._selected.remove(obj)\n obj.set_edit(False)\n\n def select_add(self, obj):\n if obj not in self._selected:\n self._selected.append(obj)\n obj.set_edit(True)\n\n def select_stop(self, canvas, button, data_x, data_y, viewer):\n #print(\"getting items\")\n objs = canvas.select_items_at(viewer, data_x, data_y,\n test=self._is_selectable)\n if len(objs) == 0:\n # no objects\n return False\n\n # pick top object\n obj = objs[-1]\n\n if obj not in self._selected:\n self._selected.append(obj)\n obj.set_edit(True)\n else:\n self._selected.remove(obj)\n obj.set_edit(False)\n obj = None\n\n self.logger.debug(\"selected: %s\" % (str(self._selected)))\n self.process_drawing(viewer)\n\n #self.make_callback('edit-select', obj, self._selected)\n return True\n\n def group_selection(self):\n Compound = self.getDrawClass('compoundobject')\n c_obj = Compound(self._selected)\n self._selected = [ comp_obj ]\n\n\n#END\n","sub_path":"ginga/canvas/DrawingMixin.py","file_name":"DrawingMixin.py","file_ext":"py","file_size_in_byte":23253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"131307090","text":"#Rewrite your pay computation with time-and-a-half for overtime and\n#create a function called computepay which takes two parameters (hours and rate).\n\ndef computepay(hours, rate):\n if hours > 40:\n pay = (40 * rate) + (1.5 * rate * (hours - 40))\n else:\n pay = rate * hours\n return pay\n\ntry:\n hours = float(input(\"Enter Hours: \"))\n rate = float(input(\"Enter Rate: \"))\n pay = computepay(hours, rate)\n print(\"Pay:\", round(pay,2))\n\nexcept:\n print(\"Error, please enter numeric input\")","sub_path":"chapter_4/n6_payrate_func.py","file_name":"n6_payrate_func.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"595544991","text":"def parse(mesg):\n\n msglist = []\n\n while len(mesg) > 0:\n msg = {}\n tmplen, tmpid, payload = [ 0, 0, b'']\n tmplen = struct.unpack('>i', mesg[:4])[0]\n mesg = mesg[4:]\n payload = mesg[1:tmplen]\n tmpid = mesg[0]\n mesg = mesg[tmplen:]\n msg['meslen'] = tmplen\n msg['mesgid'] = tmpid\n if tmpid in range(4):\n pass\n elif tmpid == 4:\n msg['piece index'] = bytes(payload)\n elif tmpid == 5:\n msg['bitfield'] = bytes(payload)\n elif tmpid == 6 or tmpid == 8:\n piece = struct.unpack('>3i', bytes(payload))\n msg['index'] = piece[0]\n msg['begin'] = piece[1]\n msg['length'] = piece[2]\n elif tmpid == 7:\n msg['index'] = bytes(payload[0:4])\n msg['begin'] = bytes(payload[4:8])\n msg['block'] = bytes(payload[8:])\n elif tmpid == 9:\n msg['port'] = piece[2]\n msglist.append(msg)\n return msglist\n\nimport struct\ndef bf(bitfield):\n bytefield = list(bitfield)\n bitfield = ''\n r = []\n for byte in bytefield:\n x = bin(byte)[2:]\n bitfield += x\n index = 0\n bitfield = list(bitfield)\n for bit in bitfield:\n if bit == '1':\n\n r.append(index)\n index += 1\n return r\n\n\ndef piecelist(mesglist):\n for msg in mesglist:\n if msg['mesgid'] == 5:\n r = bf(msg['bitfield'])\n elif msg['mesgid'] == 4:\n if msg['piece index'] not in r:\n r.append(struct.unpack(\">i\", msg['piece index'])[0])\n return r\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"297782411","text":"from django.urls import path, include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nimport request.views\nfrom request import views2\nfrom request.filters.filters import RequestFilter\nfrom .. import reqSpecViews\nfrom django_filters.views import FilterView\nfrom request.viewsFolder.request.request import (RequestList, RequestFilterView)\n\nurlpatterns = [\n path('project_type', request.views2.project_type_form, name='project_type_form'),\n path('project-type/index', request.views2.projects_type_index, name='projects_type_index'),\n\n path('form', request.views2.request_form, name='request_form'),\n path('req_form', request.views2.req_form, name='req_form'),\n path('wrong_data', request.views2.wrong_data, name='wrong_data'),\n path('wrong_data2', request.views2.wrong_data2, name='wrong_data2'),\n path('req_form_copy', request.views2.req_form_copy, name='req_form_copy'),\n path('insert', request.views2.request_insert, name='request_insert'),\n path('index', request.views2.request_index, name='request_index'),\n path('index-p', request.views2.request_index_paginate, name='request_index_paginate'),\n path('index-vue', request.views2.request_index_vue, name='request_index_vue'),\n path('index-vue-deleted', request.views2.request_index_vue_deleted, name='request_index_vue_deleted'),\n path('requests', request.views2.req_search, name='req_search'),\n path('fsearch', request.views2.fsearch, name='fsearch'),\n path('fsearch3', request.views2.fsearch3, name='fsearch3'),\n path('fsearch2', request.views2.fsearch2, name='fsearch2'),\n path('search', RequestList.as_view(), name='req_search2'),\n # path('search-req', RequestSearch.as_view(), name='search_req'),\n path('fsearch5', request.views2.fsearch5, name='fsearch5'),\n path('search-req2', RequestFilterView.as_view(), name='search_req'),\n # path('/details', RequestDetailsView.as_view(), name='request_details_cbv'),\n path('/', include([\n # path('details', RequestDetailsView.as_view(), name='request_details_cbv'),\n ])),\n path('find', request.views2.request_find, name='request_find'),\n path('/', include([\n path('', request.views2.request_read, name='request_details'),\n path('read-vue', request.views2.read_vue, name='read_vue'),\n path('delete', request.views2.request_delete, name='request_delete'),\n path('edit', request.views2.request_edit, name='request_edit'),\n path('editForm', request.views2.request_edit_form, name='request_edit_form'),\n path('finish', request.views2.finish, name='request_finish'),\n ])),\n\n path('/reqSpec/form', reqSpecViews.reqspec_form, name='reqSpec_form'),\n path('/reqSpec/spec_form', reqSpecViews.spec_form, name='spec_form'),\n path('reqSpec/insert', request.reqSpecViews.reqspec_insert, name='reqSpec_insert'),\n path('reqSpec/index', request.reqSpecViews.reqspec_index, name='reqSpec_index'),\n path('/reqSpec//', include([\n path('', request.reqSpecViews.reqspec_details, name='reqSpec_details'),\n path('delete', request.reqSpecViews.reqspec_delete, name='reqSpec_delete'),\n path('edit', request.reqSpecViews.reqspec_edit, name='reqSpec_edit'),\n path('editForm', request.reqSpecViews.reqspec_edit_form, name='reqspec_edit_form'),\n path('copy', request.reqSpecViews.reqspec_copy, name='reqspec_copy'),\n ])),\n\n]\n","sub_path":"request/urls/req_urls.py","file_name":"req_urls.py","file_ext":"py","file_size_in_byte":3483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"239210434","text":"class Node:\n def __init__(self, data=None, next=None):\n self.data = data\n self.next = next\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n def insert_at_beginning(self, data):\n node = Node(data)\n if self.head is None:\n self.head = node\n return\n else:\n node.next = self.head\n self.head = node\n\n def print(self):\n if self.head is None:\n print('prazna lista')\n else:\n llstr = \"\"\n node = self.head\n while node:\n llstr += str(node.data) + '--->'\n node = node.next\n print(llstr)\n\n\nll = LinkedList()\nll.insert_at_beginning(2)\nll.insert_at_beginning(3)\nll.insert_at_beginning(4)\nll.print()\n","sub_path":"Data Structures & Algorithms/LinkedList.py","file_name":"LinkedList.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"416884194","text":"import datetime\nimport os\nfrom itertools import groupby\n\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.views.generic import TemplateView\n\nfrom lifeapp.models.TimeEntry import TimeEntry\n\n\nclass WeeklySummaryView(LoginRequiredMixin, TemplateView, ):\n template_name = os.path.join('lifeapp', 'weekly_summary.html')\n\n def get_context_data(self):\n entries = TimeEntry.objects.all()\n grouped_entries = groupby(entries,\n key=lambda x: {'year': datetime.date.isocalendar(x.start_date)[0],\n 'week': datetime.date.isocalendar(x.start_date)[1]})\n summary = []\n for key, group in grouped_entries:\n summary.append({\n 'year':\n key['year'],\n 'week':\n key['week'],\n 'duration':\n sum((i.duration for i in group), datetime.timedelta(0)).total_seconds()\n })\n summary.sort(key=lambda x: (-x['year'], -x['week']))\n return {\n 'title': 'Weekly Summary',\n 'summary': summary,\n }","sub_path":"lifeapp/views/WeeklySummaryView.py","file_name":"WeeklySummaryView.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"428357918","text":"#!/usr/bin/env python3\n\nimport smtplib\nimport xlsxwriter\nfrom string import Template\n\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.base import MIMEBase\nfrom email.mime.text import MIMEText\nfrom email import encoders\nfrom application.models import database, weekly_stats\nimport datetime\nimport json\nimport os\nfrom os import getenv\n\ndef user_list(main_workbook):\n \"\"\"\n gets information of users from database\n\n Return: List of dictionaries\n \"\"\"\n users = database.all('User')\n email_users = {'Not Enough Weeks': [], 'Warning': [], 'Good': [], 'Recommendation': []}\n for user in users.values():\n message = make_message(user, main_workbook)\n email_users[message['standing']].append(message)\n return email_users\n\ndef make_message(user, main_workbook):\n name = user.name.replace(' ' , '')\n workbook = xlsxwriter.Workbook(name + '.xlsx')\n\n # Create sheets for student's workbook and main_workbook (staff)\n worksheet = workbook.add_worksheet()\n main_worksheet = main_workbook.add_worksheet(name)\n\n date_range = weekly_stats.generate_week_range(datetime.date.today())\n dates = {'start_date': date_range[0], 'end_date': date_range[1]}\n applied_jobs = user.get_jobs_applied(**dates)\n applied_stats = user.get_jobs_applied_stats(datetime.date.today())\n applied_jobs = applied_jobs['applied'] + applied_jobs['screening'] + applied_jobs['offerStage'] + applied_jobs['archived']\n three_week_total = applied_stats['three_week_total']\n # applied_jobs = database.userAppliedJobs(user.id)\n message = ['{} Weekly Report\\n'.format(user.name)]\n message.append('Number Applied this Week: {}\\n\\n'.format(len(applied_jobs)))\n\n message.append('All Time Total: {}\\n'.format(applied_stats['total_applications']))\n message.append('Avg Over {} Week(s): {}\\n\\n'.format(applied_stats['num_weeks'], applied_stats['avg_applications']))\n message.append('Total in Last 3 Weeks: {}\\n'.format(three_week_total))\n\n # standing to represent a student's standing for career sprint\n three_week_avg = three_week_total / 3\n if applied_stats['num_weeks'] < 3:\n standing = 'Not Enough Weeks'\n elif three_week_avg >= 15:\n standing = 'Recommendation'\n elif three_week_avg >= 5:\n standing = 'Good'\n else:\n standing = 'Warning'\n\n message.append('Avg Over Last 3 Weeks: {:.2f}\\n'.format(three_week_avg))\n message.append('Standing: {}\\n\\n'.format(standing))\n\n main_worksheet.write('A1', 'STUDENT FIRST and LAST NAME')\n main_worksheet.write('A2', user.name)\n main_worksheet.write('B1', 'DATE')\n main_worksheet.write('B2', str(datetime.date.today()))\n main_worksheet.write('C1', 'COHORT')\n\n worksheet.write('A1', 'STUDENT FIRST and LAST NAME')\n main_worksheet.write('A2', user.name)\n worksheet.write('B1', 'DATE')\n main_worksheet.write('B2', str(datetime.date.today()))\n worksheet.write('C1', 'COHORT')\n\n main_worksheet.write('A4', 'Date of Application')\n main_worksheet.write('B4', 'Company Name')\n main_worksheet.write('C4', 'URL to Job Post')\n main_worksheet.write('D4', 'Job Title')\n main_worksheet.write('E4', 'Address')\n main_worksheet.write('F4', 'Additional Notes')\n main_worksheet.write('G4', 'Current Status')\n main_worksheet.write('H4', 'Interview Progress')\n worksheet.write('A4', 'Date of Application')\n worksheet.write('B4', 'Company Name')\n worksheet.write('C4', 'URL to Job Post')\n worksheet.write('D4', 'Job Title')\n worksheet.write('E4', 'Address')\n worksheet.write('F4', 'Additional Notes')\n worksheet.write('G4', 'Current Status')\n worksheet.write('H4', 'Interview Progress')\n\n for index, job in enumerate(applied_jobs):\n date = str(job.get('date_applied')).ljust(30)\n company = job.get('company').ljust(40)\n title = job.get('job_title').ljust(40)\n message.append(''.join([date, company, title, '\\n']))\n # Add to Worksheet\n row = str(index + 5)\n worksheet.write('A' + row, str(job['date_applied']))\n worksheet.write('B' + row, job['company'])\n worksheet.write('C' + row, job['url'])\n worksheet.write('D' + row, job['job_title'])\n worksheet.write('E' + row, job['location'])\n worksheet.write('F' + row, job['notes'])\n worksheet.write('G' + row, job['status'])\n worksheet.write('H' + row, job['interview_progress'])\n\n main_worksheet.write('A' + row, job['date_applied'])\n main_worksheet.write('B' + row, job['company'])\n main_worksheet.write('C' + row, job['url'])\n main_worksheet.write('D' + row, job['job_title'])\n main_worksheet.write('E' + row, job['location'])\n main_worksheet.write('F' + row, job['notes'])\n main_worksheet.write('G' + row, job['status'])\n main_worksheet.write('H' + row, job['interview_progress'])\n\n workbook.close()\n\n return {\n 'name' : user.name,\n 'standing' : standing,\n 'email' : user.email if user.email else 'jobodysseynotifications@gmail.com',\n # FOR TESTING PURPOSES\n #'email': 'jobodyssey19@gmail.com',\n 'message' : ''.join(message),\n 'excel': name + '.xlsx'\n }\n\ndef send_email(user_email, email_address, email_pwd, email_body, email_excel):\n msg = MIMEMultipart()\n\n message = email_body\n\n msg['From'] = email_address\n msg['To'] = user_email\n msg['Subject'] = 'Your Weekly Job Odyssey Report!'\n\n msg.attach(MIMEText(message, 'plain'))\n\n part = MIMEBase('application', 'octet-stream')\n part.set_payload(open(email_excel, 'rb').read())\n encoders.encode_base64(part)\n part.add_header('Content-Disposition', 'attachment; filename=\"' + email_excel + '\"')\n msg.attach(part)\n\n with smtplib.SMTP_SSL(host='smtp.gmail.com', port=465) as s:\n s.login(email_address, email_pwd)\n s.send_message(msg)\n\n del msg\n os.remove(email_excel)\n\ndef email_standing(users, standing, total_report, email_address, email_pwd):\n total_report.append('--------------------------------------------------\\n')\n total_report.append('Students with {} Standing\\n'.format(standing))\n total_report.append('--------------------------------------------------\\n')\n for user in users:\n try:\n send_email(user['email'], email_address, email_pwd, user['message'], user['excel'])\n except e:\n pass\n total_report.append(user['message'])\n\ndef main():\n email_address = getenv('JO_EMAIL')\n email_pwd = getenv('JO_EMAIL_PWD')\n\n # Sets up the workbook for Michelle and staff at Holberton School\n # Each sheet will contain the jobs summary page for each student\n main_workbook_name = 'StudentSummaries' + '.xlsx'\n main_workbook = xlsxwriter.Workbook(main_workbook_name)\n\n total_report = []\n\n users = user_list(main_workbook)\n for standing in users.keys():\n email_standing(users[standing], standing, total_report, email_address, email_pwd)\n\n main_workbook.close()\n send_email('sf-students-hr@holbertonschool.com', email_address,\n email_pwd, '\\n\\n'.join(total_report), main_workbook_name)\n # FOR TESTING PURPOSES\n #send_email('jobodysseynotifications@gmail.com', email_address,\n # email_pwd, '\\n\\n'.join(total_report), main_workbook_name)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"application/emails/send.py","file_name":"send.py","file_ext":"py","file_size_in_byte":7352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"540071028","text":"'''\nCreated on Apr 28, 2016\n\n@author: pblajev\n'''\n\nimport datetime\n\ndef main():\n #n1 = input('Your name: ')\n #y1 = int(input('Your age: '))\n n1 = 'Peter'\n y1 = 42\n rep = 4\n \n yrAt100 = datetime.date.today().year + (100 - y1)\n\n for i in range(rep):\n print('{}, you will be 100 in {}'.format(n1, yrAt100))\n\nif __name__ == '__main__': main()","sub_path":"Practice/20160428-CharInput.py","file_name":"20160428-CharInput.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"66855252","text":"\ndef csv_writer(data, path):\n \"\"\"\n Write data to a CSV file path\n \"\"\"\n with open(path, \"w\", newline='') as csv_file:\n writer = csv.writer(csv_file, delimiter=',')\n for line in data:\n writer.writerow(line)\n\ndef csv_dict_reader(file_obj):\n \"\"\"\n Read a CSV file using csv.DictReader\n \"\"\"\n myList = []\n reader = csv.DictReader(file_obj, delimiter=',')\n for line in reader:\n #data = [['File','path']]\n myList.append((line['File']))\n return myList\n\ndef regExp(myList):\n longest_first = sorted(myList, key=len, reverse=True)\n print(myList)\n p = re.compile(r'(?:{})'.format('|'.join(map(re.escape, myList))))\n return p\n\ndef onlyFileType(s):\n for elem in only_types:\n if s.endswith(elem):\n return True\n return False\n\ndef filterReg (myList):\n #intended result re.compile(\".*(cat|wil)\")\n s = '.*('\n n = 1\n l = len(myList)\n for elem in myList:\n s += elem\n if n < l:\n n +=1\n s += '|'\n s += ')'\n p = re.compile(s)\n return p\n\ndef fileNPath(localReport, myList,loc):\n tempData =[]\n for f in myList:\n tempData.append([f,loc])\n return tempData\n\ndef find(l, elem):\n for row, i in enumerate(l):\n if elem in i[0]:\n return i\n return -1\n\ndef folderList(localReport, targetPaths,ldt,searchType):\n n = ldt # last modified date\n data = []\n for mypath in targetPaths:\n for root, dirs, files in os.walk(mypath) :\n myRoot = root\n #dt = os.path.getmtime(root)\n #if dt > n :\n # if the Folder was created after the last report generated\n if(searchType == \"f\"):\n FinalList = list(filter(filtNames.match, files)) # Name filter\n elif(searchType == \"d\"):\n FinalList = list(filter(filtNames.match, dirs))\n\n\n if len(FinalList) > 0:\n tData = fileNPath(localReport,FinalList,myRoot)\n data.extend(tData)\n #break # FOr testing\n else:\n continue\n return data\n\n\n\nif __name__ == '__main__':\n import os, sys, csv, re\n from datetime import datetime, time\n from shutil import copyfile\n\n root_path = '/Users/anandihalli/Documents/01_Work/brazil/Reports/'\n report_path = root_path + 'xbr_LE_3_Assets_Folder_list.csv'\n\n assets_to_download =root_path + 'LE_3.csv'\n\n ldt = datetime(2017,7,1,0,0).timestamp()\n\n # To Skip older Folder we use fallowing date\n #------------year,m,d,h,m(24hours format)\n n = datetime(2017,4,11,0,0).timestamp()\n\n file_names = ['','']\n only_dirs = ['']\n exclude_dir =['']\n data = [['File','path']]\n\n file_names = ['xha','brazil']\n only_types = ['png','swf','jpg']\n\n targetPaths = [\"/Volumes/Farm_Art/Local-vendors/LaughingDots/2017\", \"/Volumes/Farm_Art/Local-vendors/Pixalot\", \"/Volumes/Farm_Art/VendorSubmission/starart_2017\",\"/Volumes/Farm_Art/Local-vendors/RockSalt/RockSalt_2017\"]\n\n p = regExp(only_dirs)\n e = regExp(exclude_dir)\n\n if os.path.isfile(assets_to_download):\n with open(assets_to_download) as f_obj:\n myAssetsList = csv_dict_reader(f_obj)\n\n filtNames = filterReg(myAssetsList) # Looks for short and long mname of expansion\n filtTypes = filterReg(only_types) # Looks for jpg png swf\n\n filesToCopy = [\"File\",\"Path\"]\n\n print (filtNames)\n\n data =folderList(myAssetsList,targetPaths,ldt,\"f\")\n\n print(data)\n\n path = report_path\n print(path)\n csv_writer(data, path)\n\n","sub_path":"Pyhton/Asset_Searching/Search_Individual_Asset_files_1.py","file_name":"Search_Individual_Asset_files_1.py","file_ext":"py","file_size_in_byte":3571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"390075896","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\nfrom argcomplete.completers import FilesCompleter\nfrom azure.mgmt.batch.models.batch_management_client_enums import \\\n (AccountKeyType)\n\nfrom azure.cli.core.commands import \\\n (register_cli_argument, CliArgumentType)\nfrom azure.cli.core.commands.parameters import \\\n (tags_type, location_type, resource_group_name_type,\n get_resource_name_completion_list, enum_choice_list)\n\nfrom ._validators import \\\n (application_enabled)\n\n# pylint: disable=line-too-long\n# ARGUMENT DEFINITIONS\n\nbatch_name_type = CliArgumentType(help='Name of the Batch account.', options_list=('--account_name',), completer=get_resource_name_completion_list('Microsoft.Batch/batchAccounts'), id_part=None)\n\n\n# PARAMETER REGISTRATIONS\n\nregister_cli_argument('batch', 'account_name', batch_name_type, options_list=('--name', '-n'))\nregister_cli_argument('batch', 'resource_group_name', resource_group_name_type, completer=None, validator=None)\nregister_cli_argument('batch account create', 'location', location_type)\nregister_cli_argument('batch account create', 'tags', tags_type)\nregister_cli_argument('batch account set', 'tags', tags_type)\nregister_cli_argument('batch account keys renew', 'key_name', **enum_choice_list(AccountKeyType))\nregister_cli_argument('batch application', 'account_name', batch_name_type, options_list=('--name', '-n'), validator=application_enabled)\nregister_cli_argument('batch application package create', 'package_file', help='The path of the application package in zip format', completer=FilesCompleter())\nregister_cli_argument('batch location quotas show', 'location_name', location_type)\n","sub_path":"src/command_modules/azure-cli-batch/azure/cli/command_modules/batch/_params.py","file_name":"_params.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"457998220","text":"import socket\nimport argparse\nimport sys\nimport re\nfrom urllib.parse import urlparse\n\nCRLF = \"\\r\\n\"\n\n# Method to make a TCP connection to a specified hostname and port\n# Connection is set on the global conn variable\ndef connect(host, port):\n global conn\n conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n conn.settimeout(100.00)\n conn.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n conn.connect((host, port))\n\n# Method to close the open TCP connection\ndef close_connection():\n\tglobal conn\n\tconn.close()\n\n# Method that takes in the response returned and parses it and returns a dictionary to allow a user to\n# view which section of the response they prefer or to view the entirety of the response\ndef parse_response(response):\n status = \"\"\n code = \"\"\n body = \"\"\n header = \"\"\n value = 0\n temp = response.split()\n \n for c in range(len(temp)):\n if temp[c] == \"HTTP/1.1\":\n code = temp[c + 1]\n status = temp[c + 2]\n \n for c in range(len(temp)):\n if temp[c] != \"chunked\":\n header += temp[c]\n header += \" \"\n if temp[c] == \"chunked\":\n header += temp[c]\n header += \" \"\n value = c + 1\n break\n\n for c in range(len(temp)):\n if c < value:\n continue\n else:\n body += temp[c]\n body += \" \"\n\n display = {\"status\": status, \"code\": code, \"body\": body, \"header\": header, \"response\": response}\n return display\n\n# Method to perform a get request to a specified url with the given headers and body\n# @param url: the url to perform the get request on\n# @param port: the port to perform the get request on\n# @param headers: a dict of http headers where keys are the header names and values are the header values\n# @param body: a string containing the http body\n# @return: the response from the server\ndef get_request(url, port, headers, body):\n global conn\n # Parse the url\n url = urlparse(url)\n path = url.path\n if path == \"\":\n path = \"/\"\n host = url.netloc\n headers[\"Host\"] = host\n try:\n # Connect to the host\n connect(host, port)\n # Construct the message\n message = \"GET %s HTTP/1.1%s\" % (path, CRLF)\n for header in headers:\n message = \"%s%s: %s%s\"%(message, header, headers[header], CRLF)\n message = message + CRLF + body + CRLF\n # Send message\n conn.send(message.encode('utf-8'))\n buf = conn.recv(10000)\n buf = buf.decode('utf-8')\n finally:\n close_connection()\n return parse_response(buf)\n\n# Method to perform a post request to a specified url with the given headers and query\n# @param url: the url to perform the get request on\n# @param port: the port to perform the get request on\n# @param headers: a dict of http headers where keys are the header names and values are the header values\n# @param queries: a dict containing the queries for this request where keys are the query names and values are the query values\n# @return: the response from the server\ndef post_request(url, port, headers, body):\n global conn\n url = urlparse(url)\n path = url.path\n if path == \"\":\n path = \"/\"\n host = url.netloc\n headers[\"Host\"] = host\n try:\n # Connect to the host\n connect(host, port)\n # Construct the message\n message = \"POST %s HTTP/1.1%s\" % (path, CRLF)\n for header in headers:\n message = \"%s%s: %s%s\"%(message, header, headers[header], CRLF)\n message = message + CRLF\n byte_message = message.encode('utf-8')\n # If there are queries, then add those to the message\n byte_message = byte_message + body + CRLF.encode('utf-8')\n # Send message\n conn.send(byte_message)\n buf = conn.recv(10000)\n buf = buf.decode('utf-8')\n finally:\n close_connection()\n return parse_response(buf)\n","sub_path":"Assignment 2/httplib.py","file_name":"httplib.py","file_ext":"py","file_size_in_byte":3936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"334517645","text":"import pygame, sys, random\nfrom pygame.locals import *\nFPS = 30\nWINDOWWIDTH = 640\nWINDOWHEIGHT = 480\n\nBLACK = (0,0,0)\nWHITE = (255,255,255)\nGRAY = (186, 204, 200)\nBLUE = (158, 230, 218)\n\n# bgColor = BLUE\nbgColor = GRAY\ndotColor = BLACK \nsquareColor = WHITE\n# borderColor = GRAY\nborderColor = BLACK\nfontSize = 10\nrollSize = 365\ntopDot = 60\nbotDot = 300\nmidDot = 180\nlineDot = 100\ndotRad = 30\nrollLeft = 140\nrollTop = 60\ndiceSide = 6\n\ndef main():\n global screen, FPSCLOCK, BASICFONT\n pygame.init()\n FPSCLOCK = pygame.time.Clock()\n \n screen = pygame.display.set_mode((WINDOWWIDTH,WINDOWHEIGHT))\n pygame.display.set_caption(\"Rolling Dice\")\n BASICFONT = pygame.font.Font('freesansbold.ttf', 20)\n roll_surf, roll_rect = makeText(\"Roll!\", 10, 10)\n start_surf, start_rect = makeText(\"Start/Stop\",10,50)\n screen.fill(bgColor)\n drawDice()\n rollDisplay(random.randint(1,diceSide))\n \n while True:\n roll = False\n nonStop = False\n screen.blit(roll_surf, roll_rect)\n screen.blit(start_surf, start_rect)\n pygame.display.flip()\n \n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n elif event.type == MOUSEBUTTONUP:\n xmouse, ymouse = event.pos\n if roll_rect.collidepoint(xmouse, ymouse):\n roll = True\n elif start_rect.collidepoint(xmouse, ymouse):\n roll = not roll\n nonStop = not nonStop\n elif event.type == KEYUP:\n if event.key == K_SPACE:\n roll = True\n \n if roll and not nonStop:\n #num = 0\n for x in range (10):\n x = random.randint(1,diceSide)\n # while x == num:\n # x = random.randint(1,diceSize)\n rollDisplay(x)\n #num = x\n # elif not roll and not nonStop:\n # x = random.randint(1,diceSide)\n # rollDisplay(x)\n while nonStop:\n x = random.randint(1,diceSide)\n rollDisplay(x)\n if not nonStop:\n break\n\n pygame.display.update()\n FPSCLOCK.tick(FPS)\ndef drawDice():\n pygame.draw.rect(screen, borderColor, (rollLeft-5, rollTop-5, rollSize+10, rollSize+10), 5)\n pygame.draw.rect(screen, squareColor, (rollLeft, rollTop, rollSize, rollSize))\ndef rollDisplay(num):\n drawDice()\n if num == 1:\n pygame.draw.circle(screen, dotColor, (320, 240), dotRad)\n elif num == 2:\n pygame.draw.circle(screen, dotColor, (rollLeft + topDot, rollTop + topDot), dotRad)\n pygame.draw.circle(screen, dotColor, (rollLeft + botDot, rollTop + botDot), dotRad)\n elif num == 3:\n pygame.draw.circle(screen, dotColor, (rollLeft + botDot, rollTop + topDot), dotRad)\n pygame.draw.circle(screen, dotColor, (rollLeft + midDot, rollTop + midDot), dotRad)\n pygame.draw.circle(screen, dotColor, (rollLeft + topDot, rollTop + botDot), dotRad)\n elif num == 4:\n pygame.draw.circle(screen, dotColor, (rollLeft + botDot, rollTop + topDot), dotRad)\n pygame.draw.circle(screen, dotColor, (rollLeft + botDot, rollTop + botDot), dotRad)\n pygame.draw.circle(screen, dotColor, (rollLeft + topDot, rollTop + topDot), dotRad)\n pygame.draw.circle(screen, dotColor, (rollLeft + topDot, rollTop + botDot), dotRad)\n elif num == 5:\n pygame.draw.circle(screen, dotColor, (rollLeft + botDot, rollTop + topDot), dotRad)\n pygame.draw.circle(screen, dotColor, (rollLeft + botDot, rollTop + botDot), dotRad)\n pygame.draw.circle(screen, dotColor, (rollLeft + topDot, rollTop + topDot), dotRad)\n pygame.draw.circle(screen, dotColor, (rollLeft + topDot, rollTop + botDot), dotRad)\n pygame.draw.circle(screen, dotColor, (rollLeft + midDot, rollTop + midDot), dotRad)\n elif num == 6:\n pygame.draw.circle(screen, dotColor, (rollLeft + lineDot, rollTop + topDot), dotRad)\n pygame.draw.circle(screen, dotColor, (rollLeft + lineDot, rollTop + topDot + dotRad*4), dotRad)\n pygame.draw.circle(screen, dotColor, (rollLeft + lineDot, rollTop + topDot + dotRad*8), dotRad)\n pygame.draw.circle(screen, dotColor, (rollLeft + lineDot + dotRad*6, rollTop + topDot), dotRad)\n pygame.draw.circle(screen, dotColor, (rollLeft + lineDot + dotRad*6, rollTop + topDot + dotRad*4), dotRad)\n pygame.draw.circle(screen, dotColor, (rollLeft + lineDot + dotRad*6, rollTop + topDot + dotRad*8), dotRad)\n pygame.display.update()\n pygame.time.wait(130)\n FPSCLOCK.tick(FPS)\ndef makeText(text, top, left):\n # create the Surface and Rect objects for some text.\n textSurf = BASICFONT.render(text, True, (0,0,0), (240,240,240))\n textRect = textSurf.get_rect()\n textRect.topleft = (top, left)\n return (textSurf, textRect)\n\nif __name__ == '__main__':\n main()","sub_path":"making_game_with_python/rolling dice/rollingdice 2.py","file_name":"rollingdice 2.py","file_ext":"py","file_size_in_byte":4986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"589065895","text":"##\n## python detector.py --srcdir /home/xufeng02/develop/ai/origin/tensorflow-for-poets-2/tf_files/foods/train --out result --num 10 --threshold 0.99##\n## 2 classes, class0 from none dish and others dishes\n##\n\nimport argparse\nimport os\nimport trainer\nfrom utils import Utils\nfrom const import const\nfrom justor import label_image\nimport numpy as numpy\nimport time\n\nif __name__ == '__main__':\n srcdir = \"./\"\n outdir = \"result\"\n num = 10\n threshold = \"0.99\"\n dict=[]\n const.ROOTDIR=os.getcwd();\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--srcdir\", help=\"src dir\")\n parser.add_argument(\"--outdir\", help=\"output dir\")\n parser.add_argument(\"--num\", help=\"number to simpling\")\n parser.add_argument(\"--threshold\", help=\"just threshold\")\n\n FLAGS, unparsed = parser.parse_known_args()\n print(FLAGS)\n print(type(FLAGS))\n\n args = parser.parse_args()\n\n if args.srcdir:\n srcdir = args.srcdir\n if args.outdir:\n outdir = args.outdir\n if args.num:\n num = args.num\n if args.threshold:\n threshold = float(args.threshold)\n\n Utils.removeSubFilesInDir(outdir) #clean out files last time\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n\n train = trainer.Trainer()\n train.clean() #clean training files last time\n\n Utils.removeSubFilesInDir(const.TRAIN_NEG) # clean out files last time\n\n listfile = os.listdir(srcdir)\n print(listfile)\n\n dirnum = len(listfile)\n if dirnum == 0:\n exit(0)\n\n start = time.time()\n result_path = os.path.join(outdir, const.RESULTFILE)\n resultfile = open(result_path, \"w\")\n\n for i in range(dirnum - 1): #training every dir\n traindir = os.path.join(srcdir,listfile[i])\n if not os.path.isdir(traindir):\n print(listfile[i]+' is not a dir')\n continue\n\n for j in range(1, dirnum):\n if j == i:\n continue\n otherdir = os.path.join(srcdir, listfile[j])\n if not os.path.isdir(otherdir):\n continue\n Utils.randomCopyFile(otherdir, const.TRAIN_NEG, int(num))\n Utils.randomCopyFile(const.NEG_PICTURES, const.TRAIN_NEG, 700)\n train.train(traindir)\n resultfile.write(\"%s,%s\\n\" % (listfile[i], \",\".join(\"\")))\n\n output_path = os.path.join(outdir, listfile[i]+\".csv\")\n output = open(output_path, \"w\")\n result_array = []\n\n for j in range(i+1, dirnum): #test other dir\n testdir = os.path.join(srcdir, listfile[j])\n if not os.path.isdir(testdir):\n print(listfile[j] + ' is not a dir')\n continue\n print (\"calculate... \", listfile[j])\n output.write(\"%s,%s\\n\" % (listfile[j], \",\".join(\"\")))\n\n Utils.randomCopyFile(testdir, const.DEV_DIR, int(num))\n sum = 0\n testfile = os.listdir(const.DEV_DIR)\n labels = []\n\n for file in testfile: #test every pic\n filepath = os.path.join(const.DEV_DIR, file)\n\n ret = label_image(filepath)\n if ret > threshold:\n sum = sum + 1\n labels.append((file, ret))\n labels.sort(key=lambda x:x[1],reverse=True)\n for k in labels:\n output.write(\"%s,,%f\\n\" % (k[0], k[1]))\n output.write(\"%d,,%s\\n\" % (sum, \"\"))\n print('%s : %d' % (testdir, sum))\n\n Utils.removeFilesInDir(const.DEV_DIR)\n result_array.append((listfile[j], sum))\n\n result_array.sort(key=lambda x: x[1], reverse=True)\n for k in result_array:\n resultfile.write(\"%s,,%d\\n\" % (k[0], k[1]))\n resultfile.flush()\n train.clean()\n Utils.removeSubFilesInDir(const.TRAIN_NEG)\n end = time.time()\n print('\\n finish time : {:.3f}s\\n'.format(end - start))\n","sub_path":"tensorflow/tensorflow_tools/simlar_dish_detect/detector2.py","file_name":"detector2.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"453330826","text":" # Television and Rooms Question\n\nimport math\n\nN = int(input(\"Enter The No. Of Rooms >>> \"))\nR1 = int(input(\"Enter Price Of TV Rooms >>> \"))\nR2 = int(input(\"Enter Price Of Non-TV Rooms >>> \"))\nTarget = int(input(\"Enter The Target Revenue >>> \"))\n\noddeve = 0\nflag = 0\npatient = 0\n#temp = N\nrevenue = 0\ninc = 0\n\n\n'''s = 0\nfor j in range(1,12+1): # Months\n #print(\"\\n\\t-: \",j,\" :-\")\n for k in range(1,31+1): # Days\n if j == 2 and k == 29: # For February\n break\n if k == 31:\n if oddeve%2 != 0: # For Odd Months\n break\n oneday = (6-j)**2 + abs(k-15)\n #print(\"\\n\\t\", oneday )\n #patient += oneday\n #print(\" \",k)\n if s == 0:\n small = oneday\n if s > 0:\n if oneday < small:\n small = oneday\n s+=1\n \n if j == 7:\n oddeve = -1\n oddeve += 1\n\nprint(small)\n#print(temp) '''\n\nfor i in range(1,N+1): # Rooms\n #print(\"\\n\\t\",i)\n for j in range(1,12+1): # Months\n for k in range(1,31+1): # Days\n if j == 2 and k == 29: # For February\n break\n if k == 31:\n if oddeve%2 != 0: # For Odd Months\n break\n oneday = (6-j)**2 + abs(k-15)\n #print(\"\\n\\t\", oneday )\n #patient += oneday\n #print(\" \",k)\n temp = oneday\n if temp > 20:\n temp = 20\n drev = (R1*inc) + (R2*(temp-inc))\n #print(\"\\n-----\",drev)\n #print(\" \",oneday)\n revenue = revenue + drev\n #print(\"~~~~~~~~~~\",revenue)\n\n if j == 7:\n oddeve = -1\n oddeve += 1\n \n print(\"=\",revenue)\n if revenue >= Target:\n TV = i\n flag = 1\n break\n else:\n revenue = 0\n inc = inc + 1\n #temp = temp - 1\n\n#print(\"\\n\\tpatient=\",patient,\"\\n\\trevenue=\",revenue,\"\\n\\tflag=\",flag,\"\\n\\ti=\",i,\"\\n\\tTV=\",TV)\n#print(\"\\n\\npatient=\", patient,\"\\nsmall=\",small )\n\nif flag == 1:\n print(\"\\n\\tNo. Of TVs : \", TV )\n print(\"\\n\\trevenue=\", revenue)\nelif flag == 0:\n print(\"\\n\\tNo. Of Rooms : \",N)\n \n","sub_path":"p42.py","file_name":"p42.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"253516345","text":"# Copyright 2011 Tijmen Roberti\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nAll functions that are used to interface with the system. At some\npoint, these functions have to be transformed to a JSON-based api, but\nfor now just return python objects. The transformation to JSON should\nbe pretty straightforward.\n\"\"\"\nimport re\nfrom google.appengine.ext import db\nfrom google.appengine.api import users\nfrom model import Domain, Task, TaskIndex, Context, User\nimport workers\n\nVALID_DOMAIN_IDENTIFIER = r'[a-z][a-z0-9-]{1,100}'\n\n\ndef member_of_domain(domain, user, *args):\n \"\"\"Returns true iff all the users are members of the domain.\n\n Args:\n domain: The domain identifier\n user: Instance of the User model class\n *args: Instances of the User model class\n\n Returns:\n True if all the users are members of the domain.\n \"\"\"\n if not domain in user.domains:\n return False\n for other in args:\n if not domain in other.domains:\n return False\n return True\n\n\ndef get_user():\n \"\"\"Gets the currently logged in user.\n\n The login is based on the GAE user system, but Users are stored as\n separate entities. If the user does not have an entity, one will\n be created using the information in his Google account.\n\n Returns:\n An instance of the User model, or None if the user is not\n logged in.\n \"\"\"\n guser = users.get_current_user()\n if not guser:\n return None\n user = User.get_by_key_name(guser.user_id())\n if not user:\n user = User(key_name=guser.user_id(), name=guser.nickname())\n user.put()\n return user\n\ndef get_user_from_identifier(user_identifier):\n \"\"\"Returns the user corresponding to the given identifier\"\"\"\n # TODO(tijmen): Name this get_user and rename the current\n # function to something like get_logged_in_user().\n return User.get_by_key_name(user_identifier)\n\n\ndef get_and_validate_user(domain_identifier):\n \"\"\"Gets the currently logged in user and validates if he\n is a member of the domain.\n\n If the user is not logged in, or is not a member of the domain\n with |domain_identifier|, then None will be returned.\n\n Args:\n domain_identifier: The domain identifier string.\n\n Returns:\n An instance of the User model, or None if the user\n is not logged in or not a member of the domain.\n \"\"\"\n user = get_user()\n if not user or not member_of_domain(domain_identifier, user):\n return None\n return user\n\n\ndef get_domain(domain_identifier):\n \"\"\"\n Returns the Domain model instance corresponding to the identifier.\n\n Args:\n domain_identifier: The domain identifier string\n\n Returns:\n An instance of the Domain model, or None if no domain exist\n with the given identifier.\n \"\"\"\n return Domain.get_by_key_name(domain_identifier)\n\n\ndef get_all_domains_for_user(user):\n \"\"\"\n Returns a list with domain instances of the domains that\n the given user is a member of.\n\n Args:\n user: An instance of the User model\n\n Returns:\n A list of Domain model instances.\n \"\"\"\n keys = [db.Key.from_path('Domain', domain)\n for domain in user.domains]\n return Domain.get(keys)\n\n\ndef get_task(domain, task):\n \"\"\"Gets a task in a domain.\n\n Args:\n domain: The domain identifier\n task: The task key id or name. Can either be an int\n or a string.\n\n Returns:\n A task instance or None if no task exists.\n \"\"\"\n domain_key = Domain.key_from_name(domain)\n try:\n task_id = int(task)\n return Task.get_by_id(task_id, parent=domain_key)\n except ValueError:\n return Task.get_by_key_name(task, parent=domain_key)\n\n\ndef can_complete_task(task, user):\n \"\"\"Returns true if the task can be completed by the user.\n\n Task can only be completed if the user is the assignee and\n the task is an atomic task. Composite tasks are automatically\n completed when all its subtasks are completed.\n\n Args:\n task: An instance of the Task model\n user: An instance of the User model\n\n Returns:\n True if the user can set the task to completed.\n \"\"\"\n return task.atomic() and task.assignee_key() == user.key()\n\ndef can_assign_to_self(task, user):\n \"\"\"Returns true if a user can assign the task to himself.\n\n Args:\n task: An instance of the Task model\n user: A User model instance\n\n Returns:\n True if the user can assign the task to himself. If the user\n is already assigned to the task, then this function will\n return false.\n \"\"\"\n if not task.atomic() or task.assignee_identifier():\n return False\n return can_assign_task(task, user, user)\n\n\ndef can_assign_task(task, user, assignee):\n \"\"\"Checks whether a user can assign the task to assignee.\n\n A task can only be assigned if the task is an atomic task and\n one of the following conditions is true:\n - The |user| is the current assignee of the task. Assignees\n can change the assignee of their tasks.\n - The |task| does not have an assignee yet and the user assigns\n the task to himself (assignee == user).\n - The |user| has admin rights. Admins can always change the assignee.\n\n Args:\n task: A Task model instance\n user: A User model instance\n assignee: A User model instance, or None\n\n Returns:\n True if user is allowed to set the assignee of the task to the\n given assignee and the task is atomic.\n\n Raises:\n ValueError: If the user and assignee are not both members of\n the domain of the task.\n \"\"\"\n domain_identifier = task.domain_identifier()\n if not member_of_domain(domain_identifier, user, assignee):\n raise ValueError(\"User and assignee not in the same domain\")\n\n if not task.atomic():\n return False\n if user.identifier() == task.assignee_identifier():\n return True\n if not task.assignee_key() and user.identifier() == assignee.identifier():\n return True\n if user.admin:\n # TOOD(tijmen): Old admin code, change\n return True\n return False\n\n\ndef create_task(domain, user, description, assignee=None, parent_task=None):\n \"\"\"Create and store a task in the Datastore.\n\n The task will be stored in the specified domain. The user must be\n a member of the domain to create the task. If a |parent_task| is\n specified, the new task will be added as subtask of that task. All\n tasks in the task hierarchy will also be updated.\n\n Args:\n domain: The key name of the domain in which the task is created.\n user: The User model instance of the user that creates the task.\n description: The task description. Must be a non-empty string.\n assignee: The user model instance of the user to whom this task is\n assigned. The assignee must be in the same domain as the user.\n A value of None indicates no assignee for this task.\n parent_task: The task identifier of the optional parent task.\n\n Returns:\n The model instance of the newly created task.\n\n Raises:\n ValueError: The |assignee| and |user| domain do not match or\n the user is not a member of domain.\n ValueError: The parent task does not exist.\n \"\"\"\n if not member_of_domain(domain, user):\n raise ValueError(\"User '%s' not a member of domain '%s'\" %\n (user.name, domain))\n if assignee and not member_of_domain(domain, user, assignee):\n raise ValueError(\"Assignee and user domain do not match\")\n\n def txn():\n super_task = None\n if parent_task:\n super_task = get_task(domain, parent_task)\n if not super_task:\n raise ValueError(\"Parent task does not exist\")\n task = Task(parent=Domain.key_from_name(domain),\n description=description,\n user=user,\n context=user.default_context_key(),\n parent_task=super_task,\n level=super_task.level + 1 if super_task else 0)\n if super_task:\n super_task.number_of_subtasks = super_task.number_of_subtasks + 1\n super_task.increment_incomplete_subtasks()\n super_task.put()\n if assignee:\n task.baked_assignee_description = assignee.name\n task.put()\n return task\n\n task = db.run_in_transaction(txn)\n workers.UpdateTaskIndex.queue_task(domain, task.identifier())\n if assignee:\n assign_task(domain, task.identifier(), user, user)\n return task\n\n\ndef assign_task(domain_identifier, task_identifier, user, assignee):\n \"\"\"Assigns a task to an assignee.\n\n Sets the assignee property of task. user is the user performing\n the operation. The assignment will only succeed if the user is\n allowed to perform the operation, which can be checked beforehand\n through can_assign_task().\n\n Args:\n domain_identifier: The domain identifier string\n task_identifier: The task identifier of the task that is assigned\n user: An instance of the User model that is performing the\n assignment operation.\n assignee: An instance of the User model to whom the task is\n assigned to.\n\n Returns:\n The task instance. The assignee will be set and the task instance\n is stored in the datastore.\n\n Raises:\n ValueError: If the assignment operation is invalid, or if the\n task does not exist.\n \"\"\"\n def txn():\n task = get_task(domain_identifier, task_identifier)\n if not task:\n raise ValueError(\"Task does not exist\")\n if not can_assign_task(task, user, assignee):\n raise ValueError(\"Cannot assign\")\n\n previous_assignee = task.assignee_identifier()\n task.assignee = assignee\n workers.UpdateAssigneeIndex.queue_worker(\n task,\n add_assignee=assignee.identifier(),\n remove_assignee=previous_assignee)\n task.put()\n return task\n\n return db.run_in_transaction(txn)\n\n\ndef set_task_completed(domain, user, task_identifier, completed):\n \"\"\"Sets the completion status of a task.\n\n A task can only be set to completed if |user| is the assignee of\n the task and if the task is an atomic task. This function will\n also propagate the complete status up the task hierarchy.\n\n Args:\n domain: The domain identifier string\n user: An instance of the User model\n task: The task identifier\n completed: The new value of the completed property of the task\n\n Returns:\n An instance of the Task model if setting the property was\n succesful.\n\n Raises:\n ValueError: The task does not exist or the user is not the\n assignee of the task.\n \"\"\"\n def txn():\n task = get_task(domain, task_identifier)\n if not task or not task.atomic() or not can_complete_task(task, user):\n raise ValueError(\"Invalid task\")\n\n if not task.completed ^ completed:\n return task # no changes\n\n task.completed = completed\n task.put()\n parent_task = task.parent_task\n while parent_task:\n propagate = False\n if completed:\n parent_task.decrement_incomplete_subtasks()\n propagate = parent_task.completed\n else: # Task went from complete to incomplete\n parent_completed = parent_task.completed\n parent_task.increment_incomplete_subtasks()\n propagate = parent_task.completed ^ parent_completed\n parent_task.put()\n parent_task = parent_task.parent_task if propagate else None\n return task\n\n return db.run_in_transaction(txn)\n\n\ndef create_domain(domain, domain_title, user):\n \"\"\"Creates a new domain, if none already exists with that identifier.\n\n The user will become an admin on the newly created domain, and the\n domain will be added to the list of domains of the user. The updates\n will be stored in the datastore.\n\n Args:\n domain: The domain identifier of the new domain. Must be a lowercase\n alphanumeric string of length less than 100. The identifier\n must match the VALID_DOMAIN_IDENTIFIER regexp.\n domain_title: The string title of the new domain. The string must\n be non-empty.\n user: Instance of the User model that creates the domain.\n\n Returns:\n The newly created Domain instance. |user| will be set as\n admin of the new domain. Returns None if a domain already\n exists with that identifier, the identifier is not valid or\n the domain_title is empty.\n \"\"\"\n domain_title = domain_title.splitlines()[0].strip()\n if (not re.match(VALID_DOMAIN_IDENTIFIER, domain) or\n not domain_title):\n return None\n existing = Domain.get_by_key_name(domain)\n if existing:\n return None\n new_domain = Domain(key_name=domain,\n name=domain_title,\n admins=[user.key().name()])\n new_domain.put()\n def txn(user_key):\n txn_user = User.get(user_key)\n if not domain in txn_user.domains:\n txn_user.domains.append(domain)\n txn_user.put()\n db.run_in_transaction(txn, user.key())\n return new_domain\n\n\ndef _group_tasks(tasks, complete_hierarchy=False, domain=None):\n \"\"\"\n Reorders the list of tasks such that supertasks are listed before\n their subtasks.\n\n The original order is retained as much as possible while still\n satisfying the above listed constraint.\n\n If complete_hierarchy is set to true, then tasks are fetched from\n the datastore are made to fill in the blanks, all the way up the\n hierarchy. The function must also be run in the same transaction\n as where the input tasks are fetched to get consistent results.\n\n Args:\n tasks: A list of Task model instances\n complete_hierarchy: If set to True, then the parent tasks will\n be fetched to complete the hierarchy.\n domain: The domain identifier string. Required if\n complete_hierarchy is set to True.\n\n Returns:\n A list of Task model instances, ordered such that supertasks are\n before their subtasks.\n\n Raises:\n ValueError: If complete_hierarchy is enabled but not domain\n identifier is specified.\n \"\"\"\n if complete_hierarchy and not domain:\n raise ValueError(\"Domain identifier is required\")\n\n index = dict([(task.identifier(), task) for task in tasks])\n trees = {} # Index of all tree nodes, by task\n # The output of the algorithm, all the tree root nodes\n roots = []\n\n class _Tree(object):\n \"\"\"Very basic n-tree node\"\"\"\n def __init__(self, value, parent=None):\n self.value = value\n self.parent = parent\n if self.parent:\n self.parent.children.append(self)\n self.children = []\n\n def pre_order(self, output):\n output.append(self.value)\n for child in self.children:\n child.pre_order(output)\n\n\n def fetch_tree(task_identifier):\n if not task_identifier:\n return None\n\n task = index.get(task_identifier)\n if not task and complete_hierarchy:\n task = get_task(domain, task_identifier)\n if task:\n index[task_identifier] = task\n if not task:\n return None\n\n tree = trees.get(task)\n if not tree:\n parent_tree = fetch_tree(task.parent_task_identifier())\n tree = _Tree(task, parent=parent_tree)\n if not parent_tree:\n roots.append(tree)\n trees[task] = tree\n return tree\n\n for task in tasks:\n fetch_tree(task.identifier())\n output = []\n for root in roots:\n root.pre_order(output)\n return output\n\n\ndef get_all_subtasks(domain, task, limit=50, depth_limit=None):\n \"\"\"\n Returns a list of all subtasks of the given task, in the order\n as a pre-order traversal through the task hierarchy.\n\n This function will perform one query for each level of the subtask\n hierarchy.\n\n Args:\n domain: The domain identifier string.\n task: An instance of the Task model.\n limit: The maximum number of subtasks to return.\n depth_limit: The maximum depth of subtasks in the task\n hierarchy.\n\n Returns:\n A list with all subtasks of the given task.\n\n Raises:\n ValueError: The depth_limit or limit are not positive integers\n \"\"\"\n if not depth_limit:\n # ListProperties cannot contain more than 5000 elements anyway\n depth_limit = 5000\n if depth_limit < 0 or limit < 0:\n raise ValueError(\"Invalid limits\")\n\n task_level = task.level\n tasks = []\n for depth in range(depth_limit):\n query = TaskIndex.all(keys_only=True).\\\n ancestor(Domain.key_from_name(domain)).\\\n filter('level = ', task_level + depth + 1).\\\n filter('hierarchy = ', task.identifier())\n fetched = query.fetch(limit)\n tasks.extend(Task.get([key.parent() for key in fetched]))\n limit = limit - len(fetched)\n if not fetched or limit < 1:\n break # stop\n\n # Sort the tasks on completion status and then on time, as this is\n # not possible in the query.\n def task_cmp(t1, t2):\n if t1.completed != t2.completed:\n return cmp(t1.completed, t2.completed)\n return -cmp(t1.time, t2.time)\n\n tasks.sort(cmp=task_cmp)\n return _group_tasks(tasks)\n\n\ndef get_all_open_tasks(domain):\n \"\"\"\n Returns all tasks from |domain| that are not yet completed and not\n assigned to anyone.\n\n Args:\n domain: The domain identifier string\n\n Returns:\n A list of Task model instances that are not yet completed\n and do not have an assignee. The tasks will be ordered on\n hierarchy.\n \"\"\"\n def txn():\n query = Task.all().ancestor(Domain.key_from_name(domain)).\\\n filter('number_of_subtasks =', 0).\\\n filter('completed =', False).\\\n filter('assignee =', None).\\\n order('-time')\n return _group_tasks(query.fetch(50),\n complete_hierarchy=True,\n domain=domain)\n return db.run_in_transaction(txn)\n\n\ndef get_all_assigned_tasks(domain, user):\n \"\"\"Returns all tasks that are assigned to |user| in |domain|.\n\n Args:\n domain: The domain identifier string\n user: An instance of the User model.\n\n Returns:\n A list of tasks instances that the given |user| is the assignee for.\n At most 50 instances will be returned. The order will be on completion\n status, with uncompleted tasks first. A secondary order is on time,\n with newest tasks first.\n \"\"\"\n def txn():\n query = user.assigned_tasks.ancestor(Domain.key_from_name(domain)).\\\n order('completed').\\\n order('-time')\n return _group_tasks(query.fetch(50),\n complete_hierarchy=True,\n domain=domain)\n return db.run_in_transaction(txn)\n\n\ndef get_all_tasks(domain):\n \"\"\"Returns all the tasks in the |domain|.\n\n Args:\n domain: The domain identifier string\n\n Returns:\n A list of at most 50 task instances of |domain|, ordered on task\n creation time, with the newest task first.\n \"\"\"\n def txn():\n query = Task.all().ancestor(Domain.key_from_name(domain)).\\\n order('-time')\n return _group_tasks(query.fetch(50),\n complete_hierarchy=True,\n domain=domain)\n return db.run_in_transaction(txn)\n","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":20463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"382730807","text":"#/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# 以灰度模式读入图片,这样img.shape就只有二维。否则还会多一维表示彩色\nimg=cv2.imread('Lena.jpg',cv2.IMREAD_GRAYSCALE)\nimg2 = img.copy()\n# 指定第二个参数0会导致mathTemplate执行报错:template = cv2.imread('Lena_eyes.png',0)\ntemplate = cv2.imread('Lena_eyes.png',cv2.IMREAD_GRAYSCALE)\n\nw, h = template.shape[::-1]\n\n# Apply template Matching\nres = cv2.matchTemplate(img2,template,cv2.TM_CCOEFF_NORMED)\nmin_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)\n\ntop_left = max_loc\nbottom_right = (top_left[0] + w, top_left[1] + h)\n\ncv2.rectangle(img2,top_left,bottom_right,255,2)\n\n# 绘制1行2列的grid,图片显示在第二个位置\nplt.subplot(122), plt.imshow(img2,cmap = 'gray')\n# 使用plt.xticks([])关闭坐标轴刻度\nplt.title('Detected Point'), plt.xticks([]), plt.yticks([])\nplt.suptitle(\"TM_CCOEFF_NORMED\")\nplt.show()\n","sub_path":"test/plt.py","file_name":"plt.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"5300364","text":"from __future__ import print_function\n\nimport sys\nfrom operator import add\nfrom pyspark import SparkContext\nfrom csv import reader\n\ndef find_hd(x):\n\tif x=='':\n\t\treturn (x,'TEXT','HADEVELOPT','Null')\n\n\telse:\n\t\treturn(x,'TEXT','HADEVELOPT','Valid')\n \n\nif __name__ == \"__main__\":\n\tif len(sys.argv) != 2:\n\t\tprint(\"Usage: bigram \", file=sys.stderr)\n\t\texit(-1)\n\tsc = SparkContext()\n\tcrime = sc.textFile(sys.argv[1], 1)\n\t\n\tcrime = crime.mapPartitions(lambda x: reader(x)).map(lambda x: x[18]).map(lambda x:find_hd(x))\n\ta=crime.map(lambda x: x[0]+' '+x[1]+' '+x[2]+' '+x[3])\n\ta.saveAsTextFile('crime_hd.out')\n\tsc.stop()","sub_path":"output_script_liwei_15_23/crime_hd.py","file_name":"crime_hd.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"646275007","text":"#finding interquartile range\nn=int(input())\nx=list(map(int, input().split(\" \")))\nf=list(map(int, input().split(\" \")))\ns=[]\nfor j in range(n):\n for i in range(f[j]):\n s.append(x[j])\ns.sort()\nl=len(s)\ndef median(array,m):\n if m%2==0:\n median=(array[m//2-1]+array[(m//2)])/2\n else:\n median=array[m//2]\n return round(median)\nq1=median(s,l//2)\nif l%2==0:\n q2=median(s[l//2:],l//2)\nelse:\n q2=median(s[l//2+1:],l//2)\nprint(round(float(q2-q1),1))\n","sub_path":"interquartile.py","file_name":"interquartile.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"377007260","text":"import tensorflow as tf\n\nfrom constants import *\n\n\nclass DPGModel(object):\n def __init__(self, state_size, action_size):\n self.sess = tf.Session()\n self.state_size = state_size\n self.action_size = action_size\n self._create_network()\n\n # training for Q function\n self.targetQ_tensor = tf.placeholder(tf.float32, [None], name=\"targetQ\")\n self.loss_tensor = tf.nn.l2_loss(self.value_tensor - self.targetQ_tensor)\n self.event_Q_regression = tf.train.AdamOptimizer(learning_rate=LEARNING_RATE_Q, name='Adam_Critic').minimize(\n loss=self.loss_tensor)\n # gradient of Q on action\n self.event_grad_for_action = tf.gradients(self.value_tensor, self.action_tensor)\n\n # apply chain rule on policy function\n self.grad_for_action_tensor = tf.placeholder(tf.float32, [None, self.action_size], name=\"grad_for_action\")\n # set policy weights\n self.policy_weights = []\n with tf.variable_scope('state_h1', reuse=True):\n self.policy_weights.extend([\n tf.get_variable('kernel'),\n tf.get_variable('bias'),\n ])\n with tf.variable_scope('state_h2', reuse=True):\n self.policy_weights.extend([\n tf.get_variable('kernel'),\n tf.get_variable('bias'),\n ])\n with tf.variable_scope('policy', reuse=True):\n self.policy_weights.extend([\n tf.get_variable('kernel'),\n tf.get_variable('bias'),\n ])\n self.policy_grads = tf.gradients(self.policy_tensor, self.policy_weights,\n grad_ys=-self.grad_for_action_tensor)\n self.event_policy_gradient = tf.train.AdamOptimizer(learning_rate=LEARNING_RATE_Pi,\n name='Adam_Actor').apply_gradients(\n zip(self.policy_grads, self.policy_weights))\n\n # tf summary & metrics\n self.summary_Q_loss = tf.summary.scalar('Q-learning loss', self.loss_tensor)\n self._create_abs_error_summary()\n\n self.sess.run(tf.global_variables_initializer())\n self.sess.run(tf.local_variables_initializer())\n\n def _create_network(self):\n self.state_tensor = tf.placeholder(tf.float32, [None, self.state_size], name=\"state\")\n self.action_tensor = tf.placeholder(tf.float32, [None, self.action_size], name=\"action\")\n\n # create policy network\n state_h1 = tf.layers.dense(inputs=self.state_tensor, units=64, activation=tf.nn.relu, name=\"state_h1\",\n reuse=None)\n state_h2 = tf.layers.dense(inputs=state_h1, units=32, activation=tf.nn.relu, name=\"state_h2\", reuse=None)\n self.policy_tensor = tf.layers.dense(inputs=state_h2, units=self.action_size, activation=tf.nn.softmax,\n name=\"policy\")\n\n # create critic network\n state_h1 = tf.layers.dense(inputs=self.state_tensor, units=64, activation=tf.nn.relu, name=\"state_h1\",\n reuse=True)\n state_h2 = tf.layers.dense(inputs=state_h1, units=32, activation=tf.nn.relu, name=\"state_h2\", reuse=True)\n action_h1 = tf.layers.dense(inputs=self.action_tensor, units=64, activation=tf.nn.relu, name=\"action_h1\")\n action_h2 = tf.layers.dense(inputs=action_h1, units=32, activation=tf.nn.relu, name=\"action_h2\")\n fc = tf.layers.dense(inputs=tf.concat([state_h2, action_h2], axis=1), units=32, activation=tf.nn.relu,\n name=\"fully_connected\")\n self.value_tensor = tf.layers.dense(inputs=fc, units=1, activation=None, name=\"value\")\n\n def _create_abs_error_summary(self):\n self.metric_graph = tf.Graph()\n self.correct_action_tensor = tf.placeholder(tf.float32, [None, self.action_size], name=\"correct_action\")\n self.input_action_tensor = tf.placeholder(tf.float32, [None, self.action_size], name=\"test_action\")\n with self.metric_graph.as_default():\n self.metric_action, _ = tf.metrics.mean_absolute_error(self.correct_action_tensor,self.input_action_tensor)\n self.summary_action_error = tf.summary.scalar('Absolute Action Error', self.metric_action)\n\n def train_Q(self, state_batch, action_batch, targetQ_batch):\n \"\"\"train value function Q\"\"\"\n _, loss = self.sess.run([self.event_Q_regression, self.summary_Q_loss], feed_dict={\n self.state_tensor: state_batch,\n self.action_tensor: action_batch,\n self.targetQ_tensor: targetQ_batch,\n })\n return loss\n\n def train_Pi(self, state_batch, action_batch):\n \"\"\"train policy function pi\"\"\"\n grad_for_action_batch = self.sess.run(self.event_grad_for_action, feed_dict={\n self.state_tensor: state_batch,\n self.action_tensor: action_batch,\n })[0]\n self.sess.run(self.event_policy_gradient, feed_dict={\n self.state_tensor: state_batch,\n self.grad_for_action_tensor: grad_for_action_batch,\n })\n\n def predict_Q(self, state_batch, action_batch):\n return self.sess.run(self.value_tensor, feed_dict={\n self.state_tensor: state_batch,\n self.action_tensor: action_batch,\n })\n\n def predict_Pi(self, state_batch):\n \"\"\"return behavior action given states\"\"\"\n return self.sess.run(self.policy_tensor, feed_dict={\n self.state_tensor: state_batch,\n })\n\n def metric_Pi(self, action_batch, correct_action_batch):\n \"\"\"test behavior action given states & correct actions\"\"\"\n with self.metric_graph.as_default():\n return self.sess.run(self.summary_action_error, feed_dict={\n self.input_action_tensor: action_batch,\n self.correct_action_tensor: correct_action_batch,\n })\n","sub_path":"DPGModel.py","file_name":"DPGModel.py","file_ext":"py","file_size_in_byte":5907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"405680236","text":"import numpy as np\nimport av\nfrom av.video.stream import VideoStream\nfrom utils import convert_to_avi\nfrom dream import *\nimport inception5h\n\ninception5h.maybe_download()\nmodel = inception5h.Inception5h()\nlayer_tensor = model.layer_tensors[6]\n\n# Load deep dreaming lib\ndream = Dream(layer=6)\n\n### Some base functions\ndef transform_img(img, iterations=1, repeats=1):\n# img_result = img * 0.3\n img_result = dream.recursive_optimize(image=img,\n num_iterations=iterations,\n num_repeats=repeats,\n step_size=3.0,\n rescale_factor=0.7,\n blend=0.5)\n result = np.clip(img_result, 0.0, 255.0).astype(np.uint8)\n return result\n\ndef get_writer(file, width, height, fps):\n container = av.open(file, 'w')\n stream = container.add_stream('mpeg4', rate=fps)\n stream.width = width\n stream.height = height\n stream.pix_fmt = 'yuv420p'\n return container, stream\n\ndef get_reader(file):\n return av.open(file, 'r')\n\ndef write_frame(container, stream, frame):\n for packet in stream.encode(frame):\n container.mux(packet)\n\n### First input video\ninput_video = 'sea.mp4'\n\n# Get information\nprobe = ffmpeg.probe(input_video)\nvideo_info = next(s for s in probe['streams'] if s['codec_type'] == 'video')\nwidth = int(video_info['width'])\nheight = int(video_info['height'])\nfps = round(eval(video_info['avg_frame_rate']))\nprint(f'Fps: {fps}, Width: {width}, Height: {height}')\n\n### Convert video to 1 key-frame avi\nno_key_video = 'no_key_frames.avi'\nconvert_to_avi(input_video, no_key_video, fps, 0, 5)\n\n\n## Input video\ncontainer = get_reader(no_key_video)\n\n## Ouput video\noutput_container, output_stream = get_writer('moshed_videos/pyav_output.mp4', width, height, fps)\n\ntemp_file = 'moshed_videos/temp_packets.mp4'\n\ntemp_output_container, tmp_strm = get_writer(temp_file, width, height, fps)\n\nf_index = 0\nfor packet in container.demux():\n if packet.stream.type == 'video':\n ## I am converting every video to have only 1 key-frame\n if packet.is_keyframe:\n ## Extract full frame and deep dream\n for frame in packet.decode():\n print(frame)\n img = np.asarray(frame.to_image())\n result = transform_img(img, iterations=10, repeats=4)\n new_frame = av.VideoFrame.from_ndarray(result, format='rgb24')\n ## Add frame to streams\n write_frame(output_container, output_stream, new_frame)\n write_frame(temp_output_container, tmp_strm, new_frame)\n\n # Every frame other than the first is not a key-frame\n else:\n ## Put p-frame into temp stream\n temp_output_container.mux_one(packet)\n temp_output_container.close()\n\n # Now read full frame from temp\n temp_input_container = av.open(temp_file, 'r')\n\n last_frame = None\n for packet in temp_input_container.demux():\n if packet.stream.type == 'video':\n for frame in packet.decode():\n print(frame)\n last_frame = frame\n img = np.asarray(frame.to_image())\n print(img.shape)\n\n # Get transformed img\n result = transform_img(img, iterations=10)\n\n new_frame = av.VideoFrame.from_ndarray(result, format='rgb24')\n\n # Reopen output\n temp_output_container, tmp_strm = get_writer(temp_file, width, height, fps)\n ## Add frame to streams\n write_frame(output_container, output_stream, new_frame)\n write_frame(temp_output_container, tmp_strm, new_frame)\n\n print('Did frame:', f_index)\n f_index += 1\noutput_container.close()\n","sub_path":"pyav.py","file_name":"pyav.py","file_ext":"py","file_size_in_byte":3881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"409943304","text":"import sys\nimport numpy as np\nfrom Bio import SeqIO\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport pylab as pl\nfrom matplotlib import collections as mc\nfrom matplotlib.colors import ListedColormap\n\nSTATE = ['A+', 'A-', 'G+', 'G-', 'C+', 'C-', 'T+', 'T-', 'N+', 'N-'] \nOBS = ['A', 'G', 'C', 'T', 'N']\n\n\ndef load_cpg(fpath):\n \"\"\"\n rtn type: pandas DataFrame\n \"\"\"\n columns = ['bin','chrom','chromStart','chromEnd','name','length','cpgNum','gcNum','perCpg','perGc','obsExp']\n cpg = pd.read_csv(fpath,sep='\\t', names = columns)\n return cpg\n\n\ndef sample_seq(chr_seq, cpg_df, start, end):\n \"\"\"\n sample a subseq from chromosome and build cpg_df for it\n \"\"\"\n seq = chr_seq[start:end]\n cpg_sample = []\n for i in range(len(cpg_df)):\n if start < cpg_df.iloc[i]['chromStart'] and cpg_df.iloc[i]['chromEnd'] < end:\n cpg_sample.append([cpg_df.iloc[i]['chromStart']-start, cpg_df.iloc[i]['chromEnd']-start])\n elif cpg_df.iloc[i]['chromStart'] < start < cpg_df.iloc[i]['chromEnd']:\n cpg_sample.append([0, cpg_df.iloc[i]['chromEnd']-start])\n elif cpg_df.iloc[i]['chromStart'] < end < cpg_df.iloc[i]['chromEnd']:\n cpg_sample.append([cpg_df.iloc[i]['chromStart']-start, end-start])\n cpg_df_sample = pd.DataFrame(cpg_sample, columns=['chromStart','chromEnd'])\n return seq, cpg_df_sample\n\n\ndef getFreq(seq, cpg_df):\n \"\"\"\n count the transitions frequencies and nucleotide frequencies\n \"\"\"\n cpg_df = cpg_df.sort_values(by=['chromStart'])\n cpg_starts = cpg_df['chromStart']\n cpg_ends = cpg_df['chromEnd']\n d = {c:{s:c+s for s in ['+','-']} for c in OBS}\n # initialize counter\n pseudo_count = 0\n transition = {n_prev:{n_next:pseudo_count for n_next in STATE} for n_prev in STATE}\n prior = {s:pseudo_count for s in STATE}\n # count\n state = '-' # indicator of whether i is in CpG or not\n idx = 0 # index of cpg info\n state_prev = seq[0] + state\n for i in range(len(seq)):\n # if i % 1000000 == 0:\n # print(i)\n if idx < cpg_df.shape[0]:\n if i == cpg_starts[idx]:\n state = '+'\n if i == cpg_ends[idx]:\n state = '-'\n idx += 1\n # count transition\n state_next = d[seq[i]][state]\n transition[state_prev][state_next] += 1\n state_prev = state_next\n # count prior\n prior[d[seq[i]][state]] += 1\n return pd.DataFrame(transition), pd.Series(prior)\n\n\ndef getLogTransitionProb(freq):\n \"\"\"\n freq: pandas DataFrame, transition frequencies\n \"\"\"\n neg_inf = 1e-30\n #freq = freq.drop(columns=['N+','N-'],index=['N+','N-'])\n prob = freq / np.sum(freq, axis = 0) + neg_inf\n return np.log(prob)\n\n\ndef getLogPriorProb(prior_count):\n \"\"\"\n prior_count: pandas Series, nucleotide frequencies\n \"\"\"\n neg_inf = 1e-30\n prob = prior_count / np.sum(prior_count) + neg_inf\n return np.log(prob)\n\n\ndef viterbi(seq, log_trans_prob, log_prior_prob):\n path = []\n prob_mem = {j : { i : 0 for i in STATE} for j in range(len(seq))}\n prev_state_mem = {j : { i : None for i in STATE} for j in range(len(seq))}\n state_dict = {\"A\" : {\"A+\", \"A-\"}, \"T\" : {\"T+\", \"T-\"}, \"G\" : {\"G+\", \"G-\"}, \"C\" : {\"C+\", \"C-\"}}\n # prior\n for s in STATE:\n prob_mem[0][s] = log_prior_prob[s]\n #\n for i in range(1,len(seq)):\n cur_state = state_dict[seq[i]]\n for cur in cur_state:\n max_prob = -np.inf\n max_prev = -1\n for prev in STATE:\n p = prob_mem[i - 1][prev] + log_trans_prob[prev][cur] + 0\n if p > max_prob:\n max_prob = p\n max_prev = prev \n prob_mem[i][cur] = max_prob\n prev_state_mem[i][cur] = max_prev\n for s in STATE:\n if s not in cur_state:\n prob_mem[i][s] = -np.inf\n #\n cur_prob = prob_mem[len(seq) - 1]\n max_prob = max(cur_prob.values())\n best_score = max_prob\n for s in cur_prob.keys():\n if cur_prob[s] == max_prob:\n max_state = s\n path.append(max_state)\n #\n for i in range(len(seq) - 1, 0, -1):\n prev_max_state = prev_state_mem[i][max_state]\n path.append(prev_max_state)\n max_state = prev_max_state\n #\n result_path = path[::-1]\n return result_path, best_score\n\n\ndef path2cpg(result_path):\n \"\"\"\n build cpg dataframe from resulting hidden state sequence\n \"\"\"\n cpg_df = []\n cpg_state = ''\n for idx in range(len(result_path)):\n if result_path[idx][1] == '+' and cpg_state != '+':\n cpg_state = '+'\n start = idx\n if result_path[idx][1] == '-' and cpg_state == '+':\n cpg_state = '-'\n end = idx\n cpg_df.append([start, end])\n if cpg_state == '+':\n cpg_df.append([start, len(result_path)])\n if len(cpg_df) > 0:\n return pd.DataFrame(np.array(cpg_df), columns=['chromStart', 'chromEnd'])\n else:\n return pd.DataFrame(columns=['chromStart', 'chromEnd'])\n\n\n\ndef getCpgInfo(cpg_df, seq):\n \"\"\"\n extract CpG information from predicted CpG islands\n \"\"\"\n cpg_df['length'] = np.nan\n cpg_df['cpgNum'] = np.nan\n cpg_df['gcNum'] = np.nan\n cpg_df['perCpg'] = np.nan\n cpg_df['perGc'] = np.nan\n cpg_df['obsExp'] = np.nan\n info = cpg_df.values\n for idx in range(len(cpg_df)):\n start = info[idx,0]\n end = info[idx,1]\n subseq = seq[int(start):int(end)]\n length = end - start\n cpgNum = len(subseq.split('CG')) - 1\n gNum = np.sum(np.array(list(subseq)) == 'G')\n cNum = np.sum(np.array(list(subseq)) == 'C')\n obsExp = cpgNum * length / (gNum * cNum)\n info[idx,2] = length\n info[idx,3] = cpgNum\n info[idx,4] = gNum + cNum\n info[idx,5] = (2 * cpgNum / length) * 100\n info[idx,6] = ((gNum + cNum) / length) * 100\n info[idx,7] = obsExp\n return pd.DataFrame(info, columns=cpg_df.columns)\n\n\n\ndef iou(start1, end1, start2, end2):\n if start1 < end1 < start2 < end2:\n return 0\n elif start2 < end2 < start1 < end1: \n return 0\n else:\n intersect = min(end1, end2) - max(start1, start2)\n union = max(end1, end2) - min(start1, start2)\n return intersect / union\n\n\ndef score(cpg_gt, cpg_pred, thresholds=[0.5]):\n \"\"\"\n scoring function\n \"\"\"\n if len(cpg_gt) == 0:\n print(\"Aborted: ground truth does not contain any CpG islands.\")\n return np.nan\n iou_matrix = np.zeros((len(cpg_gt), len(cpg_pred)))\n for i in range(len(cpg_gt)):\n for j in range(len(cpg_pred)):\n iou_matrix[i,j] = iou(cpg_gt.iloc[i]['chromStart'], cpg_gt.iloc[i]['chromEnd'], cpg_pred.iloc[j]['chromStart'], cpg_pred.iloc[j]['chromEnd'])\n scores = []\n for threshold in thresholds:\n match = (iou_matrix > threshold) * 1\n TP = np.sum(np.sum(match))\n FP = len(cpg_pred) - TP\n FN = len(cpg_gt) - TP\n scores.append(TP / (TP + FP + FN))\n return np.sum(scores) / len(thresholds)\n\n\ndef seqwiseGcPer(seq, win_size = 200):\n num_win = int(np.ceil(len(seq) / win_size))\n perGc_list = np.zeros(num_win)\n perCpg_list = np.zeros(num_win)\n for idx in range(num_win):\n subseq = seq[idx * win_size:(idx + 1) * win_size]\n perGc = (np.sum(np.array(list(subseq)) == 'G') + np.sum(np.array(list(subseq)) == 'C')) / win_size * 100\n perCpg = (len(subseq.split('CG')) - 1) * 2 / win_size * 100\n perGc_list[idx] = perGc\n perCpg_list[idx] = perCpg\n return perCpg_list, perGc_list\n\n\ndef visualize(gt_cpg, pred_cpg, perGc_list, win_size): #line1 = []\n gt_line= []\n pred_line = []\n for i in range(len(pred_cpg)):\n s = pred_cpg.iloc[i]['chromStart']\n e = pred_cpg.iloc[i]['chromEnd']\n pred_line.append(s)\n pred_line.append(e)\n pred_y = [1] * len(pred_line)\n pred_line = list(zip(pred_line, pred_y))\n pred_line = [pred_line[x:x + 2] for x in range(0, len(pred_line), 2)]\n for i in range(len(gt_cpg)):\n s = gt_cpg.iloc[i]['chromStart']\n e = gt_cpg.iloc[i]['chromEnd']\n gt_line.append(s)\n gt_line.append(e)\n #print start, end\n gt_y = [0] * len(gt_line)\n gt_line = list(zip(gt_line, gt_y))\n gt_line = [gt_line[x:x + 2] for x in range(0, len(gt_line), 2)]\n # zip into tuple\n x = np.linspace(0, win_size*len(perGc_list), len(perGc_list))\n perGc_list = list(zip(x, perGc_list/100))\n perGc_list = [perGc_list[x:x + 2] for x in range(0, len(perGc_list), 1)]\n # colors = [mcolors.to_rgba(c) for c in plt.rcParams['axes.prop_cycle'].by_key()['color']]\n gc = mc.LineCollection(gt_line, colors = 'c', linewidths=3, label = 'Grounded CPG Islands')\n lc = mc.LineCollection(pred_line, colors= 'm', linewidths=3, label ='Predicted CPG Islands' )\n gcp = mc.LineCollection(perGc_list, colors= 'k', linewidths=1, label ='CG Percent in Sequence' )\n cMap = ListedColormap(['white', 'green', 'blue', 'red'])\n #ax.legend((pred_line, gt_line), ('Predicted CPG', 'Grouded CPG'))\n fig, ax1 = pl.subplots(2, sharex=True)\n ax1[1].set_xlim(0, 100000)\n ax1[1].set_yticklabels(list([\"0\", \"0.2\", \"0.4\", \"0.6\", \"0.8\",\"1.0\"]), minor=False)\n ax1[1].set_ylim(-0.5, 2.5)\n ax1[1].add_collection(lc)\n ax1[1].add_collection(gc)\n ax1[0].add_collection(gcp)\n # ax1[0].set_ylabels(\"Cg Percent\", minor=False)\n ax1[1].set_ylim(-0.5, 2.5)\n ax1[1].legend(frameon=False, loc='upper left', shadow = 'True', title=\"Predicted results v.s Grounded Truth\")\n #ax1.autoscale()\n ax1[0].set_title('CG Percent in Squence')\n #ax.xlabel('Sequence Index')\n # heatmap = ax1[0].pcolor(perGc_list, cmap=cMap)\n # cbar = plt.colorbar(heatmap)\n # cbar.ax.set_yticklabels(['0', '0.25', '0.5', '> 0.75'])\n # cbar.set_label('Percentage of CG', rotation=270)\n pl.show()\n\n\n\n\nif __name__ == '__main__':\n if len(sys.argv) == 5:\n train_start = int(sys.argv[1])\n train_end = int(sys.argv[2])\n test_start = int(sys.argv[3])\n test_end = int(sys.argv[4])\n elif len(sys.argv) == 1:\n train_start = 2500000\n train_end = 3500000\n test_start = 1600000\n test_end = 1700000\n else:\n print(\"Argument Error: predictCPG.py accpets 0 or 4 parameters.\")\n\n seqPath = 'data/chr1.fa'\n cpgPath = 'data/hg38-cpgIslandExt.txt'\n outputPath = './output/predicted_CpG.csv'\n \n print(\"Loading dataset...\")\n chr = SeqIO.read(seqPath,'fasta')\n chr_id = chr.id\n chr_seq = chr.seq.upper()\n cpg_df = load_cpg(cpgPath)\n cpg_df_chr1 = cpg_df[cpg_df['chrom'] == chr_id]\n print(\"Loading complete.\")\n\n train_seq, train_cpg = sample_seq(chr_seq, cpg_df_chr1, start=train_start, end=train_end) \n test_seq, test_cpg = sample_seq(chr_seq, cpg_df_chr1, start=test_start, end=test_end)\n\n print(\"Getting transition matrix and prior...\")\n transitionFreq, priorFreq = getFreq(train_seq, train_cpg)\n log_trans_prob = getLogTransitionProb(transitionFreq)\n log_prior_prob = getLogPriorProb(priorFreq)\n print(\"Transition matrix and prior built.\")\n\n print(\"Running viterbi to predict hidden states...\")\n pred_path, best_score = viterbi(test_seq, log_trans_prob, log_prior_prob)\n pred_cpg = path2cpg(pred_path)\n pred_cpg = getCpgInfo(pred_cpg, test_seq)\n pred_cpg.to_csv(outputPath)\n print(\"Prediction complete.\")\n\n print(\"Predicted CpG Island Info:\")\n print(pred_cpg)\n print(\"Detection Score: %s\" %score(test_cpg, pred_cpg, thresholds = [0.5]))\n\n print(\"Visualization: \")\n perCpg_list, perGc_list = seqwiseGcPer(test_seq, 200)\n win_size = 200\n visualize(test_cpg, pred_cpg, perGc_list, win_size)\n\n\n","sub_path":"predictCPG.py","file_name":"predictCPG.py","file_ext":"py","file_size_in_byte":11773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"447997934","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef zero_pad(X, pad):\n \"\"\"\n Pad with zeros all images of the dataset X. The padding is applied to the height and width of an image,\n as illustrated in Figure 1.\n\n Argument:\n X -- python numpy array of shape (m, n_H, n_W, n_C) representing a batch of m images\n pad -- integer, amount of padding around each image on vertical and horizontal dimensions\n\n Returns:\n X_pad -- padded image of shape (m, n_H + 2*pad, n_W + 2*pad, n_C)\n \"\"\"\n\n ### START CODE HERE ### (≈ 1 line)\n X_pad = np.pad(X, ((0, 0), (pad, pad), (pad, pad), (0, 0)), mode='constant', constant_values=(0, 0))\n ### END CODE HERE ###\n\n return X_pad\n\n\ndef conv_single_step(a_slice_prev, W, b):\n \"\"\"\n Apply one filter defined by parameters W on a single slice (a_slice_prev) of the output activation\n of the previous layer.\n\n Arguments:\n a_slice_prev -- slice of input data of shape (f, f, n_C_prev)\n W -- Weight parameters contained in a window - matrix of shape (f, f, n_C_prev)\n b -- Bias parameters contained in a window - matrix of shape (1, 1, 1)\n\n Returns:\n Z -- a scalar value, the result of convolving the sliding window (W, b) on a slice x of the input data\n \"\"\"\n\n ### START CODE HERE ### (≈ 2 lines of code)\n # Element-wise product between a_slice_prev and W. Do not add the bias yet.\n s = a_slice_prev * W\n # Sum over all entries of the volume s.\n Z = np.sum(s)\n # Add bias b to Z. Cast b to a float() so that Z results in a scalar value.\n Z = Z + float(b)\n ### END CODE HERE ###\n\n return Z\n\n\ndef conv_forward(A_prev, W, b, hparameters):\n \"\"\"\n Implements the forward propagation for a convolution function\n\n Arguments:\n A_prev -- output activations of the previous layer,\n numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev)\n W -- Weights, numpy array of shape (f, f, n_C_prev, n_C)\n b -- Biases, numpy array of shape (1, 1, 1, n_C)\n hparameters -- python dictionary containing \"stride\" and \"pad\"\n\n Returns:\n Z -- conv output, numpy array of shape (m, n_H, n_W, n_C)\n cache -- cache of values needed for the conv_backward() function\n \"\"\"\n\n ### START CODE HERE ###\n # Retrieve dimensions from A_prev's shape (≈1 line)\n (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape\n\n # Retrieve dimensions from W's shape (≈1 line)\n (f, f, n_C_prev, n_C) = W.shape\n\n # Retrieve information from \"hparameters\" (≈2 lines)\n stride = hparameters['stride']\n pad = hparameters['pad']\n\n # Compute the dimensions of the CONV output volume using the formula given above.\n # Hint: use int() to apply the 'floor' operation. (≈2 lines)\n n_H = int((n_H_prev - f + 2 * pad) / stride) + 1\n n_W = int((n_W_prev - f + 2 * pad) / stride) + 1\n\n # Initialize the output volume Z with zeros. (≈1 line)\n Z = np.zeros((m, n_H, n_W, n_C))\n\n # Create A_prev_pad by padding A_prev\n A_prev_pad = zero_pad(A_prev, pad)\n\n for i in range(m): # loop over the batch of training examples\n a_prev_pad = A_prev_pad[i, :, :, :] # Select ith training example's padded activation\n for h in range(n_H): # loop over vertical axis of the output volume\n # Find the vertical start and end of the current \"slice\" (≈2 lines)\n vert_start = h * stride\n vert_end = vert_start + f\n\n for w in range(n_W): # loop over horizontal axis of the output volume\n # Find the horizontal start and end of the current \"slice\" (≈2 lines)\n horiz_start = w * stride\n horiz_end = horiz_start + f\n\n for c in range(n_C): # loop over channels (= #filters) of the output volume\n\n # Use the corners to define the (3D) slice of a_prev_pad (See Hint above the cell). (≈1 line)\n a_slice_prev = a_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :]\n\n # Convolve the (3D) slice with the correct filter W and bias b, to get back one output neuron. (≈3 line)\n weights = W[:, :, :, c]\n biases = b[:, :, :, c]\n Z[i, h, w, c] = conv_single_step(a_slice_prev, weights, biases)\n\n ### END CODE HERE ###\n\n # Making sure your output shape is correct\n assert (Z.shape == (m, n_H, n_W, n_C))\n\n # Save information in \"cache\" for the backprop\n cache = (A_prev, W, b, hparameters)\n\n return Z, cache\n\ndef edge_filter(image, explicit_factor=2, stride = 5, pad = 0):\n\n # create kernel\n kernel = np.ones((3, 3)) * (-1 / 8)\n kernel[1][1] = 1\n kernel = kernel.reshape(3, 3, 1, 1)\n '''kernel = np.zeros((3, 3))\n kernel[0][0] = 1/4\n kernel[1][0] = 1/2\n kernel[2][0] = 1/4\n kernel[0][2] = -1/4\n kernel[1][2] = -1/2\n kernel[2][2] = -1/4\n kernel = kernel.reshape(3, 3, 1, 1)'''\n\n # plot raw image\n if image.shape[0] != 3:\n plt.subplot(1, 2, 1)\n plt.imshow(image)\n\n # convolve for each channel\n for channel in range(2):\n if image.shape[0] == 3:\n channel_of_image = image[channel] # shape of image in cifar: (3, 32, 32)\n else:\n channel_of_image = image[:, :, channel] # shape of user image: (X, Y, 3)\n channel_of_image = channel_of_image.reshape(1, channel_of_image.shape[0], channel_of_image.shape[1], 1)\n channel_convolved, _ = conv_forward(channel_of_image, kernel, np.zeros((1, 1, 1, 1)), {'stride': stride, 'pad': pad})\n channel_convolved = (np.abs(channel_convolved) / 255 * explicit_factor)[0, :, :, :]\n if channel == 0:\n channels_convolved = channel_convolved\n else:\n channels_convolved = np.concatenate((channels_convolved, channel_convolved), axis=2)\n channels_convolved = np.max(channels_convolved, axis=2)\n # print('max intensity: ' + str(np.max(channels_convolved)))\n\n # plot edges\n plt.subplot(1, 2, 2)\n plt.imshow(channels_convolved)\n plt.show()","sub_path":"edge_filter.py","file_name":"edge_filter.py","file_ext":"py","file_size_in_byte":6008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"189524840","text":"from django.shortcuts import render, get_object_or_404, render_to_response\nfrom django.http import HttpResponse, Http404, HttpResponseRedirect\nfrom django.template import RequestContext, loader\nfrom CalPages.models import Calendar, Event\nfrom django.views import generic\nfrom django.utils import timezone\nfrom django.contrib.auth import authenticate, login, logout #login and logout\nfrom CalPages.forms import eventForm #for create view\nfrom django.core.context_processors import csrf\n\n#display a page with all of the calendars that exist on it\ndef index(request):\n allCal = Calendar.objects.all()\n template = loader.get_template('CalPages/index.html')\n context = RequestContext(request, {'allCal': allCal,})\n context = addBaseVars(request,context)\n return HttpResponse(template.render(context))\n\ndef patch(request):\n template = loader.get_template('CalPages/patches.html')\n dictionary = {}\n dictionary.update({'pageName':'patch'})\n dictionary = addBaseVars(request, dictionary)\n context = RequestContext(request, dictionary)\n return HttpResponse(template.render(context))\n\ndef test(request, calpk):\n cal = Calendar.objects.get(pk=calpk)\n allEvents = Event.objects.all()\n events =[]\n for each in allEvents:\n if each.memberOf == cal:\n events.append(each)\n template = loader.get_template('CalPages/JScal.html')\n context = RequestContext(request, {'events':events, })\n return HttpResponse(template.render(context))\n\n#diaplay all of the events which appear on a specific calendar\ndef calendar(request, calpk):\n cal = Calendar.objects.get(pk=calpk)\n allEvents = Event.objects.all()\n events =[]\n for each in allEvents:\n if each.memberOf == cal:\n events.append(each)\n template = loader.get_template('CalPages/calendar.html')\n context = RequestContext(request, {'events':events, })\n return HttpResponse(template.render(context))\n\n#V#V#V#not ready. no url pointing towards them\n#show specifics on on a given event.\ndef event(request, eventpk):\n template = loader.get_template('CalPages/details.html')\n EventToPrint = Event.objects.get(pk=eventpk)\n context = RequestContext(request, {'event': EventToPrint,})\n return HttpResponse(template.render(context))\n #return HttpResponse(\"You are attempting to view the deails page for an for the specific event that you are attempting to view is %s.\" % eventpk )\n\n\n#show events in the area of the user.\ndef browse(request):\n template = loader.get_template('CalPages/browseConnect.html')\n dictionary = {}\n dictionary.update({'pageName':'browse'})\n dictionary = addBaseVars(request, dictionary)\n context = RequestContext(request, dictionary)\n return HttpResponse(template.render(context))\n\n\ndef addBaseVars(request, thingies):#Used without URL called by other views\n#adds the variabels to context like username that are used for all sites which load the base site. Variables like pageName will be specific to the page so, despite the fact that they are used by base.html you will find them in the specific view\n thingies.update({'full_name':request.user.username})\n \n return thingies\n\ndef about(request):\n template = loader.get_template('CalPages/about.html')\n dictionary = {}\n dictionary.update({'pageName':'about'})\n dictionary = addBaseVars(request, dictionary)\n context = RequestContext(request, dictionary)\n return HttpResponse(template.render(context))\n\ndef connect(request):#URL: CalPages/connect | Template: calendar.html\n template = loader.get_template('CalPages/calendar.html')\n dictionary = {}\n dictionary.update({'pageName':'connect'})\n dictionary = addBaseVars(request, dictionary)\n context = RequestContext(request, dictionary)\n return HttpResponse(template.render(context))\n\ndef manage(request): #URL: CalPages/manage | Template: calendar.html\n template = loader.get_template('CalPages/calendar.html')\n dictionary = {}\n dictionary.update({'pageName':'manage'})\n dictionary = addBaseVars(request, dictionary)\n context = RequestContext(request, dictionary)\n return HttpResponse(template.render(context))\n\ndef create(request):\n dictionary = {}\n dictionary = addBaseVars(request,dictionary)\n if request.POST:\n form= eventForm(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect('/CalPages/')\n else:\n form = eventForm()\n dictionary.update(csrf(request))\n dictionary['form'] = form\n return render_to_response('Calpages/createManage.html',dictionary)\n\ndef contact(request):\n template = loader.get_template('CalPages/contact.html')\n dictionary = {}\n dictionary.update({'pageName':'email'})\n dictionary = addBaseVars(request, dictionary)\n context = RequestContext(request, dictionary)\n return HttpResponse(template.render(context))\n\n","sub_path":"CalPages/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"567346831","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport csv\n\nfile = open(\"quantities.csv\", \"r\");\na = np.array(list(csv.reader(file, delimiter=' ')), dtype=float)\n\nplt.title(\"Magnetization\")\nplt.xlabel(\"T\")\nplt.ylabel(\"M\")\nplt.plot(a[:, 0], a[:, 1],'.')\nplt.axvline(2.69, c='r', ls='--')\nplt.show()\n\nplt.title(\"Energy\")\nplt.xlabel(\"T\")\nplt.ylabel(\"E\")\nplt.plot(a[:, 0], a[:, 2],'.')\nplt.axvline(2.69, c='r', ls='--')\nplt.show()\n\nplt.title(\"Susceptibility\")\nplt.xlabel(\"T\")\nplt.ylabel(\"X\")\nplt.plot(a[:, 0], a[:, 3],'.')\nplt.axvline(2.69, c='r', ls='--')\nplt.show()\n\nplt.title(\"Specific Heat\")\nplt.xlabel(\"T\")\nplt.ylabel(\"C\")\nplt.plot(a[:, 0], a[:, 4],'.')\nplt.axvline(2.69, c='r', ls='--')\nplt.show()\n\nt = (2.69-a[:,0]) / 2.69\nplt.title(\"Log-log Plot of Magnetization versus Reduced Temperature\")\nplt.xlabel(\"(Tc-T)/Tc\")\nplt.ylabel(\"M\")\nplt.loglog(t, a[:, 1], \".\")\nplt.show()\n\nt = np.abs(2.69-a[:,0]) / 2.69\nplt.title(\"Log-log Plot of Susceptibility versus Reduced Temperature\")\nplt.xlabel(\"|T-Tc|/Tc\")\nplt.ylabel(\"X\")\nplt.loglog(t, a[:, 3], \".\")\nplt.show()\n","sub_path":"Ising_MCS/plot_quantities.py","file_name":"plot_quantities.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"587879115","text":"\"\"\"\nwidget which handles the creation of linear models and determining the gains\n\"\"\"\n\nimport PyQt5.QtCore as QtCore\nimport PyQt5.QtGui as QtGui\nimport PyQt5.QtWidgets as QtWidgets\n\nfrom ..Controls import VehiclePerturbationModels\nfrom ..Containers import Controls\nfrom ..Containers import Linearized\nfrom ..Controls import VehicleControlGains\nfrom ..Constants import VehiclePhysicalConstants\nimport sys\nimport os\nimport datetime\n\nimport math\nimport threading\nimport pickle\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport time\n\ntestGainsFileName = 'LastGainsTest.png'\ntestNumSteps = 1000\n\nlateralNames = ['Wn_roll', 'Zeta_roll', 'Wn_course', 'Zeta_course', 'Wn_sideslip', 'Zeta_sideslip']\nlongitudinalNames = ['Wn_pitch', 'Zeta_pitch', 'Wn_altitude','Zeta_altitude', 'Wn_SpeedfromThrottle',\n 'Zeta_SpeedfromThrottle', 'Wn_SpeedfromElevator', 'Zeta_SpeedfromElevator']\n\ngainNames = ['kp_roll', 'kd_roll', 'ki_roll', 'kp_sideslip', 'ki_sideslip', 'kp_course', 'ki_course',\n\t\t\t\t'kp_pitch', 'kd_pitch', 'kp_altitude', 'ki_altitude', 'kp_SpeedfromThrottle', 'ki_SpeedfromThrottle',\n 'kp_SpeedfromElevator', 'ki_SpeedfromElevator']\nlongitudinalGainNames = []\n\ndefaultTuningParameterFileName = \"VehicleTuningParameters_Data.pickle\"\ndefaultGainsFileName = \"VehicleGains_Data.pickle\"\n\ngainTypes = ['Roll', 'SideSlip', 'Course', 'Pitch', 'Altitude', 'Speed']\nrollNames = ['kp_roll', 'kd_roll', 'ki_roll']\nsideslipNames = ['kp_sideslip', 'ki_sideslip']\ncourseNames = ['kp_course', 'ki_course']\npitchNames = ['kp_pitch', 'kd_pitch']\naltitudeNames = ['kp_altitude', 'ki_altitude']\nspeedNames = ['kp_SpeedfromThrottle', 'ki_SpeedfromThrottle', 'kp_SpeedfromElevator', 'ki_SpeedfromElevator']\n\n\nclass displayGainsTest(QtWidgets.QDialog):\n\tdef __init__(self, imagePath, parent=None):\n\t\tsuper().__init__(parent)\n\t\tself.usedLayout = QtWidgets.QVBoxLayout()\n\t\tself.setLayout(self.usedLayout)\n\t\tself.setWindowTitle(\"Test of Control Gains\")\n\t\tself.gainResponse = QtWidgets.QLabel(\"sls\")\n\t\tself.gainResponse.setPixmap(QtGui.QPixmap(imagePath))\n\t\tself.gainResponse.setScaledContents(True)\n\t\tself.gainResponse.setSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored)\n\t\tself.setMinimumSize(1280, 960)\n\n\t\tself.usedLayout.addWidget(self.gainResponse)\n\nclass controlGainsWidget(QtWidgets.QWidget):\n\ttestFinishedSignal = QtCore.pyqtSignal(bool)\n\tdef __init__(self, guiControls, callBackOnSuccesfulGains=None, parent=None):\n\t\tsuper().__init__(parent)\n\t\tself.parentInstance = parent\n\t\t# self.perturbationInstance = VehiclePerturbationModels.VehiclePerturbation()\n\t\t# self.gainsInstance = VehicleControlGains.VehicleControlGains()\n\t\tself.curGains = Controls.controlGains()\n\t\tself.curParameters = Controls.controlTuning()\n\t\tself.callBackOnSuccesfulGains = callBackOnSuccesfulGains\n\t\tself.usedLayout = QtWidgets.QVBoxLayout()\n\t\tself.setLayout(self.usedLayout)\n\t\tself.currentLinearModel = Linearized.transferFunctions\n\n\t\tself.testWindow = None\n\n\t\ttopBoxEnclosure = QtWidgets.QHBoxLayout()\n\t\tself.usedLayout.addLayout(topBoxEnclosure)\n\n\t\ttuningBox = QtWidgets.QVBoxLayout()\n\t\ttuningBox.addWidget(QtWidgets.QLabel(\"Tuning Parameters\"))\n\t\tcontrolBox = QtWidgets.QVBoxLayout()\n\t\t# outputBox.addWidget(QLabel(\"Calculated Gains\"))\n\t\tgainsBox = QtWidgets.QVBoxLayout()\n\t\tgainsBox.addWidget(QtWidgets.QLabel(\"Gains\"))\n\t\ttopBoxEnclosure.addLayout(tuningBox)\n\t\ttopBoxEnclosure.addLayout(controlBox)\n\t\ttopBoxEnclosure.addLayout(gainsBox)\n\t\ttopBoxEnclosure.addStretch()\n\n\t\t# self.ParameterTabs = QTabWidget()\n\t\t# self.usedLayout.addWidget(self.ParameterTabs)\n\n\t\t# self.lateralGainsWidget = QWidget()\n\t\t# self.ParameterTabs.addTab(self.lateralGainsWidget, \"Lateral Gains\")\n\n\t\t# lateralGainsLayout = QGridLayout()\n\t\t# self.lateralGainsWidget.setLayout(lateralGainsLayout)\n\t\tself.parameterGainValues = dict()\n\n\t\ttuningFormLayout = QtWidgets.QFormLayout()\n\t\ttuningBox.addLayout(tuningFormLayout)\n\t\ttuningBox.addStretch()\n\n\t\ttry:\n\t\t\twith open(os.path.join(sys.path[0], defaultTuningParameterFileName), 'rb') as f:\n\t\t\t\tsavedParameters = pickle.load(f)\n\t\texcept (FileNotFoundError, EOFError):\n\t\t\tsavedParameters = Controls.controlTuning()\n\t\t\tfor pName in lateralNames+longitudinalNames:\n\t\t\t\tsetattr(savedParameters, pName, 1)\n\n\t\tfor boxName, parNames in zip(['Lateral Autopilot', 'Longitudinal Autopilot'], [lateralNames, longitudinalNames]):\n\t\t\tsectionName = QtWidgets.QLabel(boxName)\n\t\t\tsectionName.setAlignment(QtCore.Qt.AlignLeft)\n\t\t\ttuningFormLayout.addRow(sectionName)\n\t\t\tfor parameterName in parNames:\n\t\t\t\t# newInput = doubleInputWithLabel.doubleInputWithLabel(parameterName)\n\t\t\t\tnewInput = QtWidgets.QLineEdit()\n\t\t\t\tnewValidator = QtGui.QDoubleValidator()\n\t\t\t\tnewInput.setValidator(newValidator)\n\t\t\t\tnewInput.setText(\"{}\".format(getattr(savedParameters, parameterName)))\n\t\t\t\ttuningFormLayout.addRow(parameterName, newInput)\n\t\t\t\t# inputBox.addWidget(newInput)\n\t\t\t\tself.parameterGainValues[parameterName] = newInput\n\n\t\tgainFormLayout = QtWidgets.QFormLayout()\n\t\tgainsBox.addLayout(gainFormLayout)\n\t\tself.gainValuesDict = dict()\n\n\t\tfor boxName, gainNames in zip(gainTypes, [rollNames, sideslipNames, courseNames, pitchNames, altitudeNames, speedNames]):\n\t\t\t# print(boxName, gainNames)\n\t\t\tsectionName = QtWidgets.QLabel(boxName)\n\t\t\tsectionName.setAlignment(QtCore.Qt.AlignLeft)\n\t\t\tgainFormLayout.addRow(sectionName)\n\t\t\tfor gainName in gainNames:\n\t\t\t\tnewInput = QtWidgets.QLineEdit()\n\t\t\t\tnewValidator = QtGui.QDoubleValidator()\n\t\t\t\tnewInput.setText(str(0.0))\n\t\t\t\tnewInput.setValidator(newValidator)\n\t\t\t\tgainFormLayout.addRow(gainName, newInput)\n\t\t\t\tself.gainValuesDict[gainName] = newInput\n\n\n\t\tgainsBox.addStretch()\n\n\t\tself.calcGainsButton = QtWidgets.QPushButton(\"Calculate Gains ->\")\n\t\tself.calcGainsButton.clicked.connect(self.calculateGainsResponse)\n\t\tcontrolBox.addWidget(self.calcGainsButton)\n\n\t\tself.calcParametersButton = QtWidgets.QPushButton(\"<- Calculate Parameters\")\n\t\tself.calcParametersButton.clicked.connect(self.calculateParametersResponse)\n\t\tcontrolBox.addWidget(self.calcParametersButton)\n\n\t\tapplyGainsButton = QtWidgets.QPushButton(\"Apply Gains\")\n\t\tapplyGainsButton.clicked.connect(self.applyGains)\n\t\tcontrolBox.addWidget(applyGainsButton)\n\n\t\tself.testGainsButton = QtWidgets.QPushButton(\"&Test Gains\")\n\t\tself.testGainsButton.clicked.connect(self.startTestGains)\n\t\tcontrolBox.addWidget(self.testGainsButton)\n\n\t\tself.saveGainsButton = QtWidgets.QPushButton(\"Save Parameters and Gains\")\n\t\tself.saveGainsButton.clicked.connect(self.saveParametersGainsResponse)\n\t\tcontrolBox.addWidget(self.saveGainsButton)\n\t\tcontrolBox.addStretch()\n\t\tself.statusText = QtWidgets.QLabel(\"No Info\")\n\t\tself.usedLayout.addWidget(self.statusText)\n\t\t# compression.addStretch()\n\n\n\t\tself.testFinishedSignal.connect(self.gainTestOverSignal)\n\t\t# self.gainsTextBox = QPlainTextEdit()\n\t\t# self.gainsTextBox.setReadOnly(True)\n\t\t# outputBox.addWidget(self.gainsTextBox)\n\t\t# outputBox.addStretch()\n\n\t\ttry:\n\t\t\twith open(os.path.join(sys.path[0], defaultGainsFileName), 'rb') as f:\n\t\t\t\tself.curGains = pickle.load(f)\n\t\t\tself.updateGainsDisplay(self.curGains)\n\t\texcept (FileNotFoundError, EOFError):\n\t\t\tpass\n\t\tself.usedLayout.addStretch()\n\n\tdef createLinearizedModels(self, trimState=None, trimInput=None):\n\t\tif trimState is None:\n\t\t\ttrimState = self.perturbationInstance.trimState\n\t\tif trimInput is None:\n\t\t\ttrimInput = self.perturbationInstance.trimInputs\n\t\ttry:\n\t\t\tself.currentLinearModel = VehiclePerturbationModels.CreateTransferFunction(trimState, trimInput)\n\t\texcept Exception:\n\t\t\timport traceback\n\t\t\tself.parentInstance.raiseExceptionToUser(traceback.format_exc())\n\t\t\treturn\n\t\tself.statusText.setText(\"Linearized Models Made at {}\".format(datetime.datetime.now()))\n\t\treturn\n\n\tdef calculateGainsResponse(self):\n\t\t\"\"\"\n\t\tcalculate the gains given the linear model here\n\n\t\t:return:\n\t\t\"\"\"\n\t\tnewParameters = Controls.controlTuning()\n\t\tfor parameter in lateralNames+longitudinalNames:\n\t\t\tif hasattr(newParameters, parameter):\n\t\t\t\tsetattr(newParameters, parameter, float(self.parameterGainValues[parameter].text()))\n\t\t\telse:\n\t\t\t\tprint(parameter)\n\t\t# with open(os.path.join(sys.path[0], defaultTuningParameterFileName), 'wb') as f:\n\t\t# \tpickle.dump(newParameters, f)\n\t\t# self.gainsInstance.setLinearizedModel(self.perturbationInstance.transferFunction)\n\t\t# self.gainsInstance.computeGains(newParameters)\n\t\ttry:\n\t\t\tself.curGains = VehicleControlGains.computeGains(newParameters, self.currentLinearModel)\n\t\texcept Exception:\n\t\t\timport traceback\n\t\t\tself.parentInstance.raiseExceptionToUser(traceback.format_exc())\n\t\t\treturn\n\t\tself.updateGainsDisplay(self.curGains)\n\t\tself.statusText.setText((\"Gains Calculated\"))\n\t\tif self.callBackOnSuccesfulGains is not None:\n\t\t\tself.callBackOnSuccesfulGains()\n\t\treturn\n\n\tdef calculateParametersResponse(self):\n\t\t\"\"\"\n\t\tcalculate the gains given the linear model here\n\n\t\t:return:\n\t\t\"\"\"\n\t\tnewGains = Controls.controlGains()\n\t\tfor gain in newGains.__dict__.keys():\n\t\t\tsetattr(newGains, gain, float(self.gainValuesDict[gain].text()))\n\n\t\t# with open(os.path.join(sys.path[0], defaultGainsFileName), 'wb') as f:\n\t\t# \tpickle.dump(newGains, f)\n\t\t# self.gainsInstance.setLinearizedModel(self.perturbationInstance.transferFunction)\n\t\t# self.gainsInstance.computeGains(newParameters)\n\t\ttry:\n\t\t\tself.curParameters = VehicleControlGains.computeTuningParameters(newGains, self.currentLinearModel)\n\t\texcept Exception:\n\t\t\timport traceback\n\t\t\tself.parentInstance.raiseExceptionToUser(traceback.format_exc())\n\t\t\treturn\n\t\tself.updateParametersDisplay(self.curParameters)\n\t\tself.statusText.setText((\"Parameters Calculated\"))\n\t\treturn\n\n\tdef updateGainsDisplay(self, newGains):\n\t\tfor name in gainNames:\n\t\t\tself.gainValuesDict[name].setText(str(getattr(newGains, name)))\n\n\tdef updateParametersDisplay(self, newParameters):\n\t\tfor name in newParameters.__dict__.keys():\n\t\t\tself.parameterGainValues[name].setText(str(getattr(newParameters, name)))\n\n\n\tdef applyGains(self):\n\t\tself.curGains = self.buildCurrentGains()\n\t\tif self.callBackOnSuccesfulGains is not None:\n\t\t\tself.callBackOnSuccesfulGains()\n\t\treturn\n\n\tdef saveParametersGainsResponse(self):\n\t\t\"\"\"\n\t\twe save the gains here\n\t\t\"\"\"\n\t\twith open(os.path.join(sys.path[0], defaultGainsFileName), 'wb') as f:\n\t\t\tpickle.dump(self.buildCurrentGains(), f)\n\t\twith open(os.path.join(sys.path[0], defaultTuningParameterFileName), 'wb') as f:\n\t\t\tpickle.dump(self.buildCurrentParameters(), f)\n\t\tself.statusText.setText(\"Parameters and Gains Saved\")\n\t\treturn\n\n\tdef buildCurrentGains(self):\n\t\tnewGains = Controls.controlGains()\n\t\tfor name in gainNames:\n\t\t\t# self.gainValuesDict[name].setText(str(getattr(newGains, name)))\n\t\t\ttry:\n\t\t\t\tsetattr(newGains, name, float(self.gainValuesDict[name].text()))\n\t\t\texcept ValueError:\n\t\t\t\tpass\n\t\treturn newGains\n\n\tdef buildCurrentParameters(self):\n\t\tnewGains = Controls.controlTuning()\n\t\tfor name in lateralNames+longitudinalNames:\n\t\t\t# self.gainValuesDict[name].setText(str(getattr(newGains, name)))\n\t\t\ttry:\n\t\t\t\tsetattr(newGains, name, float(self.parameterGainValues[name].text()))\n\t\t\texcept ValueError:\n\t\t\t\tpass\n\t\treturn newGains\n\n\tdef startTestGains(self):\n\t\tself.statusText.setText(\"Starting Gains Test\")\n\t\t# self.testWindow = displayGainsTest('LastGainsTest.png')\n\t\t# self.testWindow.open()\n\t\tself.curGains = self.buildCurrentGains()\n\t\tthreading.Thread(target=self.runGainsTest, daemon=True).start()\n\t\t# self.runGainsTest()\n\t\tself.testGainsButton.setDisabled(True)\n\t\treturn\n\n\tdef gainTestOverSignal(self, itFinished):\n\t\tself.testGainsButton.setDisabled(False)\n\t\tself.testWindow = displayGainsTest(testGainsFileName)\n\t\tself.statusText.setText('Test Run was Completed')\n\t\tself.testWindow.open()\n\t\treturn\n\n\tdef runGainsTest(self):\n\t\tsimInstance = self.parentInstance.simulateInstance\n\t\tsimInstance.reset() # reset the model\n\t\trefControls = self.parentInstance.referenceControl.currentReference # grab the controls for the run\n\n\t\tsimInstance.underlyingModel.setControlGains(self.curGains) # and make sure the gains are set\n\t\ttrimSettings = self.parentInstance.trimCalcWidget.currentTrimControls\n\n\t\twantedValues = dict()\n\n\t\twantedValues['chi'] = list()\n\t\twantedValues['Va'] = list()\n\t\twantedValues['pd'] = list()\n\t\twantedValues['cPitch'] = list()\n\t\twantedValues['aPitch'] = list()\n\t\twantedValues['cRoll'] = list()\n\t\twantedValues['aRoll'] = list()\n\t\twantedValues['Throttle'] = list()\n\t\twantedValues['Aileron'] = list()\n\t\twantedValues['Elevator'] = list()\n\t\twantedValues['Rudder'] = list()\n\n\t\tfor i in range(testNumSteps+1):\n\t\t\tsimInstance.takeStep(refControls)\n\t\t\tcurState = simInstance.getVehicleState()\n\n\t\t\twantedValues['chi'].append(math.degrees(curState.chi))\n\t\t\twantedValues['Va'].append(curState.Va)\n\t\t\twantedValues['pd'].append(-curState.pd)\n\n\t\t\twantedValues['cPitch'].append(math.degrees(refControls.commandedPitch))\n\t\t\twantedValues['aPitch'].append(math.degrees(curState.pitch))\n\n\t\t\twantedValues['cRoll'].append(math.degrees(refControls.commandedRoll))\n\t\t\twantedValues['aRoll'].append(math.degrees(curState.roll))\n\n\t\t\tActualControl = simInstance.underlyingModel.getVehicleControlSurfaces()\n\n\t\t\twantedValues['Throttle'].append(ActualControl.Throttle)\n\t\t\twantedValues['Aileron'].append(math.degrees(ActualControl.Aileron))\n\t\t\twantedValues['Elevator'].append(math.degrees(ActualControl.Elevator))\n\t\t\twantedValues['Rudder'].append(math.degrees(ActualControl.Rudder))\n\n\t\t# print(wantedValues)\n\t\tmatplotlib.use('agg')\n\t\tplotData = list()\n\t\tstaticLength = len(wantedValues['chi'])\n\t\tplotData.append([[math.degrees(refControls.commandedCourse)]*staticLength, wantedValues['chi'], 'Course'])\n\t\tplotData.append([[refControls.commandedAirspeed]*staticLength, wantedValues['Va'], 'Speed'])\n\t\tplotData.append([[refControls.commandedAltitude]*staticLength, wantedValues['pd'], 'Height'])\n\t\tplotData.append([wantedValues['cPitch'], wantedValues['aPitch'], 'Pitch'])\n\t\tplotData.append([wantedValues['cRoll'], wantedValues['aRoll'], 'Roll'])\n\t\tplotData.append([[trimSettings.Throttle]*staticLength, wantedValues['Throttle'], 'Throttle'])\n\t\tplotData.append([[math.degrees(trimSettings.Aileron)]*staticLength, wantedValues['Aileron'], 'Aileron'])\n\t\tplotData.append([[math.degrees(trimSettings.Elevator)]*staticLength, wantedValues['Elevator'], 'Elevator'])\n\t\tplotData.append([[math.degrees(trimSettings.Rudder)]*staticLength, wantedValues['Rudder'], 'Rudder'])\n\n\t\ttimeSteps = [VehiclePhysicalConstants.dT*x for x in range(staticLength)]\n\n\t\tfor index, (refValues, actualValues, plotName) in enumerate(plotData):\n\t\t\tplt.subplot(3, 4, index+1)\n\t\t\tref = plt.plot(timeSteps, refValues, label='Reference') # we want the colors to match for the legend\n\t\t\tact = plt.plot(timeSteps, actualValues, label='Actual')\n\t\t\tplt.title(plotName)\n\n\t\tplt.gcf().legend(handles=(ref[0], act[0]), labels=('Reference', 'Actual'), loc='lower center')\n\t\t# the oddity with the list is that even with single values it returns a list\n\t\t# and if you feed it a named argument, it can't parse it correctly\n\t\t# unnamed argument works but then matplotlib throws a warning\n\t\t# have to use named as many of them we do not wish to use.\n\n\t\tplt.tight_layout()\n\t\tplt.savefig(testGainsFileName, dpi=300)\n\n\t\tplt.close('all')\n\t\ttime.sleep(.25)\n\t\tself.testFinishedSignal.emit(True)\n\t\treturn","sub_path":"UAV_Payload_Delivery/CodeBase/ece163/Display/controlGainsWidget.py","file_name":"controlGainsWidget.py","file_ext":"py","file_size_in_byte":15105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"565689202","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3351)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/philanim/PycharmProjects/trelloreporter/trelloreporter/writer/excel.py\n# Compiled at: 2017-12-20 06:37:50\n# Size of source mod 2**32: 14072 bytes\nimport asyncio, logging, uvloop\nfrom openpyxl import Workbook\nfrom openpyxl.styles import NamedStyle\nfrom openpyxl.styles.cell_style import CellStyle\nfrom trelloreporter.rest import trello\n\nclass TrelloReader(object):\n\n def __init__(self):\n \"\"\"\n\n \"\"\"\n self._reader = trello.TrelloRest()\n self._cards = dict()\n self._lists = dict()\n self._members = dict()\n self._boards = dict()\n asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())\n self._loop = asyncio.get_event_loop()\n self._logger = logging.getLogger('trelloreporter')\n\n def configure_api_parameters(self, api_token, api_key, api_url, api_organisation):\n \"\"\"\n A function to initialise the API parameters of the trello reader object\n :param api_token: the API token\n :param api_key: the API key\n :param api_url: the API URL\n :param api_organisation: the API organisation\n :return: \n \"\"\"\n self._reader.configure_api_parameters(api_token, api_key, api_url, api_organisation)\n\n def populate_boards(self):\n \"\"\"\n Boards are the highest level concept within the Trello workflow.\n The Boards API allows you to list, view, create, and edit Boards.\n Each Board has a name, description, a set of members attached, and an ordered array of Lists.\n\n Populates the boards found under the api_key's endpoint as a JSON dict.\n :return: initialises the cards to the json list of boards\n \"\"\"\n self._loop.run_until_complete(self._reader.populate_boards())\n self._boards = self._reader.boards\n\n def populate_cards(self):\n \"\"\"\n Extracts the cards found at the api_key's endpoint, storing each\n card as a JSON item in a dict\n :return:\n \"\"\"\n if self._boards == {}:\n self.populate_boards()\n self._loop.run_until_complete(self._reader.populate_cards())\n self._cards = self._reader.cards\n\n def populate_lists(self):\n \"\"\"\n Populates the lists found under the organisation and stores them in the lists() dictionary\n :return: of Trello lists\n \"\"\"\n if self._boards == {}:\n self.populate_boards()\n self._loop.run_until_complete(self._reader.populate_lists())\n self._lists = self._reader.lists\n\n def populate_members(self):\n \"\"\"\n Method to populate the members of the Trello organisation\n :return: : Initialises the members() dict\n \"\"\"\n self._loop.run_until_complete(self._reader.populate_members())\n self._members = self._reader.members\n\n def get_members(self):\n \"\"\"\n\n :return: : return the members of the organisation\n \"\"\"\n return self._members\n\n def get_list_cards(self, list_id):\n \"\"\"\n Returns a dict of cards based on a filter argument \"lane\"\n\n :param lane: The lane in which the cards reside\n :return: The cards which all belong to the lane\n \"\"\"\n list_found = 0\n my_cards = dict()\n for board_id in self._boards.keys():\n for card_id in self._cards[board_id]:\n if list_id == self._cards[board_id][card_id]['idList']:\n my_cards[card_id] = self._cards[board_id][card_id]\n list_found = 1\n\n if list_found == 1:\n return my_cards\n else:\n return 'List ' + list_id + ' not found'\n\n def get_boards(self):\n \"\"\"\n\n :return: : returns a json array of boards\n \"\"\"\n return self._boards\n\n def get_board(self, board_id):\n \"\"\"\n :param: : the ID of the board to return\n :return: : returns a json array of boards\n \"\"\"\n if board_id in self._boards.keys():\n return self._boards[board_id]\n else:\n return 'Board ' + board_id + ' not found'\n\n def get_board_cards(self, board_id):\n \"\"\"\n\n :param board_id: The boardID of the cards to return\n :return: All the cards which belong ot the board at hand\n \"\"\"\n if board_id in self._boards.keys():\n return self._cards[board_id]\n else:\n return 'Board ' + board_id + ' not found'\n\n def get_board_lists(self, board_id):\n \"\"\"\n\n :param board_id: the boardID of the lists\n :return: : returns a dict of all the lists in a given board\n \"\"\"\n if board_id in self._boards.keys():\n return self._lists[board_id]\n else:\n return 'Board ' + board_id + ' not found'\n\n def get_lists(self):\n \"\"\"\n\n :return: : returns a dict of lists\n \"\"\"\n return self._lists\n\n def get_list(self, list_id):\n \"\"\"\n :param list_id: : the ID of the list\n :return: : returns a json representation of a list item\n \"\"\"\n for board in self._boards.keys():\n board_id = board\n for list in self._lists:\n if list_id in self._lists[board_id].keys():\n return self._lists[board_id][list_id]\n\n return 'List ' + list_id + ' not found'\n\n def get_cards(self):\n \"\"\"\n\n :return: : returns a json dict of cards\n \"\"\"\n return self._cards\n\n def get_card(self, card_id):\n \"\"\"\n :param card_id: : the ID of the card to retrieve\n :return: : returns a json representation of the card\n \"\"\"\n for board in self._boards.keys():\n board_id = board\n for card in self._cards:\n if card_id in self._cards[board_id].keys():\n return self._cards[board_id][card_id]\n\n return 'Card ' + card_id + ' not found'\n\n def get_card_summary(self, card_id):\n \"\"\"\n :parameter : str : The ID of the card to return a summary of\n :return: A summarized version of the card object in cards[board_id][boards]\n \"\"\"\n for board in self._boards.keys():\n board_id = board\n for card in self._cards:\n if card_id in self._cards[board_id].keys():\n self._logger.debug('Summarizing card ID: {0} {1}'.format(card_id, self._cards[board_id][card_id]['name']))\n my_card = {'Board': '', \n 'Description': '', \n 'Status': '', \n 'DueDate': '', \n 'Members': '', \n 'LastUpdate': '', \n 'URL': ''}\n my_card['Board'] = self._boards[board_id]['name']\n my_card['Description'] = self._cards[board_id][card_id]['name']\n listID = self._cards[board_id][card_id]['idList']\n my_card['Status'] = self._lists[board_id][listID]['name']\n my_card['DueDate'] = self._cards[board_id][card_id]['due']\n my_card['LastUpdate'] = self._cards[board_id][card_id]['dateLastActivity']\n my_card['URL'] = self._cards[board_id][card_id]['url']\n my_card['Members'] = dict()\n counter = 1\n for member_id in self._cards[board_id][card_id]['idMembers']:\n try:\n member_user_name = self._members[member_id]['username']\n my_card['Members'][member_user_name] = self._members[member_id]['fullName']\n except KeyError:\n my_card['Members']['Removed Member ID {0}:'.format(counter)] = member_id\n counter = counter + 1\n\n return my_card\n\n return 'Card ' + card_id + ' not found'\n\n def get_board_summary(self, board_id):\n \"\"\"\n :parameter : str : The ID of the card to return a summary of\n :return: A summarized version of the card object in cards[board_id][boards]\n \"\"\"\n card_id = ''\n for card_id in self._cards[board_id].keys():\n self._logger.debug('Summarizing card ID: {0} {1}'.format(card_id, self._cards[board_id][card_id]['name']))\n my_card = {'Board': '', \n 'Description': '', \n 'Status': '', \n 'DueDate': '', \n 'Members': '', \n 'LastUpdate': '', \n 'URL': ''}\n my_card['Board'] = self._boards[board_id]['name']\n my_card['Description'] = self._cards[board_id][card_id]['name']\n listID = self._cards[board_id][card_id]['idList']\n my_card['Status'] = self._lists[board_id][listID]['name']\n my_card['DueDate'] = self._cards[board_id][card_id]['due']\n my_card['LastUpdate'] = self._cards[board_id][card_id]['dateLastActivity']\n my_card['URL'] = self._cards[board_id][card_id]['url']\n my_card['Members'] = dict()\n counter = 1\n for member_id in self._cards[board_id][card_id]['idMembers']:\n try:\n member_user_name = self._members[member_id]['username']\n my_card['Members'][member_user_name] = self._members[member_id]['fullName']\n except KeyError:\n my_card['Members']['Removed Member ID {0}:'.format(counter)] = member_id\n counter = counter + 1\n\n return my_card\n\n return 'Card ' + card_id + ' not found'\n\n def write_to_excel(self, filename):\n \"\"\"\n Create named styles, using the bellow color schemes in Excel\n Neutral, Bad, Input, WarningText, Good\n \"\"\"\n self._logger.info('Creating spreadsheet')\n wb = Workbook()\n ws = wb.active\n for board in self.get_boards().keys():\n board_object = self.get_board(board_id=board)\n board_name = board_object['name'].replace('[', '(')\n trunc_board_name = board_name[:31] if len(board_name) > 31 else board_name\n ws.title = trunc_board_name.replace(']', ')')\n self._logger.debug('Create worksheet :{0}'.format(ws.title))\n ws['A1'] = 'Task Name'\n ws['B1'] = 'Status'\n ws['C1'] = 'Due Date'\n ws['D1'] = 'Members'\n ws['E1'] = 'URL'\n row = 2\n row_counter = 0\n for card in self.get_board_cards(board):\n card_object = self.get_card_summary(card_id=card)\n ws['A{0}'.format(row)] = card_object['Description']\n ws['B{0}'.format(row)] = card_object['Status']\n ws['C{0}'.format(row)] = card_object['DueDate']\n if len(card_object['Members']) == 0:\n ws['D{0}'.format(row)] = 'None'\n else:\n members = ''\n for member in card_object['Members'].values():\n members = member + '\\n' + members\n\n ws['D{0}'.format(row)] = members\n ws['E{0}'.format(row)] = card_object['URL']\n if card_object['Status'] == 'Backlog':\n cell = ws['C{0}'.format(row)]\n cell.style = 'Accent4'\n else:\n if card_object['Status'] == 'In Progress':\n cell = ws['C{0}'.format(row)]\n cell.style = 'Accent1'\n else:\n if card_object['Status'] == 'Impeded':\n cell = ws['C{0}'.format(row)]\n cell.style = 'Bad'\n else:\n if card_object['Status'] == 'Stopped':\n cell = ws['C{0}'.format(row)]\n cell.style = 'Accent2'\n elif card_object['Status'] == 'Completed':\n cell = ws['C{0}'.format(row)]\n cell.style = 'Good'\n ws['E{0}'.format(row)].style = 'Hyperlink'\n if 'Platform' in board_name:\n ws.sheet_properties.tabColor = '976360'\n else:\n if 'Client' in board_name:\n ws.sheet_properties.tabColor = '6878CC'\n else:\n if 'Core' in board_name:\n ws.sheet_properties.tabColor = 'FFA500'\n else:\n ws.sheet_properties.tabColor = '500FFA'\n row_counter += row_counter\n\n wb.create_sheet('New Worksheet')\n ws = wb['New Worksheet']\n\n try:\n wb.save(filename)\n self._logger.info('Spreadsheet {0} successfully created'.format(filename))\n except Exception:\n self._logger.error('Unable to save {0}'.format(filename))","sub_path":"pycfiles/trelloreporter-1.0.0.tar/excel.cpython-35.py","file_name":"excel.cpython-35.py","file_ext":"py","file_size_in_byte":13409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"64670627","text":"'''\r\n Decimal to Hex\r\n'''\r\ndef decToHex(dec):\r\n hex = []\r\n while (float(dec) != 0):\r\n a = float(dec) / 16\r\n b = int(dec / 16)\r\n c = a - b\r\n dec = b\r\n\r\n if (c == .0):\r\n hex.insert(0,0)\r\n elif (c == .0625):\r\n hex.insert(0,1)\r\n elif (c == .125):\r\n hex.insert(0,2)\r\n elif (c == .1875):\r\n hex.insert(0,3)\r\n elif (c == .25):\r\n hex.insert(0,4)\r\n elif (c == .3125):\r\n hex.insert(0,5)\r\n elif (c == .375):\r\n hex.insert(0,6)\r\n elif (c == .4375):\r\n hex.insert(0,7)\r\n elif (c == .5):\r\n hex.insert(0,8)\r\n elif (c == .5625):\r\n hex.insert(0,9)\r\n elif (c == .625):\r\n hex.insert(0,\"A\")\r\n elif (c == .6875):\r\n hex.insert(0,\"B\")\r\n elif (c == .75):\r\n hex.insert(0,\"C\")\r\n elif (c == .8125):\r\n hex.insert(0,\"D\")\r\n elif (c == .875):\r\n hex.insert(0,\"E\")\r\n elif (c == .9375):\r\n hex.insert(0,\"F\")\r\n return hex\r\n\r\n'''\r\n Hex to Decimal\r\n'''\r\ndef hexToDec(hex):\r\n sumOfHex = 0\r\n for i in range(0, len(hex)):\r\n sixteen = pow(16, len(hex)-i-1)\r\n if (hex[i] == \"A\"):\r\n sumOfHex += 10 * sixteen\r\n elif (hex[i] == \"B\"):\r\n sumOfHex += 11 * sixteen\r\n elif (hex[i] == \"C\"):\r\n sumOfHex += 12 * sixteen\r\n elif (hex[i] == \"D\"):\r\n sumOfHex += 13 * sixteen\r\n elif (hex[i] == \"E\"):\r\n sumOfHex += 14 * sixteen\r\n elif (hex[i] == \"F\"):\r\n sumOfHex += 15 * sixteen\r\n else:\r\n sumOfHex += int(hex[i]) * sixteen\r\n return sumOfHex\r\n\r\n'''\r\n Binary to Hex\r\n'''\r\ndef binToHex(bin):\r\n #bin to dec\r\n sumOfBi = 0\r\n for i in range(0, len(bin)):\r\n sumOfBi += int(bin[i]) * pow(2, len(bin) - i - 1)\r\n #dec to hex\r\n return decToHex(sumOfBi)\r\n\r\n'''\r\n Hex to Binary\r\n'''\r\ndef hexToBin(hex):\r\n #hex to dec\r\n dec = hexToDec(hex)\r\n #dec to bin\r\n bin = []\r\n while (dec != 0):\r\n bi = int(dec) % 2\r\n dec = int(dec) / 2\r\n bin.insert(0,bi)\r\n bin.pop(0)\r\n return bin\r\n\r\n'''\r\n MAIN AREA\r\n'''\r\n\r\n#For Hex to Decimal\r\n#print(hexToDec(\"4ED9A2\"))\r\n\r\n#For Dec to Hex\r\n#print(decToHex(736876))\r\n\r\n#For Binary to Hex - Add a 0 to front if there isn't one\r\nprint(binToHex(\"0101101101\"))\r\n\r\n#For Hex to Bin\r\n#print(hexToBin(\"4ED9A2\"))","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"427999202","text":"import requests \nurl= 'https://www.nlotto.co.kr/common.do?method=getLottoNumber&drwNo=837'\nresponse=requests.get(url, verify=False)\nlotto_data = response.json()\nreal_numbers=[]\n# for key in data:\n# if 'drwtNo' in key:\n# real_numbers.append(data[key])\n# print (real_numbers)\n\nfor key, value in lotto_data.items():\n if 'drwtNo'in key:\n real_numbers.append(value)\nbonus_number=lotto_data['bnusNo']\nprint (real_numbers)","sub_path":"01startcamp/day_1/getlotto.py","file_name":"getlotto.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"414659254","text":"import base64\nimport requests\nimport os\nimport json\nimport csv\n\nfrom tencentcloud.common import credential\nfrom tencentcloud.common.profile.client_profile import ClientProfile\nfrom tencentcloud.common.profile.http_profile import HttpProfile\nfrom tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException\nfrom tencentcloud.ocr.v20181119 import ocr_client, models\n\n\ndef isContainChinese(s):\n for c in s:\n if ('\\u4e00' <= c <= '\\u9fa5'):\n return True\n return False\n\n\ndef ocrFiles():\n try:\n resourceList = []\n\n for filename in os.listdir(r\"./resources\"):\n if 'JPG' in filename.upper():\n resourceList.append(filename)\n print(\"总图片数: \", len(resourceList))\n\n cred = credential.Credential(os.environ.get(\"TENCENTCLOUD_SECRET_ID\"),\n os.environ.get(\"TENCENTCLOUD_SECRET_KEY\"))\n httpProfile = HttpProfile()\n httpProfile.endpoint = \"ocr.tencentcloudapi.com\"\n\n clientProfile = ClientProfile()\n clientProfile.httpProfile = httpProfile\n client = ocr_client.OcrClient(cred, \"ap-shanghai\", clientProfile)\n\n for filename in resourceList:\n postDict = { 'filename': filename, 'ocrStatus': False, 'postKey': '' }\n try:\n with open(\"./resources/%s\" % filename, 'rb') as file:\n req = models.GeneralEfficientOCRRequest()\n content = file.read()\n b64 = str(base64.b64encode(content), 'utf-8')\n req.ImageBase64 = b64\n resp = client.GeneralEfficientOCR(req)\n data = json.loads(resp.to_json_string())\n # print(resp.to_json_string())\n for index, value in enumerate(data['TextDetections']):\n if '页面' in value['DetectedText'] or '扫码' in value['DetectedText']:\n targetItem1 = data['TextDetections'][index + 1]['DetectedText'].replace(' ', '')\n targetItem2 = data['TextDetections'][index + 2]['DetectedText'].replace(' ', '')\n if isContainChinese(targetItem1):\n postDict['postKey'] = targetItem2\n else:\n postDict['postKey'] = targetItem1\n except Exception as e:\n pass\n if postDict['postKey']:\n postDict['ocrStatus'] = True\n print(postDict)\n yield(postDict)\n\n except TencentCloudSDKException as err:\n print(err)\n\n\ndef output():\n with open('ocr_output.csv', 'w+') as csvFile:\n csvWriter = csv.writer(csvFile)\n csvWriter.writerow([\"文件名\", \"券码\"])\n for i in ocrFiles():\n csvWriter.writerow([i['filename'], i['postKey']])\n","sub_path":"rh/ocr.py","file_name":"ocr.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"93068548","text":"#-*- coding:utf-8 -*-\r\nimport uuid\r\nfrom django.shortcuts import get_object_or_404, render\r\nfrom django.http import *\r\nfrom django.http import HttpResponse,HttpResponseRedirect\r\nfrom django.core.urlresolvers import reverse\r\nfrom django.views import generic\r\nfrom django.shortcuts import render_to_response\r\nfrom django.http import HttpResponse,HttpResponseRedirect\r\nfrom django.core.paginator import Paginator,InvalidPage,EmptyPage,PageNotAnInteger\r\nimport time,datetime\r\nfrom django.db.models import Q\r\nfrom django.db import connection\r\nfrom django.template import RequestContext \r\nfrom django.contrib.auth.models import User\r\nfrom django.views.generic.base import TemplateView\r\nfrom django.contrib.auth.decorators import login_required\r\n\r\nfrom UUBlog.common import pub,utility\r\nfrom UUBlog.apps.accounts.models import UserProfile\r\nfrom UUBlog.apps.accounts.views import viewaccounts\r\n\r\nfrom UUBlog.apps.blog.models import *\r\nfrom UUBlog.apps.blog.views import viewcategory,baseblogview\r\nfrom UUBlog.apps.blog.views.baseblogview import *\r\nfrom UUBlog.apps.blog import modules\r\nfrom UUBlog.core.ubasetemplateView import UBaseTemplateView\r\n\r\n#未分类和草稿不计入统计\r\n\r\n#用户博客首页\r\nclass HomeView(UBaseBlogView):\r\n\r\n def GetContext(self, **kwargs):\r\n from django.views.generic import RedirectView\r\n\r\n uid=int(kwargs.get(\"uid\",0))\r\n\r\n blogWidgetList=self.GetBlogWidgetList(uid)\r\n\r\n navigateCategoryList=self.GetNavigateCategoryList(uid)\r\n followBlogIds=self.GetFollowBlogIds(uid)\r\n suggestBlogIds=self.GetSuggestBlogIds(uid)\r\n articleList=self.GetArticleList(uid)\r\n\r\n #更新博客浏览总数\r\n self.guestBlog.todayviews+=1\r\n self.guestBlog.totalviews+=1\r\n self.guestBlog.save()\r\n \r\n #更新博客访客\r\n self.AddVisit(uid)\r\n\r\n self.template_name=\"blog/skins/\"+self.guestBlog.template+\"/home.html\"\r\n\r\n return locals()\r\n\r\n#文章页面\r\nclass ShowView(UBaseBlogView):\r\n\r\n def PostContext(self, **kwargs):\r\n uid=int(kwargs.get(\"uid\",0))\r\n aid=int(kwargs.get(\"aid\",0))\r\n\r\n if self.HasPostData(\"ok\"):\r\n username = self.GetPostData('username')\r\n content = self.GetPostData('content')\r\n\r\n articleInfo=Article.objects.get(id=aid)\r\n comment=Comment()\r\n comment.article=articleInfo\r\n comment.content=content\r\n comment.user_id=self.currentUserProfile.user_id\r\n comment.username=username\r\n comment.createtime=datetime.datetime.now()\r\n comment.save()\r\n\r\n articleInfo.comments+=1\r\n articleInfo.save()\r\n\r\n self.guestBlog.comments+=1\r\n self.guestBlog.save()\r\n\r\n def GetContext(self, **kwargs):\r\n uid=int(kwargs.get(\"uid\",0))\r\n aid=int(kwargs.get(\"aid\",0))\r\n\r\n blogWidgetList=self.GetBlogWidgetList(uid)\r\n\r\n navigateCategoryList=self.GetNavigateCategoryList(uid)\r\n followBlogIds=self.GetFollowBlogIds(uid)\r\n suggestBlogIds=self.GetSuggestBlogIds(uid)\r\n articleList=self.GetArticleList(uid)\r\n\r\n #更新用户文章总数\r\n self.guestBlog.todayviews+=1\r\n self.guestBlog.totalviews+=1\r\n self.guestBlog.save()\r\n \r\n self.AddVisit(uid)\r\n \r\n \r\n articleInfo=Article.objects.get(id=aid)\r\n\r\n if self.HasPostData(\"ok\"):\r\n username = self.GetPostData('username')\r\n content = self.GetPostData('content')\r\n\r\n comment=Comment()\r\n comment.article=articleInfo\r\n comment.content=content\r\n comment.user_id=self.currentUserProfile.user_id\r\n comment.username=username\r\n comment.createtime=datetime.datetime.now()\r\n comment.save()\r\n\r\n articleInfo.comments+=1\r\n\r\n self.guestBlog.comments+=1\r\n self.guestBlog.save()\r\n\r\n #更新文章浏览量\r\n articleInfo.views+=1\r\n articleInfo.save()\r\n\r\n commentList=Comment.objects.filter(article_id=aid)\r\n\r\n\r\n self.template_name=\"blog/skins/\"+self.guestBlog.template+\"/show.html\"\r\n\r\n return locals()\r\n\r\n#分类浏览\r\nclass CategoryView(UBaseBlogView):\r\n\r\n\r\n def GetContext(self, **kwargs):\r\n uid=int(kwargs.get(\"uid\",0))\r\n cid=int(kwargs.get(\"cid\",0))\r\n\r\n blogWidgetList=self.GetBlogWidgetList(uid)\r\n\r\n navigateCategoryList=self.GetNavigateCategoryList(uid)\r\n followBlogIds=self.GetFollowBlogIds(uid)\r\n suggestBlogIds=self.GetSuggestBlogIds(uid)\r\n\r\n articleList=Article.objects.order_by(\"-createtime\").filter(user_id=uid).filter(category_id=cid).filter(status=1)\r\n\r\n #更新用户文章总数\r\n self.guestBlog.todayviews+=1\r\n self.guestBlog.totalviews+=1\r\n self.guestBlog.save()\r\n \r\n self.AddVisit(uid)\r\n\r\n self.template_name=\"blog/skins/\"+self.guestBlog.template+\"/home.html\"\r\n\r\n return locals()\r\n\r\n#Tag浏览\r\nclass TagView(UBaseBlogView):\r\n\r\n\r\n def GetContext(self, **kwargs):\r\n uid=int(kwargs.get(\"uid\",0))\r\n cid=int(kwargs.get(\"cid\",0))\r\n\r\n blogWidgetList=self.GetBlogWidgetList(uid)\r\n\r\n navigateCategoryList=self.GetNavigateCategoryList(uid)\r\n followBlogIds=self.GetFollowBlogIds(uid)\r\n suggestBlogIds=self.GetSuggestBlogIds(uid)\r\n\r\n articleList=Article.objects.order_by(\"-createtime\").filter(user_id=uid).filter(category_id=cid).filter(status=1)\r\n\r\n #更新用户文章总数\r\n self.guestBlog.todayviews+=1\r\n self.guestBlog.totalviews+=1\r\n self.guestBlog.save()\r\n \r\n self.AddVisit(uid)\r\n\r\n self.template_name=\"blog/skins/\"+self.guestBlog.template+\"/home.html\"\r\n\r\n return locals()\r\n\r\n#文章管理列表\r\nclass PubListView(UBaseBlogView):\r\n\r\n def GetContext(self, **kwargs):\r\n uid=int(kwargs.get(\"uid\",0))\r\n draft=kwargs.get(\"draft\",None)\r\n cid=int(kwargs.get(\"cid\",-1))\r\n\r\n categoryList=self.GetCategoryList(self.currentUserProfile.user_id)\r\n\r\n articleList=Article.objects.order_by(\"-createtime\").filter(user_id=self.currentUserProfile.user_id)\r\n\r\n if draft:\r\n articleList=articleList.filter(status=0)\r\n\r\n if cid and cid>0:\r\n articleList=articleList.filter(category_id=cid)\r\n\r\n self.template_name=\"blog/pub/articlelist.html\"\r\n\r\n return locals()\r\n\r\n#文章添加\r\nclass ArticleAddView(UBaseBlogView):\r\n\r\n def GetContext(self, **kwargs):\r\n\r\n categoryList=self.GetCategoryList(self.currentBlog.id)\r\n channelList=Channel.objects.filter(parent_id=0)\r\n\r\n articleInfo=Article()\r\n\r\n self.template_name=\"blog/pub/articleedit.html\"\r\n\r\n return locals()\r\n\r\n def PostContext(self, **kwargs):\r\n\r\n if self.HasPostData('ok'):\r\n channel1Id=int(self.GetPostData('channel1',0))\r\n channel2Id=int(self.GetPostData('channel2',0))\r\n titlepic=None\r\n if self.request.FILES.has_key(\"titlepic\"):\r\n titlepic = self.request.FILES['titlepic']\r\n\r\n category=Category.objects.get(id=self.GetPostData('category'))\r\n\r\n articleInfo=Article()\r\n articleInfo.category=category\r\n articleInfo.createtime=datetime.datetime.now()\r\n articleInfo.user_id=self.currentUser.id\r\n articleInfo.username=self.currentUser.username\r\n SetArticleValues(self.request,articleInfo)\r\n if titlepic:\r\n #20130711205603+guid\r\n #201307/11/205603+guid\r\n currentTime=datetime.datetime.now()\r\n path=\"%s/%s/%s/\" %(\"blog/attachment\",currentTime.strftime(\"%Y%m\"),currentTime.strftime(\"%d\"))\r\n filename=\"%s%s\" %(currentTime.strftime(\"%H%M%S\"),uuid.uuid1())\r\n \r\n savedInfo=pub.SaveFile(titlepic,path,filename)\r\n articleInfo.titlepic=savedInfo[0]\r\n\r\n else:\r\n pics=utility.GetImgSrc(articleInfo.content)\r\n if pics:\r\n articleInfo.titlepic=pics[0]\r\n \r\n articleInfo.save()\r\n\r\n if titlepic:\r\n attachmentInfo=Attachment()\r\n attachmentInfo.article_id=articleInfo.id\r\n attachmentInfo.user_id=self.currentUser.id\r\n attachmentInfo.filepath=savedInfo[0]\r\n attachmentInfo.filename=savedInfo[1]\r\n attachmentInfo.filetitle=savedInfo[2]\r\n attachmentInfo.extension=savedInfo[3]\r\n attachmentInfo.createtime=datetime.datetime.now()\r\n\r\n attachmentInfo.save()\r\n\r\n #更新分类统计信息 不是默认分类并且是发布的文章\r\n if category.id !=1 and articleInfo.status:\r\n category.articles+=1\r\n category.save()\r\n\r\n #更新用户文章统计信息\r\n self.currentBlog.articles+=1\r\n self.currentBlog.save()\r\n\r\n self.UpdateChannelArticles(channel1Id,channel2Id)\r\n \r\n\r\n self.template_name=\"blog/pub/articleedit.html\"\r\n\r\n return locals()\r\n\r\n#文章修改\r\nclass ArticleEditView(UBaseBlogView):\r\n\r\n def GetContext(self, **kwargs):\r\n uid=int(kwargs.get(\"uid\",0))\r\n aid=int(kwargs.get(\"aid\",0))\r\n\r\n categoryList=self.GetCategoryList(self.currentBlog.id)\r\n channelList=Channel.objects.filter(parent_id=0)\r\n\r\n articleInfo=Article.objects.get(id=aid)\r\n\r\n self.template_name=\"blog/pub/articleedit.html\"\r\n\r\n return locals()\r\n\r\n def PostContext(self, **kwargs):\r\n uid=int(kwargs.get(\"uid\",0))\r\n aid=int(kwargs.get(\"aid\",0))\r\n\r\n articleInfo=Article.objects.get(id=aid)\r\n\r\n oldCategory=articleInfo.category\r\n oldStatus=articleInfo.status\r\n\r\n if self.HasPostData('ok'):\r\n \r\n category=Category.objects.get(id=self.GetPostData('category'))\r\n\r\n articleInfo.category=category\r\n SetArticleValues(self.request,articleInfo)\r\n\r\n if oldCategory != category:\r\n #不是未分类,并且已经发布\r\n if category.id !=1 and articleInfo.status:\r\n category.articles+=1\r\n category.save()\r\n #不是未分类,并且已经是草稿\r\n if oldCategory.id!=1 and oldStatus:\r\n oldCategory.articles=oldCategory.articles-1 if oldCategory.articles>1 else 0\r\n oldCategory.save()\r\n else:\r\n if not articleInfo.status:\r\n category.articles-=1\r\n category.save()\r\n\r\n \r\n articleInfo.save()\r\n\r\n\r\n self.template_name=\"blog/pub/articleedit.html\"\r\n\r\n return locals()\r\n\r\ndef SetArticleValues(request,articleInfo):\r\n channel1Id=int(pub.GetPostData(request,'channel1',0))\r\n channel2Id=int(pub.GetPostData(request,'channel2',0))\r\n\r\n title = pub.GetPostData(request,'title')\r\n tags=pub.GetPostData(request,'tags')\r\n summary=pub.GetPostData(request,'summary')\r\n content = pub.GetPostData(request,'content')\r\n status = pub.GetPostData(request,'status')\r\n \r\n \r\n istop = pub.GetPostData(request,'istop')\r\n isoriginal=pub.GetPostData(request,'isoriginal')\r\n cancomment = pub.GetPostData(request,'cancomment')\r\n password = pub.GetPostData(request,'password')\r\n\r\n ishome=pub.GetPostData(request,'ishome')\r\n isrecommend = pub.GetPostData(request,'isrecommend')\r\n\r\n if summary==\"\":\r\n tempContent=utility.RemoveTags(content)\r\n summary=tempContent[0:200] if len(tempContent)>200 else tempContent\r\n else:\r\n summary=utility.RemoveTags(summary)\r\n\r\n articleInfo.channel1_id=channel1Id\r\n articleInfo.channel2_id=channel2Id\r\n\r\n articleInfo.title = title\r\n articleInfo.tags=tags\r\n articleInfo.summary=summary\r\n articleInfo.content = content\r\n #articleInfo.createtime=datetime.datetime.now()\r\n\r\n #articleInfo.views=0\r\n #articleInfo.comments=0\r\n #articleInfo.goods=0\r\n #articleInfo.bads=0\r\n articleInfo.status=status\r\n \r\n articleInfo.istop=istop\r\n articleInfo.isoriginal=isoriginal\r\n articleInfo.cancomment=cancomment\r\n articleInfo.password=password\r\n\r\n articleInfo.ishome=ishome\r\n articleInfo.isrecommend=isrecommend\r\n\r\n#文章删除\r\nclass ArticleDeleteView(UBaseBlogView):\r\n\r\n def GetContext(self, **kwargs):\r\n uid=int(kwargs.get(\"uid\",0))\r\n aid=int(kwargs.get(\"aid\",0))\r\n \r\n\r\n categoryList=self.GetCategoryList(uid)\r\n\r\n articleInfo=Article.objects.get(id=aid)\r\n \r\n if articleInfo.status:\r\n category=articleInfo.category\r\n\r\n #更新分类统计信息\r\n if category.articles>0:\r\n category.articles-=1\r\n category.save()\r\n\r\n if self.currentBlog.articles>0:\r\n self.currentBlog.articles-=1\r\n self.currentBlog.save()\r\n\r\n articleInfo.delete()\r\n\r\n articleList=Article.objects.order_by(\"-createtime\").filter(user_id=currentUser.id)\r\n \r\n\r\n return HttpResponseRedirect('blog/pub/article/list/')\r\n\r\n return locals()\r\n\r\n\r\n","sub_path":"build/20130801/source/UUBlog/apps/blog/views/viewarticle.py","file_name":"viewarticle.py","file_ext":"py","file_size_in_byte":13314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"564694235","text":"# encoding=utf8\n\nimport os\nimport requests\nimport json\nimport datetime\n\n#const \nUNNECESSARY_ELEMENTS = ['campaign', 'confirmed_at', 'created_at', 'creator', 'directions', \\\n 'ends_at', 'ends_at_utc', 'fields', 'host_is_confirmed', 'max_attendees', \\\n 'note_to_attendees', 'notes', 'phone', 'plus4', 'updated_at'\\\n ]\nSUPER_GROUP = 'PeoplePower'\nEVENT_TYPE = 'Launch'\n\n#Headers\n_TITLE = 'title'\n_URL = 'browser_url'\n_STARTDATE = 'starts_at'\n\n_PREURL = \"https://go.peoplepower.org/event/launch/\"\n_LIMIT = 20\n\ndef grab_data():\n cleaned_data = retrieve_and_clean_data()\n translated_data = translate_data(cleaned_data)\n \n return translated_data\n \ndef retrieve_and_clean_data():\n \"\"\"\n We retrieve data through the API and URL given to us by the \n partner organization. We remove the unnecessary elements as \n defined in UNNECESSARY_ELEMENTS\n \"\"\"\n \n print(\" -- Retrieving ACLU People Power Launches\")\n # start at page 1\n page = 1\n has_more_content = True\n event_endpoint = os.environ.get('PEOPLEPOWER_LAUNCH_URL')\n \n cleaned_data = []\n \n total_signups = 0\n \n while has_more_content:\n offset = page * _LIMIT\n req = requests.get(event_endpoint + (\"?_offset=%d\" % offset), data={'_limit': _LIMIT}, headers={\"Access\": 'application/json'})\n print (\"---- Going to Page\", page, offset, req.status_code)\n \n page = page + 1\n if req.status_code != 200:\n raise ValueError(\"Error in retrieving \", req.status_code)\n else:\n json_data = json.loads(req.text)\n events = json_data['objects']\n has_more_content = len(events) == _LIMIT\n \n for event in events:\n # remove private data\n \n if not event[\"is_approved\"]:\n continue\n \n if not event[\"status\"] == \"active\":\n continue\n \n for unneeded_key in UNNECESSARY_ELEMENTS:\n if unneeded_key in event:\n del event[unneeded_key]\n # print(\"\\n\\n\")\n total_signups = total_signups + event['attendee_count']\n cleaned_data.append(event)\n \n # will continue to traverse if has more content\n #endof while has content\n \n return cleaned_data\n\n\ndef translate_data(cleaned_data):\n \"\"\"\n This is where we translate the data to the necessary information for the map\n \"\"\"\n print(\" -- Translating People Power Launch\")\n translated_data = []\n \n for data in cleaned_data:\n address = clean_venue(data)\n \n group_name = data['title']\n has_coords = 'latitude' in data and 'longitude' in data\n \n if not has_coords:\n continue\n \n if data['starts_at'][:10] < datetime.date.today().strftime('%Y-%m-%d'):\n continue\n\n event = {\n 'title': data[_TITLE] if _TITLE in data else None, \n 'url': _PREURL + (\"%d\" % data['id']),\n 'supergroup' : SUPER_GROUP,\n 'group': group_name,\n 'event_type': EVENT_TYPE,\n 'start_datetime': data[_STARTDATE] if _STARTDATE in data else None,\n 'venue': address,\n 'lat': data['latitude'] if has_coords else None,\n 'lng': data['longitude'] if has_coords else None\n }\n \n translated_data.append(event)\n\n return translated_data\n\ndef clean_venue(location):\n \"\"\"\n We translate the venue information to a flat structure\n \"\"\"\n venue = location['venue'] + '.' if 'venue' in location else None\n address = ''.join([location['address1'], location['address2']])\n locality = location['city'] if 'city' in location else None\n region = location['region'] if 'region' in location else None\n postal_code = location['postal'] if 'postal' in location else None\n \n return ' '.join(['' if i is None else i for i in [venue, address, locality, region, postal_code]])\n","sub_path":"etl/peoplepower/launch.py","file_name":"launch.py","file_ext":"py","file_size_in_byte":4132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"109660348","text":"#!/usr/bin/python3\nfrom flask_mail import Mail, Message\n\n\ndef mail_sender(email, url, app):\n mail = Mail(app)\n msg = Message('Завершение регистрации в Ticket Huiket', recipients=[email])\n message_body = 'Завершите регистрацию пройдя по ссылке {}' \\\n 'Если вы не регистрируетесь в Ticket Huiket, проигнорируйте это сообщение' \\\n 'Ссылка на регистрацию будет действительна в течении часа' \\\n 'Вы всегда можете пройти регистрацию повторно, если не успели завершить в течении часа'.format(url)\n\n msg.body = message_body\n mail.send(msg)\n","sub_path":"middleware/email_controler.py","file_name":"email_controler.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"326365159","text":"import theano\nimport theano.tensor as T\nx = T.dmatrix('x')\ns = 1 / (1 + T.exp(-x))\nlogistic = theano.function([x], s)\n\nprint(logistic([[0, 1], [-1, -2]]))\n\n\n\ns2 = (1 + T.tanh(x / 2)) / 2\nlogistic2 = theano.function([x], s2)\n\nprint(logistic2([[0, 1], [-1, -2]]))\n\n\n\na, b = T.dmatrices('a', 'b')\ndiff = a - b\nabs_diff = abs(diff)\ndiff_squared = diff**2\nf = theano.function([a, b], [diff, abs_diff, diff_squared])\n\nprint(f([[1, 1], [1, 1]], [[0, 1], [2, 3]]))\n\n\n\n\n\n\n","sub_path":"basics/logistic-function.py","file_name":"logistic-function.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"422930930","text":"__author__ = 'cristiroma'\n\n\nclass DjangoAppUtils(object):\n\n @staticmethod\n def get_from_request(request, param_name, default_value=None):\n \"\"\"\n Retrieve parameter value by looking into request.POST and request.GET\n\n :param request: Django HttpRequest object\n :param param_name: Name of the request parameter\n :param default_value: Default value when parameter is missing\n :return: Parameter value as string\n \"\"\"\n ret = default_value\n if request.POST.get(param_name, None):\n return request.POST.get(param_name)\n elif request.GET.get(param_name, None):\n return request.GET.get(param_name)\n return ret\n","sub_path":"informea.ai_manager/ai/app_utils.py","file_name":"app_utils.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"600821361","text":"N, A, B = map(int, input().split())\ncnt = 0\nfor i in range(N+1):\n n = i\n sum = 0\n while n > 0:\n sum += n % 10\n n = n // 10\n if A <= sum <= B:\n cnt += i\nprint(cnt)","sub_path":"AtCoder Beginner/AtCGC_6.py","file_name":"AtCGC_6.py","file_ext":"py","file_size_in_byte":195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"403195972","text":"import numpy as np\nfrom math import *\nfrom matplotlib import pyplot as plt\n\n# Differential equation\n# diff = y'= diff(x,y)\ndef diff(x,y):\n return 0.04*y*(1-y/1000)\nprint(\"definition diff function process\")\n\n#input\nx_min, x_max, x_num = -5, 200, 30\ny_min, y_max, y_num = -5, 1200, 30\nx_init, y_init = 0,150\ngridSetting = True\nprint(\"input process\")\n\n# x,y range\nx = np.linspace(x_min, x_max, x_num)\ny = np.linspace(y_min, y_max, y_num)\n\nx_dis = (x_max-x_min)/(x_num+1)\ny_dis = (y_max-y_min)/(y_num+1)\nprint(\"x domain process\")\n\n# drawing direction field\nfor j in x:\n for k in y:\n slope = diff(j,k)\n if abs(slope) <= y_dis/x_dis :\n domain = np.linspace(j-x_dis/2.5,j+x_dis/2.5,2)\n else :\n domain = np.linspace(j-y_dis/slope/2.5,j+y_dis/slope/2.5,2)\n def fun(x1,y1):\n z = slope*(domain-x1)+y1\n return z\n plt.plot(domain,fun(j,k),solid_capstyle='projecting',solid_joinstyle='bevel')\nprint(\"drawing direction field process\")\n\n# Error\nclass outOfRange(Exception) :\n def __init__(self, msg) :\n self.msg = msg\n def __str__(self) :\n return self.msg\nprint(\"Error setting process\")\n\n# drawing graph by newton method\nif not x_min <= x_init <= x_max or not y_min <= y_init <= y_max :\n raise outOfRange('초기값이 범위를 벗어났습니다')\nprint(\"Error check process\")\n\n\n# x right\nx = x_init\ny = y_init\nwhile x_min <= x <= x_max and y_min <= y <= y_max:\n xNext = x+0.1\n yNext = y+diff(x,y)*0.1\n plt.plot([x,xNext], [y,yNext], 'k', linewidth=1)\n x, y = xNext, yNext\nprint(\"right drawing graph process\")\n\n# x left\nx = x_init\ny = y_init\nwhile x_min <= x <= x_max and y_min <= y <= y_max:\n xNext = x-0.1\n yNext = y-diff(x,y)*0.1\n plt.plot([x,xNext], [y,yNext], 'k', linewidth=1)\n x, y = xNext, yNext\nprint(\"left drawing graph process\")\n\nplt.title(\"Direction Field\")\nplt.xlabel('x axis')\nplt.ylabel('y axis')\nplt.grid(gridSetting)\nplt.show()\n \nprint(\"End of the program\")","sub_path":"Drawing_DirectionFiled_f(x,y).py","file_name":"Drawing_DirectionFiled_f(x,y).py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"559169317","text":"\"\"\"Predicts the Her2 score from a histogram of pixel intensities.\"\"\"\n\n# Python imports.\nimport os\nimport sys\n\n# 3rd party imports.\nimport numpy as np\nimport scipy.ndimage\nfrom sklearn.linear_model import ElasticNet\n\n# User imports.\nimport Utilities.merge_dictionaries\nimport Utilities.partition_dataset\n\n# Globals.\nmodelChoices = { # The choices of models available to use.\n \"ElasticNet\": {\"Model\": ElasticNet, \"Stratified\": True}\n}\n\n\ndef main(arguments):\n \"\"\"\n\n Assumes 8 bit greyscale or color images.\n\n :param arguments: The Her2 histogram prediction arguments in JSON format.\n :type arguments: JSON object\n\n \"\"\"\n\n # Process the parameters.\n dirImages = arguments[\"ImageLocation\"]\n if not os.path.isdir(dirImages):\n print(\"Image location {0:s} is not a directory.\".format(dirImages))\n sys.exit()\n fileGroundTruth = arguments[\"GroundTruth\"]\n backgroundThreshold = arguments[\"BackgroundThreshold\"] # The lowest pixel value that makes up the background.\n isPredictingHer2 = arguments[\"TargetHer2\"] # Whether we are attempting to predict Her2 or cell staining percentage.\n foldsToUse = arguments[\"CVFolds\"] # The number of CV folds to use.\n dirResults = arguments[\"ResultsLocation\"] # Directory to save the results in.\n if not os.path.exists(dirResults):\n # The results directory doesn't exist, so try and create it.\n try:\n os.makedirs(dirResults)\n except Exception as err:\n print(\"Error creating results directory: {0:s}\".format(err))\n sys.exit()\n modelToUse = arguments[\"ModelToUse\"] # The type of model to train.\n modelParams = arguments[\"ModelParameters\"]\n\n # Extract the ground truth values.\n caseNumbers = []\n her2Scores = []\n stainingPercent = []\n with open(fileGroundTruth, 'r') as fidGroundTruth:\n fidGroundTruth.readline() # Strip off the header.\n for line in fidGroundTruth:\n chunks = (line.strip()).split('\\t')\n caseNumbers.append(int(chunks[0]))\n her2Scores.append(int(chunks[1]))\n stainingPercent.append(float(chunks[2]))\n groundTruth = np.array([caseNumbers, her2Scores, stainingPercent])\n\n # Determine the mask for removing the background pixel colors.\n backgroundMask = np.array([(False if i >= backgroundThreshold else True) for i in range(256)])\n\n # Initalise the matrix that will hold the histogram data.\n # There will be one row per image and one column for each of the non-background pixel values, one\n # for the case number, one for the Her2 score and one for the percentage of stained cells).\n dataMatrix = np.empty((len(os.listdir(dirImages)), (backgroundMask.sum() + 3)))\n\n # Generate the matrix of histogram feature vectors.\n for ind, i in enumerate(os.listdir(dirImages)):\n # Read in the file.\n filePath = \"{0:s}/{1:s}\".format(dirImages, i)\n image = scipy.ndimage.imread(filePath)\n\n # Generate the histogram. One bin per color value.\n histogram = scipy.ndimage.histogram(image, 0, 255, 256)\n\n # Strip out the background color.\n histogram = histogram[backgroundMask]\n\n # Convert histogram to relative values. This will remove issues with image sizes being different.\n histogram = histogram / histogram.sum()\n\n # Determine the number case identifier for the image.\n caseID = int(i.split('_')[0])\n\n # Create the feature vector.\n caseGroundTruth = groundTruth[:, groundTruth[0, :] == caseID] # The ground truth values for this image.\n dataMatrix[ind, 0] = caseID\n dataMatrix[ind, 1] = caseGroundTruth[1]\n dataMatrix[ind, 2] = caseGroundTruth[2]\n dataMatrix[ind, 3:] = histogram\n\n # Determine the target vector and the subset of the dataset used for training.\n trainingDataMatrix = dataMatrix[:, 3:]\n targetVector = dataMatrix[:, 1] if isPredictingHer2 else dataMatrix[:, 2]\n\n # Determine all combinations of the model parameters. The parameters to be considered are stored as a dictionary,\n # with the value for each dictionary entry being a list of the values to use when training the model.\n # The goal is therefore to convert a dictionary of lists into a list of dictionaries, where each dictionary\n # contains the same keys as the original dictionary, but has a single value associated with each key (instead of\n # a list).\n # For example, modelParams = {\"lambda\": [1, 2, 3, 4], \"alpha\": [0.001, 0.01, 0.1]} would become:\n # [{\"lambda\": 1, \"alpha\": 0.001}, {\"lambda\": 1, \"alpha\": 0.01}, {\"lambda\": 1, \"alpha\": 0.1},\n # {\"lambda\": 2, \"alpha\": 0.001}, {\"lambda\": 2, \"alpha\": 0.01}, {\"lambda\": 2, \"alpha\": 0.1},\n # {\"lambda\": 3, \"alpha\": 0.001}, {\"lambda\": 3, \"alpha\": 0.01}, {\"lambda\": 3, \"alpha\": 0.1},\n # {\"lambda\": 4, \"alpha\": 0.001}, {\"lambda\": 4, \"alpha\": 0.01}, {\"lambda\": 4, \"alpha\": 0.1}]\n paramList = []\n for i in modelParams:\n if paramList:\n # The parameter list already has some dictionaries in it. Therefore, create every combination of the\n # dictionaries in the list with the dictionaries made from the values in the modelParams[i] list.\n paramList = [Utilities.merge_dictionaries.main(k, {i: j}) for j in modelParams[i] for k in paramList]\n else:\n # If this is the first parameter, then take this entry of the modelParams dict and split it into a list\n # containing one dict for each list element.\n paramList = [{i: j} for j in modelParams[i]]\n\n # Perform the model training.\n if foldsToUse < 2:\n # Train on the entire dataset and predict on the test observations.\n for params in paramList:\n # Create the model.\n model = modelChoices[modelToUse][\"Model\"](**params)\n\n # Train the model.\n model.fit(trainingDataMatrix, targetVector)\n else:\n # Train using cross validation. With two folds this is equivalent to hold out testing.\n\n # Partition the dataset.\n partition = Utilities.partition_dataset.main(trainingDataMatrix, targetVector, foldsToUse,\n modelChoices[modelToUse][\"Stratified\"])\n\n # Perform cross validation.\n for params in paramList:\n for i in range(foldsToUse):\n # Determine the subset of data to use for training and testing in this fold.\n trainingExamples = partition != i\n trainingDataSubset = trainingDataMatrix[trainingExamples]\n trainingTargetVector = targetVector[trainingExamples]\n testingExamples = partition == i\n testingDataSubset = trainingDataMatrix[testingExamples]\n testingTargetVector = targetVector[testingExamples]\n\n # Create the model.\n model = modelChoices[modelToUse][\"Model\"](**params)\n\n # Train the model.\n model.fit(trainingDataSubset, trainingTargetVector)\n\n # Test the model.\n model.predict(testingDataSubset)\n","sub_path":"Code/HistogramPrediction/histogram_predictions.py","file_name":"histogram_predictions.py","file_ext":"py","file_size_in_byte":7132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"168351301","text":"#切片\n#取一个list或tuple的部分元素是非常常见的操作\nL = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']\n#取前3个元素\nprint(L[0:3])\n#L[0:3]表示,从索引0开始取,直到索引3为止,但不包括索引3\n#如果第一个索引是0,还可以省略\nprint(L[:3])\nprint(L[-2:-1])\nprint(L[-3:])\n#倒数第一个元素的索引是-1\nL = list(range(100))\n#所有数,每10个取一个:\nprint(L[::10])\n#前20个数,每2个取一个\nprint(L[:20:2])\n#最后20个数,每4个取一个\nprint(L[-20::4])\n\n#tuple也是一种list,唯一区别是tuple不可变。因此,tuple也可以用切片操作,只是操作的结果仍是tuple\n\n#字符串'xxx'也可以看成是一种list,每个元素就是一个字符。因此,字符串也可以用切片操作,只是操作结果仍是字符串\ns = 'ABCDEFGHIJK'\nprint(s[:4])\nprint(s[::2])\n\n#practice\n#利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法:\ndef trim(s):\n while (len(s) > 0 and s[0] == ' '):\n s = s[1:]\n while (len(s) > 0 and s[-1] == ' '):\n s = s[:-2]\n print(s)\ntrim(' ')\ntrim('hello ')\ntrim(' hello')\ntrim(' hello world ')\n\n\n\n#迭代\n#只要是可迭代对象,无论有无下标,都可以迭代,比如dict就可以迭代\nd = {'a':1, 'b':2, 'c':3}\nfor key in d:\n print(key, ':', d[key], '', end = '')\nprint()\n#因为dict的存储不是按照list的方式顺序排列,所以,迭代出的结果顺序很可能不一样。\n#默认情况下,dict迭代的是key。如果要迭代value,可以用for value in d.values(),\n#如果要同时迭代key和value,可以用for k, v in d.items()。\nfor value in d.values():\n print(value, '', end = '')\nprint()\nfor k, v in d.items():\n print(k, ':', v, '', end = '')\nprint()\n\n#字符串也是可迭代对象,因此,也可以作用于for循环:\nfor c in 'ABCD':\n print(c, end = ' ')\nprint()\n#判断一个对象是可迭代对象\nfrom collections.abc import Iterable\nprint(isinstance('abc', Iterable))\nprint(isinstance(12345, Iterable))\n\n#Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身:\nL = ['a', 'b', 'c']\nfor i, value in enumerate(L):\n print(i, ':', value, end = ' ', sep = '')\nprint()\n\n#print()函数的参数,sep表示字符串之间的连接符,end表示以什么结尾\n#默认sep=' ',end='\\n',\n\n#for循环里,同时引用了两个变量\nfor x, y in [(1,1), (2,4), (3,9)]:\n print(x, y)\n\n#practice\n#请使用迭代查找一个list中最小和最大值,并返回一个tuple:\ndef findMinAndMax(L):\n if (len(L) == 0):\n return (None, None);\n maxi = L[0]\n mini = L[0]\n for val in L:\n maxi = max(val, maxi)\n mini = min(val, mini)\n return (mini, maxi)\n\n#测试\nif findMinAndMax([]) != (None, None):\n print('测试失败!')\nelif findMinAndMax([7]) != (7, 7):\n print('测试失败!')\nelif findMinAndMax([7, 1]) != (1, 7):\n print('测试失败!')\nelif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):\n print('测试失败!')\nelse:\n print('测试成功!')\nprint('\\n')\n\n\n\n#列表生成式\nL = list(range(10, 20))\nprint(L)\n#生成[1x1, 2x2, 3x3, ..., 10x10]\nL = [x * x for x in range(1, 11)]\nprint(L)\n#for循环后面还可以加上if判断,这样我们就可以筛选出仅偶数的平方:\nL = [x * x for x in range(1, 11) if x % 2 == 0]\nprint(L)\n#还可以使用两层循环,可以生成全排列:\nL = [m + n for m in 'abc' for n in 'xyz']\nprint(L)\n#三层和三层以上的循环很少用\n\n#列出当前目录下的所有文件和目录名\nimport os\nprint([d for d in os.listdir('.')]) # os.listdir可以列出文件和目录\n\n#列表生成式也可以使用两个变量来生成list\nd = {'x':'A', 'y':'b', 'z':'c'}\nprint([k + '=' + v for k, v in d.items()])\n\n#把一个list中所有的字符串变成小写\nL = ['Hello', 'World', 'IBM', 'Apple']\nprint([s.lower() for s in L])\n\n#practice\n#如果list中既包含字符串,又包含整数,由于非字符串类型没有lower()方法,所以列表生成式会报错\n#使用内建的isinstance函数可以判断一个变量是不是字符串\n#请修改列表生成式,通过添加if语句保证列表生成式能正确地执行:\nL1 = ['Hello', 'World', 18, 'Apple', None]\nL2 = [x.lower() for x in L1 if isinstance(x, str)]\nprint(L2)\n\n\n\n\n\n\n\n#生成器\n#通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。\n#而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,\n#如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。\n\n#如果列表元素可以按照某种算法推算出来,那我们可以在循环的过程中不断推算出后续的元素,\n#这样就不必创建完整的list,从而节省大量的空间。\n#在Python中,这种一边循环一边计算的机制,称为生成器:generator。\n\n#要创建一个generator,有很多种方法。\n#第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator:\nL = [x * x for x in range(10)]\ng = (x * x for x in range(10))\nprint(L)\nprint(next(g), next(g), next(g))\n#generator也是可迭代对象,可以用for循环\nfor n in g:\n print(n, end = ' ')\nprint() \n\n#斐波拉契数列\n#函数版本\ndef fib_1(maxi):\n n, a, b = 0, 0, 1\n while n < maxi:\n print(b, end = ' ')\n a, b = b, a + b\n n = n + 1\n return 'done'\nfib_1(6)\nprint()\n\n#生成器版本\n#如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,\n#而是一个generator:\ndef fib_2(maxi):\n n, a, b = 0, 0, 1\n while n < maxi:\n yield b\n a, b = b, a + b\n n = n + 1\n return 'done'\nprint(fib_2(6))\n#generator和函数的执行流程不一样。\n#函数是顺序执行,遇到return语句或者最后一行函数语句就返回。\\\n#而变成generator的函数,在每次调用next()的时候执行,遇到yield语句停住,然后返回,\n#再次执行时从上次返回的yield语句处继续执行。\n\n#举个简单的例子,定义一个generator,依次返回数字1,3,5:\ndef odd():\n print('step 1: ', end = ' ')\n yield 1\n print('step 2: ', end = ' ')\n yield 3\n print('step 3: ', end = ' ')\n yield 5\n#调用该generator时,首先要生成一个generator对象,然后用next()函数不断获得下一个返回值:\no = odd()\nprint(next(o))\nprint(next(o))\nprint(next(o))\n\n#使用for循环来迭代:\nfor n in fib_2(6):\n print(n, end = ' ')\n\n\n#但是用for循环调用generator时,发现拿不到generator的return语句的返回值。\n#如果想要拿到返回值,必须捕获StopIteration错误,返回值包含在StopIteration的value中:\ng = fib_2(6)\nwhile True:\n try:\n x = next(g)\n print('g:', x)\n except StopIteration as e:\n print('Generator return value:', e.value)\n break;\n\n#practice\n\"\"\"\n杨辉三角定义如下:\n 1\n / \\\n 1 1\n / \\ / \\\n 1 2 1\n / \\ / \\ / \\\n 1 3 3 1\n / \\ / \\ / \\ / \\\n 1 4 6 4 1\n / \\ / \\ / \\ / \\ / \\\n1 5 10 10 5 1\n把每一行看做一个list,试写一个generator,不断输出下一行的list\n\"\"\"\n\ndef triangles(n):\n c = 0;\n L = [1]\n while c < n:\n yield L\n L2 = [1]\n for i, v in enumerate(L):\n if (i < len(L) - 1):\n L2.append(L[i] + L[i+1])\n L2.append(1)\n L = L2\n c = c + 1\n \ng = triangles(5)\nwhile True:\n try:\n L = next(g)\n print(L)\n except StopIteration as e:\n break;\n\n#比较牛批的写法\ndef triangles_(n):\n c = 0;\n L = [1]\n while c < n:\n yield L\n L = [1] + [L[i] + L[i+1] for i in range(len(L)-1)] + [1]\n c = c + 1\n \ng = triangles_(5)\nwhile True:\n try:\n L = next(g)\n print(L)\n except StopIteration as e:\n break\n\nprint('\\n')\n\n\n\n\n\n\n#迭代器\n\n#我们已经知道,可以直接作用于for循环的数据类型有以���几种:\n#一类是集合数据类型,如list、tuple、dict、set、str等;\n#一类是generator,包括生成器和带yield的generator function。\n#这些可以直接作用于for循环的对象统称为可迭代对象:Iterable。\n#可以使用isinstance()判断一个对象是否是Iterable对象:\nfrom collections.abc import Iterable\nprint(isinstance([], Iterable))\nprint(isinstance((x for x in range(10)), Iterable))\n\n\n#而生成器不但可以作用于for循环,还可以被next()函数不断调用并返回下一个值,直到最后抛出StopIteration错误表示无法继续返回下一个值了。\n#可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。\n#可以使用isinstance()判断一个对象是否是Iterator对象:\nfrom collections.abc import Iterator\nprint(isinstance([], Iterator))\nprint(isinstance((x for x in range(10)), Iterator))\n\n#生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。\n#把list、dict、str等Iterable变成Iterator可以使用iter()函数:\nprint(isinstance(iter([]), Iterator))\nprint(isinstance(iter('abc'), Iterator))\n\n\n\n\n","sub_path":"learn04_advanced.py","file_name":"learn04_advanced.py","file_ext":"py","file_size_in_byte":9335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"638961712","text":"# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.\n#\n# This source code is licensed under the BSD license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport collections\nimport copy\nimport io\nfrom itertools import chain\nfrom typing import Any, Callable, Dict, List, Optional, Type\n\nimport torch\nimport torch.distributed as dist\nfrom torch.optim import Optimizer\nimport logging\n\n__all__ = [\"ZeroRedundancyOptimizer\"]\n\n\n# Credits: classy_vision/generic/distributed_util.py\ndef _recursive_copy_to_device(value: Any, non_blocking: bool, device: torch.device) -> Any:\n r\"\"\"\n Recursively searches lists, tuples, dicts and copies tensors to device if\n possible. Non-tensor values are passed as-is in the result.\n\n .. note: These are all copies, so if there are two objects that reference\n the same object, then after this call, there will be two different objects\n referenced on the device.\n \"\"\"\n\n if isinstance(value, torch.Tensor):\n return value.to(device, non_blocking=non_blocking)\n\n if isinstance(value, (list, tuple)):\n values = [_recursive_copy_to_device(val, non_blocking=non_blocking, device=device) for val in value]\n return values if isinstance(value, list) else tuple(values)\n\n if isinstance(value, collections.abc.Mapping):\n return {\n key: _recursive_copy_to_device(val, non_blocking=non_blocking, device=device) for key, val in value.items()\n }\n\n return value\n\n\ndef _is_trainable(param: torch.Tensor) -> bool:\n return param.requires_grad\n\n\ndef _broadcast_object(\n obj: Any,\n src_rank: int,\n group: object = dist.group.WORLD,\n dist_device: torch.device = torch.device(\"cpu\"),\n) -> Any:\n r\"\"\"\n Either broadcast from master to the fleet (default),\n or use the src setting as the original rank.\n \"\"\"\n\n if dist.get_rank() == src_rank:\n # Emit data\n buffer = io.BytesIO()\n torch.save(obj, buffer)\n data = bytearray(buffer.getbuffer())\n length_tensor = torch.LongTensor([len(data)]).to(dist_device)\n data_send_tensor = torch.ByteTensor(data).to(dist_device)\n dist.broadcast(length_tensor, src=src_rank, group=group, async_op=False)\n dist.broadcast(data_send_tensor, src=src_rank, group=group, async_op=False)\n else:\n # Fetch from the source\n length_tensor = torch.LongTensor([0]).to(dist_device)\n dist.broadcast(length_tensor, src=src_rank, group=group, async_op=False)\n data_recv_tensor = torch.empty([int(length_tensor.item())], dtype=torch.uint8, device=dist_device)\n dist.broadcast(data_recv_tensor, src=src_rank, group=group, async_op=False)\n buffer = io.BytesIO(data_recv_tensor.cpu().numpy())\n obj = torch.load(buffer, map_location=dist_device)\n return obj\n\n\ndef _get_global_rank(group: Any, rank: int) -> int:\n return rank if group is dist.group.WORLD else dist.distributed_c10d._get_global_rank(group, rank)\n\n\nclass ZeroRedundancyOptimizer(Optimizer):\n r\"\"\"\n This class wraps an arbitrary :class:`optim.Optimizer `\n and shards its states across ranks in the group as described by\n ZeRO_. The optimizer instance in each rank is only responsible for\n updating ``1 / world_size`` parameters and hence only needs to keep\n ``1 / world_size`` optimizer states. After parameters are updated locally,\n each rank will broadcast its parameters to all other peers to keep all\n model replicas in the same state. ``ZeroRedundancyOptimizer`` can be used\n in conjunction with :class:`torch.nn.parallel.DistributedDataparallel` to\n reduce per-rank peak memory consumption.\n\n ``ZeroRedundancyOptimizer`` uses a sorted-greedy algorithm to pack a number of\n parameters at each rank. Each parameter belongs to a single rank and is not\n divided among ranks. The partition is arbitrary and might not match the\n the parameter registration or usage order.\n\n Arguments:\n params (``Iterable``): an ``Iterable`` of :class:`torch.Tensor` s\n\n Keyword Args:\n optimizer_class (:class:`torch.nn.Optimizer`): the class of the local\n optimizer.\n group (``ProcessGroup``, optional): ``torch.distributed``\n ``ProcessGroup`` (default: ``group.WORLD`` initialized by\n :meth:`torch.distributed.init_process_group`).\n parameters_as_bucket_view (bool): when enabled, parameters will\n be packed into larger buckets to speed up communication and\n ``param.data`` fields will point to bucket views at different\n offsets. When disabled, each individual parameter will be\n communicated separately, but ``params.data`` will stay intact.\n **default: all trailing arguments will be forwarded to the given optimizer.\n\n Example::\n\n >>> import torch.nn as nn\n >>> from torch.distributed.optim import ZeroRedundancyOptimizer\n >>> from torch.nn.parallel import DistributedDataParallel as DDP\n\n >>> model = nn.Sequential(*[nn.Linear(2000, 2000).to(rank) for _ in range(20)])\n >>> ddp = DDP(model, device_ids=[rank])\n >>> opt = ZeroRedundancyOptimizer(\n >>> ddp.parameters(),\n >>> optimizer_class=torch.optim.Adam,\n >>> lr=0.01\n >>> )\n >>> ddp(inputs).sum().backward()\n >>> opt.step()\n\n .. note: Currently, ``ZeroRedundancyOptimizer`` requires that all of the\n passed-in parameters are on the same device and that they are the same\n dense type.\n\n .. warning: ZeroRedundancyOptimizer is experimental and subject to change.\n\n .. _ZeRO: https://arxiv.org/abs/1910.02054\n\n \"\"\"\n\n def __init__(\n self,\n params,\n optimizer_class: Type[Optimizer],\n group: Optional[Any] = None,\n parameters_as_bucket_view: bool = False,\n **default: Any,\n ):\n # Perform type and assumption checks on the input parameters\n self._verify_and_init_params(params)\n self._verify_same_param_device()\n self._verify_same_dense_param_type()\n self._device = self._all_params[0].device\n\n # Hold all the model params in the root .param_groups\n # NOTE: the default constructor uses `add_param_group` which is partially overloaded here\n # we introduce the `initialized` flag for be able to dissociate the behaviour of\n # `add_param_group` in between super() and ZeroRedundancyOptimizer\n self.initialized = False\n super().__init__(self._all_params, default)\n\n # Partition information (evaluated lazily)\n self._param_to_rank_cache: Dict[torch.Tensor, int] = {}\n self._param_to_index_cache: Dict[int, int] = {}\n self._partition_parameters_cache: List[List[Dict]] = []\n self._index_to_param_cache: List[torch.Tensor] = []\n\n # Build the wrapped optimizer, responsible for a shard of the params\n self.group = group if group is not None else dist.group.WORLD\n self.world_size = dist.get_world_size(self.group)\n self.rank = dist.get_rank(self.group)\n self.global_rank = _get_global_rank(self.group, self.rank)\n self.parameters_as_bucket_view = parameters_as_bucket_view\n\n self._optim_defaults = default\n self._optim_constructor = optimizer_class\n\n # Optional consolidated optimizer state\n self._all_states: List[Dict[str, Any]] = []\n\n self._reference_is_trainable_mask = list(map(_is_trainable, self._all_params))\n self.buckets: List[torch.Tensor] = []\n\n self._update_trainable()\n self.initialized = True\n\n def _clear_cache(self) -> None:\n r\"\"\"\n Clears the cached data structures giving partition information.\n \"\"\"\n self._partition_parameters_cache.clear()\n self._param_to_rank_cache.clear()\n self._index_to_param_cache.clear()\n self._param_to_index_cache.clear()\n\n def add_param_group(self, param_group: dict) -> None:\n r\"\"\"\n Add a param group to the :class:`Optimizer` s ``param_groups``.\n\n This can be useful when fine tuning a pre-trained network, as frozen\n layers can be made trainable and added to the :class:`Optimizer` as\n training progresses.\n\n Arguments:\n param_group (dict): Specifies what Tensors should be optimized\n along with group specific optimization options.\n\n .. warning: This method handles updating the shards on all partitions,\n but needs to be called on all ranks. Calling this on a subset of the\n ranks will cause the training to hang, because communication\n primitives are called depending on the managed parameters, and\n expect all the ranks to participate on the sane set of parameters.\n \"\"\"\n\n super().add_param_group(param_group)\n if self.initialized:\n # Force a re-partitioning\n self._clear_cache()\n\n param_groups = self.partition_parameters()[self.rank]\n if len(param_groups) == len(self.optim.param_groups) + 1:\n self.optim.add_param_group(param_groups[-1])\n\n # Update the bucketing strategy accordingly\n if self.parameters_as_bucket_view:\n self._setup_flat_buffers()\n\n def consolidate_state_dict(self, to: int = 0) -> None:\n r\"\"\"\n Update the consolidated state_dict list, one per rank.\n\n Arguments:\n to (int): the rank that receives the global states. (default: 0)\n\n .. warning: This needs to be called on all replicas\n \"\"\"\n\n # Sync lr and other attributes in case its been updated\n self._sync_param_groups(self.param_groups, self.optim.param_groups)\n\n empty_messenger = torch.tensor([0], dtype=torch.uint8, device=self._device)\n\n # Pull the sharded state from all the other replicas\n # Store all the states in order, rank by rank\n\n # NOTE: In practice, `broadcast` is used, which is wasteful (gather would have been appropriate)\n # compatibility issues with some backends make the use of broadcast mandatory for now.\n # a possible follow up would be to move all sharded state management to RPC RRef\n\n self._all_states = []\n for rank in range(self.world_size):\n global_rank = _get_global_rank(self.group, rank)\n\n # This rank collects the whole state\n if self.rank == to:\n if rank == self.rank:\n self._all_states.append(\n _recursive_copy_to_device(\n self.local_state_dict(),\n non_blocking=True,\n device=torch.device(\"cpu\"),\n )\n )\n else:\n # Fetch the optim state from the other replicas\n replica_state = _broadcast_object(\n empty_messenger,\n src_rank=global_rank,\n group=self.group,\n dist_device=self._device,\n )\n\n self._all_states.append(\n _recursive_copy_to_device(replica_state, non_blocking=True, device=torch.device(\"cpu\"))\n )\n else:\n # Acknowledge broadcasts, and send this rank's shard when needed\n # Default to CPU space to gain some memory headroom\n if rank == self.rank:\n # Send the state to the reference replica\n _ = _broadcast_object(\n self.local_state_dict(),\n src_rank=self.global_rank,\n group=self.group,\n dist_device=self._device,\n )\n\n elif rank != to:\n # Discard this tensor/rank, broadcast was being use for compatibility reasons\n _ = _broadcast_object(\n empty_messenger,\n src_rank=global_rank,\n group=self.group,\n dist_device=self._device,\n )\n\n def partition_parameters(self) -> List[List[Dict]]:\n r\"\"\"\n Partitions parameters across distributed data parallel ranks.\n\n Returns:\n a list of ``param_groups`` (which is a list of dict) where each\n element of the list contains the param_groups for a rank. Element 0\n corresponds to rank 0, etc. We need all the ranks for the broadcast\n inside ``step()``.\n\n NOTE: `test_sharding()` and `test_add_param_group()` rely on this\n function using the sorted-greedy algorithm for partitioning. If the\n algorithm is changed, please re-examine those two tests in\n `test_zero_redundancy_optimizer.py` accordingly.\n \"\"\"\n if len(self._partition_parameters_cache) == 0:\n self._partition_parameters_cache = [list() for _ in range(self.world_size)]\n sizes = [0] * self.world_size\n for param_group in self.param_groups:\n param_lists: List[List] = [list() for _ in range(self.world_size)]\n # Sort the params by size (largest first)\n params_sorted = sorted(param_group[\"params\"], key=lambda t: t.size()[0], reverse=True)\n for param in params_sorted:\n # Add this param to rank with smallest size.\n rank = sizes.index(min(sizes))\n param_lists[rank].append(param)\n sizes[rank] += param.numel()\n\n for rank, params in enumerate(param_lists):\n param_group_rank = copy.copy(param_group)\n param_group_rank[\"params\"] = params\n self._partition_parameters_cache[rank].append(param_group_rank)\n\n return self._partition_parameters_cache\n\n @property\n def _param_to_rank(self) -> Dict[torch.Tensor, int]:\n r\"\"\"\n Hash table mapping parameters to their assigned data parallel rank in\n the partition.\n \"\"\"\n if len(self._param_to_rank_cache) == 0:\n for rank, param_groups in enumerate(self.partition_parameters()):\n for param_group in param_groups:\n for param in param_group[\"params\"]:\n self._param_to_rank_cache[param] = rank\n return self._param_to_rank_cache\n\n @property\n def _param_to_index(self) -> Dict[int, int]:\n r\"\"\"\n Hash table mapping parameters to their indices in the global optimizer\n scheme.\n \"\"\"\n if len(self._param_to_index_cache) == 0:\n self._param_to_index_cache = {\n id(p): i for i, p in enumerate(chain(*(g[\"params\"] for g in self.param_groups)))\n }\n return self._param_to_index_cache\n\n @property\n def _index_to_param(self) -> Dict[int, torch.Tensor]:\n r\"\"\"\n List mapping parameter indices in the global optimizer scheme to the\n actual params.\n \"\"\"\n if len(self._index_to_param_cache) == 0:\n self._index_to_param_cache = list(chain(*(g[\"params\"] for g in self.param_groups)))\n return self._index_to_param_cache\n\n def step(self, closure: Optional[Callable[[], float]] = None, **kwargs: Any) -> Optional[float]:\n r\"\"\"\n Performs a single optimization step (parameter update).\n\n Arguments:\n closure (callable): A closure that reevaluates the model and\n returns the loss. Optional for most optimizers.\n Returns:\n optional loss, depends on the underlying optimizer\n\n .. note: Any extra parameter is passed to the base optimizer as-is\n \"\"\"\n\n # Check whether the model trainability graph changed\n trainable_mask = list(map(_is_trainable, self._all_params))\n if trainable_mask != self._reference_is_trainable_mask:\n logging.warning(\n \"ZeroRedundancyOptimizer detected that the trainable params \"\n \"changed, updating the partitioning\"\n )\n self._update_trainable()\n self._reference_is_trainable_mask = trainable_mask\n\n # Sync oss param_groups attributes in case they've been updated by a scheduler.\n self._sync_param_groups(self.param_groups, self.optim.param_groups)\n\n # Run the optimizer step on this shard only:\n if closure is not None:\n loss = self.optim.step(closure=closure, **kwargs) # type: ignore[call-arg]\n else:\n loss = self.optim.step(**kwargs)\n\n # Sync all the updated shards in between the ranks\n handles = []\n if self.parameters_as_bucket_view:\n for rank, bucket in enumerate(self.buckets):\n global_rank = _get_global_rank(self.group, rank)\n handles.append(\n dist.broadcast(tensor=bucket, src=global_rank,\n group=self.group, async_op=True)\n )\n else:\n for rank, param_groups in enumerate(self.partition_parameters()):\n global_rank = _get_global_rank(self.group, rank)\n for param_group in param_groups:\n for param in param_group[\"params\"]:\n handles.append(\n dist.broadcast(tensor=param.data, src=global_rank,\n group=self.group, async_op=True)\n )\n _ = list(map(lambda x: x.wait(), handles))\n\n # Sync hypothethical new results from the wrapped optimizer to the exposed param_groups\n self._sync_param_groups(self.optim.param_groups, self.param_groups)\n\n return loss\n\n def load_state_dict(self, state_dict: Dict[str, Any]) -> None:\n r\"\"\"\n Restore the global parameter groups as well as the shard.\n\n Arguments:\n state_dict (dict): optimizer state. Should be an object returned\n from a call to :meth:`state_dict`\n \"\"\"\n\n for key, value in state_dict[\"state\"].items():\n param = self._index_to_param[key]\n\n # Populate the sharded optimizer state on the fly\n if self._param_to_rank[param] != self.rank:\n state_dict[\"state\"][key] = None\n else:\n self.optim.state[param] = _recursive_copy_to_device(value, non_blocking=True, device=param.device)\n\n super().load_state_dict(state_dict)\n\n # Sync with the optimizer param groups\n self._sync_param_groups(state_dict[\"param_groups\"], self.param_groups)\n self._sync_param_groups(self.param_groups, self.optim.param_groups)\n\n def local_state_dict(self) -> Dict:\n r\"\"\"\n Gets this rank's ``state_dict``.\n\n Returns:\n The state of the optimizer as a :class:`dict`.\n It contains two entries:\n\n * state - a dict holding current optimization state. Its content\n differs between optimizer classes.\n * param_groups - a dict containing all parameter groups\n \"\"\"\n return self.optim.state_dict()\n\n def state_dict(self) -> Dict[str, Any]:\n r\"\"\"\n Returns:\n the last known global optimizer state, which consist of a list of\n the shards.\n\n .. warning:\n If the state has not been consolidated, this returns a shard's worth,\n not the global state.\n\n .. warning:\n Returning the global state is limited to the replica which was\n responsible for the consolidation. The state may also not be up to\n date, depending on when :meth:`consolidate_state_dict` was last called.\n \"\"\"\n\n if len(self._all_states) == 0:\n raise RuntimeError(\n \"Optimizer state has not been consolidated on this rank. \\\n Please call `consolidate_state_dict()` on all ranks beforehand if you meant to save the global state\"\n )\n\n # Unify the shard states and the state that pytorch would expect, given the model.\n # Indexation needs several redirections, since each shard only knows a limited scope of the model\n # - get the pytorch compliant parameter indexing\n state_dict = super().state_dict()\n\n # - go through the per-shard states, which are all indexed locally\n for rank, s in enumerate(self._all_states):\n # -- match the local indexing and the global partition, update the corresponding saved state globally\n for local_pg, global_pg in zip(s[\"param_groups\"], self.partition_parameters()[rank]):\n local_index_to_param_id = {\n i_param: id(global_pg[\"params\"][i]) for i, i_param in enumerate(local_pg[\"params\"])\n }\n\n for local_param_index in local_pg[\"params\"]:\n # Update the state, if any\n if local_param_index in s[\"state\"].keys():\n global_id = self._param_to_index[local_index_to_param_id[local_param_index]]\n state_dict[\"state\"][global_id] = s[\"state\"][local_param_index]\n\n # Make sure that the parameters are sorted in the state, as expected\n state_dict[\"state\"] = dict(sorted(state_dict[\"state\"].items()))\n return state_dict\n\n @staticmethod\n def rank_local_state_dict(rank: int, state_dict: dict) -> dict:\n r\"\"\"\n Returns the local_state_dict for a given rank.\n\n Arguments:\n rank (int): rank to get ``local_state_dict`` for\n state_dict (dict): global ``state_dict``\n \"\"\"\n param_groups = state_dict[\"param_groups\"][state_dict[\"partition\"][rank][0] : state_dict[\"partition\"][rank][1]]\n return {\"state\": state_dict[\"state\"][rank], \"param_groups\": param_groups}\n\n @staticmethod\n def _sync_param_groups(source: List[Dict[Any, Any]], destination: List[Dict[Any, Any]]) -> None:\n r\"\"\"Sync learning rate and other optimizer attributes (needed to support schedulers).\"\"\"\n\n for source_group, destination_group in zip(source, destination):\n # Sync everything but the parameters\n for k in filter(lambda x: x != \"params\", source_group.keys()):\n destination_group[k] = source_group[k]\n\n def _setup_flat_buffers(self) -> None:\n r\"\"\"\n Make all params which are on the same device and tied to the same rank\n views of a single buffer. This is used at construction time, and\n anytime parameter trainability is changed (frozen or unfrozen) and\n ``_update_trainable`` is called.\n \"\"\"\n for rank, param_groups in enumerate(self.partition_parameters()):\n # Clone the non-trainable params, find the buffer size and dtype\n # for the trainable params' bucket, and compile a list of the\n # trainable params\n buffer_size = 0\n dtype = None\n trainable_params = []\n for param_group in param_groups:\n for param in param_group[\"params\"]:\n if not _is_trainable(param):\n param.data = param.data.detach().clone()\n else:\n buffer_size += param.numel()\n trainable_params.append(param)\n dtype = param.dtype # assumes all dense and same dtype\n\n # Create a dummy bucket if there are no params\n if buffer_size == 0:\n self.buckets.append(torch.zeros(1, device=self._device))\n continue\n\n # Otherwise, construct the bucket\n bucket = torch.empty(buffer_size, dtype=dtype, device=self._device)\n offset = 0\n for param in trainable_params:\n offset_next = offset + param.numel()\n bucket[offset:offset_next].copy_(param.data.flatten())\n param.data = bucket[offset:offset_next].view_as(param.data)\n offset = offset_next\n\n # Either replace the existing bucket or create it\n if len(self.buckets) != rank:\n self.buckets[rank] = bucket\n else:\n self.buckets.append(bucket)\n\n def _update_trainable(self) -> None:\n r\"\"\"\n Updates the partitioning and communication patterns if the trainability\n (``requires_grad``) of some parameters changed.\n \"\"\"\n\n # Create the optim which will work on the param shard\n if not hasattr(self, \"optim\"):\n self._clear_cache()\n self.optim = self._optim_constructor(self.partition_parameters()[self.rank], **self._optim_defaults)\n self._sync_param_groups(self.optim.param_groups, self.param_groups)\n\n if self.parameters_as_bucket_view:\n self._setup_flat_buffers()\n\n def _verify_and_init_params(self, params: Any) -> None:\n r\"\"\"\n Verifies the type of ``params`` and initializes ``self._all_params``\n if ``params`` is valid.\n\n While :class:`optim.Optimizer ` allows\n ``params`` to be an iterable of :class:`dict` s, currently\n ``ZeroRedundancyOptimizer`` strictly requires ``params`` to be an\n iterable of :class:`torch.Tensor` s.\n\n Raises:\n TypeError: ``params`` has an invalid type.\n ValueError: ``params`` is empty.\n \"\"\"\n if isinstance(params, torch.Tensor):\n raise TypeError(\"params argument should be an iterable of \"\n f\"Tensors, but got {torch.typename(params)}\")\n try:\n self._all_params = list(params)\n except TypeError:\n raise TypeError(\"params argument should be an iterable of \"\n f\"Tensors, but got {torch.typename(params)}\")\n if len(self._all_params) == 0:\n raise ValueError(\"ZeroRedundancyOptimizer got an empty parameter \"\n \"list\")\n for param in self._all_params:\n if not isinstance(param, torch.Tensor):\n raise TypeError(\"params argument should be an iterable of \"\n \"Tensors, but got an iterable containing \"\n f\"{torch.typename(param)}\")\n\n def _verify_same_param_device(self) -> None:\n r\"\"\"\n Verifies that ZeRO is being used under the single-process single-\n device regime where a process operates exclusively on a full model\n replica on a single device.\n\n The function assumes that ``self._all_params`` has been initialized\n and is non-empty.\n\n Raises:\n ValueError: ``params`` contains parameters across multiple\n devices.\n\n NOTE: This function can be removed once support for sharding a rank's\n model parameters across multiple devices is added.\n \"\"\"\n device = self._all_params[0].device\n for param in self._all_params[1:]:\n if param.device != device:\n raise ValueError(\"ZeroRedundancyOptimizer assumes that each \"\n \"rank's model parameters are on the same \"\n f\"device but got both {device} and \"\n f\"{param.device}\")\n\n def _verify_same_dense_param_type(self) -> None:\n r\"\"\"\n Verifies that all parameters are of the same dense type.\n\n The function assumes that ``self._all_params`` has been initialized\n and is non-empty.\n\n Raises:\n ValueError: ``params`` contains sparse parameters or parameters\n of varying dense types.\n\n NOTE: This function can be removed once support for sparse parameters\n and varying parameter types is added.\n \"\"\"\n typename = torch.typename(self._all_params[0])\n if self._all_params[0].is_sparse:\n raise ValueError(\"ZeroRedundancyOptimizer only supports using \"\n \"the same dense type for all parameters but got \"\n f\"{typename}\")\n for param in self._all_params[1:]:\n other_typename = torch.typename(param)\n if other_typename != typename:\n raise ValueError(\"ZeroRedundancyOptimizer only supports \"\n \"using the same dense type for all \"\n f\"parameters but got both {typename} and \"\n f\"{other_typename}\")\n","sub_path":"torch/distributed/optim/zero_redundancy_optimizer.py","file_name":"zero_redundancy_optimizer.py","file_ext":"py","file_size_in_byte":28699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"660625","text":"# Connor Bottcher (cb4wa) Luke Masters (lsm5fm)\n\nimport pygame\nimport gamebox\nimport global_stage\nimport level_one\nimport level_two\n\n\nmusic1 = gamebox.load_sound('Spongebob_Uke.wav')\nmusic2 = gamebox.load_sound('Spongebob Pizza song.wav')\n\n\nmusic2_count = 0\ncounter = 0\ncredit_count = 0\nplay_count = 0\noption_count = 0\ncontrol_count = 0\nsound_count = 0\ncamera = global_stage.camera\nlevel_1 = 0\nlevel_2 = 0\nlevel_3 = 0\nwasd_count = 0\nsound_level = 0.5\nchar1 = gamebox.from_color(10, 10, \"red\", 50, 5)\nchar2 = gamebox.from_text(250, 50, \"ya Motha\", \"Cambria\", 70, \"orange\", True, True)\n# char3 = gamebox.from_image(100, 100, \"http://images6.fanpop.com/\n# image/photos/33000000/The-Customer-s-House-krusty-krab-pizza-33032845-512-384.jpg\")\nchar3 = gamebox.from_image(200, 400,\n \"http://3219a2.medialib.glogster.com/creeperman913/media\"\n \"/18/18ee0bb8dd40f9d96af0d3dfd14687f97923fdf2/spongebob.png\")\nchar4 = gamebox.from_text(350, 150, \"By Luke and Connor (lsm5fm and cb4wa)\", \"Cambria\", 30, \"orange\", False, True)\nchar5 = gamebox.from_text(683, 200, \"Press 'P' to Play\", \"Cambria\", 50, \"red\")\nchar6 = gamebox.from_text(683, 400, \"Press 'O' for Options\", \"Cambria\", 50, \"red\")\nchar7 = gamebox.from_text(683, 600, \"Press 'C' for Credits\", \"Cambria\", 50, \"red\")\ntitlebackground = gamebox.from_image(683, 384, \"http://i.imgur.com/liXLthM.png\")\ntitlebackground.size = 1366, 768\npygame.mouse.set_visible(False)\n\n\ndef set_all_volume(keys):\n global sound_count, sound_level\n camera.clear(\"sky blue\")\n if pygame.K_q in keys:\n quit()\n toggle_off = gamebox.from_text(683, 200, \"To turn off sound, press 'n'\", \"Cambria\", 40, \"red\")\n back = gamebox.from_text(125, 50, \"press 'b' for back\", \"Cambria\", 30, \"red\")\n if pygame.K_n in keys:\n music1.stop()\n music2_count = 1\n if pygame.K_b in keys:\n sound_count = 0\n title(keys)\n camera.draw(toggle_off)\n camera.draw(back)\n camera.display()\n\n\ndef control(keys):\n global control_count, wasd_count, arrow_keys_count\n camera.clear(\"sky blue\")\n if pygame.K_q in keys:\n quit()\n txt1 = gamebox.from_text(683, 200, \"press '1' to make your controls wasd\", \"Cambria\", 40, \"red\")\n txt2 = gamebox.from_text(683, 400, \"press '2' to make your controls the arrow keys\", \"Cambria\", 40, \"red\")\n back = gamebox.from_text(125, 50, \"press 'b' for back\", \"Cambria\", 30, \"red\")\n camera.draw(txt1)\n camera.draw(txt2)\n camera.draw(back)\n if pygame.K_b in keys:\n control_count = 0\n title(keys)\n if pygame.K_1 in keys:\n global_stage.wasd_count = 1\n if pygame.K_2 in keys:\n global_stage.wasd_count = 0\n\n camera.display()\n\n\ndef tick_options(keys):\n global control_count, option_count, sound_count\n camera.clear(\"sky blue\")\n if pygame.K_q in keys:\n quit()\n opt1 = gamebox.from_text(683, 200, \"press 't' for controller controls\", \"Cambria\", 40, \"red\")\n opt2 = gamebox.from_text(683, 500, \"press 's' for sound controls\", \"Cambria\", 40, \"red\")\n pic1 = gamebox.from_image(683, 350, \"https://d30y9cdsu7xlg0.cloudfront.net/png/195040-200.png\")\n pic2 = gamebox.from_image(683, 650, \"http://images.clipartpanda.com/music-note-transparent-background-RTAR6agTL.png\")\n back = gamebox.from_text(125, 50, \"press 'b' for back\", \"Cambria\", 30, \"red\")\n pic1.size = 200, 220\n pic2.size = 200, 220\n camera.draw(opt1)\n camera.draw(opt2)\n camera.draw(pic1)\n camera.draw(pic2)\n camera.draw(back)\n if pygame.K_t in keys:\n control_count += 1\n if pygame.K_s in keys:\n sound_count += 1\n if control_count != 0:\n control(keys)\n if pygame.K_b in keys:\n option_count = 0\n if option_count == 0:\n title(keys)\n if sound_count != 0:\n set_all_volume(keys)\n if control_count == 0 and sound_count == 0:\n camera.display()\n\n\ndef tick_creds(keys):\n global credit_count\n cred_char = gamebox.from_text(683, 200,\n \"A special thanks to the following: Luther Tychonievich for the gamebox functions\", \"Cambria\", 40, \"red\")\n back = gamebox.from_text(125, 50, \"press 'b' for back\", \"Cambria\", 30, \"red\")\n camera.clear(\"sky blue\")\n if pygame.K_q in keys:\n quit()\n camera.draw(cred_char)\n camera.draw(back)\n camera.display()\n if pygame.K_b in keys:\n credit_count = 0\n if credit_count == 0:\n title(keys)\n\n\ndef title(keys):\n global credit_count, play_count, option_count, sound_level\n pygame.mixer.music.set_volume(sound_level)\n if pygame.K_q in keys:\n quit()\n camera.clear(\"red\")\n camera.draw(titlebackground)\n camera.draw(char2)\n camera.draw(char4)\n camera.draw(char5)\n camera.draw(char6)\n camera.draw(char7)\n camera.draw(char3)\n if pygame.K_p in keys:\n global_stage.level += 1\n if pygame.K_o in keys:\n option_count += 1\n if pygame.K_c in keys:\n credit_count += 1\n if credit_count != 0:\n tick_creds(keys)\n if option_count != 0:\n tick_options(keys)\n if global_stage.level == 1:\n musicplayer1 = music1.play(-1)\n gamebox.timer_loop(30, level_one.tick)\n elif global_stage.level == 2:\n music1.stop()\n musicplayer2 = music2.play(-1)\n gamebox.timer_loop(30, level_two.sponge_run_function)\n if play_count == 0 and credit_count == 0 and option_count == 0:\n camera.display()\n\nwhile global_stage.quit_check == 0:\n if global_stage.level == 0:\n gamebox.timer_loop(30, title)\n if global_stage.level == 1:\n music1 = gamebox.load_sound('Spongebob_Uke.wav')\n musicplayer1 = music1.play(-1)\n gamebox.timer_loop(30, level_one.tick)\n if global_stage.level == 2:\n music1.stop()\n music2 = gamebox.load_sound('Spongebob Pizza song.wav')\n musicplayer2 = music2.play(-1)\n if music2_count != 0:\n music2.stop()\n gamebox.timer_loop(30, level_two.sponge_run_function)\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"630249862","text":"import re\n\nimport discord\n\nfrom . import listener\nfrom .client import log\n\nURL = 'https://discordapp.com/oauth2/authorize?&client_id={bot_id}&scope={scope}&permissions=0x{permissions:x}'\n\n\nclass OnStart(listener.StartTask):\n\n async def task(self):\n log.info('Logged in as ' + self.client.user.name)\n log.info('Add me to your server using {url}'.format(\n url=URL.format(bot_id=self.client.user.id, scope='bot', permissions=self.client.perms))\n )\n\n\nclass HelpCommand(listener.Listener):\n\n async def on_private_message(self, msg: discord.Message):\n if msg.channel.is_private and re.match(r'help', msg.content):\n output = '__**Available commands:**__\\n\\n'\n for cat, helps in sorted(self.get_categories().items()):\n output += '**{}**\\n'.format(cat)\n for h in helps:\n output += '`{title}` {desc}\\n'.format(title=h.title, desc=h.desc)\n output += '\\n'\n await self.client.send_message(msg.channel, output)\n\n def get_categories(self):\n categories = {}\n for c in self.client.listeners:\n help = c.get_help()\n if help is not None:\n cat = help.category\n if cat not in categories:\n categories[cat] = []\n categories[cat].append(help)\n return categories\n\n def get_help(self):\n return listener.Help('Private Message', 'help', 'Display this message')\n","sub_path":"src/bot_framework/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"558303710","text":"import rospy \nfrom sensor_msgs.msg import LaserScan\nfrom geometry_msgs.msg import Twist, Vector3\n\n\nclass Naive_wall_follow:\n def __init__(self):\n rospy.init_node(\"naive-follower\")\n\n self.move = rospy.Publisher('/cmd_vel', Twist, queue_size=10)\n self.tol = rospy.get_param('tol', 0.05)\n \n rospy.Subscriber('/scan', LaserScan, self.differential)\n self.last_range = None\n def differential(self, msg):\n d1, d2 = msg.ranges[10], msg.ranges[100]\n if d1 == 0.0 or d2 == 0.0:\n self.move.publish(self.fwd())\n if self.last_range is None:\n self.last_range = (d1, d2)\n delta1, delta2 = self.last_range[0]-d1, self.last_range[1]-d2\n print(delta1, delta2)\n if delta1 < self.tol or delta2 > self.tol:\n self.move.publish(self.left())\n return\n elif delta1 > self.tol or delta2 < self.tol:\n self.move.publish(self.right())\n return\n else:\n self.move.publish(self.fwd())\n return\n\n def run(self):\n rate = rospy.Rate(2)\n try:\n while not rospy.is_shutdown(): \n rate.sleep()\n except:\n self.move.publish(self.stop())\n\n \n @staticmethod\n def fwd():\n return Twist(linear=Vector3(0.3, 0, 0),\n angular=Vector3(0, 0, 0))\n @staticmethod\n def left():\n return Twist(linear=Vector3(0.1, 0, 0),\n angular=Vector3(0, 0, 0.1))\n\n @staticmethod\n def right():\n return Twist(linear=Vector3(0.1, 0, 0),\n angular=Vector3(0, 0, -0.1))\n @staticmethod\n def stop():\n return Twist(linear=Vector3(0, 0, 0),\n angular=Vector3(0, 0, 0))\nr = Naive_wall_follow()\nr.run()\n","sub_path":"warmup_project/scripts/wall_follower2.py","file_name":"wall_follower2.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"307036159","text":"\"\"\"Blueprint for machine learning endpoints.\"\"\"\nfrom flask import Blueprint, jsonify, request\n\nimport csv\nimport numpy as np\nimport sklearn\n\nimport engine\nimport state\n\nbp_ml = Blueprint('ml', __name__)\n\n@bp_ml.route('/classifiers')\ndef get_classifiers():\n \"\"\"\n List Available Machine Learning Classifiers\n ---\n tags: [\"Machine Learning\"]\n responses:\n 200:\n description: \"Array of objects specifying available classifers is returned\"\n content:\n application/json:\n schema:\n type: array\n items:\n type: object\n \"\"\"\n\n classifiers = engine.classification.get_classifiers()\n return jsonify(classifiers)\n\n@bp_ml.route('/crossValidate', methods=['POST'])\ndef crossValidate_algorithm():\n \"\"\"\n CrossValidate a machine learning algorithm on the loaded training corpus and return the results.\n ---\n tags: [\"Machine Learning\"]\n requestBody:\n description: \"Cross Validation Options\"\n content:\n application/json:\n schema:\n type: object\n properties:\n classifierId:\n description: \"Identifier for the classification method\"\n type: string\n crossvalidationMethod:\n description: \"Identifier for a cross-validation method. Currently supported options, 'Stratified', 'Random'\"\n type: string\n nFolds:\n description: \"Identifier for a cross-validation method. Currently supported options, 'Stratified', 'Random'\"\n type: integer\n required: [\"classifierId\", \"crossvalidationMethod\", \"nFolds\"]\n responses:\n 200:\n description: \"Cross-validation successful, results returned\"\n content:\n application/json:\n schema:\n type: object\n 428:\n description: \"No corpus loaded\"\n content:\n text/plain:\n schema:\n type: string\n \"\"\"\n\n if not state.corpus:\n return 'No corpus loaded.', 428\n\n classifier_name = request.json.get(\"classifierId\")\n crossvalidation_name = request.json.get(\"crossvalidationMethod\")\n n_folds = int(request.json.get(\"nFolds\"))\n\n # set_feature_expressions()\n clf = engine.classification.build_classifier(classifier_name)\n\n ds = state.proc.run(state.corpus)\n\n # retain only observations from classes with >= n_folds instances\n target_counts = [[t, ds.targets.count(t)] for t in set(ds.targets)]\n keep_targets = [t for [t,c] in target_counts if c >= n_folds]\n keep_obs = [True if t in keep_targets else False for t in ds.targets]\n\n ds = ds.get_obs(keep_obs)\n\n if crossvalidation_name == 'Stratified':\n fold_strategy = sklearn.model_selection.StratifiedKFold(n_splits=n_folds)\n elif crossvalidation_name == 'Random':\n fold_strategy = sklearn.model_selection.KFold(n_splits=n_folds, shuffle=True, random_state=0)\n\n keys = np.zeros(len(ds.y))\n iFold = 0\n for (_, test_index) in fold_strategy.split(ds.data, np.array(ds.y)):\n keys[test_index] = iFold*np.ones(len(test_index))\n iFold = iFold + 1\n\n confs = clf.cross_validate(ds, keys)\n \n state.classifier = clf\n\n confs = np.round(confs, 4)\n\n scores = sklearn.model_selection.cross_val_score(clf.classifier, ds.data, ds.y, cv=fold_strategy)\n\n true_conf = [row[label] for row, label in zip(confs, ds.y)]\n\n class_names = ds.class_names\n result = [(class_names[row.argmax()], row.max()) for row in confs]\n\n [max_label, max_conf] = zip(*result)\n\n output = {'labels':class_names, 'confs':confs.tolist(), 'true_label':ds.targets, 'true_conf':true_conf,\n 'max_label':max_label, 'max_conf':max_conf, 'scores':scores.tolist(), 'mean':scores.mean(),\n 'std':scores.std(), 'obs_info':ds.obs_info, 'method': \"crossValidate\"}\n\n state.last_result = output\n\n return jsonify(output)\n\n@bp_ml.route('/train', methods=['POST'])\ndef train_algorithm():\n \"\"\"\n Train a machine learning algorithm on the loaded training corpus\n ---\n tags: [\"Machine Learning\"]\n requestBody:\n description: \"Classifier Options\"\n content:\n application/json:\n schema:\n type: object\n properties:\n classifierId:\n description: \"Identifier for the classification method\"\n type: string\n required: [\"classifierId\"]\n responses:\n 200:\n description: \"Training successful\"\n content:\n application/json:\n schema:\n type: object\n properties:\n trained:\n description: \"indicates valid training\"\n type: boolean\n 428:\n description: \"No corpus loaded\"\n content:\n text/plain:\n schema:\n type: string\n \"\"\"\n\n if not state.corpus:\n return 'No corpus loaded.', 428\n\n classifier_name = request.json.get(\"classifierId\")\n\n ds = state.proc.run(state.corpus)\n\n clf = engine.classification.build_classifier(classifier_name)\n clf.train(ds)\n state.classifier = clf\n return jsonify({\"trained\":True})\n\n@bp_ml.route('/evaluate', methods=['POST'])\ndef evaluate_algorithm():\n \"\"\"\n Evaluate a previously trained machine learning algorithm on the test corpus\n ---\n tags: [\"Machine Learning\"]\n responses:\n 200:\n description: \"Evaluation successful, results returned\"\n content:\n application/json:\n schema:\n type: object\n 428:\n description: \"No test corpus loaded\"\n content:\n text/plain:\n schema:\n type: string\n \"\"\"\n\n if not state.test_corpus:\n return 'No test corpus loaded.', 428\n\n ds = state.proc.run(state.test_corpus)\n confs = state.classifier.test(ds)\n confs = np.round(confs, 4)\n\n class_names = state.classifier.class_names\n result = [(class_names[row.argmax()], row.max()) for row in confs]\n\n [max_label, max_conf] = zip(*result)\n\n output = {'labels':class_names, 'confs':confs.tolist(), 'max_label':max_label, 'max_conf':max_conf, 'obs_info':ds.obs_info, 'method': \"test\"}\n\n state.last_result = output\n return jsonify(output)\n\n@bp_ml.route('/results/export', methods=['POST'])\ndef export_data():\n \"\"\"\n Export the results of most recent classifier evaluations\n ---\n tags: [\"Machine Learning\"]\n requestBody:\n description: \"Path to the file to write\"\n content:\n application/json:\n schema:\n type: object\n properties:\n path:\n description: \"file/path/to/the/export\"\n type: string\n required: [\"path\"]\n responses:\n 200:\n description: \"Export successful\"\n content:\n application/json:\n schema:\n type: object\n properties:\n export:\n description: \"indiciation of successful export\"\n type: boolean\n 400:\n description: \"Unable to write to file\"\n content:\n text/plain:\n schema:\n type: string\n 428:\n description: \"No recent results found\"\n content:\n text/plain:\n schema:\n type: string\n \"\"\"\n\n export_file = request.json.get('path')\n\n if not state.last_result:\n return \"No recent results found\", 428\n\n success = False\n with open(export_file, \"w\", newline='') as fid:\n data = engine.io.results_dict_to_array(state.last_result)\n cw = csv.writer(fid)\n cw.writerows(data)\n success = True\n\n if success:\n return jsonify({\"export\":True})\n else:\n return 'Failed to export results to this file.', 400","sub_path":"server/blueprint_ml.py","file_name":"blueprint_ml.py","file_ext":"py","file_size_in_byte":8602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"294335856","text":"from mnist import MNIST\nimport tensorflow.examples.tutorials.mnist.input_data\n\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\nprob = svm_problem(trainLabel, trainImage)\n\nparam = svm_parameter('-t 0 -c 10')\n\nm = svm_train(prob, param)\n\nm.predict(testLabel, testImage)","sub_path":"DigitRecognition/DigitRecog.py","file_name":"DigitRecog.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"151210910","text":"import os\nfrom time import sleep as _sleep\nfrom time import time as _time\nfrom .logger import Logger\nfrom clients.NarrativeJobServiceClient import NarrativeJobService as NJS\nfrom clients.authclient import KBaseAuth\nfrom .MethodRunner import MethodRunner\nfrom .SpecialRunner import SpecialRunner\nfrom .callback_server import start_callback_server\nfrom socket import gethostname\nfrom multiprocessing import Process, Queue\nfrom .provenance import Provenance\nfrom queue import Empty\nimport socket\nimport signal\nfrom .CatalogCache import CatalogCache\nimport requests\n\n\nclass JobRunner(object):\n \"\"\"\n This class provides the mechanisms to launch a KBase job\n on a container runtime. It handles starting the callback service\n to support subjobs and provenenace calls.\n \"\"\"\n\n def __init__(self, config, njs_url, job_id, token, admin_token):\n \"\"\"\n inputs: config dictionary, NJS URL, Job id, Token, Admin Token\n \"\"\"\n self.njs = NJS(url=njs_url, timeout=60)\n self.logger = Logger(njs_url, job_id, njs=self.njs)\n self.token = token\n self.client_group = os.environ.get(\"AWE_CLIENTGROUP\", \"None\")\n self.admin_token = admin_token\n self.config = self._init_config(config, job_id, njs_url)\n self.hostname = gethostname()\n self.auth = KBaseAuth(config.get('auth-service-url'))\n self.job_id = job_id\n self.workdir = config.get('workdir', '/mnt/awe/condor')\n self.jr_queue = Queue()\n self.callback_queue = Queue()\n self.prov = None\n self._init_callback_url()\n self.mr = MethodRunner(self.config, job_id, logger=self.logger)\n self.sr = SpecialRunner(self.config, job_id, logger=self.logger)\n self.cc = CatalogCache(config)\n self.max_task = config.get('max_tasks', 20)\n signal.signal(signal.SIGINT, self.shutdown)\n\n def _init_config(self, config, job_id, njs_url):\n \"\"\"\n Initialize config dictionary\n \"\"\"\n config['hostname'] = gethostname()\n config['job_id'] = job_id\n config['njs_url'] = njs_url\n config['cgroup'] = self._get_cgroup()\n token = self.token\n config['token'] = token\n config['admin_token'] = self.admin_token\n return config\n\n def _check_job_status(self):\n \"\"\"\n returns True if the job is still okay to run.\n \"\"\"\n try:\n status = self.njs.check_job_canceled({'job_id': self.job_id})\n except Exception:\n self.logger.error(\"Warning: Job cancel check failed. Continuing\")\n return True\n if status.get('finished', False):\n return False\n return True\n\n def _init_workdir(self):\n # Check to see for existence of /mnt/awe/condor\n if not os.path.exists(self.workdir):\n self.logger.error(\"Missing workdir\")\n raise OSError(\"Missing Working Directory\")\n\n def _get_cgroup(self):\n pid = os.getpid()\n cfile = \"/proc/{}/cgroup\".format(pid)\n if not os.path.exists(cfile):\n return None\n with open(cfile) as f:\n for line in f:\n if line.find('htcondor') > 0:\n items = line.split(':')\n if len(items) == 3:\n return items[2]\n return \"Unknown\"\n\n def _submit_special(self, config, job_id, data):\n \"\"\"\n Handler for methods such as CWL, WDL and HPC\n \"\"\"\n (module, method) = data['method'].split('.')\n self.logger.log(\"Submit %s as a %s:%s job\" % (job_id, module, method))\n\n self.sr.run(config, data, job_id,\n callback=self.callback_url,\n fin_q=[self.jr_queue])\n\n def _submit(self, config, job_id, data, subjob=True):\n (module, method) = data['method'].split('.')\n version = data.get('service_ver')\n module_info = self.cc.get_module_info(module, version)\n\n git_url = module_info['git_url']\n git_commit = module_info['git_commit_hash']\n if not module_info['cached']:\n fstr = 'Running module {}: url: {} commit: {}'\n self.logger.log(fstr.format(module, git_url, git_commit))\n else:\n version = module_info['version']\n f = 'WARNING: Module {} was already used once for this job. '\n f += 'Using cached version: url: {} '\n f += 'commit: {} version: {} release: release'\n self.logger.error(f.format(module, git_url, git_commit, version))\n\n vm = self.cc.get_volume_mounts(module, method, self.client_group)\n config['volume_mounts'] = vm\n action = self.mr.run(config, module_info, data, job_id,\n callback=self.callback_url, subjob=subjob,\n fin_q=self.jr_queue)\n self._update_prov(action)\n\n def _cancel(self):\n self.mr.cleanup_all()\n\n def shutdown(self, sig, bt):\n print(\"Recieved an interupt\")\n # Send a cancel to the queue\n self.jr_queue.put(['cancel', None, None])\n\n def _watch(self, config):\n # Run a thread to check for expired token\n # Run a thread for 7 day max job runtime\n cont = True\n ct = 1\n exp_time = self._get_token_lifetime(config) - 600\n while cont:\n try:\n req = self.jr_queue.get(timeout=1)\n if _time() > exp_time:\n err = \"Token has expired\"\n self.logger.error(err)\n self._cancel()\n return {'error': err}\n if req[0] == 'submit':\n if ct > self.max_task:\n self.logger.error(\"Too many subtasks\")\n self._cancel()\n return {'error': 'Canceled or unexpected error'}\n if req[2].get('method').startswith('special.'):\n self._submit_special(config, req[1], req[2])\n else:\n self._submit(config, req[1], req[2])\n ct += 1\n elif req[0] == 'finished_special':\n job_id = req[1]\n self.callback_queue.put(['output', job_id, req[2]])\n ct -= 1\n elif req[0] == 'finished':\n subjob = True\n job_id = req[1]\n if job_id == self.job_id:\n subjob = False\n output = self.mr.get_output(job_id, subjob=subjob)\n self.callback_queue.put(['output', job_id, output])\n ct -= 1\n if not subjob:\n if ct > 0:\n err = \"Orphaned containers may be present\"\n self.logger.error(err)\n return output\n elif req[0] == 'cancel':\n self._cancel()\n return {}\n except Empty:\n pass\n if ct == 0:\n print(\"Count got to 0 without finish\")\n # This shouldn't happen\n return\n # Run cancellation / finish job checker\n if not self._check_job_status():\n self.logger.error(\"Job canceled or unexpected error\")\n self._cancel()\n _sleep(5)\n return {'error': 'Canceled or unexpected error'}\n\n def _init_callback_url(self):\n # Find a free port and Start up callback server\n if os.environ.get('CALLBACK_IP') is not None:\n self.ip = os.environ.get('CALLBACK_IP')\n self.logger.log(\"Callback IP provided ({})\".format(self.ip))\n else:\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"gmail.com\", 80))\n self.ip = s.getsockname()[0]\n s.close()\n sock = socket.socket()\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.bind(('', 0))\n self.port = sock.getsockname()[1]\n sock.close()\n url = 'http://{}:{}/'.format(self.ip, self.port)\n self.logger.log(\"Job runner recieved Callback URL {}\".format(url))\n self.callback_url = url\n\n def _update_prov(self, action):\n self.prov.add_subaction(action)\n self.callback_queue.put(['prov', None, self.prov.get_prov()])\n\n def _validate_token(self):\n # Validate token and get user name\n try:\n user = self.auth.get_user(self.config['token'])\n except Exception:\n self.logger.error(\"Token validation failed\")\n raise Exception()\n\n return user\n\n def _get_token_lifetime(self, config):\n try:\n url = config.get('auth.service.url.v2')\n header = {'Authorization': self.config['token']}\n resp = requests.get(url, headers=header).json()\n return resp['expires']\n except Exception as e:\n self.logger.error(\"Failed to get token lifetime\")\n raise e\n\n def run(self):\n \"\"\"\n This method starts the actual run. This is a blocking operation and\n will not return until the job finishes or encounters and error.\n This method also handles starting up the callback server.\n \"\"\"\n self.logger.log('Running on {} ({}) in {}'.format(self.hostname,\n self.ip,\n self.workdir))\n self.logger.log('Client group: {}'.format(self.client_group))\n\n # Check to see if the job was run before or canceled already.\n # If so, log it\n if not self._check_job_status():\n self.logger.error(\"Job already run or canceled\")\n raise OSError(\"Canceled job\")\n\n # Get job inputs from njs db\n try:\n job_params = self.njs.get_job_params(self.job_id)\n except Exception as e:\n self.logger.error(\"Failed to get job parameters. Exiting.\")\n raise e\n\n params = job_params[0]\n config = job_params[1]\n config['job_id'] = self.job_id\n\n server_version = config['ee.server.version']\n fstr = 'Server version of Execution Engine: {}'\n self.logger.log(fstr.format(server_version))\n\n # Update job as started and log it\n self.njs.update_job({'job_id': self.job_id, 'is_started': 1})\n\n self._init_workdir()\n config['workdir'] = self.workdir\n config['user'] = self._validate_token()\n\n self.prov = Provenance(params)\n\n # Start the callback server\n cb_args = [self.ip, self.port, self.jr_queue, self.callback_queue,\n self.token]\n cbs = Process(target=start_callback_server, args=cb_args)\n cbs.start()\n\n # Submit the main job\n self._submit(config, self.job_id, params, subjob=False)\n\n output = self._watch(config)\n\n cbs.kill()\n self.logger.log('Job is done')\n self.njs.finish_job(self.job_id, output)\n # TODO: Attempt to clean up any running docker containers\n # (if something crashed, for example)\n return output\n\n # Run docker or shifter\tand keep a record of container id and\n # subjob container ids\n # Run a job shutdown hook\n","sub_path":"JobRunner/JobRunner.py","file_name":"JobRunner.py","file_ext":"py","file_size_in_byte":11384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"205602862","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /tmp/pip-install-m_4qh6p6/tqdm/tqdm/_utils.py\n# Compiled at: 2019-07-30 18:47:12\n# Size of source mod 2**32: 7868 bytes\nimport os, subprocess\nfrom platform import system as _curos\nimport re\nCUR_OS = _curos()\nIS_WIN = CUR_OS in ('Windows', 'cli')\nIS_NIX = not IS_WIN and any(CUR_OS.startswith(i) for i in ('CYGWIN', 'MSYS', 'Linux',\n 'Darwin', 'SunOS', 'FreeBSD',\n 'NetBSD', 'OpenBSD'))\nRE_ANSI = re.compile('\\\\x1b\\\\[[;\\\\d]*[A-Za-z]')\ntry:\n _range = xrange\nexcept NameError:\n _range = range\n\ntry:\n _unich = unichr\nexcept NameError:\n _unich = chr\n\ntry:\n _unicode = unicode\nexcept NameError:\n _unicode = str\n\ntry:\n if IS_WIN:\n import colorama\n colorama.init()\n else:\n colorama = None\nexcept ImportError:\n colorama = None\n\ntry:\n from weakref import WeakSet\nexcept ImportError:\n WeakSet = set\n\ntry:\n _basestring = basestring\nexcept NameError:\n _basestring = str\n\ntry:\n from collections import OrderedDict as _OrderedDict\nexcept ImportError:\n try:\n from ordereddict import OrderedDict as _OrderedDict\n except ImportError:\n from collections import MutableMapping\n\n class _OrderedDict(dict, MutableMapping):\n\n def __init__(self, *args, **kwds):\n if len(args) > 1:\n raise TypeError('expected at 1 argument, got %d', len(args))\n if not hasattr(self, '_keys'):\n self._keys = []\n (self.update)(*args, **kwds)\n\n def clear(self):\n del self._keys[:]\n dict.clear(self)\n\n def __setitem__(self, key, value):\n if key not in self:\n self._keys.append(key)\n dict.__setitem__(self, key, value)\n\n def __delitem__(self, key):\n dict.__delitem__(self, key)\n self._keys.remove(key)\n\n def __iter__(self):\n return iter(self._keys)\n\n def __reversed__(self):\n return reversed(self._keys)\n\n def popitem(self):\n if not self:\n raise KeyError\n key = self._keys.pop()\n value = dict.pop(self, key)\n return (key, value)\n\n def __reduce__(self):\n items = [[k, self[k]] for k in self]\n inst_dict = vars(self).copy()\n inst_dict.pop('_keys', None)\n return (self.__class__, (items,), inst_dict)\n\n setdefault = MutableMapping.setdefault\n update = MutableMapping.update\n pop = MutableMapping.pop\n keys = MutableMapping.keys\n values = MutableMapping.values\n items = MutableMapping.items\n\n def __repr__(self):\n pairs = ', '.join(map('%r: %r'.__mod__, self.items()))\n return '%s({%s})' % (self.__class__.__name__, pairs)\n\n def copy(self):\n return self.__class__(self)\n\n @classmethod\n def fromkeys(cls, iterable, value=None):\n d = cls()\n for key in iterable:\n d[key] = value\n\n return d\n\n\nclass Comparable(object):\n __doc__ = 'Assumes child has self._comparable attr/@property'\n\n def __lt__(self, other):\n return self._comparable < other._comparable\n\n def __le__(self, other):\n return self < other or self == other\n\n def __eq__(self, other):\n return self._comparable == other._comparable\n\n def __ne__(self, other):\n return not self == other\n\n def __gt__(self, other):\n return not self <= other\n\n def __ge__(self, other):\n return not self < other\n\n\nclass SimpleTextIOWrapper(object):\n __doc__ = \"\\n Change only `.write()` of the wrapped object by encoding the passed\\n value and passing the result to the wrapped object's `.write()` method.\\n \"\n\n def __init__(self, wrapped, encoding):\n object.__setattr__(self, '_wrapped', wrapped)\n object.__setattr__(self, 'encoding', encoding)\n\n def write(self, s):\n \"\"\"\n Encode `s` and pass to the wrapped object's `.write()` method.\n \"\"\"\n return getattr(self, '_wrapped').write(s.encode(getattr(self, 'encoding')))\n\n def __getattr__(self, name):\n return getattr(self._wrapped, name)\n\n def __setattr__(self, name, value):\n return setattr(self._wrapped, name, value)\n\n\ndef _is_utf(encoding):\n try:\n '█▉'.encode(encoding)\n except UnicodeEncodeError:\n return False\n except Exception:\n try:\n return encoding.lower().startswith('utf-') or 'U8' == encoding\n except:\n return False\n\n return True\n\n\ndef _supports_unicode(fp):\n try:\n return _is_utf(fp.encoding)\n except AttributeError:\n return False\n\n\ndef _is_ascii(s):\n if isinstance(s, str):\n for c in s:\n if ord(c) > 255:\n return False\n\n return True\n else:\n return _supports_unicode(s)\n\n\ndef _environ_cols_wrapper():\n \"\"\"\n Return a function which gets width and height of console\n (linux,osx,windows,cygwin).\n \"\"\"\n _environ_cols = None\n if IS_WIN:\n _environ_cols = _environ_cols_windows\n if _environ_cols is None:\n _environ_cols = _environ_cols_tput\n if IS_NIX:\n _environ_cols = _environ_cols_linux\n return _environ_cols\n\n\ndef _environ_cols_windows(fp):\n try:\n from ctypes import windll, create_string_buffer\n import struct\n from sys import stdin, stdout\n io_handle = -12\n if fp == stdin:\n io_handle = -10\n else:\n if fp == stdout:\n io_handle = -11\n h = windll.kernel32.GetStdHandle(io_handle)\n csbi = create_string_buffer(22)\n res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)\n if res:\n _bufx, _bufy, _curx, _cury, _wattr, left, _top, right, _bottom, _maxx, _maxy = struct.unpack('hhhhHhhhhhh', csbi.raw)\n return right - left\n except:\n pass\n\n\ndef _environ_cols_tput(*_):\n \"\"\"cygwin xterm (windows)\"\"\"\n try:\n import shlex\n cols = int(subprocess.check_call(shlex.split('tput cols')))\n return cols\n except:\n pass\n\n\ndef _environ_cols_linux(fp):\n try:\n from termios import TIOCGWINSZ\n from fcntl import ioctl\n from array import array\n except ImportError:\n return\n else:\n try:\n return array('h', ioctl(fp, TIOCGWINSZ, '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'))[1]\n except:\n try:\n return int(os.environ['COLUMNS']) - 1\n except KeyError:\n return\n\n\ndef _term_move_up():\n if os.name == 'nt':\n if colorama is None:\n return ''\n return '\\x1b[A'","sub_path":"pycfiles/djay-0.0.8-py2.py3-none-any/_utils.cpython-36.py","file_name":"_utils.cpython-36.py","file_ext":"py","file_size_in_byte":7152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"143471188","text":"import mysql.connector\nimport pandas as pd\nimport config\n\nbeers = pd.read_csv('beers_revised.csv')\nbeers = beers.where((pd.notnull(beers)), '')\nbreweries = pd.read_csv('breweries_revised.csv')\nbreweries = breweries.where((pd.notnull(breweries)), '')\n\ncnx = mysql.connector.connect(**config.creds)\ncursor = cnx.cursor()\n\nfor _, row in breweries.iterrows():\n\ttry:\n\t\tcursor.execute(\"\"\"\n\t\t\tINSERT INTO breweries VALUES (%s,%s,%s,%s);\n\t\t\"\"\", (row['id'],row['name'],row['city'],row['state']))\n\texcept mysql.connector.errors.IntegrityError:\n\t\tcontinue\n\nfor _, row in beers.iterrows():\n\ttry:\n\t\tcursor.execute(\"\"\"\n\t\t\tINSERT INTO beers VALUES(%s,%s,%s);\n\t\t\"\"\", (row['name'],row['style'],row['brewery_id']))\n\texcept:\n\t\tcontinue\n\nif not input('Press enter if okay'):\n\tcnx.commit()\n\ncursor.close()\ncnx.close()\n\n","sub_path":"pf/data/migrate.py","file_name":"migrate.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"359037","text":"# pylint: disable=no-member,not-callable,wrong-import-order,too-many-locals\n\nimport falcon\nimport murmurhash\nimport numpy as np\nimport scipy.spatial\n\nfrom corpus_index.base_index import Aggregation\nfrom db.models import Sentence\nfrom resources.base import get_raw_sentences_from_payload, CovidResource\n\n\nclass CovidSimilarityResource(CovidResource):\n \"\"\"Corpus Semantic Search.\n\n\n { 'results': [ { 'dist': 0.7293307781219482,\n 'id': 2021055,\n 'label': ['business_commentary_neg'],\n 'nearest': -388907830,\n 'text': 'However, if you were to exclude the Hilton '\n 'Waikoloa Village resort, which was negatively '\n 'impacted by Hurricane Lane and the Klauea '\n 'volcano eruption, RevPAR performance for the '\n 'group would have been 2.1%.'},\n { 'dist': 0.7448862195014954,\n 'id': 125912,\n 'label': ['contract_agreement_deal_pos'],\n 'nearest': -1130842295,\n 'text': 'And then, obviously, you need to find a '\n 'location, which is not too far away from '\n 'downtown San Francisco and downtown L.A. And '\n 'you need to sign up contracts.'},\n { 'dist': 0.7739783525466919,\n 'id': 1584208,\n 'label': ['financial_results_neg'],\n 'nearest': -1130842295,\n 'text': 'This is significantly better than San '\n \"Francisco's RevPAR decline of 3.8% in 2017 and \"\n 'again that is for the city of San Francisco '\n 'not the metropolitan market.'},\n { 'dist': 0.7758655548095703,\n 'id': 628653,\n 'label': ['deception_revenue_neg', 'weather_neg'],\n 'nearest': -1130842295,\n 'text': 'So we looked at our Washington, D.C. '\n 'restaurant or our Houston restaurant, you can '\n 'clearly see significant negative numbers '\n 'coming from the one-off rollovers and we have '\n 'other restaurants that are less impacted by '\n 'weather that are trending positively '\n 'year-to-date.'},\n { 'dist': 0.7799857258796692,\n 'id': 1553453,\n 'label': ['business_commentary_pos'],\n 'nearest': -388907830,\n 'text': 'So you need to see it both, and we see very '\n \"positive developments let's in the Southern \"\n 'cities like Bangalore or Hyderabad.'},\n { 'dist': 0.7810379862785339,\n 'id': 1076013,\n 'label': ['business_commentary_pos'],\n 'nearest': -1130842295,\n 'text': 'We are well positioned with our assets and our '\n 'Play New Jersey brand or Play NJ. And when we '\n 'look on the state level, we now see movements '\n 'in six states, everything from New York, '\n 'Michigan, Illinois, Rhode Island, '\n 'Massachusetts and Connecticut, where we all '\n 'there is something can happen in 2018 '\n 'already.'},\n { 'dist': 0.7842773199081421,\n 'id': 1740568,\n 'label': ['business_commentary_neg'],\n 'nearest': -1130842295,\n 'text': 'And I think Q4 was quite slow for launches in '\n 'Dubai, but I noticed that Emaar had a '\n 'successful launch of Beach Vista.'},\n { 'dist': 0.7871336936950684,\n 'id': 194754,\n 'label': ['headwinds_tailwinds_pos'],\n 'nearest': -1130842295,\n 'text': \"So, you'll see markets like Washington, D.C. \"\n 'or Chicago improving.'},\n { 'dist': 0.7891233563423157,\n 'id': 1431841,\n 'label': ['financial_commentary_pos'],\n 'nearest': -1130842295,\n 'text': 'Hotel Zoe, San Francisco and Skamania Lodge '\n 'also generated healthy EBITDA increases in '\n '2017.'},\n { 'dist': 0.7893946766853333,\n 'id': 400243,\n 'label': ['headwinds_tailwinds_neg'],\n 'nearest': -1130842295,\n 'text': 'Divisions where we felt the greatest impact '\n 'for market conditions were Jacksonville, '\n 'Phoenix and Tampa.'}],\n 'sentences': [ { 'id': -1130842295,\n 'text': \"I think it's like a 25% increase in \"\n 'profits.'},\n { 'id': -484700953,\n 'text': 'So this has been units, I mean, really an '\n 'increase in units in the stores.'},\n { 'id': -388907830,\n 'text': 'Our bookings have continued in the last '\n 'couple of quarters to increase.'}]}\n\n \"\"\"\n\n def on_post(self, req, resp):\n \"\"\"Handle POST request.\"\"\"\n sentences = get_raw_sentences_from_payload(req)\n method = req.params.get('method', 'union')\n limit = int(req.params.get('limit', '10'))\n\n sentence_encoder = self.sentence_encoder\n corpus_index = self.corpus_index\n db_session = self.db_session\n\n try:\n resp.status = falcon.HTTP_200\n resp.media = self.similar_k(sentences, sentence_encoder, corpus_index, db_session, method=method,\n limit=limit)\n except Exception as e:\n self.logger.error('fatal error: %s', e)\n raise falcon.HTTP_INTERNAL_SERVER_ERROR('Internal Server Error')\n\n @staticmethod\n def similar_k(input_sentences, sentence_encoder, corpus_index, db_session, limit=10, method='union',\n group_by='cosine'):\n \"\"\"Find similar sentences.\n\n Args:\n input_sentences (str/list[str]): one or more input sentences.\n sentence_encoder : encoder\n limit (int): limit result set size to ``limit``.\n corpus_index : type of corpus where to fetch the suggestions from\n db_session : Database to get neighbors from\n method (str): aggregation method ('union', 'mean', 'pc1', 'pc2').\n group_by (str): distance metric to use to group the result set. Default is 'cosine'.\n\n Returns:\n list\n \"\"\"\n res = []\n nearest = dict()\n\n if method == 'textrank':\n from nlp.textrank import calc_textrank # pylint: disable=import-outside-toplevel\n _, _, _, phrase_list = calc_textrank(input_sentences, num_phrases=5)\n input_sentences = [' '.join(phrase[0] for phrase in phrase_list)]\n method = Aggregation.UNION\n\n embeddings = sentence_encoder.encode(input_sentences)\n indices = [murmurhash.hash(sent) for sent in input_sentences]\n\n for idx, dist in corpus_index.knn_query_batch(embeddings, ids=indices, limit=limit, method=method):\n if idx not in nearest:\n nearest[idx] = dist\n else:\n nearest[idx] = min(nearest[idx], dist)\n\n for sentence in db_session.query(Sentence).filter(Sentence.id.in_(nearest.keys())).all():\n sentence_dict = sentence.to_dict()\n encoding = sentence_encoder.encode(sentence.sentence)\n distances = scipy.spatial.distance.cdist(encoding, embeddings, group_by)\n nearest_idx = int(np.argmax(distances))\n sentence_dict['nearest'] = indices[nearest_idx]\n sentence_dict['dist'] = nearest[sentence.id]\n res.append(sentence_dict)\n\n return {\n 'results': sorted(res, key=lambda x: x['dist']),\n 'sentences': [\n {\n 'id': sent_id,\n 'text': sent\n } for sent_id, sent in zip(indices, input_sentences)\n ]\n }\n","sub_path":"src/resources/similarity.py","file_name":"similarity.py","file_ext":"py","file_size_in_byte":9348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"565247544","text":"\"\"\"\nServer socket for multi client connections\n\"\"\"\n\nimport socket\nimport sys\nimport traceback\nimport select\nimport queue\n\n\ndef server(log_buffer=sys.stderr):\n # set an address for our server\n address = ('127.0.0.1', 10000)\n\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)\n\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n # log that we are building a server\n print(\"making a server on {0}:{1}\".format(*address), file=log_buffer)\n\n sock.bind(address)\n sock.listen(5)\n\n inputs = [sock]\n outputs = []\n message_queues = {}\n\n try:\n # the outer loop controls the creation of new connection sockets. The\n # server will handle each incoming connection one at a time.\n while inputs:\n\n read_server, write_server, excep_server = select.select(inputs, outputs, [])\n\n for s in read_server:\n if s is sock:\n conn, addr = s.accept()\n print('connection - {0}:{1}'.format(*addr), file=log_buffer)\n conn.setblocking(0)\n inputs.append(conn)\n message_queues[conn] = queue.Queue()\n else:\n # Collecting 16 bytes of data at a time\n data = s.recv(16)\n if data:\n print('Received: {}'.format(data), file=log_buffer)\n message_queues[s].put(data)\n if s not in outputs:\n outputs.append(s)\n break\n else:\n if s in outputs:\n outputs.remove(s)\n inputs.remove(s)\n print('Closing conn - {0}:{1}'.format(*addr), file=log_buffer)\n s.close()\n del message_queues[s]\n\n for s in write_server:\n try:\n next_msg = message_queues[s].get_nowait()\n print('Sending: {}'.format(next_msg), file=log_buffer)\n except queue.Empty:\n outputs.remove(s)\n else:\n s.send(next_msg)\n\n for s in excep_server:\n inputs.remove(s)\n if s in outputs:\n outputs.remove(s)\n s.close()\n del message_queues[s]\n\n except Exception as e:\n traceback.print_exc()\n print(f'Exception: {e}')\n sock.close()\n print('quitting echo server', file=log_buffer)\n\n\nif __name__ == '__main__':\n server()\n sys.exit(0)\n","sub_path":"echo_server_multi.py","file_name":"echo_server_multi.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"13808505","text":"import requests\nfrom django.http import HttpResponse\n\nfrom ScrapWeb.ScrapApi.main.scrap import MyApi\n\n\n# define view to return API call\ndef myapi(request):\n if request.GET['scrap']:\n url = request.GET['scrap']\n\n html_st = requests.get(url)\n html_str = html_st.text\n\n return HttpResponse(MyApi(url, html_str))\n else:\n return HttpResponse(\"ERROR in atleast one parameter\")","sub_path":"ScrapWeb/ScrapApi/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"344344253","text":"# -*- coding: utf-8 -*-\nimport json\nimport sys\nimport junopy\n\n\ndef main(arg):\n\n junopy.Juno('4E1574938F3DD69306BC336E348276ACC9CBE72B4E8396B2520436663C66C08E',\n '9OuOfYM2QZRhmUug', 'gw self.max_depth:\n return\n\n for entry in os.scandir(path):\n if entry.is_file():\n self._rename_file(entry.path)\n else:\n self._handle_dir(entry.path, depth + 1)\n\n def _rename_file(self, path):\n names = path.rsplit('.', 1)\n\n if len(names) > 1 and names[1] == self.old:\n os.rename(path, '.'.join([names[0], self.new]))\n","sub_path":"fileutils/rename/file_extension.py","file_name":"file_extension.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"476363581","text":"import csv\n\nfout=open('union_input','a')\n\n\nwith open('arealm.csv','rb') as f:\n for line in f:\n eachinput=line.split(',')\n fout.write(eachinput[2]+','+eachinput[3]+','+eachinput[4]+','+eachinput[5]+'\\n')\n\n\n\n","sub_path":"testCases/preprocess/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"209524919","text":"#verbose=False\ndef planar_analysis(is_hyades,t_min=0.1,polar=False,verbose=False,is_1d=False):\n \"\"\"\n Analysis of planar foils. Should be updated to have same dictionary as capsule_analysis\n \"\"\"\n import os\n import numpy as np\n import matplotlib as mpl\n import matplotlib.animation as animation\n from mpl_toolkits.mplot3d import Axes3D\n from matplotlib import pyplot as plt\n import time\n import re\n from netCDF4 import Dataset\n import pyh2d as h2d\n\n if is_hyades:\n a = h2d.read_hyades()\n nz,nr,nt = h2d.g.r_t.shape\n #derived arrays\n h2d.g.dpdr_t = np.zeros((nz-1,nr,nt))\n iz=1\n a = np.diff(h2d.g.ptot_t[:,iz,:],axis=0)/np.diff(h2d.g.r_t[:,iz,:],axis=0)\n im = a <= 0\n a[im] = 1e-12\n h2d.g.dpdr_t[:,iz,:] = np.log(a)\n\n h2d.g.dpdt_t = np.zeros((nz,nr,nt-1))\n a = np.diff(h2d.g.ptot_t[:,iz,:],axis=1)/np.diff(h2d.g.times,axis=0)\n im = a <= 0\n a[im] = 1e-12\n h2d.g.dpdt_t[:,iz,:] = np.log(a)\n\n h2d.g.r_t0 = np.ones_like(h2d.g.den_t)*h2d.g.r_t[:,:,0][:,:,np.newaxis]\n h2d.g.times2d = np.ones_like(h2d.g.den_t)*h2d.g.times\n h2d.g.lsr_pwr_inc_t = 1e-12*np.diff(h2d.g.lsr_eng_inc_t)/np.diff(h2d.g.times*1e-9)\n h2d.g.lsr_pwr_abs_t = np.sum(h2d.g.deplsr_t[:,1,:],axis=0) #W\n elif is_1d:\n a = h2d.read_1d()\n else:\n a = h2d.read(t=0,analysis=False)\n nz,nr = h2d.g.den.shape\n\n ntimes = h2d.g.ntimes\n ts_mn = np.max(np.where(h2d.g.timesW/cm^2\n mass_ = vol_*den_\n if polar:\n z_ = z_.T[::-1,:]\n r_ = r_.T[::-1,:]\n ti_ = ti_.T[::-1,:]\n te_ = te_.T[::-1,:]\n ne_ = ne_.T[::-1,:]\n vz_ = vz_.T[::-1,:]\n vol_ = vol_.T[::-1,:]\n den_ = den_.T[::-1,:]\n lint_ = lint_.T[::-1,:]\n mass_ = vol_*den_\n #Calculate density scalelength\n #itgtz1 = -1\n #print('nr=',nr)\n for ir1 in np.arange(nr):\n failed_dsl = False\n failed_abl = False\n failed_nc = False\n if not is_hyades:\n r1d = r_[ir1,:] \n z1d = z_[ir1,:] \n ti1d = ti_[ir1,:]\n te1d = te_[ir1,:]\n ne1d = ne_[ir1,:]\n vz1d = vz_[ir1,:]\n den1d = den_[ir1,:]\n mass1d= mass_[ir1,:]\n lint1d= lint_[ir1,:]\n imx0 = np.where(h2d.g.reg[0,:]<5)[0][-1]\n else:\n r1d = h2d.g.r_t[:,ir1,n]\n r01d = h2d.g.r_t[:,ir1,0]\n ti1d = h2d.g.tion_t[:,ir1,n]\n te1d = h2d.g.tele_t[:,ir1,n]\n ne1d = h2d.g.ne_t[:,ir1,n]\n vz1d = h2d.g.vr_t[:,ir1,n]\n den1d = h2d.g.den_t[:,ir1,n]\n mass1d= h2d.g.mass_t[:,ir1,n]\n lint1d= h2d.g.lint_t[:,ir1,n]\n \n imx = np.argmax(den1d[:]) #index of maximum density\n try:\n #equation of line between pts either side of nc/4\n #h2d.g.i_nc4[ir1,n] = np.min(np.where(ne1d[:imx]>(nc/4.)))-1 #pt below nc/4\n #h2d.g.i_nc4[ir1,n] = np.min(np.where(ne1d[:imx]>(nc/4.))) #pt above nc/4\n h2d.g.i_nc4[ir1,n] = np.argmin(np.abs(ne1d[:imx]-(nc/4.))) #pt closest to nc/4\n iz = h2d.g.i_nc4[ir1,n]\n di = 3\n if di>1: #average the derivatives over di zones below nc/4\n dne = np.average(np.diff(ne1d[iz-di:iz+1])[0])\n dz = np.average(np.diff( z1d[iz-di:iz+1])[0])\n else:\n dne = np.diff(ne1d[iz-1:iz+1])[0]\n dz = np.diff( z1d[iz-1:iz+1])[0]\n\n m = dne/dz\n c = ne1d[iz] - m*z1d[iz]\n #h2d.g.z_nc4[ir1,n] = (nc/4. - c)/m #Z location of nc/4 at ir1\n h2d.g.z_nc4[ir1,n] = z1d[iz] #don't use linear extrapolation - gets wrong answer when inc4 < nc/4 \n h2d.g.r_nc4[ir1,n] = r1d[iz]\n h2d.g.dsl_nc4[ir1,n] = ne1d[iz]*dz/dne\n '''\n if ir1 == 0:\n plt.semilogy(z1d,ne1d,'-k')\n plt.semilogy(z1d[iz],ne1d[iz],'og')\n print('n=%d, z1d[iz]=%2.2f z actual = %2.2f, ne1d[iz]=%e,nc/4=%e'%(n, z1d[iz],h2d.g.z_nc4[ir1,n],ne1d[iz],nc/4))\n plt.title('timestep %d'%(n))\n plt.draw()\n plt.pause(1)\n '''\n #ne2 = ne1d[inc4b]*np.exp((z1d[:inc4b]-z1d[inc4b])/h2d.g.dsl_nc4[n])\n #Calculate average plasma temperature between nc/10 and nc/4\n i_nc10 = np.min(np.where(ne1d[:iz]>nc/10.))\n h2d.g.tele_nc4[ir1,n] = te1d[iz]\n h2d.g.tion_nc4[ir1,n] = ti1d[iz]\n h2d.g.lint_nc4[ir1,n] = lint1d[iz]\n h2d.g.tele_avg[ir1,n] = np.average(te1d[i_nc10:iz])\n h2d.g.tion_avg[ir1,n] = np.average(ti1d[i_nc10:iz])\n except:\n failed_dsl = True\n\n if not failed_dsl:\n i = h2d.g.i_nc4[ir1,n]\n h2d.g.nc4_areal[ir1,n] = np.sum(den1d[i:-1]*np.diff(z1d[i:]*1e-4))\n\n #position of critical surface\n try:\n arr = np.abs(ne1d[:imx]-nc)\n h2d.g.i_nc[ir1,n] = np.where(arr==np.min(arr))[0][0] #pt nearest nc\n h2d.g.z_nc[ir1,n] = z1d[h2d.g.i_nc[ir1,n]]\n h2d.g.r_nc[ir1,n] = r1d[h2d.g.i_nc[ir1,n]]\n except:\n failed_nc = True\n\n #Calculate ablation front position\n try:\n h2d.g.i_abl[ir1,n] = np.max(np.where(vz1d[:imx] < 0))\n h2d.g.r_abl[ir1,n] = r1d[h2d.g.i_abl[ir1,n]]\n h2d.g.z_abl[ir1,n] = z1d[h2d.g.i_abl[ir1,n]] \n h2d.g.r_abl0[ir1,n] = r01d[h2d.g.i_abl[ir1,n]]\n except:\n failed_abl = True\n if verbose:\n if failed_dsl:\n print('Unable to calculate density scalelength @index %d, @time = %2.3f'%(ir1,times[n]))\n if failed_abl:\n print('Unable to calculate ablation front position @index %d, @time = %2.3f'%(ir1,times[n]))\n if failed_nc:\n print('Unable to calculate critical surface position @index %d, @time = %2.3f'%(ir1,times[n]))\n\n h2d.g.ts_bt = -1\n h2d.g.ts_rho_mx = -1\n","sub_path":"build/lib/pyh2d/planar_analysis.py","file_name":"planar_analysis.py","file_ext":"py","file_size_in_byte":8322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"459570675","text":"ROMANS = {\n 'M': 1000,\n 'CM': 900,\n 'D': 500,\n 'C': 100,\n 'XC': 90,\n 'L': 50,\n 'X': 10,\n 'V': 5,\n 'IV': 4,\n 'I': 1,\n}\n\nclass RomanNumerals:\n def to_roman(n):\n s = ''\n for key, value in ROMANS.items():\n while n % value != n:\n n = n - value\n s += key\n return s\n\n def from_roman(r):\n s = 0\n for key, value in ROMANS.items():\n while r.startswith(key):\n r = r[len(key):]\n s += value\n return s","sub_path":"roman_numeral_helper2.py","file_name":"roman_numeral_helper2.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"163597224","text":"\"\"\"\nThis script creates a matrix of number of moves from location A to B given a\nwindow.\n\"\"\"\nimport json\nimport csv\nfrom collections import defaultdict\nfrom tqdm import tqdm\nfrom src.utils import get_logger, make_dir\nfrom src.models.movement import longest_seq_move, MoveNotPossible\n\n\nlogger = get_logger(__file__, snakemake.log[0])\n\nstart = snakemake.params.start\nmid = snakemake.params.mid\nend = snakemake.params.end\n\nwindow = (int(start), int(mid), int(end))\nassert window[0] <= window[1] <= window[2], \\\n f\"window years are not in increasing order: {window}\"\n\nlogger.info(f'Starting to create move matrix for window {window}')\n\nauthor_move_json_path = snakemake.input[0]\noutput_path = snakemake.output[0]\nmake_dir(output_path)\n\nlogger.info(f'loading: {author_move_json_path}')\nwith open(author_move_json_path) as f:\n author_move_dict = json.load(f)\n\nlogger.info(f'extracting unique locations for {len(author_move_dict)} authors')\n\n\nmapping_file = snakemake.input.mapping\nlogger.info(f'loading mapping file {mapping_file}')\nwith open(mapping_file) as f:\n city_mapping = json.load(f)\n\n\nlogger.info(f'counting moves')\nmove_dict = defaultdict(lambda: defaultdict(lambda: 0))\ncomplete_paths = 0\nfor _, data in tqdm(author_move_dict.items()):\n locations, times = data['locations'], data['dates']\n loc_times = zip(locations, times)\n filtered_loc_time_zip = [(city_mapping[city], time) for city, time in loc_times\n if city in city_mapping]\n if not filtered_loc_time_zip: # if no valid locations skip\n continue\n locations, times = list(zip(*filtered_loc_time_zip))\n try:\n source, target = longest_seq_move(locations, times, window)\n except MoveNotPossible:\n continue\n move_dict[source][target] += 1\n complete_paths += 1\n\nlogger.info(f'extracted moves for {complete_paths} valid/complete author paths')\nwith open(output_path, 'w') as f:\n writer = csv.writer(f)\n writer.writerow(['Source', 'Target', 'Weight'])\n for source in move_dict:\n for target, weight in move_dict[source].items():\n writer.writerow([source, target, weight])\nlogger.info(f'writing moves to {output_path}')\n","sub_path":"src/rules/create_movement_network.py","file_name":"create_movement_network.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"268146579","text":"#* encoding:utf-8 *#\n\nimport sys, time\nif sys.version < \"3\":\n import Tkinter\n import thread\nelse:\n import tkinter as Tkinter\n import _thread as thread\nimport filedialog\n\nclass GUI(object):\n def __init__(self, config, worldtypes = (), background = True):\n if background:\n thread.start_new_thread(self.init,(config,worldtypes))\n else:\n self.init(config,worldtypes)\n\n def init(self, config, worldtypes):\n self.queue = {}\n self.stats = {}\n self.lock = thread.allocate_lock() #lock that shows whether it is save to do window stuff\n # WINDOW\n root = Tkinter.Tk()\n root.title(\"MCGCraft Server GUI\")\n def on_closing():\n config[\"run\"] = False\n config[\"quit\"] = True\n self.lock.acquire() #wait for lock to be available, lock forever because no one will be able to use window once it's destroyed\n root.destroy()\n root.protocol(\"WM_DELETE_WINDOW\", on_closing)\n root.protocol(\"WM_SAVE_YOURSELF\", on_closing)\n root.grid_columnconfigure(1,weight=1)\n self.root = root\n self.row = 0\n\n # Name des Spiels\n def setname(name):\n config[\"name\"] = name\n self.add_label(\"Name\")\n self.add_entry(config[\"name\"], setname)\n\n # Speicherort\n def setfile(fn, autocorrect=False):\n if fn == config[\"file\"]:\n return\n if not fn.endswith(\".mc.zip\") and autocorrect:\n fn += \".mc.zip\"\n fileentry.delete(0, Tkinter.END)\n fileentry.insert(0,fn)\n fileentry.xview_moveto(1)\n config[\"file\"] = fn\n def file_focus_out(fn):\n if fn:\n setfile(fn)\n fileentry.isempty = fileentry.get() == \"\"\n if fileentry.isempty:\n fileentry.insert(0,\"Welt nicht speichern\")\n fileentry.configure(fg=\"grey\")\n def file_focus_in(event):\n if fileentry.isempty:\n fileentry.delete(0, Tkinter.END)\n fileentry.configure(fg=defaultfg)\n self.add_label(\"Speicherort\")\n fileentry = self.add_entry(config[\"file\"], file_focus_out)\n defaultfg = fileentry[\"fg\"]\n fileentry.xview_moveto(1)\n fileentry.bind(\"\",file_focus_in)\n file_focus_out(None)\n \n def openfile():\n fn = filedialog.open_dialog(\"\")\n if fn != False:\n setfile(fn, False)\n fileopenbutton = Tkinter.Button(root, text=\"öffnen\", command=openfile)\n fileopenbutton.grid(column = 2, row = self.row-1, sticky = Tkinter.W+Tkinter.E)\n def newfile():\n fn = filedialog.save_dialog(\"\")\n if fn != False:\n setfile(fn, True)\n filenewbutton = Tkinter.Button(root, text=\"neu\", command=newfile)\n filenewbutton.grid(column = 3, row = self.row-1, sticky = Tkinter.W+Tkinter.E)\n\n # Worldtype #http://effbot.org/tkinterbook/optionmenu.htm\n def setworldtype(*args):\n config[\"worldtype\"] = wtvar.get()\n wtvar = Tkinter.StringVar(root)\n wtvar.set(config[\"worldtype\"]) # default value\n wtvar.trace(\"w\",setworldtype)\n if config[\"worldtype\"] not in worldtypes:\n worldtypes = (config[\"worldtype\"],) + tuple(worldtypes)\n\n self.add_label(\"Welttyp\")\n wtmenu = Tkinter.OptionMenu(root, wtvar, *worldtypes)\n wtmenu.grid(column = 1, row = self.row, sticky = Tkinter.W+Tkinter.E)\n wtmenu.configure(takefocus=1)\n self.row += 1\n \n # Whitelist\n def setwhitelist(*args):\n config[\"whitelist\"] = whitelistvar.get()\n whitelistvar = Tkinter.StringVar(root)\n whitelistvar.set(config[\"whitelist\"])\n whitelistvar.trace(\"w\",setwhitelist)\n self.add_label(\"Whitelist\")\n whitelist_entry = Tkinter.Entry(root, textvariable = whitelistvar)\n whitelist_entry.grid(column = 1, row = self.row, sticky = Tkinter.W+Tkinter.E)\n whitelist_button_local = Tkinter.Radiobutton(text = \"localhost\", variable = whitelistvar, value = \"127.0.0.1\")\n whitelist_button_local.grid(column = 2, row = self.row, sticky = Tkinter.W)\n whitelist_button_local = Tkinter.Radiobutton(text = \"LAN\", variable = whitelistvar, value = \"192.168.0.0/16\")\n whitelist_button_local.grid(column = 3, row = self.row, sticky = Tkinter.W)\n self.row += 3\n \n # Parole\n\n # Start/Stop\n def togglerun():\n root.focus()\n config[\"run\"] = not config[\"run\"]\n update_buttontexts()\n startbutton = Tkinter.Button(root, command = togglerun)\n startbutton.grid(column = 1, row = self.row, sticky = Tkinter.W+Tkinter.E)\n\n # Play\n def play():\n root.focus()\n config[\"run\"] = True\n config[\"play\"] = True\n update_buttontexts()\n playbutton = Tkinter.Button(root, command = play)\n playbutton.grid(column = 2, columnspan = 2, row = self.row, sticky = Tkinter.W+Tkinter.E)\n \n # SAVE?\n \n # BUTTONS\n def update_buttontexts():\n startbutton.configure(text = \"Stop\" if config[\"run\"] else \"Start\")\n playbutton.configure(text = \"Play\" if config[\"run\"] else \"Start & Play\")\n update_buttontexts()\n self.row += 1\n \n self.statsframe = Tkinter.LabelFrame(root, text=\"Stats\")\n self.statsframe.grid(column = 0, columnspan = 4, row = self.row, sticky = Tkinter.W+Tkinter.E)\n\n playbutton.focus()\n try:\n while 1:\n time.sleep(0.01)\n root.update()\n while self.queue:\n name, value = self.queue.popitem()\n self._set_stats(name,value)\n except:\n pass\n \n def add_entry(self, content, callback):\n def apply_changes(event):\n callback(entry.get())\n entry = Tkinter.Entry(self.root)\n entry.insert(0, content)\n entry.grid(column = 1, row = self.row, sticky = Tkinter.W+Tkinter.E)\n entry.bind(\"\",apply_changes)\n entry.bind(\"\",apply_changes)\n self.row += 1\n return entry\n def add_label(self, labeltext):\n Tkinter.Label(self.root, text=labeltext).grid(column = 0, row = self.row, sticky = Tkinter.W)\n\n def set_stats(self,name,value):\n self.queue[name] = value\n\n def _set_stats(self,name,value):\n if self.lock.acquire(False): # doing stuff when the window is already closed will block the application, so use lock to avoid destroying root while window get's used\n if not name in self.stats:\n Tkinter.Label(self.statsframe, text=name+\" \").grid(column = 0, row = len(self.stats), sticky = Tkinter.W)\n label = Tkinter.Label(self.statsframe)\n label.grid(column = 1, row = len(self.stats), sticky = Tkinter.W)\n self.row += 1\n self.stats[name] = label\n self.stats[name].configure(text = value)\n self.lock.release()\n\nif __name__ == \"__main__\":\n config = { \"name\" : \"MCGCraft Server\",\n \"file\" : \"\",\n \"worldtype\": \"Colorland\",\n \"whitelist\": \"127.0.0.1\",\n \"parole\" : \"\",\n \"port\" : \"\",\n \"run\" : False,\n \"play\" : False,\n \"quit\" : False,\n \"save\" : False}\n gui = GUI(config, (\"one\",\"two\",\"three\"), background = True)\n import time\n time.sleep(1)\n gui.set_stats(\"fps\",\"16\")\n","sub_path":"lib/gui/tkgui.py","file_name":"tkgui.py","file_ext":"py","file_size_in_byte":7707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"288346542","text":"# primeFactors: A function to return the list of all prime factors of a given number. \ndef primeFactors(n):\n prfact = []\t\t# Start with empty list.\n # Check for 2s that divide n:\n while n % 2 == 0: \n prfact.append(2)\n n = n/2\n\n # n must be odd at this point.\n for i in range(3, round(n**0.5), 2):\n # While i divides n, store i and divide n.\n while n % i == 0: \n prfact.append(i)\n n = n / i\n\n # This condition is to handle the case when n \n # is a prime number greater than 2.\n if (n > 2):\n prfact.append(round(n))\n return prfact\n# end primeFactors\n\n# MAIN PROGRAM.\na = int(input(\"Enter an integer number: \"))\nprint(\"Prime factors of\", a, \"are\", primeFactors(a))\n","sub_path":"scripts/p406_func2.py","file_name":"p406_func2.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"642265834","text":"\"\"\"\nRun 10 threads\n\nWe can also now pass in an argument for seconds\n\"\"\"\nimport threading\nimport time\n\nstart = time.perf_counter()\n\ndef do_something(seconds):\n print(f'Sleeping {seconds} second(s)...')\n time.sleep(seconds)\n print('Done Sleeping...')\n\n# initialize list of threads\nthreads = []\n\n# set up loop to start 10 threads\nfor _ in range(10):\n t = threading.Thread(target=do_something, args=[1.5])\n t.start()\n threads.append(t)\n\nfor thread in threads:\n thread.join()\n\nfinish = time.perf_counter()\n\nprint(f'Finished in {finish-start} second(s)')","sub_path":"LABS/Threading/multithreading2.py","file_name":"multithreading2.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"66413526","text":"from keras.models import Sequential\nfrom keras.layers import Dense, Activation\nfrom keras.layers import LSTM\nfrom keras.optimizers import RMSprop\nfrom keras.preprocessing import sequence\nimport numpy as np\nfrom natto import MeCab\nimport itertools\nimport random\nimport sys\nimport os\nfrom typing import List, Dict, Any, Optional, Tuple\n\n# Maximum length for sentences (number of words in a sentence)\nMAXLEN = 20\n\n# Punctuations (will be chosen randomly)\nPUNCTS = ['、', '。', '!', '?', '…']\nPUNCTS_PROBS = [0.0, 0.7, 0.1, 0.1, 0.1]\n\n# Dictionary path for MeCab\nif 'NEOLOGD' in os.environ:\n DICTIONARY = os.environ.get('NEOLOGD')\nelse:\n DICTIONARY = '/usr/lib/mecab/dic/mecab-ipadic-neologd/'\nOOV = 'OOV'\n\n\ndef _choose_punct():\n return np.random.choice(PUNCTS, p=PUNCTS_PROBS)\n\n\ndef tokenize(mecab: MeCab, sentence: str) -> List[str]:\n return [node.surface for node in mecab.parse(sentence, as_nodes=True) if node.surface]\n\n\ndef attach_puncts_to_words(l: List[str]) -> List[str]:\n wl = []\n for i, w in enumerate(l):\n try:\n nextword = l[i + 1]\n except IndexError:\n nextword = ''\n if nextword in PUNCTS:\n word = w + nextword\n wl.append(word)\n elif w in PUNCTS:\n pass\n else:\n wl.append(w)\n return wl\n\n\ndef load_corpus(fn: str) -> Tuple[List[List[str]], Dict[str, int]]:\n with open(fn, encoding='utf-8') as f:\n _sentences = [l.strip() for l in f.readlines()]\n with MeCab('-d {}'.format(DICTIONARY)) as mecab:\n tokenized_sentences = [attach_puncts_to_words(tokenize(mecab, s)) for s in _sentences]\n words = sorted(list(set(itertools.chain.from_iterable(tokenized_sentences))))\n word2id = {w: i + 1 for i, w in enumerate(words)}\n word2id.update({OOV: 0})\n return tokenized_sentences, word2id\n\n\ndef build_lstm_model(maxlen: int = MAXLEN, vocab_size: int = None) -> Sequential:\n model = Sequential()\n model.add(LSTM(128, input_shape=(maxlen, vocab_size), dropout=0.2, recurrent_dropout=0.2))\n model.add(Dense(vocab_size, activation='softmax'))\n optimizer = RMSprop(lr=0.01)\n model.compile(loss='categorical_crossentropy', optimizer=optimizer)\n return model\n\n\ndef get_next_words(sentences: List[List[str]]) -> List[str]:\n next_words = []\n for i in range(len(sentences)):\n try:\n next_words.append(sentences[i + 1][0])\n except IndexError:\n next_words.append('')\n return next_words\n\n\ndef vectorize_sentences(sentences: List[List[str]],\n voc2id: Dict[str, int],\n maxlen: int = MAXLEN) -> Tuple[np.array, np.array]:\n X = np.zeros(shape=(len(sentences), maxlen, len(voc2id)), dtype=np.bool)\n y = np.zeros(shape=(len(sentences), len(voc2id)), dtype=np.bool)\n\n next_words = get_next_words(sentences)\n\n for i, sentence in enumerate(sentences):\n for t, word in enumerate(sentence):\n try:\n X[i, t, voc2id[word]] = 1\n except IndexError:\n pass\n y[i, voc2id.get(next_words[i], voc2id.get(''))] = 1\n\n X = sequence.pad_sequences(X, maxlen=maxlen)\n\n return X, y\n\n\ndef sample(preds, temperature=1.0):\n # helper function to sample an index from a probability array\n preds = np.asarray(preds).astype('float64')\n preds = np.log(preds) / temperature\n exp_preds = np.exp(preds)\n preds = exp_preds / np.sum(exp_preds)\n probas = np.random.multinomial(1, preds, 1)\n return np.argmax(probas)\n\n\ndef train_and_generation(sentences: List[List[str]],\n lstm_model: Sequential,\n X: np.array,\n y: np.array,\n voc2id: Dict[str, int],\n n_iter: int = 50):\n # reverse lookup table for characters\n id2voc = {v: k for k, v in voc2id.items()}\n\n for iteration in range(1, n_iter + 1):\n print()\n print('-' * 50)\n print('- Iteration: {}'.format(iteration))\n lstm_model.fit(X, y, batch_size=128, epochs=1, verbose=0)\n\n seed_index = random.randint(0, len(sentences))\n seed_sentence = sentences[seed_index]\n print('---- Generating with seed: \"{}\"'.format(seed_sentence))\n\n for diversity in [0.2, 0.5, 1.0, 5.0]:\n print()\n print('-------- diversity: {}'.format(diversity))\n\n generated = []\n sentence = sentences[seed_index]\n generated += sentence\n\n for i in range(MAXLEN):\n x = np.zeros((1, MAXLEN, len(voc2id)))\n for t, word in enumerate(sentence):\n try:\n x[0, t, voc2id[word]] = 1.\n except IndexError:\n pass\n\n preds = lstm_model.predict(x, verbose=0)[0]\n next_index = sample(preds, diversity)\n next_word = id2voc[next_index]\n\n generated.append(next_word)\n sentence = sentence[1:] + [next_word]\n if next_word[-1] in PUNCTS:\n next_word = next_word[:-1] + _choose_punct()\n\n sys.stdout.write(next_word)\n\n sys.stdout.flush()\n else:\n sys.stdout.write(_choose_punct())\n print()\n\n\ndef help():\n print('Usage:')\n print('python wordlevel_lstm_generator.py ')\n\n\ndef run():\n try:\n fn = sys.argv[1]\n n_iter = int(sys.argv[2])\n except IndexError:\n help()\n exit(1)\n\n try:\n sentences, word2id = load_corpus(fn)\n except (IOError, OSError):\n print('Error raised when loading corpus file. Aborted.', file=sys.stderr)\n sys.exit(1)\n\n X, y = vectorize_sentences(sentences, word2id)\n train_and_generation(sentences=sentences,\n lstm_model=build_lstm_model(vocab_size=len(word2id)),\n X=X,\n y=y,\n voc2id=word2id,\n n_iter=n_iter\n )\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"textgen/wordlevel_lstm_generator.py","file_name":"wordlevel_lstm_generator.py","file_ext":"py","file_size_in_byte":6144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"407979452","text":"import os\nimport time\nimport zipfile\n\nsource = '/Users/Sergei_KIssel/Dropbox/DOCS'\ntarget_dir = '/Users/Sergei_KIssel/python3/backup_DOCS'\n\n\nif not os.path.exists(target_dir):\n os.mkdir(target_dir)\n\ntoday = target_dir + os.sep + time.strftime('%Y%m%d')\nnow = time.strftime('%H%M%S')\ncomment = input('Enter comment here:')\n\nif len(comment) == 0:\n target = today + os.sep + now + '.zip'\nelse:\n target = today + os.sep + now + '_' + comment.replace(' ', '_') + '.zip'\n\nif not os.path.exists(today):\n os.mkdir(today)\n print('Successfully created dir \"today\"')\n\n# Create archive file\nprint('creating archive..')\nzf = zipfile.ZipFile(target, mode='w')\n\n# Choose compression mode\ntry:\n import zlib\n compression = zipfile.ZIP_DEFLATED\nexcept:\n compression = zipfile.ZIP_STORED\n\nmodes = {zipfile.ZIP_DEFLATED: 'deflated',\n zipfile.ZIP_STORED: 'stored'}\n\n\n# Define recursive zip\ndef recursive_zip(zf, source_file_path, archived_file_path):\n \n for root, dirs, files in os.walk(source):\n for file in files:\n zf.write(os.path.join(root, file), compress_type=compression)\n # ZipFile.write(filename, arcname=None, compress_type=None)\n\ntry:\n print('adding files from {} with compression mode {}'.format(\n source, modes[compression]))\n\n# # This is a check not to execute *.py files ???\n# if __name__ == '__main__':\n\n # Calling the recursive_zip func defined above\n recursive_zip(zf, source, target_dir)\n\nfinally:\n print('closing')\n zf.close()\n\n# Open zip to see what's in it\nprint('reading archive:')\nzf = zipfile.ZipFile(target, mode='r')\n\nfor info in zf.infolist():\n print(info.filename, info.date_time, info.file_size, info.compress_size)\n","sub_path":"byteofpython/backup_v6.0.py","file_name":"backup_v6.0.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"112884996","text":"#!/usr/bin/env python\nimport argparse\nimport subprocess\nimport shlex\nimport os \nimport sys\n\ndef add_command(tool, argument, description=None):\n if not os.path.exists(brief_path):\n os.makedirs(brief_path)\n with open(f\"{brief_path}/{tool}.tool\", \"a\") as myfile:\n myfile.write(f\"{tool}|~|{argument}|~|{description}\\n\")\n\ndef remove_command(tool, line_number):\n with open(f\"{brief_path}/{tool}.tool\", \"r\") as infile:\n lines = infile.readlines()\n\n with open(f\"{brief_path}/{tool}.tool\", \"w\") as outfile:\n for pos, line in enumerate(lines):\n if pos != int(line_number) - 1:\n outfile.write(line)\n\ndef list_commands(tool):\n _, screen_width = os.popen('stty size', 'r').read().split()\n screen_width = int(screen_width)\n column_width = int(screen_width)//2\n\n print()\n print ('{0:<{2}}{1:<{2}}'.format(\"COMMAND\", \" DESCRIPTION\", column_width))\n print('-' * screen_width)\n with open(f\"{brief_path}/{tool}.tool\", \"r\") as myfile:\n counter = 1\n for line in myfile:\n argument = line.split(\"|~|\")[1]\n description = line.split(\"|~|\")[2]\n print ('{0}. {1:<{3}} {2:<{3}}'.format(counter, tool + \" \" + argument, description, column_width))\n counter += 1\n\nbrief_path = os.path.expanduser(\"~/.brief\")\nparser = argparse.ArgumentParser()\nparser.add_argument(\"command\", help=\"specify what argument to use, either add, ls or rm\", nargs=\"*\")\nparser.add_argument(\"-d\", \"--description\", help=\"description of command\", const=True, default=False, nargs=\"?\")\nparser.add_argument(\"-t\", \"--tool\", help=\"the name of the commandline tool\", const=True, default=False, nargs=\"?\")\n\nargs = parser.parse_args()\ncommand = args.command[0] \ntool = args.command[1].split()[0]\n\nif command == \"add\":\n argument = \" \".join(args.command[1].split()[1:])\n if args.description != False:\n add_command(tool, argument, args.description)\n else:\n add_command(tool, argument)\n\nif command == \"ls\":\n list_commands(tool)\n\n\nif command == \"rm\":\n line_number = args.command[2]\n remove_command(tool, line_number)\n","sub_path":"brief.py","file_name":"brief.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"529615480","text":"import boto3\nfrom botocore.exceptions import ClientError\nimport logging\n\n\nclass Copy_S3:\n \"\"\"\n This class is all about to copy files from list of s3 buckets to another bucket.\n If destination bucket not exists it will be created\n \"\"\"\n def __init__(self, source, dest, region=None):\n self.source_name_list = source\n self.dest_name = dest\n self.region = region\n self.s3 = boto3.resource('s3')\n self.copy()\n\n def create_bucket(self, bucket_name, region=None):\n \"\"\"Create an S3 bucket in a specified region\n\n If a region is not specified, the bucket is created in the S3 default\n region (us-east-1).\n\n :param bucket_name: Bucket to create\n :param region: String region to create bucket in, e.g., 'us-west-2'\n :return: True if bucket created, else False\n \"\"\"\n\n # Create bucket\n try:\n if region is None:\n s3_client = boto3.client('s3')\n s3_client.create_bucket(Bucket=bucket_name)\n else:\n s3_client = boto3.client('s3', region_name=region)\n location = {'LocationConstraint': region}\n s3_client.create_bucket(Bucket=bucket_name,\n CreateBucketConfiguration=location)\n except ClientError as e:\n logging.error(e)\n return False\n return True\n\n def copy(self, ):\n \"\"\"Copy all files from sourse buckets list to dest bucket string.\n Creates dest bucket if it's necessarily\n \"\"\"\n for source_name in self.source_name_list:\n sours = self.s3.Bucket(source_name)\n dest = self.s3.Bucket(self.dest_name)\n if dest not in self.s3.buckets.all():\n self.create_bucket(self.dest_name, self.region)\n try:\n for obj in sours.objects.filter():\n files = obj.key\n copy_source = {\n 'Bucket': source_name,\n 'Key': files\n }\n self.s3.meta.client.copy(copy_source, self.dest_name, files)\n print(files)\n except ClientError as e:\n logging.error(e)\n logging.error(source_name)\n\n\n\n\nif __name__ == \"__main__\":\n my_bucket_name = 'aws-hw-bucket-64c26dba-73f6-11ea-bc55-0242ac130003'\n dest_name = 'dest-test-ea35fa6d-54ed-42d8-9420-352061817d65'\n copy_those_s3 = Copy_S3\n copy_those_s3([my_bucket_name, 'trege'],'2dest-test-ea35fa6d-54ed-42d8-9420-352061817d65')\n\n","sub_path":"python/module8/s3_copy.py","file_name":"s3_copy.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"62979751","text":"import os\nimport json\nimport unittest\n\nfrom ci.lib import provision, run_cmd\n\n\nclass BaseTestCase(unittest.TestCase):\n \"\"\"Base test case to extend test cases from\"\"\"\n\n def setUp(self):\n self.hosts = json.loads(os.environ.get('CCCP_CI_HOSTS') or \"{}\") or {\n 'openshift': {\n 'host': '192.168.100.201',\n 'private_key': '~/.vagrant.d/insecure_private_key',\n 'remote_user': 'vagrant'\n },\n 'jenkins_master': {\n 'host': '192.168.100.100',\n 'private_key': '~/.vagrant.d/insecure_private_key',\n 'remote_user': 'vagrant'\n },\n 'jenkins_slave': {\n 'host': '192.168.100.200',\n 'private_key': '~/.vagrant.d/insecure_private_key',\n 'remote_user': 'vagrant'\n },\n 'controller': {\n 'host': None,\n 'private_key': '~/.vagrant.d/insecure_private_key',\n 'user': 'vagrant',\n # 'workdir': 'path/to/project/'\n # relative to this source dir\n 'inventory_path': 'provisions/hosts.vagrant'\n }\n }\n\n def provision(self, force=False, extra_args=\"\"):\n \"\"\"\n Provision CCCP nodes.\n\n By default, it runs provisioning only for the first time, and\n skips for the subsequent calls.\n\n Args:\n force (bool): Provision forcefully.\n extra_args (str): Extra cmd line args for running ansible playbook\n \"\"\"\n provision(self.hosts['controller'], force=force, extra_args=extra_args)\n\n def run_cmd(self, cmd, user=None, host=None, stream=False):\n \"\"\"\n Run command on local or remote machine (over SSH).\n\n Args:\n cmd (str): Command to execute\n user (str): Remote user to execute command as\n host (str): Remote host\n stream (bool): Whether to stream output or not\n\n Returns:\n Output string\n\n Raises:\n Exception if command execution fails\n \"\"\"\n host_info = self.hosts.get(self.node)\n return run_cmd(cmd, user=user or host_info['remote_user'],\n host=host or host_info['host'],\n private_key=host_info.get('private_key'),\n stream=stream)\n","sub_path":"ci/tests/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"584485656","text":"from alpha_vantage.timeseries import TimeSeries\nimport telegram\nimport pandas as pd\nimport time\nimport pytz\nfrom datetime import datetime, timezone\nfrom alpha_vantage.techindicators import TechIndicators\nimport pandas_ta as ta\n\n#variables required\napi_key = '4EWAGGPCYI53F188'\nsymbol = 'NSE:BANKINDIA'\nts = TimeSeries(key=api_key,output_format='pandas')\n\ndef get_data():\n data,meta_data = ts.get_intraday(symbol=symbol,interval='1min',outputsize='compact')\n data.index=data.index.tz_localize('US/Eastern').tz_convert('Asia/Calcutta')\n data = data.sort_index()\n print(meta_data)\n return data,meta_data\n\ndef add_sma_crossover():\n data['LMA']=ta.sma(data['4. close'],21)\n data['SMA']=ta.sma(data['4. close'],9)\n data['psma']=data['SMA'].shift(1)\n data['plma']=data['LMA'].shift(1)\n #if (((data['SMA'][-1]>data['LMA'][-1])and(data['psma'][-1]data['plma'][-1]))) or (((data['SMA'][-2]>data['LMA'][-2])and(data['psma'][-2]data['plma'][-2]))) :\n data['buy']=(data['SMA']>data['LMA'])&(data['psma']data['LMA'].shift(-2))\n data['sell']=(data['SMA']data['plma'])\ndef add_mfi():\n data['MSI']=ta.mfi(data['2. high'],data['3. low'],data['4. close'],data['5. volume'])\ndef add_adx():\n df=ta.adx(data['2. high'],data['3. low'],data['4. close'])\n data['ADX']=df['ADX_14']\n data['DMP']=df['DMP_14']\n data['DMN']=df['DMN_14']\ndef add_rsi():\n data['RSI']=ta.rsi(data['4. close'])\ndef test(d):\n pb=-1\n investment = 12000\n balance = 12000\n profit = 0\n stocks=0\n price = 0\n print('----------------backtest started----------------------------')\n for i in range(0,len(d)):\n if d['buy'][i]:\n if balance>= d['4. close'][i]:\n stocks =stocks+(balance//d['4. close'][i])\n if stocks>=1:\n price = stocks*d['4. close'][i]\n if balance>=price:\n balance=balance-price\n pb=i\n print('=>buy:\\n{3}\\nquantity:{0} price:{1} balance:{2}------------------------'.format(stocks,price,balance,d.iloc[[i]]))\n\t \n elif d['SELL'][i]:\n if stocks>=1 and d['4. close'][i]>d['4. close'][pb]:# and d['4. close'][i]>d['4. close'][pb]\n price = stocks*d['4. close'][i]\n balance=balance+price\n print('=>sell:\\n{3}\\n-----------quantity:{0} price:{1} balance:{2}----------'.format(stocks,price,balance,d.iloc[[i]]))\n stocks=0\n profit = balance-investment\n print(len(d))\n return profit\n\n#program starts\nstart_time = time.time()\nprint('program started')\n#getting data\ndata,meta_data = get_data()\n#add sma crossover datas\nadd_sma_crossover()\nadd_adx()\nadd_mfi()\nadd_rsi()\ndata['SELL']=(data['ADX']>23) & (data['DMP']>data['DMN']) & (data['MSI']>50) &(~data['buy'])\ndata.to_csv('out.csv')\n #if (((data['SMA'][-1]>data['LMA'][-1])and(data['psma'][-1]data['plma'][-1]))) or (((data['SMA'][-2]>data['LMA'][-2])and(data['psma'][-2]data['plma'][-2]))) :\nprint(\"-------------------------------------\")\nprint(data.tail())\n\nprint('profit:'+str(test(data)))\n#data.to_excel('out.xlsx')\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n\n \n\n#help(ta.adx)\n\n\n \n\n\n\"\"\"data['sma'] = data['4. close'].rolling(window=6).mean()\ndata['lma'] = data['4. close'].rolling(window=14).mean()\ndata.to_excel('out.xlsx')\nfig,ax1 = plt.subplots() \nax1.plot(data['4. close'][-360:],'b')\nax1.plot(data['LMA'][-360:],'r')\nax1.plot(data['SMA'][-360:],'g')\nplt.show()\"\"\"\n\"\"\"\ndata['LMA']=data['4. close'].rolling(window=21).mean()\ndata['SMA']=data['4. close'].rolling(window=5).mean()\ndata['psma']=data['SMA'].shift(1)\ndata['plma']=data['LMA'].shift(1)\"\"\"","sub_path":"backtest.py","file_name":"backtest.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"477311665","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nu\"\"\"\n# -*- coding: utf-8 -*-\n(c) 2009 Ryszard Szopa \n(c) 2010 Mahmoud Abdelkader \n\nThis work 'as-is' we provide.\nNo warranty, express or implied.\nWe’ve done our best,\nto debug and test.\nLiability for damages denied.\n\nPermission is granted hereby,\nto copy, share, and modify.\nUse as is fit,\nfree or for profit.\nOn this notice these rights rely.\n\nThis library provides two classes: Ngrams, which treats words as tokens\n\n >>> (Ngrams(u'This is a very small donkey.') *\n ... Ngrams(u'This animal is a very small donkey.')) #doctest:+ELLIPSIS\n 0.6708203932...\n\nand CharNgrams, which treats single characters as tokens:\n\n >>> (CharNgrams('supercalifragilistic') *\n ... CharNgrams('supercalifragislislistic')) #doctest:+ELLIPSIS\n 0.757...\n\nIf none of these fits your definition of `token' all you have to do is\nsubclass Ngrams and define you own tokenize method.\n\nWhen creating an Ngrams object you can provide a second argument as\nthe value of n (the default being 3). You can compare only n-grams\nwith the same value of n.\n\n >>> Ngrams('ala ma kota', 3) * Ngrams('ala ma kota', 2)\n Traceback (most recent call last):\n ...\n WrongN\n\n\"\"\"\nimport re\nimport math\nfrom collections import defaultdict\nfrom itertools import tee, izip\n\n\ndef n_wise(iterable, n):\n \"\"\"Returns n iterators for an iterable that are sequentially\n n-wise\n\n \"\"\"\n n_iterators = tee(iterable, n)\n zippables = [n_iterators[0]]\n\n for advance, iteratee in enumerate(n_iterators[1:]):\n advance += 1 # since enumerate is 0 indexed.\n while advance > 0:\n # we advance the iterator `advance+1` steps\n next(iteratee, None)\n advance -= 1\n # append everything to the zippables\n zippables.append(iteratee)\n # return the izip expansion of each iterator\n return izip(*zippables)\n\n\nclass Ngrams(object):\n \"\"\"Compare strings using an n-grams model and cosine similarity.\n\n This class uses words as tokens. See module docs.\n\n >>> import pprint\n >>> items = sorted(Ngrams('Compare strings using an n-grams model and '\n ... 'cosine similarity. This class uses words as'\n ... 'tokens. See module docs.').d.items())\n >>> pprint.pprint(items)\n [('an ngrams model', 0.2581988897471611),\n ('and cosine similarity', 0.2581988897471611),\n ('astokens see module', 0.2581988897471611),\n ('class uses words', 0.2581988897471611),\n ('compare strings using', 0.2581988897471611),\n ('cosine similarity this', 0.2581988897471611),\n ('model and cosine', 0.2581988897471611),\n ('ngrams model and', 0.2581988897471611),\n ('see module docs', 0.2581988897471611),\n ('similarity this class', 0.2581988897471611),\n ('strings using an', 0.2581988897471611),\n ('this class uses', 0.2581988897471611),\n ('uses words astokens', 0.2581988897471611),\n ('using an ngrams', 0.2581988897471611),\n ('words astokens see', 0.2581988897471611)]\n\n \"\"\"\n\n ngram_joiner = \" \"\n\n class WrongN(Exception):\n \"\"\"Error to raise when two ngrams of different n's are being\n compared.\n \"\"\"\n pass\n\n def __init__(self, text, n=3):\n self.n = n\n self.text = text\n self.d = self.text_to_ngrams(self.text)\n\n def __getitem__(self, word):\n return self.d[word]\n\n def __contains__(self, word):\n return word in self.d\n\n def __iter__(self):\n return iter(self.d)\n\n def __mul__(self, other):\n \"\"\"Returns the similarity between self and other as a float in\n (0;1).\n \"\"\"\n if self.n != other.n:\n raise self.WrongN\n\n score = 0\n if self.text == other.text:\n score = 1.0\n else:\n score = sum(self[k] * other[k] for k in self if k in other)\n\n return score\n\n def __repr__(self):\n return \"Ngrams(%r, %r)\" % (self.text, self.n)\n\n def __str__(self):\n return self.text\n\n def tokenize(self, text):\n \"\"\"Return a sequence of tokens from which the ngrams should be\n constructed.\n\n This shouldn't be a generator, because its length will be\n needed.\n \"\"\"\n\n regex = re.compile(u'[^\\w\\n ]|\\xe2', re.UNICODE)\n return regex.sub('', text).lower().split()\n\n def relative_n_gram_dist(self, other):\n \"\"\"Generates the relative n-gram distance between two strings.\n The relative n-gram distance can be used as a basis function to\n determine the similarity of strings.\n\n The smaller the relative n-gram distance is, the similar the\n two strings are.\n\n The formula is:\n |nGram(s1) INTERSECT nGram(s2)|\n Delta_q(s1, s2) = 1 - -------------------------------\n |nGram(s1) UNION nGram(s2)|\n \"\"\"\n ngrams = set(self.d.keys())\n other_ngrams = set(other.d.keys())\n result = None\n try:\n result = (1 - (abs(len(ngrams.intersection(other_ngrams))) /\n float(abs(len(ngrams.union(other_ngrams))))))\n except ZeroDivisionError:\n # I don't know, is there a more graceful way to handle this?\n raise\n\n return result\n\n def normalize(self, text):\n \"\"\"This method is run on the text right before tokenization\"\"\"\n try:\n return text.lower()\n except AttributeError:\n # text is not a string?\n raise TypeError(text)\n\n def make_ngrams(self, text):\n \"\"\"\n # -*- coding: utf-8 -*-\n Return an iterator of tokens of which the n-grams will\n consist. You can overwrite this method in subclasses.\n\n >>> import pprint\n >>> L = list(Ngrams('').make_ngrams(chr(10).join([\n ... u'This work \\\\'as-is\\\\' we provide.',\n ... u'No warranty, express or implied.',\n ... u'We\\\\'ve done our best,',\n ... u'to debug and test.',\n ... u'Liability for damages denied.'])))[:5]\n >>> pprint.pprint(L)\n [u'this work asis',\n u'work asis we',\n u'asis we provide',\n u'we provide no',\n u'provide no warranty']\n\n \"\"\"\n\n text = self.normalize(text)\n tokens = self.tokenize(text)\n return (self.ngram_joiner.join(i) for i in n_wise(tokens, self.n))\n\n def text_to_ngrams(self, text):\n counts = defaultdict(int)\n\n for ngram in self.make_ngrams(text):\n counts[ngram] += 1\n\n norm = math.sqrt(sum(x ** 2 for x in counts.itervalues()))\n\n for k, v in counts.iteritems():\n counts[k] = v / norm\n\n return counts\n\n\nclass CharNgrams(Ngrams):\n\n \"\"\"Ngrams comparison using single characters as tokens.\n\n >>> CharNgrams('ala ma kota')*CharNgrams('ala ma kota')\n 1.0\n\n >>> round(CharNgrams('This Makes No Difference') *\n ... CharNgrams('this makes no difference'), 4)\n 1.0\n >>> (CharNgrams('Warszawska')*CharNgrams('Warszawa') >\n ... CharNgrams('Warszawa')*CharNgrams('Wawa'))\n True\n\n \"\"\"\n\n ngram_joiner = \"\"\n\n def tokenize(self, st):\n \"\"\"\n >>> ''.join(CharNgrams('').tokenize('ala ma kota!'))\n 'alamakota'\n \"\"\"\n return [c for c in st if c.isalnum()]\n\n\nclass CharNgramSpaces(CharNgrams):\n \"\"\"Like CharNgrams, except it keeps whitespace as one space in\n the process of tokenization. This should be useful for analyzing\n texts longer than words, where places at which word boundaries\n occur may be important.\n\n \"\"\"\n def tokenize(self, st):\n new_st = re.sub(r'\\s+', ' ', st)\n return [c for c in new_st if c.isalnum() or c == \" \"]\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n\n","sub_path":"ngrams/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"297520368","text":"from time import time, sleep\nfrom unittest import TestCase\n\nimport stubs\n\nfrom mediator import Mediator, Event, SubscriberInterface, VENUSIAN_CATEGORY\nfrom venusian import Scanner\n\n\nclass Listener(object):\n def __init__(self):\n self.events = []\n\n def __call__(self, event):\n self.events.append(event)\n\n\nclass EventOne(Event):\n event_name = 'event_one'\n\n\nclass EventTwo(Event):\n event_name = 'event_two'\n\n\nclass EventThree(Event):\n event_name = 'event_three'\n\n\nclass Subscriber(SubscriberInterface):\n def __init__(self):\n self.results = {}\n\n def first(self, event):\n self.results['first'] = (event, time())\n\n def middle(self, event):\n sleep(0.01)\n self.results['middle'] = (event, time())\n\n def last(self, event):\n sleep(0.01)\n self.results['last'] = (event, time())\n\n def another_event_handler(self, event):\n self.results['another'] = event\n\n def even_more_event_handler(self, event):\n self.results['even_more'] = event\n\n def get_subscribed_events(self):\n return {\n 'event_one': [\n ['middle'],\n ['first', -255],\n ['last', 255],\n ],\n 'event_two': 'another_event_handler',\n 'event_three': ['even_more_event_handler']\n }\n\n\nclass BadSubscriberOne(SubscriberInterface):\n def get_subscribed_events(self):\n return {'test_event': None}\n\n\nclass BadSubscriberTwo(SubscriberInterface):\n def get_subscribed_events(self):\n return {'test_event': []}\n\n\nclass TestMediator(TestCase):\n def test_dispatch_failed(self):\n meditator = Mediator()\n with self.assertRaises(TypeError) as context:\n meditator.dispatch('unexpected_event')\n self.assertEqual(str(context.exception), 'Expects instance of Event')\n\n def test_add_listener_with_object(self):\n mediator = Mediator()\n listener = Listener()\n mediator.add_listener(Event, listener)\n event = Event()\n mediator.dispatch(event)\n self.assertEqual(len(listener.events), 1)\n self.assertIs(listener.events[0], event)\n\n def test_add_listener_with_string(self):\n mediator = Mediator()\n listener = Listener()\n mediator.add_listener('Event', listener)\n event = Event()\n event = mediator.dispatch(event)\n self.assertEqual(len(listener.events), 1)\n self.assertIs(listener.events[0], event)\n\n def test_add_listener_with_same_priority_failed(self):\n mediator = Mediator()\n mediator.add_listener(Event, lambda event: None, 0)\n with self.assertRaises(IndexError):\n mediator.add_listener(Event, lambda event: None, 0)\n\n def test_add_listener_with_invalid_event_failed(self):\n mediator = Mediator()\n listener = Listener()\n with self.assertRaises(TypeError) as context:\n mediator.add_listener(1, listener)\n self.assertEqual(str(context.exception), 'Expects subclass of Event or str')\n\n def test_remove_listener(self):\n mediator = Mediator()\n listener1 = Listener()\n listener2 = Listener()\n mediator.add_listener(Event, listener1)\n mediator.add_listener(Event, listener2)\n event = Event()\n mediator.dispatch(event)\n mediator.remove_listener(Event, listener1)\n mediator.dispatch(event)\n self.assertEqual(len(listener1.events), 1)\n self.assertEqual(len(listener2.events), 2)\n mediator.remove_listener(Event)\n mediator.dispatch(event)\n self.assertEqual(len(listener1.events), 1)\n self.assertEqual(len(listener2.events), 2)\n\n def test_remove_listener_with_invalid_event_failed(self):\n mediator = Mediator()\n listener = Listener()\n with self.assertRaises(TypeError) as context:\n mediator.remove_listener(1, listener)\n self.assertEqual(str(context.exception), 'Expects subclass of Event or str')\n\n def test_add_subscriber(self):\n mediator = Mediator()\n\n with self.assertRaises(TypeError) as context:\n mediator.add_subscriber(object())\n self.assertEqual(str(context.exception), 'Expects instance of SubscriberInterface')\n\n subscriber = Subscriber()\n mediator.add_subscriber(subscriber)\n\n event = EventOne()\n mediator.dispatch(event)\n self.assertEqual(len(subscriber.results), 3)\n events = [result[0] for result in subscriber.results.values()]\n self.assertIs(events[0], events[1])\n self.assertIs(events[1], events[2])\n first, middle, last = (\n subscriber.results['first'][1],\n subscriber.results['middle'][1],\n subscriber.results['last'][1]\n )\n self.assertTrue(first < middle < last, '%r %r %r' % (first, middle, last))\n\n event = EventTwo()\n mediator.dispatch(event)\n self.assertIs(subscriber.results['another'], event)\n\n event = EventThree()\n mediator.dispatch(event)\n self.assertIs(subscriber.results['even_more'], event)\n\n with self.assertRaises(ValueError):\n mediator.add_subscriber(BadSubscriberOne())\n\n with self.assertRaises(ValueError):\n mediator.add_subscriber(BadSubscriberTwo())\n\n\nclass TestSubscriberInterface(TestCase):\n def test_get_subscribed_events(self):\n subscriber = SubscriberInterface()\n with self.assertRaises(NotImplementedError):\n subscriber.get_subscribed_events()\n\n\nclass TestEvent(TestCase):\n def test_get_event_name(self):\n self.assertEqual(Event.get_event_name(), 'Event')\n self.assertEqual(EventOne.get_event_name(), 'event_one')\n self.assertEqual(EventTwo.get_event_name(), 'event_two')\n self.assertEqual(EventThree.get_event_name(), 'event_three')\n\n\nclass TestEventDecorator(TestCase):\n def test_event_decorator(self):\n mediator = Mediator()\n scanner = Scanner(mediator=mediator)\n event = stubs.VenusianEvent()\n mediator.dispatch(event)\n self.assertFalse(event.success)\n scanner.scan(package=stubs, categories=[VENUSIAN_CATEGORY])\n mediator.dispatch(event)\n self.assertTrue(event.success)\n\n def test_event_decorator_with_custom_args(self):\n mediator = Mediator()\n scanner = Scanner(obj=mediator)\n event = stubs.VenusianEventWithCategory()\n mediator.dispatch(event)\n self.assertFalse(event.success)\n scanner.scan(package=stubs, categories=['custom-category'])\n mediator.dispatch(event)\n self.assertTrue(event.success)\n\n\nclass Mixin(object):\n def __init__(self):\n self.mixin_value = 'mixin-value'\n\n\nclass MediatorWithMixin(Mediator, Mixin):\n pass\n\n\nclass TestMultiInheritance(TestCase):\n def test_multi_inheritance(self):\n mediator = MediatorWithMixin()\n self.assertEqual(mediator.mixin_value, 'mixin-value')\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":6965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"520569349","text":"#! /usr/bin/env python\n# coding=utf-8\n\n\"\"\"\n定义工程的监听函数,包括时间复杂度和准确度的监测。\n\n - 数据将被存储至 ``Sqlite3`` ,以 ``JSON`` 字符串的格式。\n - 封装的装饰器,时间复杂度的装饰器可添加至核心的函数,准确度的装饰器添加至 ``metric_mu.record`` 。\n \n\"\"\"\n\nimport sys\nimport time\nimport json\nimport sqlite3\n\nfrom datetime import datetime\n\n# assign default Sqlite3 path.\nSQL_PATH = '/home/shawn/Projects/x.resources/database/exp_measurement.sqlite3'\n\n\nclass Monit:\n def __init__(self, _db=None):\n self.start = datetime.now()\n self.db_path = _db or SQL_PATH\n self.conn = sqlite3.connect(self.db_path)\n self.curs = self.conn.cursor()\n\n def set_start(self):\n self.start = datetime.now()\n\n def get_runtime(self):\n return (datetime.now() - self.start).total_seconds()\n\n def save_runtime(self, dataset, params):\n ins = 'INSERT INTO runtime_tauren (dataset, params, result) VALUES(?, ?, ?)'\n attributes = [dataset, params, self.get_runtime()]\n self.curs.execute(ins, attributes)\n self.conn.commit()\n self.set_start()\n\n def save_accuracy(self, dataset, params):\n ins = 'INSERT INTO accuracy_tauren (dataset, result) VALUES(?, ?)'\n self.curs.execute(ins, [dataset, params])\n self.conn.commit()\n\n def close(self):\n self.curs.close()\n self.conn.close()\n\n\ndef rt_decorate(func):\n def func_wrapper(*args, **kwargs):\n params = {}\n for key, value in kwargs.iteritems():\n size = sys.getsizeof(value)\n if size > 256:\n params[key] = '%i-bytes' % size\n else:\n params[key] = value\n\n monit = Monit()\n monit.set_start()\n result = func(*args, **kwargs) # execute original function\n monit.save_runtime(repr(func), json.dumps(params))\n monit.close()\n return result\n\n return func_wrapper\n\n\ndef ac_decorate(func):\n def func_wrapper(*args, **kwargs):\n monit = Monit()\n result = func(*args, **kwargs) # execute original function\n assert isinstance(result, dict), 'func should return dictionary.'\n monit.save_accuracy(result.get('task', '-1'), json.dumps(result, indent=True))\n monit.close()\n return result\n\n return func_wrapper\n\n\nif __name__ == '__main__':\n # mimic a function of machine learning.\n\n @rt_decorate\n def foo2(task, **kwargs):\n time.sleep(1.5)\n return {'precision': 0.205} # mimic a precision\n\n\n import numpy as np\n\n foo2('foo', an=np.random.random([100, 10]))\n\n","sub_path":"expression/inspection.py","file_name":"inspection.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"602003936","text":"# coding: utf8\n\nimport asyncio\nfrom jinja2 import Environment, FileSystemLoader, Template\n\nfrom .. import webapi\n\n\nclass Render:\n \"\"\"Rendering interface to Jinja2 Templates\n\n Example:\n\n render= Render('templates')\n render.hello(name='jinja2')\n \"\"\"\n def __init__(self, *a, **kwargs):\n if not a:\n try:\n path = webapi.config.template.get('path', 'templates')\n except:\n path = 'templates'\n extensions = kwargs.pop('extensions', [])\n globals = kwargs.pop('globals', {})\n self._lookup = Environment(\n loader=FileSystemLoader(*a, **kwargs),\n extensions=extensions\n )\n\n self._lookup.globals.update(globals)\n\n webapi.ctx.template_vars = self._lookup.globals.copy()\n\n async def __getattr__(self, name):\n # Assuming all templates end with .html\n path = name + '.html'\n self._lookup.globals = webapi.ctx.template_vars.copy()\n co_get_template = asyncio.coroutine(self._lookup.get_template)\n t = await co_get_template(path)\n return asyncio.coroutine(t.render)\n\n async def local_vars(self, _vars={}):\n webapi.ctx.template_vars.update(_vars)\n\n async def template(self, text, _vars={}):\n co = asyncio.coroutine(Template(text).render)\n return await co(**_vars)\n\n async def filter(self, name=''):\n def decorator(f):\n if not name:\n name = f.func_name\n self._lookup.filters[name] = f\n return f\n\n return decorator\n","sub_path":"aweb/template/jinja.py","file_name":"jinja.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"429835463","text":"import pyglet\nfrom game import util\n\n\nclass PhysicalObject(pyglet.sprite.Sprite):\n\n def __init__(self, *args, **kwargs):\n super(PhysicalObject, self).__init__(*args, **kwargs)\n\n self.velocity_x = 0\n self.velocity_y = 0\n self.rotate_speed = 0\n self.dead = False\n self.new_objects = []\n self.reacts_to_bullets = True\n self.is_bullet = False\n\n def rotate(self, dt):\n if self.rotation > 360:\n self.rotation = 0\n elif self.rotation < 0:\n self.rotation = 360\n\n self.rotation += self.rotate_speed * dt\n\n def update(self, dt):\n self.x += self.velocity_x * dt\n self.y += self.velocity_y * dt\n\n self.check_bounds()\n\n if self.rotate_speed:\n self.rotate(dt)\n\n def check_bounds(self):\n min_x = -self.image.width / 2\n min_y = -self.image.height / 2\n max_x = 800 + (self.image.width / 2)\n max_y = 600 + (self.image.height / 2)\n\n if self.x < min_x:\n self.x = max_x\n elif self.x > max_x:\n self.x = min_x\n\n if self.y < min_y:\n self.y = max_y\n elif self.y > max_y:\n self.y = min_y\n\n def collides_with(self, other_object):\n if not self.reacts_to_bullets and other_object.is_bullet:\n return False\n if self.is_bullet and not other_object.reacts_to_bullets:\n return False\n\n collision_distance = ((self.image.width / 2) * self.scale) + \\\n ((other_object.image.width / 2) * other_object.scale)\n\n actual_distance = util.distance(self.position, other_object.position)\n\n return (actual_distance <= collision_distance)\n\n def handle_collision_with(self, other_object):\n if not other_object.__class__ == self.__class__:\n self.dead = True\n","sub_path":"pyglet/tutorial/asteroids/game/physicalobject.py","file_name":"physicalobject.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"643266168","text":"import os\nimport argparse\n\nfrom skeleton_sequence import SkeletonSequence\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nfrom scipy.signal import medfilt\nfrom scipy.ndimage.filters import gaussian_filter\nfrom scipy.spatial.distance import euclidean\n\nfrom fastdtw import fastdtw\n\n\nskeleton_seq = SkeletonSequence()\n\nparser = argparse.ArgumentParser(description='Visualize skeleton sequence data.')\nparser.add_argument('--data' , help='Path to the json recording of an action.')\nparser.add_argument('--sigma' , help='sigma value of the gaussian filter used for smoothening the signal')\nparser.add_argument('--filt_size', help='Median Filter size')\n\nargs = parser.parse_args()\nprint(args)\nassert args.data, \"Argument --data is required for loading a recording from a json file.\"\nskeleton_seq.load_from_json(args.data)\n\n\nif args.filt_size is None:\n filt_size = 13\nelse:\n filt_size = int(args.filt_size)\n\nif args.sigma is None:\n sigma = 0.1\nelse:\n sigma = float(args.sigma)\n\n\ndef smoothing(values):\n values = medfilt(volume=values, kernel_size=filt_size)\n values = gaussian_filter(input=values, sigma=sigma)\n\n return values\n\n\nsns.set()\n\nfor key, values in skeleton_seq.sequence_data['joint_angles'].items():\n\n values = smoothing(values)\n # skeleton_seq.sequence_data['joint_angles'][key] = list(values)\n\n plt.plot(range(len(values)),\n values)\n\n\nupper_joint_angles = ['LNeckJoint', 'RNeckJoint', 'LArmpitJoint', 'RArmpitJoint',\n'LElbowJoint', 'RElbowJoint','LHipJoint','RHipJoint']\nno_of_joints = len(upper_joint_angles)\nfor key in upper_joint_angles:\n print(key + '::')\n print('Mean: ', np.average(skeleton_seq.sequence_data['joint_angles'][key]))\n print('Variance: ', round(np.var(skeleton_seq.sequence_data['joint_angles'][key]), 2))\n print(\"=====================================\")\n\n\nlower_joint_angles = ['LThighJoint', 'RThighJoint', 'LKneeJoint', 'RKneeJoint']\nno_of_joints = len(lower_joint_angles)\nfor key in lower_joint_angles:\n print(key + '::')\n print('Mean: ', np.average(skeleton_seq.sequence_data['joint_angles'][key]))\n print('Variance: ', round(np.var(skeleton_seq.sequence_data['joint_angles'][key]), 2))\n print(\"=====================================\")\n\nplt.legend(skeleton_seq.sequence_data['joint_angles'].keys(), ncol=2, loc='upper right');\nplt.show()\n# plt.savefig\n","sub_path":"visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"156766839","text":"from django.db import models\nfrom django.contrib.postgres.fields import ArrayField\nfrom django.contrib.auth.models import User\nfrom django.utils.text import slugify\nimport os\n\n# Create your models here.\n\nclass Category(models.Model):\n \"\"\"Model definition for Category.\"\"\"\n title = models.CharField(max_length=50)\n slug = models.SlugField(blank=True, null=True)\n created = models.DateField(auto_now_add=True, blank=True, null=True)\n updated = models.DateField(auto_now=True, blank=True, null=True)\n class Meta:\n \"\"\"Meta definition for Category.\"\"\"\n verbose_name = 'Category'\n verbose_name_plural = 'Categories'\n def save(self, *args, **kwargs):\n self.slug = slugify(self.title)\n super(Category, self).save(*args, **kwargs)\n def __str__(self):\n \"\"\"Unicode representation of Category.\"\"\"\n return self.title\n\nclass SuggestedSite(models.Model):\n \"\"\"Model definition for SuggestedSite.\"\"\"\n title = models.CharField(max_length=200)\n url = models.CharField(max_length=200)\n categories = models.CharField(max_length=200)\n created = models.DateField(auto_now_add=True, blank=True, null=True)\n updated = models.DateField(auto_now=True, blank=True, null=True)\n class Meta:\n \"\"\"Meta definition for SuggestedSite.\"\"\"\n verbose_name = 'SuggestedSite'\n verbose_name_plural = 'SuggestedSites'\n def __str__(self):\n \"\"\"Unicode representation of SuggestedSite.\"\"\"\n return self.title\n\nclass Site(models.Model):\n \"\"\"Model definition for Site.\"\"\"\n title = models.CharField(max_length=200)\n url = models.CharField(max_length=200)\n available = models.BooleanField(default=False)\n created = models.DateField(auto_now_add=True, blank=True, null=True)\n updated = models.DateField(auto_now=True, blank=True, null=True)\n class Meta:\n \"\"\"Meta definition for Site.\"\"\"\n verbose_name = 'Site'\n verbose_name_plural = 'Sites'\n def __str__(self):\n \"\"\"Unicode representation of Site.\"\"\"\n return self.title\n\nclass TrackedSite(models.Model):\n \"\"\"Model definition for TrackedSite.\"\"\"\n site_id = models.ForeignKey(Site, on_delete=models.CASCADE)\n category_id = models.ForeignKey(Category, on_delete=models.CASCADE)\n path_url = models.CharField(max_length=200)\n created = models.DateField(auto_now_add=True, blank=True, null=True)\n updated = models.DateField(auto_now=True, blank=True, null=True)\n class Meta:\n \"\"\"Meta definition for TrackedSite.\"\"\"\n verbose_name = 'TrackedSite'\n verbose_name_plural = 'TrackedSites'\n def __str__(self):\n \"\"\"Unicode representation of TrackedSite.\"\"\"\n return \"Tracked-{0}-{1}\".format(self.site_id,self.category_id)\n\ndef upload_screenshot(instance, filename):\n filename_base, filename_ext = os.path.splitext(filename)\n return 'schreenshots/{0}/{1}%Y%m%d{2}'.format(instance.tracked_site, filename_base, filename_ext)\n\nclass Screenshot(models.Model):\n \"\"\"Model definition for Screenshot.\"\"\"\n \n tracked_site = models.ForeignKey(TrackedSite, on_delete=models.CASCADE)\n mobile_url = models.CharField(max_length=255, blank=True, null=True)\n tablet_url = models.CharField(max_length=255, blank=True, null=True)\n desktop_url = models.CharField(max_length=255, blank=True, null=True)\n created = models.DateField(auto_now_add=True, blank=True, null=True)\n updated = models.DateField(auto_now=True, blank=True, null=True)\n class Meta:\n \"\"\"Meta definition for Screenshot.\"\"\"\n verbose_name = 'Screenshot'\n verbose_name_plural = 'Screenshots'\n def __str__(self):\n \"\"\"Unicode representation of Screenshot.\"\"\"\n return \"Screenshot created {0}\".format(self.created)","sub_path":"api-rest/apps/core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"613908656","text":"\"\"\"\nReads in a tsv file with pre-trained bottom up attention features and\nstores it in HDF5 format. Also store {image_id: feature_idx}\n as a pickle file.\nHierarchy of HDF5 file:\n{ 'image_features': num_images x num_boxes x 2048 array of features\n 'image_bb': num_images x num_boxes x 4 array of bounding boxes }\n\"\"\"\nfrom __future__ import print_function\n\nimport os\nimport io\nimport sys\n# sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n# sys.path.append(os.path.join(os.getcwd(), 'vqa-maskrcnn-benchmark'))\n\nimport base64\nimport csv\nimport h5py\nimport pickle as cPickle\nimport numpy as np\nimport utils\nfrom tqdm import tqdm\n\ncsv.field_size_limit(sys.maxsize)\n\nFIELDNAMES = ['image_id', 'image_w', 'image_h', 'num_boxes', 'boxes', 'features']\n\nOUTPUT_BASEPATH = 'mid_pre_input'\n\nos.makedirs(OUTPUT_BASEPATH, exist_ok=True)\n\ntrain_data_file = os.path.join(OUTPUT_BASEPATH,'train36_vizwiz.hdf5')\nval_data_file = os.path.join(OUTPUT_BASEPATH, 'val36_vizwiz.hdf5')\ntrain_indices_file = os.path.join(OUTPUT_BASEPATH, 'train36_imgid2idx_vizwiz.pkl')\nval_indices_file = os.path.join(OUTPUT_BASEPATH, 'val36_imgid2idx_vizwiz.pkl')\ntrain_ids_file = os.path.join(OUTPUT_BASEPATH, 'train_ids_vizwiz.pkl')\nval_ids_file = os.path.join(OUTPUT_BASEPATH, 'val_ids_vizwiz.pkl')\n\nfeature_length = 2048\nnum_fixed_boxes = 36\n\n# npy image feature 가져오기\nimport os\nos.environ['CUDA_VISIBLE_DEVICES']='4'\nfrom tqdm import tqdm\nimport yaml\nimport cv2\nimport torch\nimport requests\nimport numpy as np\nimport gc\nimport torch.nn.functional as F\nimport pandas as pd\nimport csv\nimport base64\nimport pickle\n\nfrom glob import glob\nimport torchvision.models as models\nimport torchvision.transforms as transforms\n\nfrom PIL import Image\n# from IPython.display import display, HTML, clear_output\n# from ipywidgets import widgets, Layout\nfrom io import BytesIO\n\nfrom maskrcnn_benchmark.config import cfg\nfrom maskrcnn_benchmark.layers import nms\nfrom maskrcnn_benchmark.modeling.detector import build_detection_model\nfrom maskrcnn_benchmark.structures.image_list import to_image_list\nfrom maskrcnn_benchmark.utils.model_serialization import load_state_dict\n\ninput_img_paths = []\ntrain_paths = glob(\"../mypythia/data/vizwiz/train/*.jpg\")\nval_paths = glob(\"../mypythia/data/vizwiz/val/*.jpg\")\ntrain_paths = sorted(train_paths, key=lambda x: int(os.path.split(x)[-1].split(\"_\")[-1].split(\".\")[0]))\nval_paths = sorted(val_paths, key=lambda x: int(os.path.split(x)[-1].split(\"_\")[-1].split(\".\")[0]))\n\ninput_img_paths.extend(train_paths)\ninput_img_paths.extend(val_paths)\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '4'\ntsv_info_list = []\nBASE_PATH = '../mypythia'\n\ndef _image_transform(image_path):\n\n img = Image.open(image_path)\n im = np.array(img).astype(np.float32)\n im = im[:, :, ::-1]\n im -= np.array([102.9801, 115.9465, 122.7717])\n im_shape = im.shape\n im_size_min = np.min(im_shape[0:2])\n im_size_max = np.max(im_shape[0:2])\n im_scale = float(800) / float(im_size_min)\n # Prevent the biggest axis from being more than max_size\n if np.round(im_scale * im_size_max) > 1333:\n im_scale = float(1333) / float(im_size_max)\n im = cv2.resize(\n im,\n None,\n None,\n fx=im_scale,\n fy=im_scale,\n interpolation=cv2.INTER_LINEAR\n )\n img = torch.from_numpy(im).permute(2, 0, 1)\n return img, im_scale\n\ndef _build_detection_model():\n \n cfg.merge_from_file(os.path.join(BASE_PATH,'content/model_data/detectron_model.yaml'))\n cfg.freeze()\n\n model = build_detection_model(cfg)\n checkpoint = torch.load(os.path.join(BASE_PATH,'content/model_data/detectron_model.pth'), \n map_location=torch.device(\"cpu\"))\n\n load_state_dict(model, checkpoint.pop(\"model\"))\n\n model.to(\"cuda\")\n model.eval()\n return model\n\n# ['image_id', 'image_w', 'image_h', 'num_boxes', 'boxes', 'features']\ndef _process_feature_extraction(output,\n im_scales,\n feat_name='fc6',\n conf_thresh=0.2):\n batch_size = len(output[0][\"proposals\"])\n n_boxes_per_image = [len(_) for _ in output[0][\"proposals\"]]\n score_list = output[0][\"scores\"].split(n_boxes_per_image)\n score_list = [torch.nn.functional.softmax(x, -1) for x in score_list]\n feats = output[0][feat_name].split(n_boxes_per_image)\n cur_device = score_list[0].device\n\n feat_list = []\n keep_boxes_list = []\n\n for i in range(batch_size):\n dets = output[0][\"proposals\"][i].bbox / im_scales[i]\n # print(f\"im_scales[i]: {im_scales[i]!r}\")\n scores = score_list[i]\n\n max_conf = torch.zeros((scores.shape[0])).to(cur_device)\n\n for cls_ind in range(1, scores.shape[1]):\n cls_scores = scores[:, cls_ind]\n keep = nms(dets, cls_scores, 0.5)\n max_conf[keep] = torch.where(cls_scores[keep] > max_conf[keep],\n cls_scores[keep],\n max_conf[keep])\n\n keep_boxes = torch.argsort(max_conf, descending=True)[:num_fixed_boxes]\n feat_list.append(feats[i][keep_boxes])\n \n \n return feat_list, output[0][\"proposals\"][0].bbox[keep_boxes]\n\n#batchsize 는 1로 고정\ndef get_tsv_info(path):\n \n image_id = int(os.path.split(path)[-1].split('_')[-1].split('.')[0])\n \n im, im_scale = _image_transform(path)\n img_tensor, im_scales = [im], [im_scale]\n current_img_list = to_image_list(img_tensor, size_divisible=32)\n current_img_list = current_img_list.to('cuda')\n output = model(current_img_list)\n \n gc.collect()\n torch.cuda.empty_cache()\n \n feat_list, bbox = _process_feature_extraction(output, im_scales, 'fc6', 0.2)\n \n image_width = output[1][0].size[0]\n image_height= output[1][0].size[1]\n print(path, ' saved!!')\n return {'image_id':image_id, 'image_w':image_width, 'image_h':image_height, 'num_boxes':num_fixed_boxes, 'boxes':np.array(bbox.tolist()), 'features':np.array(feat_list[0].tolist())} \n # return {'image_id':image_id, 'image_w':image_width, 'image_h':image_height, 'num_boxes':100, 'boxes':base64.encodebytes(np.array(bbox.tolist()).tobytes()), 'features':base64.encodebytes(np.array(feat_list[0].tolist()).tobytes())}\n # return [image_id, image_width, image_height, 100, base64.encodestring(np.array(bbox.tolist()).tobytes()), base64.encodestring(np.array(feat_list[0].tolist()).tobytes())]\n\n\nmodel = _build_detection_model()\n\nh_train = h5py.File(train_data_file, \"w\")\nh_val = h5py.File(val_data_file, \"w\")\n\nif os.path.exists(train_ids_file) and os.path.exists(val_ids_file):\n print(f\"----------p train_ids_file: {train_ids_file!r}\")\n train_imgids = cPickle.load(open(train_ids_file))\n val_imgids = cPickle.load(open(val_ids_file))\nelse:\n train_imgids = utils.load_imageid('../mypythia/data/vizwiz/train')\n val_imgids = utils.load_imageid('../mypythia/data/vizwiz/val')\n cPickle.dump(train_imgids, open(train_ids_file, 'wb'),protocol=2)\n cPickle.dump(val_imgids, open(val_ids_file, 'wb'),protocol=2)\n\ntrain_indices = {}\nval_indices = {}\n\ntrain_img_features = h_train.create_dataset(\n 'image_features', (len(train_imgids), num_fixed_boxes, feature_length), 'f')\ntrain_img_bb = h_train.create_dataset(\n 'image_bb', (len(train_imgids), num_fixed_boxes, 4), 'f')\ntrain_spatial_img_features = h_train.create_dataset(\n 'spatial_features', (len(train_imgids), num_fixed_boxes, 6), 'f')\n\nval_img_bb = h_val.create_dataset(\n 'image_bb', (len(val_imgids), num_fixed_boxes, 4), 'f')\nval_img_features = h_val.create_dataset(\n 'image_features', (len(val_imgids), num_fixed_boxes, feature_length), 'f')\nval_spatial_img_features = h_val.create_dataset(\n 'spatial_features', (len(val_imgids), num_fixed_boxes, 6), 'f')\n\ntrain_counter = 0\nval_counter = 0\n\nfor path in tqdm(input_img_paths):\n item = get_tsv_info(path)\n item['num_boxes'] = int(item['num_boxes'])\n image_id = int(item['image_id'])\n image_w = float(item['image_w'])\n image_h = float(item['image_h'])\n bboxes = item['boxes'].reshape((item['num_boxes'], -1))\n\n box_width = bboxes[:, 2] - bboxes[:, 0]\n box_height = bboxes[:, 3] - bboxes[:, 1]\n scaled_width = box_width / image_w\n scaled_height = box_height / image_h\n scaled_x = bboxes[:, 0] / image_w\n scaled_y = bboxes[:, 1] / image_h\n\n box_width = box_width[..., np.newaxis]\n box_height = box_height[..., np.newaxis]\n scaled_width = scaled_width[..., np.newaxis]\n scaled_height = scaled_height[..., np.newaxis]\n scaled_x = scaled_x[..., np.newaxis]\n scaled_y = scaled_y[..., np.newaxis]\n\n spatial_features = np.concatenate(\n (scaled_x,\n scaled_y,\n scaled_x + scaled_width,\n scaled_y + scaled_height,\n scaled_width,\n scaled_height),\n axis=1)\n\n if image_id in train_imgids:\n train_imgids.remove(image_id)\n train_indices[image_id] = train_counter\n train_img_bb[train_counter, :, :] = bboxes\n train_img_features[train_counter, :, :] = item['features'].reshape((item['num_boxes'], -1))\n train_spatial_img_features[train_counter, :, :] = spatial_features\n train_counter += 1\n elif image_id in val_imgids:\n val_imgids.remove(image_id)\n val_indices[image_id] = val_counter\n val_img_bb[val_counter, :, :] = bboxes\n val_img_features[val_counter, :, :] = item['features'].reshape((item['num_boxes'], -1))\n val_spatial_img_features[val_counter, :, :] = spatial_features\n val_counter += 1\n else:\n assert False, 'Unknown image id: %d' % image_id\n\nif len(train_imgids) != 0:\n print('Warning: train_image_ids is not empty')\n\nif len(val_imgids) != 0:\n print('Warning: val_image_ids is not empty')\n\ncPickle.dump(train_indices, open(train_indices_file, 'wb'))\ncPickle.dump(val_indices, open(val_indices_file, 'wb'))\nh_train.close()\nh_val.close()\nprint(\"done!\")\n","sub_path":"bottom-up_features/tsv_vizwiz.py","file_name":"tsv_vizwiz.py","file_ext":"py","file_size_in_byte":9990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"651922294","text":"import pandas as pd\nimport numpy as np\n\n\nclass Form:\n def __init__(self):\n # Importing the csv containing the form results\n csv = pd.read_csv('./Form/DIA_Form.csv')\n csv.columns = ['Date', 'Age', 'Sex', 'AW', 'WS0', 'WS10', 'WS20', 'WS50']\n\n # Classes of customers\n c1 = csv[(csv.Sex == 'Femmina') & (csv.Age <= 35)] # C1: Females under 35\n c2 = csv[(csv.Sex == 'Maschio') & (csv.Age <= 35)] # C2: Males under 35\n c3 = csv[(csv.Sex == 'Femmina') & (csv.Age > 35)] # C3: Females over 35\n c4 = csv[(csv.Sex == 'Maschio') & (csv.Age > 35)] # C4: Males over 35\n\n # Total number of customers per class\n n1 = len(c1.Date)\n n2 = len(c2.Date)\n n3 = len(c3.Date)\n n4 = len(c4.Date)\n self.n = np.array([n1, n2, n3, n4])\n\n # Number of people per class that buy (at least) item 1\n nc1_i1 = c1.Date[c1.AW == 'Sì'].count()\n nc2_i1 = c2.Date[c2.AW == 'Sì'].count()\n nc3_i1 = c3.Date[c3.AW == 'Sì'].count()\n nc4_i1 = c4.Date[c4.AW == 'Sì'].count()\n\n # Probability (per class) that a customer buys (at least)\n c1_i1 = nc1_i1 / n1\n c2_i1 = nc2_i1 / n2\n c3_i1 = nc3_i1 / n3\n c4_i1 = nc4_i1 / n4\n self.i1_param = np.array([c1_i1, c2_i1, c3_i1, c4_i1])\n\n # Number of customers per class that buy item 2 after buying item 1 and getting promo P0\n nc1_i2_p0 = c1.Date[c1.WS0 == 'Sì'].count()\n nc2_i2_p0 = c2.Date[c2.WS0 == 'Sì'].count()\n nc3_i2_p0 = c3.Date[c3.WS0 == 'Sì'].count()\n nc4_i2_p0 = c4.Date[c4.WS0 == 'Sì'].count()\n\n # Probability (per class) that a customer buys item 2 after buying item 1 and getting promo P0\n c1_i21_p0_param = nc1_i2_p0 / n1\n c2_i21_p0_param = nc2_i2_p0 / n2\n c3_i21_p0_param = nc3_i2_p0 / n3\n c4_i21_p0_param = nc4_i2_p0 / n4\n\n # Number of customers per class that buy item 2 after buying item 1 and getting promo P1\n nc1_i2_p1 = c1.Date[c1.WS10 == 'Sì'].count()\n nc2_i2_p1 = c2.Date[c2.WS10 == 'Sì'].count()\n nc3_i2_p1 = c3.Date[c3.WS10 == 'Sì'].count()\n nc4_i2_p1 = c4.Date[c4.WS10 == 'Sì'].count()\n\n # Probability (per class) that a customer buys item 2 after buying item 1 and getting promo P1\n c1_i21_p1_param = (nc1_i2_p1 + nc1_i2_p0) / n1\n c2_i21_p1_param = (nc2_i2_p1 + nc2_i2_p0) / n2\n c3_i21_p1_param = (nc3_i2_p1 + nc3_i2_p0) / n3\n c4_i21_p1_param = (nc4_i2_p1 + nc4_i2_p0) / n4\n\n # Number of customers per class that buy item 2 after buying item 1 and getting promo P2\n nc1_i2_p2 = c1.Date[c1.WS20 == 'Sì'].count()\n nc2_i2_p2 = c2.Date[c2.WS20 == 'Sì'].count()\n nc3_i2_p2 = c3.Date[c3.WS20 == 'Sì'].count()\n nc4_i2_p2 = c4.Date[c4.WS20 == 'Sì'].count()\n\n # Probability (per class) that a customer buys item 2 after buying item 1 and getting promo P2\n c1_i21_p2_param = (nc1_i2_p2 + nc1_i2_p1 + nc1_i2_p0) / n1\n c2_i21_p2_param = (nc2_i2_p2 + nc2_i2_p1 + nc2_i2_p0) / n2\n c3_i21_p2_param = (nc3_i2_p2 + nc3_i2_p1 + nc3_i2_p0) / n3\n c4_i21_p2_param = (nc4_i2_p2 + nc4_i2_p1 + nc4_i2_p0) / n4\n\n # Number of customers per class that buy item 2 after buying item 1 and getting promo P3\n nc1_i2_p3 = c1.Date[c1.WS50 == 'Sì'].count()\n nc2_i2_p3 = c2.Date[c2.WS50 == 'Sì'].count()\n nc3_i2_p3 = c3.Date[c3.WS50 == 'Sì'].count()\n nc4_i2_p3 = c4.Date[c4.WS50 == 'Sì'].count()\n\n # Probability (per class) that a customer buys item 2 after buying item 1 and getting promo P3\n c1_i21_p3_param = (nc1_i2_p3 + nc1_i2_p2 + nc1_i2_p1 + nc1_i2_p0) / n1\n c2_i21_p3_param = (nc2_i2_p3 + nc2_i2_p2 + nc2_i2_p1 + nc2_i2_p0) / n2\n c3_i21_p3_param = (nc3_i2_p3 + nc3_i2_p2 + nc3_i2_p1 + nc3_i2_p0) / n3\n c4_i21_p3_param = (nc4_i2_p3 + nc4_i2_p2 + nc4_i2_p1 + nc4_i2_p0) / n4\n\n self.i21_param = np.array([[c1_i21_p0_param, c2_i21_p0_param, c3_i21_p0_param, c4_i21_p0_param],\n [c1_i21_p1_param, c2_i21_p1_param, c3_i21_p1_param, c4_i21_p1_param],\n [c1_i21_p2_param, c2_i21_p2_param, c3_i21_p2_param, c4_i21_p2_param],\n [c1_i21_p3_param, c2_i21_p3_param, c3_i21_p3_param, c4_i21_p3_param]])\n","sub_path":"Form/Form.py","file_name":"Form.py","file_ext":"py","file_size_in_byte":4430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"211651508","text":"import sys\nfrom PyQt5.QtWidgets import QApplication,QMainWindow\nfrom PyQt5 import uic,QtWidgets\nfrom PyQt5.QtCore import QTimer\nfrom PyQt5.QtGui import QImage,QPixmap\nimport cv2\n\n\nclass App(QMainWindow):\n def __init__(self):\n super().__init__()\n self.timer = QTimer()\n uic.loadUi(r\"EDIZ\\Kamera.ui\",self) # graphical user interface\n self.initUI()\n\n def initUI(self):\n\n self.btAc.clicked.connect(self.KameraAc)\n self.btKapat.setEnabled(False)\n self.btKapat.clicked.connect(self.KameraKapat)\n self.show()\n\n def KameraAc(self):\n if not self.timer.isActive():\n self.cam = cv2.VideoCapture(0,cv2.CAP_DSHOW)\n self.timer.start(3)\n self.btAc.setEnabled(False)\n self.btKapat.setEnabled(True)\n self.Goster()\n else:\n self.cam.release()\n self.timer.stop()\n\n \n\n def Goster(self):\n while True:\n ret,frame = self.cam.read()\n buyukFaktor = 0.6\n frame = cv2.resize(frame,None,fx=buyukFaktor,fy=buyukFaktor,interpolation=cv2.INTER_AREA)\n height,width,channel = frame.shape # (640,480,3)\n step = channel*width # (3*480)\n #-----------------\n qImg = QImage(frame.data,width,height,step,QImage.Format_BGR888) # farklı kanallardan aldığı veriyi\n # bir resim olarak ekrana yansıtmak üzere QImage kullanıldı\n self.lblCam.setPixmap(QPixmap.fromImage(qImg)) # Alınan resmi label içerisinde gösterebilmek için\n # QPixmap kullanıldı\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n break\n\n self.cam.release()\n self.timer.stop() \n\n def KameraKapat(self):\n try:\n self.cam.release()\n except:\n pass\n self.timer.stop()\n self.close()\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n ex = App()\n sys.exit(app.exec_())\n","sub_path":"HUNKAR/Kamera.py","file_name":"Kamera.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"25325075","text":"import os\nimport time\nimport argparse\nimport pickle\nimport tensorflow as tf\n# import tensorflowjs as tfjs\n\nfrom models import *\nfrom gmm import gmmrnd_easy\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--mode', type=str, default='train')\nparser.add_argument('--enc', type=str, default='ff')\nparser.add_argument('--dec', type=str, default='ff')\nparser.add_argument('--n_inds', type=int, default=None)\nparser.add_argument('--B', type=int, default=10)\nparser.add_argument('--N_min', type=int, default=300)\nparser.add_argument('--N_max', type=int, default=600)\nparser.add_argument('--K', type=int, default=4)\nparser.add_argument('--gpu', type=str, default='0')\nparser.add_argument('--lr', type=float, default=1e-3)\nparser.add_argument('--run_name', type=str, default='trial')\nparser.add_argument('--num_steps', type=int, default=50000)\nparser.add_argument('--test_freq', type=int, default=200)\nparser.add_argument('--save_freq', type=int, default=400)\nparser.add_argument('--exp_name', type=str, default='trial')\nparser.add_argument('--net', type=str, default='set_transformer')\n\nargs = parser.parse_args()\nos.environ['CUDA_VISIBLE_DEVICES'] = str(args.gpu)\n\n# Argument parameters\nB = args.B # batch_size\nn_steps = args.num_steps\nlr = args.lr\nN_min = args.N_min\nN_max = args.N_max\nK = args.K\nD = 2\nsave_freq = args.save_freq\n\n# Architecture combinations\nenc = args.enc\ndec = args.dec\nn_inds = args.n_inds\nif args.net == 'set_transformer':\n enc = 'sab'\n n_inds = 32\n dec = 'sabsab'\nelif args.net == 'deepset':\n enc = 'ff'\n dec = 'ff'\nelse:\n pass\narch = enc if enc == dec else enc + '_' + dec\n\n# Set save directory and tfjs directory\nif n_inds is not None and enc == 'sab':\n arch += '_' + str(n_inds)\nsave_dir = os.path.join('./results', arch, args.exp_name)\n# tfjs_dir = os.path.join('./results', arch, 'tfjs')\n\n# Placeholder input\nX = tf.compat.v1.placeholder(tf.float32, [None, None, D])\nmodel = build_model(X, K, D, enc=enc, dec=dec, n_inds=n_inds)\n\nif not os.path.isfile('benchmark.pkl'):\n print('you should generate a benchmark')\nelse:\n with open('benchmark.pkl', 'rb') as f:\n bench = pickle.load(f)\n\nglobal_step = tf.compat.v1.train.get_or_create_global_step()\nlr = tf.compat.v1.train.piecewise_constant(tf.cast(global_step, dtype=tf.int32), [int(0.7*n_steps)], [lr, 0.1*lr])\n\ndef train():\n if not os.path.isdir(save_dir):\n os.makedirs(save_dir)\n train_op = tf.compat.v1.train.AdamOptimizer(lr).minimize(-model['ll'][0], global_step=global_step)\n saver = tf.compat.v1.train.Saver()\n sess = tf.compat.v1.Session()\n sess.run(tf.compat.v1.global_variables_initializer())\n logfile = open(os.path.join(save_dir, time.strftime('%Y%m%d-%H%M%S') + '.log'), 'wb', 0)\n\n for t in range(1, n_steps + 1):\n N = np.random.randint(N_min, N_max)\n np_X = gmmrnd_easy(B, N, K, return_meta=False)\n _, np_train_ll = sess.run([train_op, model['ll'][0]], {X: np_X})\n if t % 200 == 0:\n np_lr = sess.run(lr)\n line = 'step {}, lr {:.3e}, train ll {:.4f}'.format(t, np_lr, np_train_ll)\n print(\"line:\", line)\n logfile.write((line + '\\n').encode())\n test(sess=sess, logfile=logfile)\n if t % save_freq == 0:\n saver.save(sess, os.path.join(save_dir, 'model'))\n model.save_weights('./model.h5')\n saver.save(sess, os.path.join(save_dir, 'model'))\n\n # tfjs.converters.save_keras_model(sess, tfjs_dir)\n logfile.close()\n\n\n\ndef gen_benchmark():\n N_list = np.random.randint(N_min, N_max, 100)\n data = {}\n data['X'] = []\n data['ll'] = 0.\n for N in N_list:\n batch = gmmrnd_easy(B, N, K)\n data['X'].append(batch['X'])\n data['ll'] += batch['true_ll']\n data['ll'] /= len(N_list)\n with open('benchmark.pkl', 'wb') as f:\n pickle.dump(data, f)\n\n\ndef test(sess=None, logfile=None):\n if sess is None:\n sess = tf.Session()\n tf.train.Saver().restore(sess, os.path.join(save_dir, 'model'))\n if logfile is None:\n logfile = open(os.path.join(save_dir, 'test.log'), 'wb')\n avg_ll = 0\n for np_X in bench['X']:\n avg_ll = np.array(sess.run(model['ll'], {X: np_X}))\n avg_ll /= len(bench['X'])\n line = 'average ll/data {:.4f} -> {:.4f}, '.format(avg_ll[0], avg_ll[1])\n line += '(oracle ll/data {:.4f})'.format(bench['ll'])\n print(line)\n logfile.write((line + '\\n\\n').encode())\n\n\nif __name__=='__main__':\n if args.mode == 'train':\n train()\n elif args.mode == 'gen_benchmark':\n gen_benchmark()\n elif args.mode == 'test':\n test()\n","sub_path":"set_transformer_tf/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"302118716","text":"#!/usr/bin/env python\n\n\"\"\"\nTests for the shell operation\n\"\"\"\n\nimport unittest\n\nimport dockerscript.operations\n\nclass TestShellOperation(unittest.TestCase):\n \"\"\"\n Tests for the ShellOperation class\n \"\"\"\n\n def test_build(self):\n \"\"\"\n Tests that the build output is correct\n \"\"\"\n\n operation = dockerscript.operations.ShellOperation('/bin/zsh', ['-c'])\n\n self.assertEqual(\n 'SHELL [\"/bin/zsh\", \"-c\"]',\n operation.build(),\n 'Shell was set correctly',\n )\n\nclass TestShell(unittest.TestCase):\n \"\"\"\n Tests for the shell function\n \"\"\"\n\n def test_operation_creation(self):\n \"\"\"\n Tests that the operation is created correctly\n \"\"\"\n\n shell = '/bin/zsh'\n arguments = ('-c', )\n image = dockerscript.Image()\n\n dockerscript.operations.shell(image, shell, *arguments)\n\n self.assertListEqual(\n [\n dockerscript.operations.ShellOperation(shell, list(arguments)),\n ],\n image.operations,\n 'Operation was added correctly',\n )\n","sub_path":"tests/operations/test_shell.py","file_name":"test_shell.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"491360400","text":"\"\"\"\nDynamic commands for tactics\n\nTactics can reload all commands in the module by calling Tactics.reload_commands().\n\nRegexes must use named groups for arguments to be passed to the function.\nCommands that need a priority should use '(?#n)' at the start of the regex.\n\nCommands may be a string or a function.\n - Strings will be sent as a reply to the nick that triggered the command.\n - Functions will be called and should handle their own output.\n\n\"\"\"\n\nfrom tactics import static\n\ndynamic_commands = {\n\t'^help': static.help,\n\t'^reload': lambda self, msg: self.reload_commands() or msg.reply(\"Reloaded commands\"),\n\n\t# Say [#] \n\t'(?#1)^say #(?P.+) (?P.+)$': lambda _, msg, chan, text: msg.server.privmsg(\"#\"+chan, text),\n\t'(?#2)^say (?P.+)$': lambda _, msg, text: msg.reply(text),\n\n\t# Get quote by id\n\t'^get #(?P\\d+)': lambda self, msg, id: msg.reply(self.phrases.format(self.phrases.get_phrase_by_id(id))),\n\n\t# Get id of last quote\n\t'^what was that': lambda self, msg: msg.reply(\"That was #{:>06}\".format(self.phrases.last['_id']) if self.phrases.last else \"I didn't say anything!\"),\n}\n","sub_path":"tactics/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"345888004","text":"from PyQt5.QtGui import QImage,QPixmap\nfrom PyQt5.QtCore import QTimer\nfrom PyQt5.QtWidgets import QApplication,QMainWindow,QMessageBox,QFileDialog\nfrom GUI.myGUIWindow import Ui_mainWindow\nimport sys\nimport numpy as np\nimport camera_configs\nimport cv2\n\nclass mainWindow(QMainWindow,Ui_mainWindow):\n def __init__(self):\n #窗口初始化\n super(mainWindow,self).__init__()\n self.setupUi(self)\n self.timer = QTimer(self) #定时器\n self.cap = cv2.VideoCapture() #视频流\n self.meanArea = 0.0 #平均面积\n self.frameCount = 0 #视频帧数\n self.IniUI()\n\n def IniUI(self):\n #初始化\n self.rightEyeImg.clear()\n self.leftEyeImg.clear()\n self.depthImg.clear()\n self.resultImg.clear()\n self.pBtn_readEyeImg.clicked.connect(self.show_initialIMG)\n self.pBtn_getDepthImg.clicked.connect(self.show_depthIMG)\n self.pBtn_getBestArea.clicked.connect(self.show_resultIMG)\n self.pBtn_refresh.clicked.connect(self.clearAll)\n self.pBtn_dynamic.clicked.connect(self.show_dynamic)\n self.timer.timeout.connect(self.dynamic_showing)\n self.slider_BlockSize.setValue(21)\n self.slider_num.setValue(3)\n self.BlockSize = self.slider_BlockSize.value()\n self.Num = self.slider_num.value()\n self.label_blocksize.setText(str(self.BlockSize))\n self.label_num.setText(str(self.Num))\n self.slider_BlockSize.valueChanged.connect(self.slider_blocksize_changed)\n self.slider_num.valueChanged.connect(self.slider_num_changed)\n self.slider_num.sliderPressed.connect(self.slider_num_changed)\n\n def slider_blocksize_changed(self):\n '''监听blocksize改变'''\n self.BlockSize = self.slider_BlockSize.value()\n self.label_blocksize.setText(str(self.slider_BlockSize.value()))\n\n def slider_num_changed(self):\n '''监听num改变'''\n self.Num = self.slider_num.value()\n self.label_num.setText(str(self.slider_num.value()))\n\n def show_dynamic(self):\n '''开启/关闭动态显示'''\n if self.timer.isActive() == False: #当按下按钮时,定时器未启动的话,启动定时器,显示图像\n path , ok = QFileDialog.getOpenFileName(self,'选取视频文件','.','(*.mp4 *.avi)')\n if ok:\n self.meanArea = 0.0 # 平均面积\n self.frameCount = 0 # 视频帧数\n ret = self.cap.open(path)\n if ret == False:\n QMessageBox.warning(self, 'warning', \"打开视频失败\", buttons=QMessageBox.Ok)\n else:\n self.timer.start(100) #开始计时,间隔为30ms\n self.pBtn_dynamic.setText('关闭动态显示')\n else:\n QMessageBox.warning(self, 'warning', \"您需要选择一个视频文件哦😯\", buttons=QMessageBox.Ok)\n return\n else: #按下按钮时,已处在播放状态\n self.timer.stop() #停止计时\n self.cap.release()\n self.clearAll()\n self.pBtn_dynamic.setText('开启动态显示')\n self.meanArea = 0.0\n self.frameCount = 0\n\n def dynamic_showing(self):\n '''动态显示'''\n ret,img = self.cap.read()\n if ret == False:\n self.timer.stop() # 停止计时\n self.cap.release()\n self.clearAll()\n self.pBtn_dynamic.setText('开启动态显示')\n self.meanArea = 0.0\n self.frameCount = 0\n return\n self.show_initialIMG(img,1)\n self.show_depthIMG()\n self.show_resultIMG()\n\n def clearAll(self):\n '''清除显示的图片'''\n self.rightEyeImg.clear()\n self.leftEyeImg.clear()\n self.depthImg.clear()\n self.resultImg.clear()\n self.coordinate_x.clear()\n self.coordinate_y.clear()\n self.coordinate_z.clear()\n self.Area.clear()\n self.meanArea = 0.0 # 平均面积\n self.frameCount = 0 # 视频帧数\n\n def show_initialIMG(self,frame,flag = 0):\n '''显示左右目图片\n flag:0代表默认静态的图片,1代表动态显示\n frame:动态显示的图片'''\n # 读取图片\n self.meanArea = 0.0 # 平均面积\n self.frameCount = 0 # 视频帧数\n if flag == 1:\n img = frame\n else:\n path , ret = QFileDialog.getOpenFileName(self,'选取双目图像','.','(*.jpg *.png *.bmp *.jpeg)')\n if ret:\n img = cv2.imread(path, cv2.IMREAD_COLOR)\n else:\n QMessageBox.warning(self, 'warning', \"您需要选择一张图片哦😯\", buttons=QMessageBox.Ok)\n return\n self.leftImg = img[0:399, 0:639]\n self.rightImg = img[0:399, 639:1279]\n\n # 根据更正map对图片进行重构\n self.leftImg = cv2.remap(self.leftImg, camera_configs.left_map1, camera_configs.left_map2, cv2.INTER_LINEAR)\n self.rightImg = cv2.remap(self.rightImg, camera_configs.right_map1, camera_configs.right_map2, cv2.INTER_LINEAR)\n\n #反转颜色为RGB\n cv2.cvtColor(self.leftImg,cv2.COLOR_BGR2RGB,self.leftImg)\n cv2.cvtColor(self.rightImg,cv2.COLOR_BGR2RGB,self.rightImg)\n\n #尺寸\n h = self.leftEyeImg.height()\n w = self.rightEyeImg.width()\n channel = self.leftImg.shape[2]\n\n #重置尺寸适应label\n self.leftImg = cv2.resize(self.leftImg,(w,h))\n self.rightImg = cv2.resize(self.rightImg,(w,h))\n\n #使用QImage绘制图像\n QIMG_left = QImage(self.leftImg.data,w,h,channel*w,QImage.Format_RGB888)\n QIMG_right = QImage(self.rightImg.data,w,h,channel*w,QImage.Format_RGB888)\n\n pixmapL = QPixmap.fromImage(QIMG_left)\n pixmapR = QPixmap.fromImage(QIMG_right)\n\n self.leftEyeImg.setPixmap(pixmapL)\n self.rightEyeImg.setPixmap(pixmapR)\n\n def show_depthIMG(self):\n '''显示深度图'''\n self.get_depthIMG()\n # 尺寸\n h = self.leftEyeImg.height()\n w = self.rightEyeImg.width()\n channel = 3\n self.disp = self.disp[:,16*self.Num:639]\n\n #伪彩色处理\n disp = cv2.applyColorMap(self.disp, cv2.COLORMAP_JET)\n disp = cv2.resize(disp,(w,h))\n\n #显示\n QIMG_depthIMG = QImage(disp.data,w,h,w*channel,QImage.Format_RGB888)\n pixmap_depthIMG = QPixmap.fromImage(QIMG_depthIMG)\n self.depthImg.setPixmap(pixmap_depthIMG)\n\n def show_resultIMG(self):\n '''显示最终的结果图'''\n self.get_landArea()\n # 尺寸\n h = self.leftEyeImg.height()\n w = self.rightEyeImg.width()\n channel = self.landAreaImg.shape[2]\n\n self.landAreaImg = cv2.resize(self.landAreaImg,(w,h))\n\n QIMG_landAreaIMG = QImage(self.landAreaImg.data,w,h,w*channel,QImage.Format_RGB888)\n pixmap_landAreaIMG = QPixmap.fromImage(QIMG_landAreaIMG)\n self.resultImg.setPixmap(pixmap_landAreaIMG)\n #显示坐标和面积\n self.coordinate_y.setText(str(round(self.y,3)))\n self.coordinate_x.setText(str(round(self.x,3)))\n self.coordinate_z.setText(str(round(self.z,3)))\n self.Area.setText(str(round(3.14*(self.R**2),3)))\n\n def get_depthIMG(self):\n '''计算深度图'''\n #转化为灰度图\n self.leftImg_gray = cv2.cvtColor(self.leftImg,cv2.COLOR_RGB2GRAY)\n self.rightImg_gray = cv2.cvtColor(self.rightImg,cv2.COLOR_RGB2GRAY)\n\n # 根据SGBM方法生成差异图\n stereo = cv2.StereoSGBM_create(numDisparities=16 * self.Num, blockSize=self.BlockSize)\n self.disparity = stereo.compute(self.leftImg_gray,self.rightImg_gray)\n self.fornorm = self.disparity\n self.fornorm[self.fornorm < 0] = 0 # 上下限截断,显示图像亮度稳定\n self.fornorm[self.fornorm > 511] = 511\n self.disp = cv2.normalize(self.fornorm, self.fornorm, alpha=-500, beta=300, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)\n\n def get_landArea(self):\n '''计算最佳降落位置'''\n self.frameCount = self.frameCount + 1\n # 视差图梯度提取\n grad_x = cv2.Sobel(self.disparity, cv2.CV_32F, 1, 0) # 对x求一阶导\n grad_y = cv2.Sobel(self.disparity, cv2.CV_32F, 0, 1) # 对y求一阶导\n grad_xx = cv2.convertScaleAbs(grad_x) # 用convertScaleAbs()函数将其转回原来的uint8形式\n grad_yy = cv2.convertScaleAbs(grad_y)\n grad_xy = cv2.addWeighted(grad_xx, 0.5, grad_yy, 0.5, 0) # 图片融合\n _, im_at_fixed = cv2.threshold(grad_xy, 4, 255, cv2.THRESH_BINARY_INV)\n\n # 使用模板匹配查找平坦区域\n template = np.zeros((120, 120), dtype=np.uint8)\n for i in range(template.shape[0]):\n for j in range(template.shape[1]):\n template[i, j] = 255\n\n result = cv2.matchTemplate(im_at_fixed, template, cv2.TM_SQDIFF_NORMED)\n min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)\n tl = min_loc\n br = (tl[0] + 120, tl[1] + 120)\n # cv2.rectangle(im_at_fixed, tl, br, (0, 0, 0), 2)\n\n # 遍历查找到的中心点,绘制降落的圆形区域\n uu = 0\n x = tl[1] + 60\n y = tl[0] + 60\n for i in range(0, x - 1):\n if im_at_fixed[x - i, y] == 255:\n uu = i\n else:\n break\n\n dd = 0\n for i in range(1, im_at_fixed.shape[0] - x - 1):\n if im_at_fixed[x + i, y] == 255:\n dd = i\n else:\n break\n\n ll = 0\n for i in range(1, y - 1):\n if im_at_fixed[x, y - 1] == 255:\n ll = i\n else:\n break\n\n rr = 0\n for i in range(0, im_at_fixed.shape[1] - y - 1):\n if im_at_fixed[x, y + rr] == 255:\n rr = i\n else:\n break\n\n # 将图片扩展至3d空间中,其z方向的值则为当前的距离\n threeD = np.zeros((400, 640), dtype=np.float32)\n threeD = cv2.reprojectImageTo3D(self.disparity.astype(np.float32) / 16., camera_configs.Q)\n\n # 取四个方向的最小半径\n R = uu\n R = dd if dd < R else R\n R = ll if ll < R else R\n R = rr if rr < R else R\n im_at_fixed = cv2.cvtColor(im_at_fixed,cv2.COLOR_GRAY2RGB)\n\n # 设置显示坐标\n self.x = threeD[x, y, 0]\n self.y = threeD[x, y, 1]\n self.z = threeD[x, y, 2]\n self.R = R\n\n #阈值及均值优化\n meanArea = (3.14*(self.R**2) + self.meanArea*(self.frameCount -1 ))/self.frameCount #当前均值\n if 3.14*(self.R**2) >= meanArea and 3.14*(self.R**2) > 7000:\n cv2.circle(im_at_fixed, (y, x), R, (255, 0, 0), 2)\n\n self.landAreaImg = im_at_fixed\n self.meanArea = meanArea #均值更新\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n win = mainWindow()\n win.show()\n sys.exit(app.exec())\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"231010736","text":"'''\nCreated on 06.09.2014\n\n@author: Johannes\n'''\nfrom simple.Exercise04 import is_vowel\n\ndef translate(x):\n resultString = \"\"\n for sign in x:\n #print(sign)\n resultString += sign \n if not is_vowel(sign) and sign != \" \":\n resultString += \"o\" + sign \n \n return resultString\n \n#print(translate(\"test\"))\nprint(translate(\"this is fun\"))","sub_path":"src/simple/Exercise05.py","file_name":"Exercise05.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"229253710","text":"class Node:\r\n def __init__(self, data):\r\n self.data = data\r\n self.left = None\r\n self.right = None\r\n\r\n\r\nclass binaryTree:\r\n def __init__(self):\r\n self.root = None\r\n\r\n def _pushUtil(self, node, element):\r\n if element < node.data:\r\n if node.left is None:\r\n node.left = Node(element)\r\n else:\r\n self._pushUtil(node.left, element)\r\n else:\r\n if node.right is None:\r\n node.right = Node(element)\r\n else:\r\n self._pushUtil(node.right, element)\r\n\r\n def push(self, element):\r\n if self.root is None:\r\n self.root = Node(element)\r\n else:\r\n self._pushUtil(self.root, element)\r\n\r\n def printTree(self):\r\n self._printUtil(self.root)\r\n\r\n def _printUtil(self, node):\r\n if node is not None:\r\n self._printUtil(node.left)\r\n print(node.data, end=\" - \")\r\n self._printUtil(node.right)\r\n\r\n\r\ndef isIdentical(root1, root2):\r\n if root1 is None and root2 is None:\r\n return True\r\n\r\n if (\r\n root1.data == root2.data\r\n and isIdentical(root1.left, root2.left)\r\n and isIdentical(root1.right, root2.right)\r\n ):\r\n return True\r\n else:\r\n return False\r\n\r\n\r\ndef main():\r\n bt1 = binaryTree()\r\n bt2 = binaryTree()\r\n bt1.push(1)\r\n bt1.push(2)\r\n bt1.push(3)\r\n bt1.push(4)\r\n bt2.push(1)\r\n bt2.push(2)\r\n bt2.push(3)\r\n bt2.push(4)\r\n bt1.printTree()\r\n print(\"\\n\")\r\n bt2.printTree()\r\n print(isIdentical(bt1.root, bt2.root))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"tree/identicalTree.py","file_name":"identicalTree.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"270342671","text":"__author__ = 'marrabld'\n\nimport ConfigParser\nimport os\n\n\nclass State():\n def __init__(self):\n self.debug = ''\n\n conf = ConfigParser.ConfigParser()\n conf.read(os.path.join(os.path.dirname(__file__), 'bootstrap.conf'))\n self.debug = conf.get('Debug', 'Level')","sub_path":"project/lib/bootstrappy/libbootstrap/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"271476725","text":"\"\"\"\n@author: Jonathan Navarrete\n\"\"\"\n\n\nimport pandas as pd\nimport itertools as it\nimport numpy as np\nfrom Probs2 import Probs ## code for calculating joint/marginal probabilities\n#from Plot import PlotDiGraph, PlotNetwork ## plotting\nfrom Discretize import Discretize\nimport DiscreteProbs as dp\nfrom tqdm import tqdm\nimport networkx as nx\n\n\nclass KDEBayes():\n\n def __init__(self, dataframe, class_col_name, maximum=True, progress_bar=False):\n \"\"\"\n Tree Augmented Naive Bayes Algorithm for building a Tree Augmented Naive Bayes Classifier\n \"\"\"\n self.class_col_name = class_col_name\n self.priors = self.Priors(dataframe, class_col_name)\n colnames = dataframe.columns.tolist()\n colnames.remove(class_col_name)\n self.colnames = colnames\n self.MIresults = self.MutualInfo(dataframe, progress_bar = progress_bar) ## a dictionary {class: dataframe}\n self.Root = self.SetRoots(dataframe) ## returns name of root\n self.MST = self.BuildMST()\n self.DAG = self.BuildForest()\n\n def Priors(self, dataframe, class_col_name):\n n = dataframe.shape[0]\n array = dataframe[class_col_name].values\n vals, counts = np.unique(array, return_counts=True)\n prop = counts/n\n priors = dict(zip(vals, prop))\n return priors\n\n \n def MutualInfo(self, df, progress_bar):\n class_col_name = self.class_col_name\n g = df.groupby(by = class_col_name) ## group df by class\n if progress_bar:\n g = tqdm(g)\n colnames = self.colnames\n ## process the following steps for each class\n ClassMats = {} ## dictionary to store MutualInfMatrix for each class\n for i, frame in g:\n colcombos = it.combinations(colnames, 2) ## will return tuples\n MutualInfo = []\n for u, v in colcombos:\n ulist = frame[u] #.tolist() ## Probs2 takes a series\n vlist = frame[v] #.tolist()\n probs = Probs(ulist, vlist) ## calculates all probs\n MI = probs.CalcMutualInfo() \n MutualInfo.append((u, v, MI)) ## no longer storing probs to save memory\n MutualInfMatrix = pd.DataFrame(MutualInfo, columns = ['U', 'V', \"MI\"])\n MutualInfMatrix.sort_values(by = \"MI\", ascending=False, inplace=True)\n MutualInfMatrix.reset_index(inplace=True, drop=True)\n ClassMats[i] = MutualInfMatrix ## store results for current class\n return ClassMats\n\n \n def SetRoots(self, dataframe):\n \"\"\"\n FAN algorithm: \n \n 1. for each attribute:\n calculate the Mutual Information with the Class variable;\n this is not the conditional-Mutual Info.\n 2. Root = attribute with max(MI)\n \n Root is the same for all trees in this version of TAN\n \"\"\"\n class_col_name = self.class_col_name\n colnames = self.colnames\n colcombos = it.product([class_col_name], colnames)\n MutualInfo = []\n ulist = dataframe[class_col_name]\n for u, v in colcombos:\n vals = dataframe[v]\n if isinstance(vals, np.float64):\n vlist = Discretize(vals) ## convert continuous values to discrete\n else:\n vlist = vals\n probs = dp.Probs(ulist, vlist)\n MI = probs.CalcMutualInfo()\n MutualInfo.append((u, v, MI))\n MutualInfo.sort(key = lambda x: x[2], reverse=False) ## descending\n ## top branch\n xclass, root, weight = MutualInfo[0]\n return root\n \n \n \n \n def BuildMST(self):\n \"\"\"\n Uses Networkx to build Maximum Spanning Tree\n \"\"\"\n ClassFrames = self.MIresults \n MST = {}\n \n for i, frame in ClassFrames.items():\n\n\n G = nx.Graph() ## number of unique attributes\n for ind, u, v, mi in frame.itertuples():\n mi = -1*mi ## -1*mi to build minimum spanning tree\n G.add_edge(u, v, weight = mi) \n ## return Maximum Spanning Tree and switched flag (list)\n maxst = nx.minimum_spanning_tree(G)\n MST[i] = maxst\n ## return dictionary of maximum spanning trees\n return MST\n\n\n\n def BuildForest(self):\n \"\"\"\n Using the Maximum Spanning Tree, we will now 'prune' the tree by\n removed edges where weight (Mutual Info) is less than mean(all_weights)\n \n For each class variable we're trying to predict:\n 1. Build DAG with from Maximum Spanning Tree using the root node\n from self.SetRoots; all edges point away from root.\n \"\"\"\n MST = self.MST ## dictionary(class: list of tuples)\n ## Step 1: Build DAG\n DAG = {}\n for key, mst in MST.items():\n root = self.Root \n pred = nx.predecessor(mst, root)\n edges = []\n weights = []\n ## U: Child\n ## V: Parent, thus Parent can be None for Roots\n for u, v in pred.items():\n if len(v) > 0:\n v = v[0]\n edge_data = mst.get_edge_data(u,v)\n w = -1*edge_data['weight']\n weights.append(w)\n else:\n v = None\n w = 0\n edges.append((u,v,w))\n \n avgweight = np.mean(weights)\n ## new rule:\n ## If weight is less than avg, break conditional probs\n final_edges = []\n print(f\"\\nClass: {key} || Directed Graph \\n(child <-- parent): \")\n print(\"--------------------------------\")\n for u, v, w in edges:\n if w < avgweight:\n v = None\n final_edges.append((u,v))\n print(f\"{u} <-- {v}\")\n\n DAG[key] = final_edges\n return DAG\n\n\n def BuildModel(self, dataframe):\n class_col_name = self.class_col_name\n g = dataframe.groupby(by = class_col_name) ## group df by class\n DAG = self.DAG\n ClassMats = {} ## dictionary to store MutualInfMatrix for each class\n for klass, frame in g:\n edges = DAG[klass]\n MutualInfo = []\n for u, v in edges:\n ulist = frame[u] #.tolist()\n if v is not None:\n vlist = frame[v] #.tolist()\n else:\n ## head node will have None\n vlist = None\n probs = Probs(ulist, vlist) ## calculates all probs\n MutualInfo.append((u, v, probs)) \n MutualInfMatrix = pd.DataFrame(MutualInfo, columns = ['U', 'V', \"Probs\"])\n ClassMats[klass] = MutualInfMatrix\n return TreeBayes(self.priors, ClassMats, self.class_col_name)\n \n\n\nclass TreeBayes():\n def __init__(self, priors, TreeModels, class_col_name):\n self.class_col_name = class_col_name\n self.priors = priors\n self.TreeModels = TreeModels\n \n def __repr__(self):\n treemodels = self.TreeModels\n out = str(treemodels) \n return out\n\n def Predict(self, newdf, log=False, progress_bar=False):\n TreeProbs = self.TreeModels\n newcols = newdf.columns.tolist()\n if self.class_col_name in newcols:\n newdf = newdf.drop(self.class_col_name, axis = 1)\n results = []\n rows = newdf.iterrows()\n if progress_bar:\n rows = tqdm(rows)\n for i, row in newdf.iterrows():\n sample = row.to_dict()\n class_probs = {}\n for class_name, treeframe in TreeProbs.items():\n prior = self.priors[class_name]\n LogPosterior = np.log(prior)\n for ind, u, v, probs in treeframe.itertuples():\n if v is not None:\n pval = probs.ConditionalProb(sample[u], sample[v])\n else:\n pval = probs.PredMarginalProb(sample[u])\n logpval = np.log(pval)\n LogPosterior += logpval\n if log:\n class_probs[class_name] = LogPosterior\n else:\n class_probs[class_name] = np.exp(LogPosterior)\n results.append(class_probs)\n dfresult = pd.DataFrame(results)\n dfresult[self.class_col_name] = dfresult.idxmax(axis=1)\n return dfresult\n","sub_path":"NaiveBayesNets/FAN/kdebayes/FAN.py","file_name":"FAN.py","file_ext":"py","file_size_in_byte":8548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"218922902","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\nfrom scipy import stats\nimport numpy as np\n\n# Import data into a DataFrame.\npath = \"../dataset/babysamp-98.txt\"\ndf = pd.read_csv(path, skiprows=1,\n sep='\\t',\n names=('MomAge', 'DadAge', 'MomEduc', 'MomMarital', 'numlive',\n \"dobmm\", 'gestation', 'sex', 'weight', 'prenatalstart',\n 'orig.id', 'preemie'))\n# Show all columns.\npd.set_option('display.max_columns', None)\npd.set_option('display.width', 1000)\nprint(df.head())\n\n# ------------------------------------------------------------------\n# Show statistics, boxplot, extreme values and returns DataFrame\n# row indexes where outliers exist.\n# ------------------------------------------------------------------\ndef viewAndGetOutliers(df, colName, threshold, plt):\n # Show basic statistics.\n dfSub = df[[colName]]\n print(\"*** Statistics for \" + colName)\n print(dfSub.describe())\n\n # Show boxplot.\n dfSub.boxplot(column=[colName])\n plt.title(colName)\n plt.show()\n\n # Note this is absolute 'abs' so it gets both high and low values.\n z = np.abs(stats.zscore(dfSub))\n rowColumnArray = np.where(z > threshold)\n rowIndices = rowColumnArray[0]\n\n # Show outlier rows.\n print(\"\\nOutlier row indexes for \" + colName + \":\")\n print(rowIndices)\n print(\"\")\n\n # Show filtered and sorted DataFrame with outliers.\n dfSub = df.iloc[rowIndices]\n dfSorted = dfSub.sort_values([colName], ascending=[True])\n print(\"\\nDataFrame rows containing outliers for \" + colName + \":\")\n print(dfSorted)\n return rowIndices\n\nTHRESHOLD_Z =2.33\npriceOutlierRows = viewAndGetOutliers(df, 'weight', THRESHOLD_Z, plt)\n","sub_path":"Labs/Lab8/lab8_example5.py","file_name":"lab8_example5.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"83114348","text":"def check(string):\n sList = list(string)\n stack = [sList[0]]\n i = 1\n while i < len(string):\n if sList[i] == '[' or sList[i] == '{' or sList[i] == '(':\n stack.append(sList[i])\n else:\n if len(stack) != 0:\n if sList[i] == ')' and stack[-1] == '(':\n stack.pop()\n elif sList[i] == '}' and stack[-1] == '{':\n stack.pop()\n elif sList[i] == ']' and stack[-1] == '[':\n stack.pop()\n i += 1\n if len(stack) != 0:\n return False\n else:\n return True\n\n\ndef solution(s):\n answer = 0\n for i in range(len(s)):\n string = s[i:] + s[0:i]\n if check(string):\n answer += 1\n return answer\n","sub_path":"2021/21주차/괄호 회전하기/김재환.py","file_name":"김재환.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"16323090","text":"#!/usr/local/python/bin/python\n# coding=utf-8\n\n\"\"\"\n一个数如果恰好等于它的因子之和,这个数就成为“完数”。例如6=1+2+3。编程找出1000以内的所有完数。\n\"\"\"\nimport time\nstart = time.clock()\nfor i in range(1, 1001):\n\tnum_list = []\n\tflag = i\n\tfor j in range(1, i):\n\t\tif i % j == 0:\n\t\t\tnum_list.append(j)\n\t\t\tflag -= j\n\tif flag == 0:\n\t\tprint(\"%s 是完全数\" % i)\nend = time.clock()\nprint(end - start)\n","sub_path":"prac_problem/day11.py","file_name":"day11.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"392407680","text":"# -*- coding: utf-8 -*-\n\n# Copyright (C) 2017 github.com/shyal\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport getpass\nfrom collections import defaultdict\n\nimport vulcan.lib.highlighter as hi\nfrom vulcan.lib.store import Card\nfrom vulcan.lib.text_utils import *\n\nfrom urwid import *\nfrom textwrap import dedent\n\nclass LineWidget(Columns):\n\n \"\"\"\n Individual lines of code in vulcan's main view.\n Reprensenting the code as individual lines enables us to\n treat each line as a column. This is so we can substitute\n clozes with urwid Edit widgets.\n \"\"\"\n\n def __init__(self, items, __edit_change_manager, cloze_to_edit=False):\n self.items = items\n self.__ignore_callback = False\n self.__edit_change_manager = __edit_change_manager\n columns = []\n text = []\n for it in items:\n if it[0] == 'cloze':\n if text:\n columns.append(('pack', Text(text)))\n text = []\n cloze = re.search(\"{c:([^}]+)}\", it[1]).group(1)\n edit = self.__edit_change_manager.Edit(cloze)\n columns.append(('fixed', len(cloze), edit))\n else:\n text.append(it)\n\n if text:\n columns.append(Text(text))\n\n self.__super.__init__(columns)\n\n def __str__(self):\n return str(self.items)\n\n def __repr__(self):\n return str(self.items)\n\nclass EditChangeHandler:\n\n \"\"\"\n Manage Clozes / urwid Edits. The same clozes may end up appearing\n multiple times at once, in which case they'll all update simultaneously.\n\n Likewise we can check whether they were all entered correctly etc.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n self.__edit is a defaultdict of lists, because the same cloze\n can appear multiple times.\n \"\"\"\n self.__edit = defaultdict(list)\n self.__text_change = \"\"\n\n def Edit(self, cloze):\n edit = Edit('', len(cloze) * '_')\n self.__edit[cloze].append(edit)\n connect_signal(edit, 'change', self.change, cloze)\n connect_signal(edit, 'postchange', self.postchange, cloze)\n return edit\n\n def change(self, edit, text, cloze):\n self.__text_change = text\n\n def postchange(self, edit, text, cloze):\n for edit in self.__edit[cloze]:\n text = edit._normalize_to_caption(self.__text_change)\n edit.highlight = None\n edit._edit_text = text[:len(cloze)]\n if edit.edit_pos > len(cloze):\n edit.edit_pos = len(cloze)\n edit._invalidate()\n\n @property\n def has_clozes(self):\n for k, v in self.__edit.items():\n for e in v:\n return True\n return False\n\n @property\n def clozes_are_correct(self):\n correct = True\n for k, v in self.__edit.items():\n for e in v:\n correct = correct and e.edit_text == k\n has_closes = True\n return correct\n\n @property\n def diffs(self):\n \"\"\"\n Get whether there were differences between the text written in the cloze\n and the actual text that should have been entered (the answer to the cloze).\n \"\"\"\n diffs = []\n for k, edit_fields in self.__edit.items():\n if edit_fields:\n if k != edit_fields[0].edit_text:\n diffs.append([edit_fields[0].edit_text, k])\n return diffs\n\nclass CardContext(WidgetWrap):\n\n \"\"\"\n Cards can have different looks based on which language they're in.\n By default, they just show up in a bash-esque environment, however\n they can appear in an interactive python shell, a mysql shell etc. \n \"\"\"\n\n def __init__(self, card, command, banner, prompt):\n self.card = card\n self.__command = command\n self.__banner = banner\n self.__prompt = prompt\n self.__edit_change_manager = EditChangeHandler()\n\n ct = ClozedText(card.clozed_preamble)\n highlighted = hi.highlight(ct.strip_clozes)\n positions = ct.positions\n highlighted.isolate_positions(positions)\n highlighted.replace_clozes(positions, ct.clozes)\n\n lines = self.lines(highlighted)\n pile = []\n if self.__banner:\n pile.append(Text(('gray', self.__banner)))\n formatted_prompt = FormattedText(self.__prompt)\n if lines:\n cols = [\n ('fixed', formatted_prompt.width, Pile([Text(formatted_prompt.items)]*len(lines)))\n ]\n cols.append(('weight', 1, Pile(lines)))\n\n pile.append(Columns(cols))\n\n if self.card.clozed_question:\n pile.append(Text(formatted_prompt.items + [('dark blue', \"# \"), ('dark blue', self.card.clozed_question)]))\n\n if command:\n pile.insert(0, Text(bash_prompt() + [command]))\n\n self.__super.__init__(Pile(pile))\n\n @property\n def clozes_are_correct(self):\n return self.__edit_change_manager.clozes_are_correct\n\n @property\n def has_clozes(self):\n return self.__edit_change_manager.has_clozes\n\n @property\n def diffs(self):\n return self.__edit_change_manager.diffs\n\n def lines(self, pygt):\n lines = []\n line = []\n for it in pygt:\n if it[1] == '\\n':\n if line:\n lines.append(LineWidget(line, self.__edit_change_manager))\n else:\n lines.append(Text(''))\n line = []\n else:\n line.append(it)\n if line:\n lines.append(LineWidget(line, self.__edit_change_manager))\n return lines\n\n @property\n def prompt(self):\n if isinstance(self.__prompt, str):\n return [self.__prompt]\n elif isinstance(self.__prompt, list):\n return self.__prompt\n\n @property\n def command(self):\n if isinstance(self.__command, str):\n if self.__command:\n return [self.__command]\n return []\n elif isinstance(self.__command, list):\n return self.__command\n\nclass PythonCardContext(CardContext):\n\n def __init__(self, *args, **kwargs):\n command = \"python\"\n banner = \"\"\"Python 2.7.10 (default, Jul 14 2015, 19:46:27)\n[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\"\"\"\n prompt = \">>> \"\n super(PythonCardContext, self).__init__(command=command, banner=banner, prompt=prompt, *args, **kwargs)\n\nclass SQLite3CardContext(CardContext):\n\n def __init__(self, *args, **kwargs):\n command = \"sqlite3\"\n banner = \"\"\"SQLite version 3.8.7.4 2014-12-09 01:34:36\nEnter \".help\" for usage hints.\nConnected to a transient in-memory database.\nUse \".open FILENAME\" to reopen on a persistent database.\"\"\"\n prompt = \"sqlite> \"\n super(SQLite3CardContext, self).__init__(command=command, banner=banner, prompt=prompt, *args, **kwargs)\n\nclass NodeCardContext(CardContext):\n\n def __init__(self, *args, **kwargs):\n command = \"node\"\n prompt = \"> \"\n super(NodeCardContext, self).__init__(command=command, banner='', prompt=prompt, *args, **kwargs)\n\nclass RubyCardContext(CardContext):\n\n def __init__(self, *args, **kwargs):\n command = \"ruby\"\n banner = \"\"\"ruby 2.0.0p481 (2014-05-08 revision 45883) [universal.x86_64-darwin14]\"\"\"\n prompt = \"\"\n super(RubyCardContext, self).__init__(command=command, banner=banner, prompt=prompt, *args, **kwargs)\n\nclass SQLCardContext(CardContext):\n\n def __init__(self, *args, **kwargs):\n command = \"mysql\"\n banner = \"\"\"Welcome to the MariaDB monitor. Commands end with ; or \\\\g.\nYour MariaDB connection id is 5\nServer version: 10.1.23-MariaDB Homebrew\n\nCopyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.\n\nType 'help;' or '\\\\h' for help. Type '\\\\c' to clear the current input statement.\"\"\"\n prompt = \"MariaDB [(none)]> \"\n super(SQLCardContext, self).__init__(command=command, banner=banner, prompt=prompt, *args, **kwargs)\n\ndef bash_prompt():\n return [(\"dark blue\", getpass.getuser()), ('', \"@\"), (\"dark green\", \"vulcan\"), ('', \":\"),(\"dark blue\", \"~ \")]\n\nclass BashCardContext(CardContext):\n\n def __init__(self, *args, **kwargs):\n super(BashCardContext, self).__init__(command='', banner='', prompt=bash_prompt(), *args, **kwargs)\n\ndef prompt(card):\n if \"python\" in card.context:\n return PythonCardContext(card)\n if card.context == \"sqlite3\":\n return SQLite3CardContext(card)\n if card.context in ['node', 'nodejs', 'react', 'redux']:\n return NodeCardContext(card)\n elif card.context == \"sql\":\n return SQLCardContext(card)\n elif card.context == \"ruby\":\n return RubyCardContext(card)\n return BashCardContext(card)\n\nclass CardWidget(WidgetWrap):\n\n def __init__(self, card: Card):\n self.__card = card\n pygt = hi.highlight(card.clozed_preamble)\n lines = self.lines(pygt)\n\n pile = Columns([\n ('pack', Text('>>> \\n'*self.__card.lines)),\n ('weight', 1, Pile(lines))\n ])\n self.__super.__init__(pile)\n\n def lines(self, pygt):\n lines = []\n line = []\n for it in pygt:\n if it[1] == '\\n':\n if line:\n lines.append(LineWidget(line))\n else:\n lines.append(Text(''))\n line = []\n else:\n line.append(it)\n return lines\n\n","sub_path":"vulcan/lib/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":10618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"284264007","text":"# -*- coding: utf-8 -*-\n\nimport urllib\nfrom core.lib.httpclient import RequestBase\nfrom core.settings import RELEASE\n\nclass CAuthRequest(RequestBase):\n def __init__(self, paramDict):\n super(CAuthRequest,self).__init__()\n self._setServerAddress(\"oauth.vk.com\")\n self._setServerPage('/access_token?' + urllib.urlencode(paramDict))\n self._setHttpType('https')\n self._setRequestType('GET')\n def _createRawRequest(self):\n request = ''\n self._setRawRequest(request)\n return True","sub_path":"auth_sys/layer/vk/authorize/client/authRequest.py","file_name":"authRequest.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"259822908","text":"# -*- coding=UTF-8 -*- # \n\nfrom Tkinter import *\n# from diary import *\n\nimport sys \nreload(sys)\nsys.setdefaultencoding('utf8') # learning from wzzlj 还是不能输入中文?\n\nclass Application(Frame):\n\tdef read(self): #? \n\t\tdiary = open('diary.txt','r')\n\t\tself.txt = Text(self,width=51,height=20) # size changeable\n\t\t# self.txt.config(state=NORMAL)\n\t\tself.txt.insert(END,diary.read())\n\t\tself.txt.see(END)\n\t\t# self.txt.config(state=DISABLED)\n\n\tdef write(self,written): # 写了written就对了。为什么?\n\t\tdiary = open('diary.txt','a')\n\t\twritten = self.entry.get() # .get can get the text\n\t\tself.entry.delete(0,END) # clear the text column\n\t\tdiary.write('\\n' + written)\n\t\tdiary.close()\n\n\tdef createWidgets(self):\n\t\t# new input\n\t\t\n\t\tself.label = Label(self,text=\"请输入您的日记:\").pack(side=LEFT)\n\t\t# self.label.grid()\n\n\t\t# define entry properties\n\t\tself.entry = Entry(self)\n\t\tself.entry.bind(\"\",self.write)\n\t\tself.entry.pack(side=LEFT) # need width\n\n\t\t# read button\n\t\tself.READ = Button(self) \n\t\tself.READ[\"text\"] = \"读取\" \n\t\tself.READ[\"fg\"] = \"red\" \n\t\tself.READ[\"command\"] = self.read\n\t\tself.READ.pack(side=LEFT)\n\n\t\t# quit button\n\t\tself.QUIT = Button(self) \n\t\tself.QUIT[\"text\"] = \"退出\" \n\t\tself.QUIT[\"fg\"] = \"red\" \n\t\tself.QUIT[\"command\"] = self.quit\n\t\tself.QUIT.pack(side=RIGHT)\n\n\n\tdef __init__(self,master=None):\n\t\tFrame.__init__(self,master)\n\t\tself.pack()\n\t\tself.createWidgets() \n\n\t\t\nroot = Tk()\n# root.geometry('400x420+400+400')\nroot.title('My Diary App')\napp = Application(master=root)\napp.mainloop()\n","sub_path":"_src/om2py2w/2wex0/diaryGUI.py","file_name":"diaryGUI.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"227799568","text":"from PyQt5 import QtCore\nfrom PyQt5.QtGui import QPixmap\nfrom PyQt5.QtWidgets import (\n QWidget, QLabel, QFrame, QVBoxLayout, QHBoxLayout, QToolButton, QGridLayout\n)\n\n\nclass Label(QLabel):\n def __init__(self, img, img_scale=0.8):\n super(Label, self).__init__()\n\n self.img_scale = img_scale\n self.pixmap = QPixmap(img)\n\n self.setFrameStyle(QFrame.StyledPanel)\n self.setMinimumSize(1, 1)\n self.setAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignHCenter)\n self.setPixmap(self.pixmap)\n\n def resizeEvent(self, event):\n w = self.size().width() * self.img_scale\n h = self.size().height() * self.img_scale\n scaled_size = QtCore.QSize(w, h)\n\n scaled_pixmap = self.pixmap.scaled(\n scaled_size,\n QtCore.Qt.KeepAspectRatio,\n QtCore.Qt.SmoothTransformation,\n )\n\n self.setPixmap(scaled_pixmap)\n\n\nclass CollapsibleSection(QFrame):\n def __init__(self, header_text, init_collapsed=False):\n super().__init__()\n\n self.setFrameShape(QFrame.StyledPanel)\n\n self._layout = QVBoxLayout(self)\n self._layout.setContentsMargins(0, 0, 0, 0)\n self._layout.setSpacing(0)\n self.setLayout(self._layout)\n self._header_widget = QWidget()\n self.body_widget = QWidget()\n self._layout.addWidget(self._header_widget)\n self._layout.addWidget(self.body_widget)\n\n self.grid = QGridLayout(self.body_widget)\n self.grid.setContentsMargins(9, 0, 9, 9)\n\n self._header_widget_layout = QHBoxLayout(self._header_widget)\n self._header_widget_layout.setContentsMargins(7, 7, 7, 7)\n self._header_widget.setLayout(self._header_widget_layout)\n\n self._button = QToolButton()\n self._button.setText(header_text)\n self._button.setCheckable(True)\n self._button.setStyleSheet(\"QToolButton { border: none; }\")\n self._button.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)\n self._button.pressed.connect(self.button_event)\n self.button_event(override=init_collapsed)\n self._header_widget_layout.addWidget(self._button)\n self._header_widget_layout.addStretch()\n\n def button_event(self, override=None):\n if override is None:\n checked = not self._button.isChecked()\n else:\n checked = override\n self._button.setChecked(checked)\n\n if checked: # collapsed\n self._button.setArrowType(QtCore.Qt.ArrowType.RightArrow)\n self.body_widget.hide()\n else:\n self._button.setArrowType(QtCore.Qt.ArrowType.DownArrow)\n self.body_widget.show()\n","sub_path":"gui/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"396035492","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nfrom sklearn.cluster import AgglomerativeClustering\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport seaborn as sn\nimport scipy.cluster.hierarchy as sch\nfrom scipy.cluster.hierarchy import linkage\n\n\n# In[2]:\n\n\nflight=pd.read_csv('C:/Users/vinay/Desktop/Clustering/eastwestairlines/EastWestAirlines.csv')\n\n\n# In[3]:\n\n\nflight\n\n\n# In[4]:\n\n\n#Normalization function \ndef norm_func(i):\n x = (i-i.min())/(i.max()-i.min())\n return (x)\n\n\n# In[5]:\n\n\ndf_norm= norm_func(flight.iloc[:,1:])\ndf_norm\n\n\n# In[6]:\n\n\ndf_norm.describe()\n\n\n# In[7]:\n\n\n# create dendrogram\ndendrogram = sch.dendrogram(sch.linkage(df_norm, method='complete'))\n\n\n# In[8]:\n\n\n#create clusters\ncluster=AgglomerativeClustering(n_clusters=14,affinity=\"euclidean\",linkage=\"complete\").fit(df_norm)\ncluster\n\n\n# In[9]:\n\n\n# save clusters for chart\nh=pd.Series(cluster.labels_)\nflight['clust']=h\n\n\n# In[10]:\n\n\nflight1=flight.iloc[:,[12,0,1,2,3,4,5,6,7,8,9,10,11]]\nflight1\n\n\n# In[11]:\n\n\nflight2= flight1.iloc[:,2:].groupby(flight1.clust).median()\nflight2\n\n\n# # Kmeans\n\n# In[12]:\n\n\nfrom sklearn.cluster import KMeans\nfrom scipy.spatial.distance import cdist \n\n\n# In[13]:\n\n\nk=list(range(10,20))\nk\nTWSS=[]\nfor i in k:\n kmeans = KMeans(n_clusters = i)\n kmeans.fit(df_norm)\n WSS = [] \n for j in range(i):\n WSS.append(sum(cdist(df_norm.iloc[kmeans.labels_==j,:],kmeans.cluster_centers_[j].reshape(1,df_norm.shape[1]),\"euclidean\")))\n TWSS.append(sum(WSS))\n\n\n# In[14]:\n\n\nTWSS\n\n\n# In[15]:\n\n\nplt.plot(k,TWSS, 'ro-')\nplt.xlabel('number of clusters')\nplt.ylabel('total within sum of squares')\nplt.xticks(k)\n\n\n# ## Selecting 14 clusters from the above scree plot which is the optimum number of clusters\n\n# In[16]:\n\n\nmodel1=KMeans(n_clusters=14)\nmodel1.fit(df_norm)\n\n\n# In[17]:\n\n\n# getting the labels of clusters assigned to each row \nmodel1.cluster_centers_\nmodel1.labels_\nmodel=pd.Series(model1.labels_)# converting numpy array into pandas series object \nmodel\n\n\n# In[18]:\n\n\n# creating a new column and assigning it to new column \nflight['clust']=model\nflight\n\n\n# In[19]:\n\n\nflightfinal=flight.iloc[:,[12,0,1,2,3,4,5,6,7,8,9,10,11]]\n\n\n# In[20]:\n\n\nAirlines=flight.iloc[:,1:13].groupby(flightfinal.clust).mean();Airlines\n\n\n# # DBSCAN\n\n# In[23]:\n\n\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.preprocessing import StandardScaler\n\n\n# In[24]:\n\n\narray=flight.values;array\n\n\n# In[25]:\n\n\nstscaler = StandardScaler().fit(array)\nX = stscaler.transform(array)\n\n\n# In[26]:\n\n\ndbscan = DBSCAN(eps=0.8, min_samples=6)\ndbscan.fit(X)\n\n\n# In[27]:\n\n\ndbscan.labels_\n\n\n# In[29]:\n\n\nDBfinal=pd.DataFrame(dbscan.labels_,columns=['cluster'])\nDBfinal\n\n\n# In[30]:\n\n\npd.concat([flight,DBfinal],axis=1)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"EastWestAirline_clustering_assignment.py","file_name":"EastWestAirline_clustering_assignment.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"33183281","text":"import os\nimport sys\nimport os.path\n\nimport random\nimport numpy as np\n\nimport torch\nimport torch.utils.data as data\n\nimport cv2\n\n\nclass YOLODataset(data.Dataset):\n image_size = 224\n\n def __init__(self, root, list_file, train, transform):\n print(\"数据初始化\")\n self.root = root\n self.train = train\n self.transform = transform # 对图像转化\n self.fnames = []\n self.boxes = []\n self.labels = []\n self.mean = (123, 117, 104)\n\n with open(list_file) as f:\n lines = f.readlines()\n\n # 遍历voc2012train.txt的每一行\n # name num_faces x y x y c ......\n # 转换后,每个index对应一组 box label\n for line in lines:\n splited = line.strip().split()\n self.fnames.append(splited[0])\n num_faces = int(splited[1]) # 一张图像中真实框的总数\n box = []\n label = []\n for i in range(num_faces):\n x = float(splited[2 + 5 * i])\n y = float(splited[3 + 5 * i])\n x2 = float(splited[4 + 5 * i])\n y2 = float(splited[5 + 5 * i])\n c = splited[6 + 5 * i]\n box.append([x, y, x2, y2])\n label.append(int(c) + 1)\n self.boxes.append(torch.Tensor(box))\n self.labels.append(torch.LongTensor(label))\n self.num_samples = len(self.boxes) # 数据集中图像的总数\n\n def __getitem__(self, idx):\n fname = self.fnames[idx]\n\n img = cv2.imread(os.path.join(self.root + fname))\n # clone 深复制,不共享内存\n # 拿出对应的bbox及 标签对应的序号\n boxes = self.boxes[idx].clone()\n labels = self.labels[idx].clone()\n\n # Todo\n # 如果为训练集,进行数据增强\n # if self.train:\n # img, boxes = self.random_flip(img, boxes)\n\n h, w, _ = img.shape\n boxes /= torch.Tensor([w, h, w, h]).expand_as(boxes) # x, y, w, h, 除以图片的长宽\n img = self.BGR2RGB(img)\n img = self.subMean(img, self.mean)\n img = cv2.resize(img, (self.image_size, self.image_size))\n target = self.encoder(boxes, labels) # 7x7x30\n for t in self.transform: # 图像转化\n img = t(img)\n return img, target\n\n def __len__(self):\n return self.num_samples\n\n def encoder(self, boxes, labels):\n \"\"\"\n 将每张图片对应的box信息编码为 (7,7,30)的target Tensor\n :param boxes: (tensor) [[x1,y1,x2,y2],[x1,y1,x2,y2],[]],注意,数值已经被规格化了,数值在0-1之间。\n :param labels: (tensor) [...]\n :return: 7x7x30,x,y转化为box中心到cell左上顶点的相对位置。w,h的取值相对于整幅图像的尺寸\n \"\"\"\n target = torch.zeros((7, 7, 30))\n cell_size = 1. / 7\n wh = boxes[:, 2:] - boxes[:, :2]\n cxcy = (boxes[:, 2:] + boxes[:, :2]) / 2\n for i in range(cxcy.size()[0]): # cxcy.size()[0]是框的数量\n cxcy_sample = cxcy[i] # 取其中一个box\n # cxcy_sample为一个物体的中心点坐标,求该坐标位于7x7网格的哪个网格\n # cxcy_sample坐标在0-1之间 现在求它再0-7之间的值,故乘以7\n # ij长度为2,代表7x7个cell中的某个cell,负责预测一个物体\n ij = (cxcy_sample / cell_size).ceil() - 1 # ceil 向上取整\n # 每行的第4和第9的值设置为1,即每个网格提供的两个真实候选框 框住物体的概率是1.\n # xml中坐标理解:原图像左上角为原点,右边为x轴,下边为y轴。\n # 而二维矩阵(x,y) x代表第几行,y代表第几列\n # 假设ij为(1,2) 代表x轴方向长度为1,y轴方向长度为2\n # 二维矩阵取(2,1) 从0开始,代表第2行,第1列的值\n target[int(ij[1]), int(ij[0]), 4] = 1\n target[int(ij[1]), int(ij[0]), 9] = 1\n target[int(ij[1]), int(ij[0]), int(labels[i]) + 9] = 1\n # cxcy_sample:第i个bbox的中心点坐标\n # cell_lt_xy:对应cell的左上角相对坐标(相对于图片长宽(224*224)的比例,0-1之间)\n # delta_xy:真实框的中心点坐标相对于该中心点所在cell左上角的相对坐标。\n # cxcy_sample - cell_lt_xy肯定小于1/7,否则box与cell不对应,故*7,扩展到0-1,猜测是为了便于收敛。\n cell_lt_xy = ij * cell_size\n delta_xy = (cxcy_sample - cell_lt_xy) / cell_size\n\n # x,y代表了检测框中心相对于cell边框的坐标。w,h的取值相对于整幅图像的尺寸\n target[int(ij[1]), int(ij[0]), 2:4] = wh[i]\n target[int(ij[1]), int(ij[0]), :2] = delta_xy\n target[int(ij[1]), int(ij[0]), 7:9] = wh[i]\n target[int(ij[1]), int(ij[0]), 5:7] = delta_xy\n return target\n\n def BGR2RGB(self, img):\n return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n def subMean(self, bgr, mean):\n mean = np.array(mean, dtype=np.float32)\n bgr = bgr - mean\n return bgr\n\n def random_flip(self, im, boxes):\n '''\n 随机翻转\n '''\n if random.random() < 0.5:\n im_lr = np.fliplr(im).copy()\n h, w, _ = im.shape\n xmin = w - boxes[:, 2]\n xmax = w - boxes[:, 0]\n boxes[:, 0] = xmin\n boxes[:, 2] = xmax\n return im_lr, boxes\n return im, boxes\n","sub_path":"data/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":5604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"250778374","text":"import average as avg\nimport unittest\n\n\nclass Test_list_mag(unittest.TestCase):\n\n def test_running_list_mag_item(self): # 2\n \"\"\"Test a one-item list.\"\"\"\n argument = [5]\n expected = 5\n argument = avg.average(argument)\n self.assertEqual(expected, argument, \"The list contains one item.\")\n\n def test_running_list_mag_items(self): # 3\n \"\"\"Test a two-item list.\"\"\"\n argument = [5, 2]\n expected = 3.5\n argument = avg.average(argument)\n self.assertEqual(expected, argument, \"The list contains two items.\")\n\n def test_running_list_mag_negative(self): # 4\n \"\"\"Test a list of negative values.\"\"\"\n argument = [-1, -5, -3, -4]\n expected = -3.25\n argument = avg.average(argument)\n self.assertEqual(expected, argument, \"The list contains only negative values.\")\n\n def test_running_list_mag_zeros(self): # 5\n \"\"\"Test a list of zeros.\"\"\"\n argument = [0, 0, 0, 0]\n expected = 0\n argument = avg.average(argument)\n self.assertEqual(expected, argument, \"The list contains only zeros.\")\n\n def test_running_list_mag_positive(self): # 6\n \"\"\"Test a list of positive values.\"\"\"\n argument = [None, 2, 3, 6]\n expected = 3.6666666666666665\n argument = avg.average(argument)\n self.assertEqual(expected, argument, \"The list contains positive values and None.\")\n\n def test_running_list_mag_mix(self): # 7\n \"\"\"Test a list containing mixture of negative values, zeros and positive values.\"\"\"\n argument = [-5, -2, 0, 1, 3, 4]\n expected = 0.16666666666666666\n argument = avg.average(argument)\n self.assertEqual(expected, argument, \"The list contains a mixture of negative values, zeros and positive values\"\n \".\")\n\n def test_running_list_mag_mix(self): # 7\n \"\"\"Test a list containing mixture of negative values, zeros and positive values.\"\"\"\n argument = [-5, None, -2, 0, 1, 3, 4, None]\n expected = 0.16666666666666666\n argument = avg.average(argument)\n self.assertEqual(expected, argument, \"The list contains a mixture of negative values, zeros, None, and positive\"\n \" values.\")\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"Intro_To_Python/HW15/test_average.py","file_name":"test_average.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"293845817","text":"\"\"\"added a gender column to the table user\n\nRevision ID: b01385e02ac5\nRevises: \nCreate Date: 2019-12-12 23:17:53.450250\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'b01385e02ac5'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('user', sa.Column('gender', sa.String(length=10), nullable=False))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('user', 'gender')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/b01385e02ac5_added_a_gender_column_to_the_table_user.py","file_name":"b01385e02ac5_added_a_gender_column_to_the_table_user.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"455350207","text":"import json\nfrom time import sleep\nfrom typing import Callable\n\nfrom httpx import Client, HTTPError\nfrom pytest import fixture, raises\nfrom starlette.datastructures import QueryParams\nfrom starlette.requests import Request\nfrom starlette.responses import JSONResponse, PlainTextResponse, Response\nfrom starlette.status import (\n HTTP_200_OK, HTTP_403_FORBIDDEN, HTTP_404_NOT_FOUND, HTTP_500_INTERNAL_SERVER_ERROR, WS_1000_NORMAL_CLOSURE,\n WS_1008_POLICY_VIOLATION\n)\nfrom starlette.websockets import WebSocket\nfrom websocket import WebSocket as WSClient, WebSocketBadStatusException, create_connection as create_ws_connection\n\nfrom yellowbox.extras.webserver import MockHTTPEndpoint, MockWSEndpoint, WebServer, http_endpoint, ws_endpoint\nfrom yellowbox.extras.webserver.class_endpoint import class_http_endpoint, class_ws_endpoint\nfrom yellowbox.extras.webserver.util import iter_side_effects\nfrom yellowbox.extras.webserver.webserver import HandlerError\nfrom yellowbox.extras.webserver.ws_request_capture import RecordedWSMessage, Sender\n\n\ndef assert_ws_closed(ws_client: WSClient, code: int = 1000):\n resp_opcode, msg = ws_client.recv_data()\n assert resp_opcode == 8\n assert msg == code.to_bytes(2, 'big')\n\n\n@fixture\ndef server():\n with WebServer('test').start() as server:\n yield server\n\n\n@fixture\ndef client(server):\n return Client(base_url=server.local_url())\n\n\n@fixture\ndef ws_client_factory(server) -> Callable[[str], WSClient]:\n def ret(url: str):\n return create_ws_connection(server.local_url('ws') + url)\n\n return ret\n\n\ndef test_make_server(server):\n pass\n\n\ndef test_capture(server, client):\n endpoint = server.add_http_endpoint('GET', '/api/foo', side_effect=PlainTextResponse('hewwo'))\n with endpoint.capture_calls() as calls0:\n assert calls0 == []\n\n with endpoint.capture_calls() as calls1:\n assert calls1 == []\n resp = client.get('/api/foo?a=15&a=17')\n assert resp.status_code == 200\n assert resp.text == 'hewwo'\n\n c1, = calls1\n assert c1.method == 'GET'\n assert c1.path == \"/api/foo\"\n assert c1.path_params == {}\n assert c1.query_params == {'a': ['15', '17']}\n\n resp = client.get('/api/foo')\n assert resp.status_code == 200\n assert resp.text == 'hewwo'\n c0_0, c0_1 = calls0\n assert c0_0 == c1\n\n\ndef test_mock_callable(server, client):\n @server.add_http_endpoint\n @http_endpoint('POST', '/{a:int}/foo')\n async def get_foo(request: Request):\n a = request.path_params['a']\n b = await request.json()\n return JSONResponse(a * b)\n\n resp = client.post('/12/foo', json=15)\n resp.raise_for_status()\n assert resp.json() == 15 * 12\n\n with get_foo.patch(JSONResponse([\"a\", \"b\"])):\n resp = client.post('/12/foo', json=15)\n resp.raise_for_status()\n assert resp.json() == [\"a\", \"b\"]\n\n resp = client.post('/12/foo', json=10)\n resp.raise_for_status()\n assert resp.json() == 10 * 12\n\n\ndef test_remove_path():\n with WebServer('test').start() as server:\n client = Client(base_url=server.local_url())\n\n @http_endpoint('POST', '/{a:int}/foo')\n async def get_foo(request):\n a = request.path_params['a']\n b = await request.json()\n return JSONResponse(a * b)\n\n assert client.post('/12/foo', json=15).status_code == HTTP_404_NOT_FOUND\n assert client.post('/12/bar', json=15).status_code == HTTP_404_NOT_FOUND\n\n with server.patch_http_endpoint(get_foo):\n resp = client.post('/12/foo', json=15)\n resp.raise_for_status()\n assert resp.json() == 15 * 12\n\n assert client.post('/12/foo', json=15).status_code == HTTP_404_NOT_FOUND\n assert client.post('/12/bar', json=15).status_code == HTTP_404_NOT_FOUND\n with raises(HTTPError):\n client.post('/12/foo', json=15)\n\n\ndef test_multi_paths(server, client):\n with server.patch_http_endpoint('GET', '/foo', PlainTextResponse('hi')):\n resp = client.get('/foo')\n resp.raise_for_status()\n assert resp.text == 'hi'\n with server.patch_http_endpoint('GET', '/bar', PlainTextResponse('ho')):\n resp = client.get('/foo')\n resp.raise_for_status()\n assert resp.text == 'hi'\n resp = client.get('/bar')\n resp.raise_for_status()\n assert resp.text == 'ho'\n resp = client.get('/foo')\n resp.raise_for_status()\n assert resp.text == 'hi'\n assert client.get('/bar').status_code == HTTP_404_NOT_FOUND\n\n\ndef test_readd_endpoint(server, client):\n ep = http_endpoint('GET', '/foo', PlainTextResponse('hi'))\n assert client.get('/foo').status_code == HTTP_404_NOT_FOUND\n with server.patch_http_endpoint(ep):\n resp = client.get('/foo')\n resp.raise_for_status()\n assert resp.text == 'hi'\n assert client.get('/foo').status_code == HTTP_404_NOT_FOUND\n with server.patch_http_endpoint(ep):\n resp = client.get('/foo')\n resp.raise_for_status()\n assert resp.text == 'hi'\n assert client.get('/foo').status_code == HTTP_404_NOT_FOUND\n\n\n@fixture\ndef squib(server):\n @server.add_http_endpoint\n @http_endpoint('GET', '/bar')\n async def bar(request):\n raise ValueError('ree')\n\n yield bar\n\n # in case the squib was called, clear the pending error\n server._pending_exception = None\n\n\ndef test_handler_error(server, client, squib):\n assert client.get('/bar').status_code == HTTP_500_INTERNAL_SERVER_ERROR\n with raises(HandlerError) as exc_info:\n server.is_alive()\n cause = exc_info.value.__cause__\n assert isinstance(cause, ValueError)\n assert cause.args == ('ree',)\n\n\ndef test_handler_error_stuck(server, client, squib):\n server.add_http_endpoint('GET', '/foo', PlainTextResponse('voodoo'))\n assert client.get('/foo').status_code == HTTP_200_OK\n assert client.get('/bar').status_code == HTTP_500_INTERNAL_SERVER_ERROR\n resp = client.get('/foo')\n assert resp.status_code == HTTP_500_INTERNAL_SERVER_ERROR\n assert \"ValueError('ree')\" in resp.text\n with raises(HandlerError):\n server.is_alive()\n\n\ndef test_methods(server, client):\n server.add_http_endpoint(('POST', 'GET'), '/foo', PlainTextResponse('voodoo'))\n resp = client.post('/foo')\n resp.raise_for_status()\n assert resp.text == 'voodoo'\n resp = client.get('/foo')\n resp.raise_for_status()\n assert resp.text == 'voodoo'\n\n assert client.put('/foo').status_code == 405\n assert client.head('/foo').status_code == 405\n\n\ndef test_methods_with_head(server, client):\n server.add_http_endpoint(('POST', 'GET'), '/foo', PlainTextResponse('voodoo'), forbid_implicit_head_verb=False)\n resp = client.post('/foo')\n resp.raise_for_status()\n assert resp.text == 'voodoo'\n resp = client.get('/foo')\n resp.raise_for_status()\n assert resp.text == 'voodoo'\n resp = client.head('/foo')\n resp.raise_for_status()\n assert not resp.content\n\n assert client.put('/foo').status_code == 405\n\n\ndef test_no_auto_read(server, client):\n ep = server.add_http_endpoint('GET', '/foo', PlainTextResponse('voodoo'), auto_read_body=False)\n resp = client.get('/foo')\n resp.raise_for_status()\n assert resp.text == 'voodoo'\n\n with raises(RuntimeError):\n with ep.capture_calls():\n ...\n\n\ndef test_parallel_capture(server):\n ep = server.add_http_endpoint('GET', '/foo', PlainTextResponse('voodoo'))\n con1 = ep.capture_calls()\n con2 = ep.capture_calls()\n\n with raises(RuntimeError):\n with con1:\n con2.__enter__()\n\n\nasync def do_some_math(ws: WebSocket):\n await ws.accept()\n query_args = QueryParams(ws.scope[\"query_string\"])\n if 'mod' in query_args:\n mod = int(query_args['mod'])\n else:\n mod = None\n\n v = ws.scope['path_params']['a']\n while True:\n if mod:\n v %= mod\n await ws.send_json(v)\n operation = await ws.receive_json()\n action = operation.get('op')\n if not action:\n return WS_1008_POLICY_VIOLATION\n if action == 'done':\n return WS_1000_NORMAL_CLOSURE\n operand = operation.get('value')\n if operand is None:\n return WS_1008_POLICY_VIOLATION\n if action == 'add':\n v += operand\n continue\n if action == 'mul':\n v *= operand\n continue\n\n\n@fixture\ndef ws_calc(server):\n ep = server.add_ws_endpoint(ws_endpoint('/{a:int}/calc', do_some_math))\n return ep\n\n\ndef test_ws_path(server, ws_calc, ws_client_factory):\n ws_client = ws_client_factory('/12/calc')\n assert json.loads(ws_client.recv()) == 12\n ws_client.send('{\"op\":\"add\", \"value\": 3}')\n assert json.loads(ws_client.recv()) == 15\n ws_client.send('{\"op\":\"mul\", \"value\": 10}')\n assert json.loads(ws_client.recv()) == 150\n ws_client.send('{\"op\":\"done\"}')\n assert_ws_closed(ws_client)\n\n\n@fixture\ndef ws_squib(server):\n @server.add_ws_endpoint\n @ws_endpoint('/bar')\n async def bar(websocket: WebSocket):\n await websocket.accept()\n await websocket.send_text(\"you remind me of the babe\")\n assert await websocket.receive_text() == \"what babe?\"\n await websocket.send_text(\"the babe with the power\")\n assert await websocket.receive_text() == \"what power?\"\n await websocket.send_text(\"the power of voodoo\")\n assert await websocket.receive_text() == \"who do?\"\n await websocket.send_text(\"you do\")\n assert await websocket.receive_text() == \"do what?\"\n await websocket.send_text(\"remind me of the babe\")\n raise ValueError('dance magic')\n\n yield bar\n\n # in case the squib was called, clear the pending error\n server._pending_exception = None\n\n\ndef test_http_squib_ws_path(server, client, ws_client_factory, squib, ws_calc):\n assert client.get('/bar').status_code == HTTP_500_INTERNAL_SERVER_ERROR\n\n with raises(WebSocketBadStatusException) as exc_info:\n ws_client_factory('/12/calc')\n assert exc_info.value.status_code == HTTP_403_FORBIDDEN\n\n\ndef test_ws_squib_ws_path(server, ws_client_factory, ws_squib, ws_calc):\n ws_client = ws_client_factory('/bar')\n assert ws_client.recv() == 'you remind me of the babe'\n ws_client.send(\"what babe?\")\n assert ws_client.recv() == 'the babe with the power'\n ws_client.send(\"what power?\")\n assert ws_client.recv() == 'the power of voodoo'\n ws_client.send(\"who do?\")\n assert ws_client.recv() == 'you do'\n ws_client.send(\"do what?\")\n assert ws_client.recv() == 'remind me of the babe'\n assert_ws_closed(ws_client, 1011)\n\n with raises(WebSocketBadStatusException) as exc_info:\n ws_client_factory('/12/calc')\n assert exc_info.value.status_code == HTTP_403_FORBIDDEN\n\n\n@fixture\ndef bridge_ep():\n @ws_endpoint('/bridge')\n async def bridge(websocket: WebSocket):\n await websocket.accept()\n await websocket.send_text('what is your name?')\n if not (await websocket.receive_text()).startswith('my name is '):\n await websocket.close(WS_1008_POLICY_VIOLATION)\n else:\n await websocket.close()\n\n return bridge\n\n\n@fixture\ndef square_ep():\n @ws_endpoint('/square')\n async def square(websocket: WebSocket):\n await websocket.accept()\n i = int(await websocket.receive_text())\n await websocket.send_text(str(i * i))\n return WS_1000_NORMAL_CLOSURE\n\n return square\n\n\n@fixture\ndef cube_ep():\n @ws_endpoint('/cube')\n async def cube(websocket: WebSocket):\n await websocket.accept()\n i = int(await websocket.receive_text())\n await websocket.send_text(str(i * i * i))\n return WS_1000_NORMAL_CLOSURE\n\n return cube\n\n\ndef test_ws_no_return(server, ws_client_factory, bridge_ep):\n server.add_ws_endpoint(bridge_ep)\n\n ws_client = ws_client_factory('/bridge')\n assert ws_client.recv() == 'what is your name?'\n ws_client.send('jimmy')\n assert_ws_closed(ws_client, 1008)\n\n ws_client = ws_client_factory('/bridge')\n assert ws_client.recv() == 'what is your name?'\n ws_client.send('my name is jimmy')\n assert_ws_closed(ws_client, 1000)\n\n\ndef test_ws_calc_capture_calls(server, ws_client_factory, ws_calc):\n with ws_calc.capture_calls() as transcripts:\n ws_client = ws_client_factory('/12/calc?tee=goo')\n assert json.loads(ws_client.recv()) == 12\n ws_client.send('{\"op\":\"add\", \"value\": 3}')\n assert json.loads(ws_client.recv()) == 15\n ws_client.send('{\"op\":\"mul\", \"value\": 10}')\n assert json.loads(ws_client.recv()) == 150\n ws_client.send('{\"op\":\"done\"}')\n assert_ws_closed(ws_client, 1000)\n\n transcript, = transcripts\n assert list(transcript) == [\n RecordedWSMessage('12', Sender.Server),\n RecordedWSMessage('{\"op\":\"add\", \"value\": 3}', Sender.Client),\n RecordedWSMessage('15', Sender.Server),\n RecordedWSMessage('{\"op\":\"mul\", \"value\": 10}', Sender.Client),\n RecordedWSMessage('150', Sender.Server),\n RecordedWSMessage('{\"op\":\"done\"}', Sender.Client),\n ]\n assert transcript.accepted\n assert transcript.close == (Sender.Server, 1000)\n\n\ndef test_ws_parallel_capture(server, ws_calc):\n con1 = ws_calc.capture_calls()\n con2 = ws_calc.capture_calls()\n\n with raises(RuntimeError):\n with con1:\n con2.__enter__()\n\n\ndef test_ws_multi_paths(server, ws_client_factory, cube_ep, square_ep):\n with server.patch_ws_endpoint(cube_ep):\n ws_client = ws_client_factory('/cube')\n ws_client.send('3')\n assert ws_client.recv() == '27'\n assert_ws_closed(ws_client)\n with server.patch_ws_endpoint(square_ep):\n ws_client = ws_client_factory('/cube')\n ws_client.send('3')\n assert ws_client.recv() == '27'\n assert_ws_closed(ws_client)\n ws_client = ws_client_factory('/square')\n ws_client.send('12')\n assert ws_client.recv() == '144'\n assert_ws_closed(ws_client)\n ws_client = ws_client_factory('/cube')\n ws_client.send('3')\n assert ws_client.recv() == '27'\n assert_ws_closed(ws_client)\n\n\ndef test_ws_readd_paths(server, ws_client_factory, square_ep):\n with raises(WebSocketBadStatusException):\n ws_client_factory('/square')\n with server.patch_ws_endpoint(square_ep):\n ws_client = ws_client_factory('/square')\n ws_client.send('12')\n assert ws_client.recv() == '144'\n assert_ws_closed(ws_client)\n with raises(WebSocketBadStatusException):\n ws_client_factory('/square')\n with server.patch_ws_endpoint(square_ep):\n ws_client = ws_client_factory('/square')\n ws_client.send('12')\n assert ws_client.recv() == '144'\n assert_ws_closed(ws_client)\n with raises(WebSocketBadStatusException):\n ws_client_factory('/square')\n\n\ndef test_from_container(server, docker_client, create_and_pull):\n ep = server.add_http_endpoint('GET', '/foo', PlainTextResponse('hi'))\n with ep.capture_calls() as calls:\n container = create_and_pull(\n docker_client,\n \"byrnedo/alpine-curl:latest\",\n f'-vvv \"{server.container_url()}/foo\" --fail -X \"GET\"', remove=False\n )\n container.start()\n container.wait()\n container.reload()\n assert container.attrs['State'][\"ExitCode\"] == 0\n calls.assert_requested_once()\n\n\ndef test_ws_capture_client_close(server, ws_client_factory):\n @server.add_ws_endpoint\n @ws_endpoint('/bar')\n async def bar(websocket: WebSocket):\n await websocket.accept()\n await websocket.send_text('do you like warhammer?')\n msg = await websocket.receive()\n assert msg['type'] == 'websocket.disconnect'\n\n with bar.capture_calls() as transcripts:\n ws_client = ws_client_factory('/bar')\n assert ws_client.recv() == 'do you like warhammer?'\n ws_client.close()\n\n sleep(0.1) # give the server time to record the closing\n transcript, = transcripts\n assert list(transcript) == [\n RecordedWSMessage('do you like warhammer?', Sender.Server),\n ]\n assert transcript.accepted\n assert transcript.close == (Sender.Client, 1000)\n\n\ndef test_ws_patch(server, ws_calc, ws_client_factory):\n ws_client = ws_client_factory('/12/calc')\n assert json.loads(ws_client.recv()) == 12\n ws_client.send('{\"op\":\"add\", \"value\": 3}')\n assert json.loads(ws_client.recv()) == 15\n ws_client.send('{\"op\":\"mul\", \"value\": 10}')\n assert json.loads(ws_client.recv()) == 150\n ws_client.send('{\"op\":\"done\"}')\n assert_ws_closed(ws_client)\n\n async def new_side_effect(ws: WebSocket):\n await ws.accept()\n await ws.receive()\n await ws.send_text('no')\n return WS_1000_NORMAL_CLOSURE\n\n with ws_calc.patch(new_side_effect):\n ws_client = ws_client_factory('/12/calc')\n ws_client.send('{\"op\":\"add\", \"value\": 3}')\n assert ws_client.recv() == 'no'\n assert_ws_closed(ws_client)\n\n ws_client = ws_client_factory('/12/calc')\n assert json.loads(ws_client.recv()) == 12\n ws_client.send('{\"op\":\"add\", \"value\": 3}')\n assert json.loads(ws_client.recv()) == 15\n ws_client.send('{\"op\":\"mul\", \"value\": 10}')\n assert json.loads(ws_client.recv()) == 150\n ws_client.send('{\"op\":\"done\"}')\n assert_ws_closed(ws_client)\n\n\ndef test_ws_capture_no_accept(server, ws_client_factory):\n @server.add_ws_endpoint\n @ws_endpoint('/bar')\n async def bar(websocket: WebSocket):\n await websocket.close(WS_1008_POLICY_VIOLATION)\n\n with bar.capture_calls() as transcripts:\n with raises(WebSocketBadStatusException):\n ws_client_factory('/bar')\n\n sleep(0.1) # give the server time to record the closing\n transcript, = transcripts\n assert list(transcript) == []\n assert not transcript.accepted\n assert transcript.close == (Sender.Server, 1008)\n\n\ndef test_ws_capture_empties(server, ws_client_factory):\n @server.add_ws_endpoint\n @ws_endpoint('/bar')\n async def bar(websocket: WebSocket):\n await websocket.accept()\n while True:\n msg = await websocket.receive()\n if msg['type'] == 'websocket.disconnect':\n return\n if 'text' in msg:\n await websocket.send_text(msg['text'])\n else:\n await websocket.send_bytes(msg['bytes'])\n\n with bar.capture_calls() as transcripts:\n ws_client = ws_client_factory('/bar')\n ws_client.send_binary(b'a')\n assert ws_client.recv() == b'a'\n ws_client.send_binary(b'')\n assert ws_client.recv() == b''\n ws_client.send('')\n assert ws_client.recv() == ''\n ws_client.send('a')\n assert ws_client.recv() == 'a'\n ws_client.close()\n\n t, = transcripts\n assert list(t) == [\n RecordedWSMessage(b'a', Sender.Client),\n RecordedWSMessage(b'a', Sender.Server),\n RecordedWSMessage(b'', Sender.Client),\n RecordedWSMessage(b'', Sender.Server),\n RecordedWSMessage('', Sender.Client),\n RecordedWSMessage('', Sender.Server),\n RecordedWSMessage('a', Sender.Client),\n RecordedWSMessage('a', Sender.Server),\n ]\n\n\ndef test_server_as_class():\n class CalculatorService(WebServer):\n square: MockHTTPEndpoint\n calc: MockWSEndpoint\n\n def start(self, retry_spec=None) -> WebServer:\n ret = super().start(retry_spec)\n\n async def square(request: Request):\n return PlainTextResponse(str(request.path_params['a'] ** 2))\n\n self.square = self.add_http_endpoint('GET', '/{a:int}/square', square)\n self.calc = self.add_ws_endpoint('/{a:int}/calc', do_some_math)\n return ret\n\n with CalculatorService('calulator').start() as server:\n with Client(base_url=server.local_url()) as client:\n with server.square.capture_calls() as calls:\n resp = client.get('/12/square')\n resp.raise_for_status()\n assert resp.text == '144'\n calls.assert_requested_once_with(path='/12/square')\n\n ws_client = create_ws_connection(server.local_url('ws') + '/12/calc?mod=20')\n assert json.loads(ws_client.recv()) == 12\n ws_client.send(json.dumps({'op': 'add', 'value': 1}))\n assert json.loads(ws_client.recv()) == 13\n ws_client.send(json.dumps({'op': 'mul', 'value': 15}))\n assert json.loads(ws_client.recv()) == 15\n ws_client.send(json.dumps({'op': 'done'}))\n\n\ndef test_server_class_endpoints():\n class CalculatorService(WebServer):\n @class_http_endpoint('GET', '/{a:int}/square')\n async def square(self, request: Request):\n return PlainTextResponse(str(request.path_params['a'] ** 2))\n\n @class_ws_endpoint('/{a:int}/calc')\n async def calc(self, websocket: WebSocket):\n return await do_some_math(websocket)\n\n with CalculatorService('calulator').start() as server:\n with Client(base_url=server.local_url()) as client:\n with server.square.capture_calls() as calls:\n resp = client.get('/12/square')\n resp.raise_for_status()\n assert resp.text == '144'\n calls.assert_requested_once_with(path='/12/square')\n\n ws_client = create_ws_connection(server.local_url('ws') + '/12/calc?mod=20')\n assert json.loads(ws_client.recv()) == 12\n ws_client.send(json.dumps({'op': 'add', 'value': 1}))\n assert json.loads(ws_client.recv()) == 13\n ws_client.send(json.dumps({'op': 'mul', 'value': 15}))\n assert json.loads(ws_client.recv()) == 15\n ws_client.send(json.dumps({'op': 'done'}))\n\n\ndef test_iter_side_effect(server, client):\n async def side_effect0(request: Request):\n return PlainTextResponse(str(int(request.query_params['x']) * 2))\n\n async def side_effect1(request: Request):\n return PlainTextResponse(str(int(request.query_params['x']) ** 2))\n\n side_effect2 = Response(status_code=526)\n\n async def side_effect3(request: Request):\n return PlainTextResponse(str(-int(request.query_params['x'])))\n\n server.add_http_endpoint('GET', '/foo', iter_side_effects([side_effect0, side_effect1, side_effect2, side_effect3]))\n\n resp = client.get('/foo?x=12')\n resp.raise_for_status()\n assert resp.text == '24'\n resp = client.get('/foo?x=12')\n resp.raise_for_status()\n assert resp.text == '144'\n resp = client.get('/foo?x=12')\n assert resp.status_code == 526\n resp = client.get('/foo?x=12')\n resp.raise_for_status()\n assert resp.text == '-12'\n","sub_path":"tests/extras/test_webserver.py","file_name":"test_webserver.py","file_ext":"py","file_size_in_byte":22790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"575004184","text":"# Sunanth Sakthivel and Caameron Nakasone\r\n# CS 510 Sound Class Project\r\n# Wave file Alterer\r\n\r\nimport numpy\r\nimport scipy.io.wavfile as sci\r\nimport sys\r\nfrom scipy.signal import hilbert\r\n\r\n'import functions from other files'\r\nfrom changeSpeed import increaseSpeed, decreaseSpeed\r\nfrom filters import lowpass, delay, repeat, flanger, invert\r\nfrom changeVolume import increase_volume, decrease_volume\r\nfrom stereoMono import stereo_to_mono\r\nfrom monoStereo import mono_to_stereo\r\nfrom spliceSilence import splice_silence\r\n'''\r\nMain file of program. It will take in a wav file as the argument and read the samples\r\nFrom there the program will augment those samples in different ways based on the users\r\nchoice and ouput back a wavfile\r\n'''\r\n'name output file'\r\noutput = \"output.wav\"\r\n\r\n'Read in wavfile'\r\nsamples = sci.read(sys.argv[1])\r\nsampleData = samples[1]\r\nsampleRate = samples[0]\r\n\r\n\r\n# Our basic UI for the project. It is a simple command line UI that will\r\n# print out all the options that user can make to alter their wav file.\r\n# The user has to give the wav file as an argument when starting the program\r\n# There is then a while loop that will keep asking the user to alter their\r\n# file until they are satisfies. Once done it will ask for a name for their\r\n# new file and place it in the current directory\r\nwhile True:\r\n print(\"1. Increase volume by factor\")\r\n print(\"2. Decrease volume by factor\")\r\n print(\"3. Increase speed by factor\")\r\n print(\"4. Decrease speed by factor\")\r\n print(\"5. Convert audio to mono\")\r\n print(\"6. low pass filter (work in progress)\")\r\n print(\"7. delay\")\r\n print(\"8. echo\")\r\n print(\"9. flangerish\")\r\n print(\"10. invert\")\r\n print('11. Convert audio to stereo')\r\n print('12. splice silence segments')\r\n\r\n '''\r\n add more options here\r\n '''\r\n print(\"0. Quit\")\r\n choice = raw_input(\"Choose how to alter sound file: \")\r\n if choice == '1':\r\n choice = int(input(\"Increase volume by a factor of how much? \"))\r\n sampleData = increase_volume(sampleData,sampleRate,choice)\r\n elif choice == '2':\r\n choice = int(input(\"Decrease volume by a factor of how much? \"))\r\n sampleData = decrease_volume(sampleData,sampleRate,choice)\r\n elif choice == '3':\r\n choice = float(input(\"Increase speed of file by how much? \"))\r\n sampleRate = increaseSpeed(sampleRate,choice)\r\n elif choice == '4':\r\n choice = float(input(\"Decrease speed of file by how much? \"))\r\n sampleRate = decreaseSpeed(sampleRate,choice)\r\n elif choice == '5':\r\n sampleData = stereo_to_mono(sampleData)\r\n elif choice == '6':\r\n sampleData = lowpass(sampleData, sampleRate)\r\n elif choice == '7':\r\n choice = int(input(\"delay but how many miliseconds?\"))\r\n sampleData = delay(sampleData, choice)\r\n elif choice == '8':\r\n sampleData = repeat(sampleData)\r\n elif choice == '9':\r\n sampleData = flanger(sampleData)\r\n elif choice == '10':\r\n sampleData = invert(sampleData)\r\n elif choice == '11':\r\n sampleData = mono_to_stereo(sampleData)\r\n elif choice == '12':\r\n sampleData = splice_silence(sampleData)\r\n elif choice == '0':\r\n break\r\n\r\nfile_name = raw_input(\"What do you want the updated name of file to be? (dont include .wav)\")\r\nsci.write(file_name +\".wav\", sampleRate, sampleData)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"58651773","text":"#!/usr/bin/env python\r\n\r\nimport asyncio\r\nimport json\r\nimport logging\r\nimport websockets\r\n\r\nlogging.basicConfig()\r\n\r\nSTATE = {'msg':'', 'nome': '','para':'Todos'}\r\n\r\nUSERS = {} #criando users como um dicionario\r\n\r\nglobal teste\r\nteste = ''\r\n\r\ndef state_event():\r\n return json.dumps({\"type\": \"msg\", **STATE})\r\n\r\ndef users_event():\r\n return json.dumps({\"type\": \"users\", \"count\": len(USERS)})\r\n\r\nasync def notify_state():\r\n global teste\r\n if USERS and STATE['para'] != 'Todos': #caso em que o comando /privado foi usado\r\n message = state_event()\r\n user1 = None\r\n user2 = None\r\n for i in USERS: #procura destinatario e mandante no dict\r\n if USERS[i] == STATE['nome']:\r\n user1 = i\r\n if USERS[i] == STATE['para']:\r\n user2 = i\r\n try: await asyncio.wait([user1.send(message), user2.send(message)])\r\n except: pass\r\n if USERS and STATE['para'] == teste: #caso em que o mandante é o server, procura-se só o destinatario\r\n message = state_event()\r\n user1 = None\r\n for i in USERS: #procura destinatario no dict\r\n if USERS[i] == teste:\r\n user1 = i\r\n try: await asyncio.wait([user1.send(message)])\r\n except: pass\r\n elif USERS: # asyncio.wait doesn't accept an empty list\r\n message = state_event()\r\n await asyncio.wait([user.send(message) for user in USERS])\r\n\r\nasync def notify_users():\r\n if USERS: # asyncio.wait doesn't accept an empty list\r\n message = users_event()\r\n await asyncio.wait([user.send(message) for user in USERS])\r\n\r\nasync def register(websocket):\r\n USERS[websocket] = None\r\n await notify_users()\r\n\r\nasync def unregister(websocket):\r\n USERS.pop(websocket)\r\n await notify_users()\r\n\r\nasync def counter(websocket, path):\r\n await register(websocket)\r\n try:\r\n\r\n await websocket.send(state_event())\r\n async for message in websocket:\r\n data = json.loads(message)\r\n usuario_novo = False\r\n if data['nome_certo'] == 'False':\r\n nome_novo = True\r\n global teste\r\n \r\n for i in USERS: #for para checar se o nome está disponível\r\n if data['msg'] == USERS[i]: # se nome == nome no dict\r\n nome_novo = False\r\n STATE['msg'] = ' Nome não disponível, por favor escolha outro com o mesmo comando'\r\n STATE['para'] = USERS[websocket]\r\n teste = USERS[websocket]\r\n STATE['nome'] = 'Server'\r\n await notify_state()\r\n if nome_novo: \r\n if USERS[websocket] == None:\r\n usuario_novo = True\r\n STATE['msg'] = ' Seu nome no chat é {}'.format(data['msg'])\r\n teste = data['msg']\r\n STATE['para'] = data['msg']\r\n USERS.update({websocket:data['msg']})\r\n STATE['nome'] = 'Server'\r\n await notify_state()\r\n else:\r\n STATE['msg'] = ' Nome do usuário \"{}\" alterado para: \"{}\"'.format(USERS[websocket], data['msg'])\r\n STATE['para'] = data['msg']\r\n USERS.update({websocket:data['msg']})\r\n STATE['nome'] = 'Server'\r\n await notify_state()\r\n if usuario_novo:\r\n STATE['msg'] = ' Novo usuário na sala: {}'.format(data['msg'])\r\n STATE['para'] = 'Todos'\r\n STATE['nome'] = 'Server'\r\n await notify_state() \r\n elif data['para'] != 'Todos' and USERS[websocket] != None:\r\n STATE['msg'] = data['msg']\r\n STATE['para'] = data['para']\r\n STATE['nome'] = USERS[websocket]\r\n await notify_state()\r\n\r\n elif data['normal'] == 'True' and USERS[websocket] != None :\r\n STATE['msg'] = data['msg']\r\n STATE['nome'] = USERS[websocket]\r\n STATE['para'] = 'todos'\r\n await notify_state() \r\n else:\r\n logging.error(\"unsupported event: {}\")\r\n finally:\r\n await unregister(websocket)\r\nstart_server = websockets.serve(counter, \"localhost\", 6789)\r\n\r\nasyncio.get_event_loop().run_until_complete(start_server)\r\nasyncio.get_event_loop().run_forever()\r\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"593848110","text":"SCREEN_WIDTH = 1500\nSCREEN_HEIGHT = 1000\nSCREEN_TITLE = \"Saddle Brother\"\nCHARACTER_SCALING = 1.0\nIMAGE_SIZE = 64.0\nMAP_TILE_COUNT_X = 40\nMAP_TILE_COUNT_Y = 40\n\n# Screen values\nGAME_WIDTH = IMAGE_SIZE * MAP_TILE_COUNT_X\nGAME_HEIGHT = IMAGE_SIZE * MAP_TILE_COUNT_Y\n\nVIEWPORT_MARGIN_HORT = SCREEN_WIDTH / 2 - IMAGE_SIZE * 2\nVIEWPORT_MARGIN_VERT = SCREEN_HEIGHT / 2 - IMAGE_SIZE * 2\n\n# Ascii values\nEMPTY = ' '\nWALL = '#'\nAGENT = '@'\nGOAL = 'x'\nGRASS = 'g'\nWATER = 'w'\n\n","sub_path":"GlobalInfo.py","file_name":"GlobalInfo.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"617537867","text":"import unittest\n\nfrom openaerostruct.aerodynamics.viscous_drag import ViscousDrag\nfrom openaerostruct.utils.testing import run_test, get_default_surfaces\n\n\nclass Test(unittest.TestCase):\n\n def test(self):\n surface = get_default_surfaces()[0]\n surface['k_lam'] = .05\n comp = ViscousDrag(surface=surface, with_viscous=True)\n\n run_test(self, comp, complex_flag=True)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"openaerostruct/aerodynamics/tests/test_viscous_drag.py","file_name":"test_viscous_drag.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"529303542","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Nov 22 13:27:19 2016\r\n\r\n@author: ZHULI\r\n\"\"\"\r\n\r\n# Stanford CoreNLP ships with a built-in server, which requires only the CoreNLP dependencies. \r\n# To run this server, simply run:\r\n# Run the server using all jars in the current directory (e.g., the CoreNLP home directory)\r\n# java -mx4g -cp \"*\" edu.stanford.nlp.pipeline.StanfordCoreNLPServer [port] [timeout]\r\n# If no value for port is provided, port 9000 will be used by default. You can then test your server by visiting \r\n# http://localhost:9000/\r\n\r\nimport re, random\r\nfrom pycorenlp import StanfordCoreNLP\r\nnlp = StanfordCoreNLP('http://localhost:9000')\r\n\r\ndef GetAnnotation(text):\r\n result = nlp.annotate(text, properties={'annotators': 'tokenize,ssplit,pos,depparse,parse',\r\n 'outputFormat': 'json'})\r\n# result = nlp.annotate(text, properties={'annotators': 'parse',\r\n# 'outputFormat': 'json'})\r\n return result\r\n\r\nfilename = '..\\..\\..\\..\\CBTest Datasets\\CBTest\\data\\cbtest_CN_test_2500ex.txt'\r\nfile = open(filename,'r')\r\nRLineNum = re.compile('^\\d+')\r\nR20 = re.compile('^\\d+ (.*)')\r\nR21 = re.compile('^\\d+ (.+)\\t+([\\S]+)\\t+([\\S]+)$')\r\n\r\nfor line in file:\r\n mLineNum = RLineNum.search(line)\r\n if(mLineNum):\r\n print (mLineNum)\r\n if(int(mLineNum.group(0)) != 21):\r\n #20 sentences\r\n sentence = R20.search(line).group(1)\r\n output=GetAnnotation(line)\r\n print(output['sentences'][0]['parse'])\r\n else:\r\n #21st sentence\r\n m21 = R21.search(line)\r\n Question = m21.group(1)\r\n Candidates = m21.group(3).split('|')\r\n CorrectAnswer = m21.group(2)\r\n #print('Q:',Question)\r\n #print('A:',CorrectAnswer)\r\n #print('C:',Candidate)\r\n else:\r\n #blank line\r\n break\r\nfile.close()","sub_path":"Stanford tool template.py","file_name":"Stanford tool template.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"78160629","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 24 16:50:01 2020\n\n@author: kemcrimmins\n\"\"\"\n\ndef isIn(char, aStr):\n '''\n char: a single character\n aStr: an alphabetized string\n \n returns: True if char is in aStr; False otherwise\n '''\n \n if len(aStr) == 0 or len(aStr) == 1: # char was not found in aStr\n return False\n \n middleChar = aStr[len(aStr)//2]\n \n if char == middleChar:\n return True\n elif char > middleChar:\n return isIn(char, aStr[len(aStr)//2:]) # check second half for char\n else:\n return isIn(char, aStr[:len(aStr)//2]) # otherwise check first half\n \n ","sub_path":"6.00.1x/week2/isIn.py","file_name":"isIn.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"299218857","text":"from django.urls import path\r\n\r\nfrom . import views\r\n\r\n\r\napp_name = 'entries'\r\n\r\nurlpatterns = [\r\n path('/', views.EntryDetailView.as_view(), name='detail'),\r\n path('/edit/', views.EntryUpdateView.as_view(), name='update'),\r\n path('/images/', views.EntryImageFormView.as_view(), name='upload-images'),\r\n path('new/', views.EntryCreateView.as_view(), name='create'),\r\n]\r\n","sub_path":"hendoors/entries/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"493959564","text":"# Wersja przetłumaczona na Pythona z Jawy.\n\n# Ilustracja do odcinka: https://www.youtube.com/watch?v=vsgKWX1lRaw\n# Inspirowane niesamowitym Danem Shiffmanem z kanału The Coding Train\n# Oparte o jego książkę The Nature Of Code (https://natureofcode.com/book/)\n# Wersja z dnia 22. grudnia 2019 r. \n# Autor: Przemysław Adam Śmiejek z kanału U źródeł programowania\n# Zachęcam do wykorzystywania i inspirowania (się i innych)\n\ndef setup():\n size(800, 600);\n colorMode( HSB, 255 );\n\n\ndef branch(len, alpha):\n w = map( len, 120, 1, 10, 1);\n strokeWeight( w );\n b = map( len, 120, 1, 0, 230);\n stroke( 88, 255, b);\n line(0, 0, 0, -len);\n translate(0, -len);\n len = len * 0.6; # len *= 0.6;\n if len > 1:\n #gałąź w prawo\n pushMatrix();\n rotate(alpha);\n branch(len, alpha);\n popMatrix();\n\n #gałąź w lewo\n pushMatrix();\n rotate(-alpha);\n branch(len, alpha);\n popMatrix();\n\ndef draw():\n background( 200 ); \n #pień\n translate(width/2, height);\n stroke( 0 );\n strokeWeight( 10 );\n line(0, 0, 0, -50);\n translate(0, -50);\n alpha = map(mouseX, 0, width, 0, PI/2);\n branch(100, alpha);\n","sub_path":"drzewko_pythonowe/drzewko_pythonowe.pyde","file_name":"drzewko_pythonowe.pyde","file_ext":"pyde","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"186946573","text":"from django.shortcuts import render, redirect\nfrom django.views import generic\nfrom django.http import JsonResponse\nfrom .models import QrCode, DynamicString\nfrom account.models import UserProfile\n\nimport uuid\nimport qrcode\nimport base64\n# Create your views here.\n\nclass HomeView(generic.View):\n\n def get(self, request):\n context = {}\n\n if not request.user.is_authenticated:\n return redirect('home:home')\n\n if request.session.get('msg_register'):\n context['new_user'] = True\n request.session.pop('msg_register')\n\n if request.session.get('msg_error'):\n context['msg_error'] = request.session.get('msg_error')\n request.session.pop('msg_error')\n\n return render(request, 'scanpage/scanpage.html', context)\n\nclass DynamicRedirect(generic.View):\n\n def get(self, request, **kwargs):\n\n get_id = str(kwargs.get('id'))\n if DynamicString.objects.filter(key=get_id).exists():\n DynamicString.objects.filter(key=get_id).delete()\n tracker = request.user.userprofile_set.get().scanned_times\n if tracker == 'First':\n return render(request, 'scanpage/first_timer.html')\n else:\n return render(request, 'scanpage/existing_timer.html')\n else:\n request.session['msg_error'] = 'Scan ID is either invalid or as expired, please scan again'\n return redirect('scanpage:home')\n\nclass VerifyUserScan(generic.View):\n\n def get(self, request, **kwargs):\n context={}\n get_id = str(kwargs.get('id')).replace('__', '/')\n\n if QrCode.objects.filter(secret_key=get_id).exists():\n newstring = DynamicString().adddynamicstring(get_id, str(uuid.uuid4()))\n edittracker = UserProfile().editprofile(request.user.userprofile_set.get().pk)\n context['status'] = True\n context['url'] = '/scanner/redirect/'+newstring.key+'/'\n else:\n context['status'] = False\n context['message'] = 'Only BAT registered QR Codes are allowed'\n\n return JsonResponse(context)\n\nclass GenerateQrView(generic.View):\n\n def generatesecret(self):\n secret = str(uuid.uuid4())\n if QrCode.objects.filter(secret_key=secret).exists():\n return self.generatesecret()\n return secret\n\n def get(self, request):\n get_secret = self.generatesecret()\n\n qr = qrcode.QRCode(\n version=1,\n box_size=15,\n border=3,\n )\n\n qr.add_data(get_secret)\n qr.make(fit=True)\n img = qr.make_image(fill=\"black\", back_color='white')\n img.save('temp_'+get_secret+'.png')\n with open('temp_'+get_secret+'.png', \"rb\") as image_file:\n encoded_string = base64.b64encode(image_file.read())\n\n newqr = QrCode().newQrCode(get_secret, encoded_string.decode(\"utf-8\"))\n\n barcode = newqr.image_obj\n\n context = {\n 'barcode': barcode\n }\n\n return render(request, 'scanpage/generateqrcode.html', context)","sub_path":"scanpage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"81567276","text":"import unicodedata\nfrom typing import AsyncGenerator\nimport pyppeteer\nfrom scrapers.base import Base\nfrom pyquery import PyQuery as pq\nfrom property import Property\n\n\nclass IdnesReality(Base):\n PROPERTY_LIST_SELECTOR = '.c-list-products'\n PROPERTY_SELECTOR = '.c-list-products article.c-list-products__item'\n\n @property\n def host(self):\n return \"https://reality.idnes.cz\"\n\n async def get_items(self) -> AsyncGenerator[Property, None]:\n \"\"\" Yield all houses to caller \"\"\"\n browser = await pyppeteer.launch()\n page = await browser.newPage()\n page.setDefaultNavigationTimeout(60000)\n await page.goto(self.get_url(self.path))\n\n await page.waitForSelector(self.PROPERTY_LIST_SELECTOR)\n html = await page.content()\n\n for link in self.get_links_from_html(html):\n async for item in self.get_houses_from_link(page, link):\n yield self.html_to_property(item)\n\n await browser.close()\n\n async def get_houses_from_link(self, page, link):\n \"\"\" Query houses on the current page and yield them \"\"\"\n await page.goto(self.get_url(link))\n await page.waitForSelector(self.PROPERTY_LIST_SELECTOR)\n html = await page.content()\n\n items = pq(html).find(self.PROPERTY_SELECTOR)\n if len(items):\n for item in items:\n yield item\n\n def get_links_from_html(self, html):\n \"\"\" Get all pagination links and return a list \"\"\"\n pagination = pq(html).find('.paginator a.paging__item')\n\n \"\"\"\n reality.idnes.cz uses for active pagination link\n so we add current path to the links right away because\n we can't get href attr from it (current page)\n \"\"\"\n links = [self.path]\n links.extend([anchor.get('href') for anchor in pagination] if len(pagination) > 0 else [])\n\n return links\n\n def html_to_property(self, item):\n name = pq(item).find('.c-list-products__title').text()\n name = unicodedata.normalize('NFKD', name)\n\n # link\n link = pq(item).find('.c-list-products__link').attr('href')\n link = f'{self.host}{link}'\n\n # locality\n locality = pq(item).find('.c-list-products__info').text()\n\n # price\n price = pq(item).find('.c-list-products__price').text()\n price = unicodedata.normalize('NFKD', price)\n\n images = list(map(\n lambda img: img.get('src'),\n pq(item).find('.c-list-products__img img'))\n )\n\n return Property(name, link, locality, price, images)\n","sub_path":"scrapers/idnes_reality.py","file_name":"idnes_reality.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"65638863","text":"class Hash_Table(object):\n\n def __init__(self, num_buckets):\n \"\"\"Initiation Method of Hash Table.\n\n Length of Table is Based on Passed Value num_buckets.\"\"\"\n self._table = [None] * num_buckets\n\n def _hash(self, key):\n \"\"\"Return the index of the table based off the hashed key.\"\"\"\n indx = 0\n for char in key:\n indx += ord(char)\n return indx % len(self._table)\n\n def set(self, key, val):\n \"\"\"Set the value to key in the table.\"\"\"\n try:\n indx = self._hash(key)\n except TypeError:\n raise TypeError(u\"Must Use Strings For Keys\")\n\n if self._table[indx] is None:\n self._table[indx] = []\n for tup in self._table[indx]:\n if tup[0] == key:\n tup_ind = self._table[indx].index(tup)\n self._table[indx][tup_ind] = (key, val)\n return\n self._table[indx].append((key, val))\n\n def get(self, key):\n \"\"\"Get the value set to key in the table.\"\"\"\n try:\n indx = self._hash(key)\n except TypeError:\n raise TypeError(u\"Must Use Strings For Keys\")\n if self._table[indx]:\n for tup in self._table[indx]:\n if tup[0] == key:\n return tup[1]\n # Key wasn't found raise a key\n raise KeyError(u\"Key Not Found in Hash Table\")\n","sub_path":"src/hash_table.py","file_name":"hash_table.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"322174451","text":"import numpy as np\n\ndef sigmoid(x):\n return 1. / (1 + np.exp(-x))\n\ndef perceptron(X, W):\n h = np.dot(X, W)\n print(\"np.dot(X, W) :\", h)\n\n return sigmoid(h)\n\ndef update_weight(X, W, Y, errors, learning_rate = 0.1):\n W = W + learning_rate * np.dot(errors, X)\n return W\n\nW = np.array([0., 0., 0.])\n\nX = np.array([[1.0, 0.0, 0.0],\n [1.0, 1.0, 0.0],\n [1.0, 0.0, 1.0],\n [1.0, 1.0, 1.0]])\n\nY = np.array([0,0,0,1])\n\nepoch = 0\nsum_error = 1\nthreashold = 0.1\nwhile sum_error > threashold:\n epoch += 1\n print(\"learning epoch :\", epoch)\n print(\"X :\", X)\n output = perceptron(X, W)\n print(\"perceptron(X) :\", np.round(output, 4))\n errors = Y - output\n print(\"errors :\", np.round(errors, 4))\n W = update_weight(X, W, Y, errors)\n sum_error = np.sum(np.absolute(errors)) / len(Y)\n print(\"sum of errors :\", np.round(sum_error, 4))\n print(\"W :\", np.round(W, 4))\n print(\"\")\n\nprint(\"final W for AND function :\", np.round(W, 4))\n\n\"\"\"\nlearning epoch : 362\nX : [[ 1. 0. 0.]\n [ 1. 1. 0.]\n [ 1. 0. 1.]\n [ 1. 1. 1.]]\nnp.dot(X, W) : [-5.68613928 -2.02976748 -2.02976748 1.62660431]\nperceptron(X) : [ 0.0034 0.1161 0.1161 0.8357]\nerrors : [-0.0034 -0.1161 -0.1161 0.1643]\nsum of errors : 0.1\nW : [-5.6933 3.6612 3.6612]\n\nfinal W for AND function : [-5.6933 3.6612 3.6612]\n\"\"\"","sub_path":"examples/ch3/sigmoid2.py","file_name":"sigmoid2.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"473918890","text":"from django.db import models\nfrom django.utils.text import slugify\n\n\n# Create your models here.\nCATEGORY_OPTIONS = (\n ('Technology', 'Technology'),\n ('Health', 'Health'),\n ('International', 'International'),\n ('Politics', 'Politics'),\n ('Society', 'Society'),\n ('Economics', 'Economics'),\n ('Education', 'Education'),\n ('Tourism', 'Tourism'),\n ('Development', 'Development'),\n ('Food', 'Food'),\n ('Fashion', 'Fashion'),\n ('Entertainment', 'Entertainment')\n)\n\n\nclass Author(models.Model):\n first_name = models.CharField(max_length=20, verbose_name = 'First Name')\n last_name = models.CharField(max_length=20, verbose_name = 'Last Name')\n age = models.IntegerField()\n email = models.EmailField(max_length=30, unique=True, verbose_name= 'Email Address')\n phone = models.IntegerField(max_length=10)\n image= models.ImageField(upload_to='authorImages/', blank=True, null =True)\n\n\n def __str__(self):\n return self.first_name + ' ' + self.last_name\n\nclass BlogPost(models.Model):\n title = models.CharField(max_length=500)\n description = models.TextField()\n featured = models.CharField(max_length=5, default = 'False', choices=(('True','True'),('False','False')))\n slug = models.SlugField(max_length=200)\n image = models.ImageField(upload_to='blogImages/', blank=True, null=True)\n posted = models.DateTimeField(auto_now_add=True, verbose_name='Posted On')\n category = models.CharField(max_length= 20, choices=CATEGORY_OPTIONS)\n author = models.ForeignKey(Author, default=1, null=1, on_delete=models.SET_NULL)\n\n class Meta:\n verbose_name_plural = \"Blog Posts\"\n ordering = ['-posted']\n\n def __str__(self):\n return self.title\n\n def __save__(self, *args, **kwargs):\n self.slug = slugify(self.title)\n super(BlogPost, self).save(*args, **kwargs)\n\nclass PostImages(models.Model):\n post = models.ForeignKey(BlogPost, default=None, on_delete=models.CASCADE)\n image = models.ImageField(upload_to='postImages/')\n\n class Meta:\n verbose_name_plural = \"Post Images\"\n\n def __str__(self):\n return self.post.title\n\nclass Search(models.Model):\n user = models.CharField(max_length=20, blank = True, null = True)\n search = models.CharField(max_length = 256)\n timestamp = models.DateTimeField(auto_now_add = True, verbose_name = \"Searched on\")\n\n class Meta:\n verbose_name_plural = \"Searches\"\n ordering = ['-timestamp']\n\n def __str__(self):\n return self.search\n\nclass Contact(models.Model):\n email = models.EmailField(verbose_name='Email Address')\n subject = models.CharField(max_length=200, blank=False, null=False)\n message = models.TextField(blank=False, null=False)\n\n class Meta:\n verbose_name_plural = 'Message from Customers'\n\n def __str__(self):\n return self.subject\n\nclass Advertisement(models.Model):\n name = models.CharField(max_length=200, verbose_name='Advertisement Name')\n company = models.CharField(max_length=50, verbose_name='Advertisement Company')\n type = models.CharField(max_length=10, choices=(('Main', 'Main'), ('Side', 'Side')))\n image = models.ImageField(upload_to=\"advertisementImages\")\n posted = models.DateTimeField(auto_now_add=True, verbose_name='Posted On')\n\n class Meta:\n verbose_name_plural = \"Advertisement Images\"\n ordering = ['-posted']\n\n def __str__(self):\n return self.name + ' from ' + self.company\n\nclass Subscriber(models.Model):\n subscriber = models.EmailField(max_length=30, unique=True, blank=False, null=False, verbose_name=\"Subscriber Email\")\n subscribed = models.DateTimeField(auto_now_add=True, verbose_name='Sunscribed On')\n\n class Meta:\n verbose_name_plural = 'Subscribers List'\n ordering = ['-subscribed']\n\n def __str__(self):\n return self.subscriber\n","sub_path":"home/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"354856090","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import gaussian_kde as GKDE\nfrom scipy.stats import norm, beta \nimport scipy.io as sio\nfrom sklearn.preprocessing import StandardScaler\n'''\nThis module contains all the necessary functions along with some useful\nplotting tools to re-generate the results shown in the two examples in the\npaper.\n'''\n\ndef compute_r(obs_dens,predict_dens,q_vals):\n '''\n This computes the ratio of observed to predicted density values at the predicted data\n '''\n # Compute the ratio\n r = np.divide(obs_dens(q_vals.T),predict_dens(q_vals.T))\n \n # Compute the diagnostic defined by the sample mean of the ratio\n diagnostic = r.mean()\n\n # Report the diagnostic results\n if np.abs(diagnostic - 1) > 0.1:\n print('Predictability assumption may be violated, mean(r) = %4.2f' %(diagnostic))\n else:\n print('mean(r) = %4.2f, everything looking good.' %(diagnostic))\n \n return(r)\n\ndef rejection_sampling(r):\n '''\n Perform accept/reject sampling on a set of proposal samples using\n the weights r associated with the set of samples and return\n the indices idx of the proposal sample set that are accepted.\n This is not used in the analysis of the paper, but is a useful function.\n '''\n N = r.size # size of proposal sample set\n check = np.random.uniform(low=0,high=1,size=N) # create random uniform weights to check r against\n M = np.max(r)\n new_r = r/M # normalize weights \n idx_accept = np.where(new_r>=check)[0] # acceptance criterion\n idx_reject = np.where(new_r1:\n if len(ms_set) != len(ns_set):\n raise ValueError('The ms and ns do not match in length')\n for (m,n) in zip(ms_set,ns_set):\n print('Mixing out of set occurs at eigenmode %i with (%i,%i)' \n %(int(num_modes-i),m,n))\n bad_modes.append(i)\n\n if bad_modes:\n print('-----------------------------')\n print('Removing bad mixing from data')\n print('-----------------------------')\n qs_unmixed = np.delete(qs_unmixed,bad_modes, axis=1)\n ms_unmixed = np.delete(ms_unmixed,bad_modes, axis=1)\n ns_unmixed = np.delete(ns_unmixed,bad_modes, axis=1)\n\n else:\n # initialize un-mixed arrays\n num_modes = qs_mixed[0,:].size\n qs_unmixed = np.zeros((num_samples, num_modes))\n ms_unmixed = np.zeros((num_samples, num_modes))\n ns_unmixed = np.zeros((num_samples, num_modes))\n unmixed_idx = np.zeros((num_samples, num_modes))\n \n # Find and remove where mixing occurred within the set\n for i in range(num_modes):\n m_to_find = ms_mixed[0,i]\n n_to_find = ns_mixed[0,i]\n for j in range(num_modes):\n idx_temp = np.where( (ms_mixed[:,j] == m_to_find) \n & (ns_mixed[:,j] == n_to_find) )\n unmixed_idx[idx_temp,i] = idx_temp\n qs_unmixed[idx_temp,i] = qs_mixed[idx_temp,j]\n ms_unmixed[idx_temp,i] = ms_mixed[idx_temp,j]\n ns_unmixed[idx_temp,i] = ns_mixed[idx_temp,j]\n\n # Remove any mixing that occurs outside of the set\n bad_modes = []\n for i in range(num_modes):\n ms_set = set(ms_unmixed[:,i])\n ns_set = set(ns_unmixed[:,i])\n if len(ns_set)>1:\n if len(ms_set) != len(ns_set):\n raise ValueError('The ms and ns do not match in length')\n for (m,n) in zip(ms_set,ns_set):\n print('Mixing out of set occurs at eigenmode %i with (%i,%i)' \n %(int(num_modes-i),m,n))\n bad_modes.append(i)\n\n if bad_modes:\n print('-----------------------------')\n print('Removing bad mixing from data')\n print('-----------------------------')\n qs_unmixed = np.delete(qs_unmixed,bad_modes, axis=1)\n ms_unmixed = np.delete(ms_unmixed,bad_modes, axis=1)\n ns_unmixed = np.delete(ns_unmixed,bad_modes, axis=1)\n \n return(ms_unmixed,ns_unmixed,qs_unmixed) \n\n\n\ndef print_modes(ms,ns):\n '''\n This is useful for checking that the unmixed data from both sets (initial and observed) are\n in the same order (i.e., that the eigen-modes appear in the same order).\n \n This is primarily useful for debugging but was not used in the scripts after debugging occurred. \n '''\n num_modes = ms[0,:].size\n for i in range(num_modes):\n ms_set = set(ms[:,i])\n ns_set = set(ns[:,i])\n print('Eigenmode %i is given by (m,n) pair(s) (plural if there is mixing): ' \n %(num_modes-i) ,(ms_set,ns_set))\n print('--------------------------------------------------------------------'\n + '---------')\n \n \n \ndef standard_scaling_xform(qs, scaler = None):\n '''\n Transforms given data (qs) using a standard scalar from sklearn, which helps\n remove the impact of outliers on analysis. \n '''\n if scaler is None: # Scaling from the predicted data is not yet learned\n \n scaler = StandardScaler()\n\n X_std = scaler.fit_transform(qs)\n \n return(X_std, scaler)\n \n else: # scaler is previously learned, this is used when applying the scalar to observations\n \n X_std = scaler.transform(qs)\n \n return(X_std)\n\n\n \ndef PCA(X_std):\n '''\n A standard principal component analysis (PCA)\n '''\n cov_mat = np.cov(X_std.T)\n \n eig_vals, eig_vecs = np.linalg.eig(cov_mat)\n \n return(eig_vals, eig_vecs)\n\ndef plot_gap(n, eig_vals, filename=None):\n '''\n This plots the percent variation explained by n of the principal components.\n \n Here, eig_vals refers to eigenvalues from principal component analysis\n '''\n fig = plt.figure(figsize=(10,10))\n fig.clear()\n plt.semilogy(np.arange(np.size(eig_vals)),eig_vals/np.sum(eig_vals)*100, Marker='.', MarkerSize=25, linestyle='')\n plt.semilogy(np.arange(np.size(eig_vals)),eig_vals[n]/np.sum(eig_vals)*100*np.ones(np.size(eig_vals)), 'r--')\n plt.semilogy(np.arange(np.size(eig_vals)),eig_vals[n+1]/np.sum(eig_vals)*100*np.ones(np.size(eig_vals)), 'r--')\n s = 'Order of magnitude of gap is %4.2f.' %(np.log10(eig_vals[n])-np.log10(eig_vals[n+1]))\n s += '\\n%2.3f' %(np.sum(eig_vals[0:n+1])/np.sum(eig_vals)*100) + '% of variation explained.'\n plt.title(s)\n plt.xlabel('Principal Component #')\n plt.ylabel('% of Variation')\n plt.tight_layout()\n if filename == None:\n print('Showing but not saving image')\n plt.show()\n else:\n print('Image saved.')\n plt.savefig(filename + '.png')\n return\n\ndef plot_PC_vecs(n, eig_vals, eig_vecs, filename=None):\n '''\n This plots the n:th principal vector.\n \n Here, eig_vals and eig_vecs refer to the eigenvalues and eigenvectors from a PCA\n '''\n fig = plt.figure(figsize=(10,10))\n fig.clear()\n plt.plot(np.arange(np.size(eig_vals)),eig_vecs[:,n], Marker='.', MarkerSize=25, linestyle='', color='k')\n plt.title('Weighting vector ' + str(n+1))\n plt.xlabel('Eigenmode #')\n plt.ylabel('Weights')\n plt.ylim([-1,1])\n plt.tight_layout() \n if filename == None:\n print('Showing but not saving image')\n plt.show()\n else:\n print('Image saved.')\n plt.savefig(filename + '.png')\n return\n\ndef plot_eigenvalue_pairs(eigs_predict, eigs_obs, eig1, eig2, filename=None):\n '''\n This is used to visualize the correlation between various eigenvalue data.\n \n Here, eigenvalues are associated with the drum problem.\n '''\n fig = plt.figure(figsize=(10,10))\n fig.clear()\n plt.scatter(eigs_predict[:,eig1], eigs_predict[:,eig2],5,marker='.')\n plt.scatter(eigs_obs[:,eig1], eigs_obs[:,eig2],25,marker='s')\n plt.xlabel('Eigenmode #%d' %(20-eig1))\n plt.ylabel('Eigenmode #%d' %(20-eig2))\n plt.tight_layout()\n if filename == None:\n print('Showing but not saving image')\n plt.show()\n else:\n print('Image saved.')\n plt.savefig(filename + '.png')\n return\n\ndef plot_QoI_pairs(q_predict, q_obs, q1, q2, filename=None):\n '''\n This visualizes the correlation between the various PCs used to define the relavant QoI.\n '''\n fig = plt.figure(figsize=(10,10))\n fig.clear()\n plt.scatter(q_predict[:,q1], q_predict[:,q2],marker='.')\n plt.scatter(q_obs[:,q1], q_obs[:,q2],25,marker='s')\n plt.xlabel('QoI #%d' %(q1+1))\n plt.ylabel('QoI #%d' %(q2+1))\n if filename == None:\n print('Showing but not saving image')\n plt.show()\n else:\n print('Image saved.')\n plt.savefig(filename + '.png')\n return \n\ndef QoI_xform(X_std,eig_vecs,eig_vals,Select_QoI=2):\n '''\n Use the PCA to transform the scaled eigen-data associated with the drum problem to define the QoI.\n '''\n if isinstance(Select_QoI, int):\n QoI_num = Select_QoI\n qs_xform = np.dot(X_std,eig_vecs[:,0:QoI_num])/eig_vals[0:QoI_num]\n elif isinstance(Select_QoI, list):\n QoI_list = Select_QoI\n qs_xform = np.dot(X_std,eig_vecs[:,QoI_list])/eig_vals[QoI_list]\n else:\n print('Improper Select_QoI specified, give an int or a list')\n return\n \n return(qs_xform)\n\n\n\ndef kernel_density_estimate(qs, rs=None):\n '''\n Use a weighted Gaussian kernel density estimator from scipy to estimate density\n on an array of data (qs).\n '''\n dens_est = GKDE(qs.T, 'silverman', weights=rs)\n \n return(dens_est)\n\n\ndef beta_density_estimate(data_array):\n '''\n Can construct beta density estimates on a given array of data for the interested reader\n who would like to see how good results can be using this in place of the non-parametric\n KDE from above.\n '''\n dim = data_array[0,:].size\n \n beta_params = np.zeros((dim,4)) #col0=a,col1=b,col2=loc,col3=scale\n \n beta_dens = []\n \n for i in range(dim):\n \n beta_params[i,:] = beta.fit(data_array[:,i])\n \n beta_dens.append(beta(a=beta_params[i,0], b=beta_params[i,1],\n loc=beta_params[i,2],scale=beta_params[i,3]))\n \n return(beta_dens,beta_params)\n\n \ndef mean_beta_distr(r, param_samples, N=25):\n '''\n Perform rejection sampling N times to fit beta distributions on parameters.\n The parameter samples may be any set of a(s) values evaluated at some spatial positions\n \\{s_i\\} (where s_i is the radial distance from center s=0 to edge s=1 of drum). \n \n Inputs:\n r = obs_dens/predict_dens evaluated at predicted points\n param_samples = array of parameter samples of size [sample_num,param_dim]\n N = number of times we re-do computations to determine mean hyperparameters for Beta distr fits. \n \n Outputs:\n (beta_dens,beta_params_means)\n '''\n\n param_dim = param_samples[0,:].size\n beta_params = np.zeros((N,param_dim,4))\n beta_params_means = np.zeros((param_dim,4))\n beta_dens = []\n \n for i in range(N):\n \n (samples_to_keep,_) = rejection_sampling(r)\n\n accepted_samples = param_samples[samples_to_keep,:]\n\n for j in range(param_dim):\n \n beta_params[i,j,:] = beta.fit(accepted_samples[:,j])\n \n beta_params_means = np.mean(beta_params, axis=0)\n \n for i in range(param_dim):\n \n beta_dens.append(beta(a=beta_params_means[i,0], b=beta_params_means[i,1],\n loc=beta_params_means[i,2],scale=beta_params_means[i,3]))\n \n return(beta_dens, beta_params_means)\n ","sub_path":"Supplemental-material/DrumAnalysis.py","file_name":"DrumAnalysis.py","file_ext":"py","file_size_in_byte":14391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"579594548","text":"class Solution:\n def binsearch(self, arr, x):\n left, right = 0, len(arr) - 1\n while left <= right:\n mid = (left + right) // 2\n if arr[mid] == x:\n return mid\n if arr[mid] < x:\n left = mid + 1\n else:\n right = mid - 1\n\n return left\n\n def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:\n if k == len(arr):\n return arr\n\n # let's find the closest arr[i] to X\n closest_i = self.binsearch(arr, x)\n\n # let's use the windows to find k closest elements\n left = closest_i - 1\n right = left + 1\n # While the sliding window's size is less than k\n while right - left - 1 < k:\n # check for out of bounds\n if left == -1:\n right += 1\n continue\n\n # Expand the window towards the side with the closer number\n # Be careful to not go out of bounds with the pointers\n # |a - num| < |b - num|,\n # |a - num| == |b - num|\n if (\n right == len(arr) or\n abs(arr[left] - x) <= abs(arr[right] - x)\n ):\n left -= 1\n else:\n right += 1\n\n # Return the window\n return arr[left + 1:right]","sub_path":"leetcode/find_k_closest_elements.py","file_name":"find_k_closest_elements.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"317783410","text":"import xml.etree.ElementTree\n\ndef loadXml(fname):\n data_list = []\n fo = open(fname)\n tmp = fo.read()\n root = xml.etree.ElementTree.fromstring(tmp)\n\n for test in root:\n data = load_child(test)\n data_list.append(data)\n return data_list\n\ndef load_child(parent):\n data = {}\n for child in parent:\n data[child.tag] = child.text\n if child.getchildren():\n data[child.tag] = load_child(child)\n return data\n\ndef loadErrorsXml(fname):\n fo = open(fname)\n tmp = fo.read()\n root = xml.etree.ElementTree.fromstring(tmp)\n\n errors = {}\n for dbms in root:\n errors[dbms.attrib['value']] = []\n for error in dbms:\n errors[dbms.attrib['value']].append(error.attrib['regexp'])\n\n return errors\n\nif __name__ == '__main__':\n s = loadErrorsXml('../../data/xml/errors.xml')\n print(s)","sub_path":"lib/common/xmlLoader.py","file_name":"xmlLoader.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"394131479","text":"from fnmatch import fnmatch # Unix filename pattern matching\n\n\n#############\n# Example 1 #\n#############\n\nfnmatch('sample.txt', '*.txt') # True\nfnmatch('sample1.txt', 'sample?.txt') # True\nfnmatch('sample_report2.csv', 'sample_report[0-5]*') # True\n\nfiles = ['roi_forcast_region1.csv', 'roi_forcast_region2.csv', 'roi_forcast.py']\nprint([f_name for f_name in files if fnmatch(f_name, 'roi_forcast*.csv')])\n# ['roi_forcast_region1.csv', 'roi_forcast_region2.csv']\n\n#############\n# Example 2 #\n#############\n\naddresses = [\n '228 W 10th St, New York',\n '222 Waverly Pl, New York',\n '228 Bleecker St, New York',\n '23 Commerce St, New York',\n '42 Grove St, New York',\n]\n\nprint([addr for addr in addresses if fnmatch(addr, '22[0-9] *St*')])\n# ['228 W 10th St, New York', '228 Bleecker St, New York']","sub_path":"data_structures/match_string_shell_wildcard.py","file_name":"match_string_shell_wildcard.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"592711953","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"All websocket routes and functions\"\"\"\nimport functools\nfrom bson import json_util\nimport json as jsn\nfrom cherrydoor.server import socket, emit, dt, db, current_user, disconnect\n\n__author__ = \"opliko\"\n__license__ = \"MIT\"\n__version__ = \"0.6.b0\"\n__status__ = \"Prototype\"\n\n\ndef authenticated_only(f):\n @functools.wraps(f)\n def wrapped(*args, **kwargs):\n if not current_user.is_authenticated:\n disconnect()\n else:\n return f(*args, **kwargs)\n\n return wrapped\n\n\n@socket.on(\"stats\", namespace=\"/api\")\n@authenticated_only\ndef stats(json={}):\n try:\n time_from = dt.datetime.fromisoformat(json[\"time_from\"].replace(\"Z\", \"\"))\n except KeyError:\n time_from = dt.datetime.today() - dt.timedelta(days=7)\n try:\n time_to = dt.datetime.fromisoformat(json[\"time_to\"].replace(\"Z\", \"\"))\n except KeyError:\n time_to = dt.datetime.now()\n\n results = db.logs.find(\n {\"timestamp\": {\"$lt\": time_to, \"$gte\": time_from}}, {\"card\": 0, \"_id\": 0}\n )\n json_results = [jsn.dumps(doc, default=json_util.default) for doc in results]\n emit(\"stats\", json_results, namespace=\"/api\")\n return json_results\n\n\n@socket.on(\"user\", namespace=\"/api\")\n@authenticated_only\ndef user(json={}):\n try:\n username = json[\"username\"]\n user = db.users.find_one({\"username\": username}, {\"password\": 0, \"_id\": 0})\n if not user:\n raise KeyError\n except KeyError:\n try:\n card = json[\"card\"]\n user = db.users.find_one({\"cards\": card}, {\"password\": 0, \"_id\": 0})\n if not user:\n raise KeyError\n except KeyError:\n return False\n try:\n if json[\"edit\"]:\n db.users.update_one(user, json[\"changes\"])\n except KeyError:\n pass\n emit(\"user\", user)\n return user\n\n\n@socket.on(\"users\", namespace=\"/api\")\n@authenticated_only\ndef users():\n try:\n users = db.users.find({}, {\"password\": 0, \"_id\": 0})\n json_results = [jsn.dumps(doc, default=json_util.default) for doc in users]\n except:\n return False\n emit(\"users\", json_results)\n return json_results\n\n\n@socket.on(\"break_times\", namespace=\"/api\")\n@authenticated_only\ndef break_times(json=[]):\n if isinstance(json, list) and len(json) != 0 and isinstance(json[0], list):\n if not any(json[0]):\n db.settings.update(\n {\"setting\": \"break_times\"},\n {\"setting\": \"break_times\", \"value\": []},\n upsert=True,\n )\n return_breaks = []\n else:\n try:\n breaks = [\n [\n dt.datetime.fromisoformat(item[0].replace(\"Z\", \"\")).replace(\n year=2020, month=2, day=2\n ),\n dt.datetime.fromisoformat(item[1].replace(\"Z\", \"\")).replace(\n year=2020, month=2, day=2\n ),\n ]\n for item in json\n ]\n except IndexError:\n return None\n db_breaks = [{\"from\": item[0], \"to\": item[1]} for item in breaks]\n db.settings.update(\n {\"setting\": \"break_times\"}, {\"$set\": {\"value\": db_breaks}}, upsert=True\n )\n breaks = [\n [item[0].isoformat() + \"Z\", item[1].isoformat() + \"Z\"]\n for item in breaks\n ]\n return_breaks = jsn.dumps(breaks, indent=4, sort_keys=True, default=str)\n emit(\"break_times\", return_breaks)\n return return_breaks\n try:\n breaks = list(db.settings.find_one({\"setting\": \"break_times\"})[\"value\"])\n breaks = [\n [item[\"from\"].isoformat() + \"Z\", item[\"to\"].isoformat() + \"Z\"]\n for item in breaks\n ]\n return_breaks = jsn.dumps(breaks, indent=4, sort_keys=True, default=str)\n except KeyError:\n return None\n emit(\"break_times\", return_breaks)\n return return_breaks\n","sub_path":"cherrydoor/server/websockets.py","file_name":"websockets.py","file_ext":"py","file_size_in_byte":4086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"307853234","text":"\nfrom node import Node\n\nclass List:\n def __init__(self):\n self.head = None\n self.end = None\n self.length = 0\n \n def __len__(self):\n return self.length\n \n def add(self, item, prt= False):\n self.length += 1\n \n temp = Node(item)\n temp.set_next(self.head)\n self.head = temp\n \n if prt == True:\n print(\"Added: \", item)\n \n def print_list(self):\n print(\"List contains:\", end=\" \")\n current = self.head\n while current != None:\n print(current.get_value(), end=\"->\")\n current = current.get_next()\n print(\"Null\") \n \n def find(self, item):\n current = self.head\n found = False\n while current != None and found == False:\n if(current.get_value() == item):\n print(\"Found: \", item)\n found = True\n else:\n current = current.get_next()\n if found == False:\n print(\"Cannot find: \", item)","sub_path":"List/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"449454180","text":"portal = context.getPortalObject()\n\nticket_title = \"Hosting Subscription %s is failing.\" % context.getTitle()\n\ndescription = \"%s contains software instances which are unallocated or reporting errors.\" % (\n context.getTitle())\n \nsupport_request = context.Base_generateSupportRequestForSlapOS(\n ticket_title,\n description,\n context.getRelativeUrl())\n\nif support_request is None:\n return\n \nperson = context.getDestinationSectionValue(portal_type=\"Person\")\nif not person:\n return\n \nif support_request.getSimulationState() != \"validated\":\n support_request.validate()\n\n# Send Notification message\nmessage = description\n\nnotification_reference = notification_message_reference\nnotification_message = portal.portal_notifications.getDocumentValue(\n reference=notification_reference)\nif notification_message is not None:\n mapping_dict = {'hosting_subscription_title':context.getTitle(),\n 'instance': instance.getTitle()}\n\n message = notification_message.asText(\n substitution_method_parameter_dict={'mapping_dict':mapping_dict})\n \nreturn support_request.SupportRequest_trySendNotificationMessage(\n ticket_title, message, person.getRelativeUrl())\n","sub_path":"master/bt5/slapos_crm/SkinTemplateItem/portal_skins/slapos_crm_monitoring/HostingSubscription_createSupportRequestEvent.py","file_name":"HostingSubscription_createSupportRequestEvent.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"531428577","text":"'''\nLeia a velocidade de um carro. Se ele ultrapassar 80km/h mostre\na mensagem informando que foi multado.\nA multa deve custar R$7,00 por cada Km acima do limite.\n'''\n#importando parte do código\nfrom mensagem import cabecalho\nfrom mensagem import rodape\n\n#função que verifica se há multa e faz o cálculo\ndef f_multa(velocidade):\n if velocidade > 80:\n print('Você foi multado!')\n multa = (velocidade - 80) * 7\n #:.2f limita o número de duas casas decimais\n print(f'Sua multa foi de R${multa:.2f}')\n else:\n print('Tenha um bom dia! Dirija com segurança.')\n\n#programa principal\ncabecalho('VERIFICAÇÃO DE VELOCIDADE')\n#1º laço fazendo o programa rodar até que o usuário decida parar\nwhile True:\n velocidade = float(input('Qual a velocidade do carro? '))\n f_multa(velocidade)\n print()\n resposta = ' '\n #2º laço enquanto a resposta não for S ou N\n while resposta not in 'SN':\n #upper: joga a string para maiúsculo\n #strip: remove os espaços no começo e no fim\n #[0] captura apenas o primeiro caractere\n resposta = input('Deseja continuar? [S/N] ').upper().strip()[0]\n print()\n if resposta == 'N':\n #quebrando o 1º laço\n break\nrodape()\n","sub_path":"ex33_velocidadeMultaCarro.py","file_name":"ex33_velocidadeMultaCarro.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"360322149","text":"import pytest\nimport shutil\nfrom pathlib import Path\nfrom . import msg_gen as mg\nfrom mindsweeper import server\nfrom mindsweeper.utils import auxiliary\n\n\nHOST = '127.0.0.1'\nPORT = 8000\n\n\ndef test_server_error(tmp_path):\n with pytest.raises(TypeError):\n server.run_server(host=1)\n server.run_server(port='string')\n server.run_server(publish=1)\n\n\ndef upload(msg):\n def publish(msg):\n return\n response = server.upload(msg, publish)\n assert response == 'OK'\n if msg['type'] in auxiliary.get_interesting_types():\n assert msg['status'] == 'unparsed'\n else:\n assert msg['status'] == 'ready'\n if msg['type'] in ['colorImage', 'depthImage']:\n path = Path(msg['data']['path'])\n assert path.exists()\n shutil.rmtree(path.parent)\n assert response == 'OK'\n\n\ndef test_upload_user_msg():\n upload(mg.create_user_msg())\n\n\ndef test_upload_color_image_msg():\n upload(mg.create_color_image_msg())\n\n\ndef test_upload_pose_msg():\n upload(mg.create_pose_msg())\n","sub_path":"tests/test_server.py","file_name":"test_server.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"330431588","text":"from ROOT import *\nimport ROOT as root\nimport numpy as np\nimport argparse\nimport os\n\ngStyle.SetOptStat(0)\n\n########################################################################\n######################## MC Part ##################################\n########################################################################\nchangeMu = 1. \nchangeE = 1. \n\n#pionInBeam60A = 0.688 # 68.8% pions\nmuonInBeam60A = 0.046*changeMu # 4.6% muons\nelecInBeam60A = 0.266*changeE # 26.6% electrons\n\npionInBeam60A = 1. - muonInBeam60A - elecInBeam60A\n\n\n# Electron to Pion and Muon to Pion Ratio\nelecScale = elecInBeam60A/pionInBeam60A\nmuonScale = muonInBeam60A/pionInBeam60A\n\ncheckFileName = \"bkgFiles/BkgSub_1.0muons_1.0electrons_60A.root\"\ncheckFile = TFile.Open(checkFileName)\nmove_XS_60A = checkFile.Get(\"move_XS_60A\")\n\n\npionMC_FileName = \"/Volumes/Seagate/Elena/TPC/XSMCPionWithSecondaries60A_histo.root\"\nmuonMC_FileName = \"/Volumes/Seagate/Elena/TPC/MC60A_Muon.root\"\nelecMC_FileName = \"/Volumes/Seagate/Elena/TPC/MC60A_Electron.root\"\n\n\n# Get Monte Carlo files\ninteractingPlotString = \"RecoXS/hRecoInteractingKE\"\nincidentPlotString = \"RecoXS/hRecoIncidentKE\"\npionMC_File = TFile.Open(pionMC_FileName)\nmuonMC_File = TFile.Open(muonMC_FileName)\nelecMC_File = TFile.Open(elecMC_FileName)\n\n\n# Get Interacting and Incident plots\npionMC_Int = pionMC_File.Get(\"RecoXSPionOnly/hRecoInteractingKE\")\nsecoMC_Int = pionMC_File.Get(\"RecoXSSec/hRecoInteractingKE\")\nmuonMC_Int = muonMC_File.Get(interactingPlotString)\nelecMC_Int = elecMC_File.Get(interactingPlotString)\npionMC_Inc = pionMC_File.Get(\"RecoXSPionOnly/hRecoIncidentKE\")\nsecoMC_Inc = pionMC_File.Get(\"RecoXSSec/hRecoIncidentKE\")\nmuonMC_Inc = muonMC_File.Get(incidentPlotString)\nelecMC_Inc = elecMC_File.Get(incidentPlotString)\n\n\n\n\n# Let's assign a color scheme\npionMC_Int.SetFillColor(9)\nsecoMC_Int.SetFillColor(kRed-2)\nmuonMC_Int.SetFillColor(41)\nelecMC_Int.SetFillColor(40) \npionMC_Inc.SetFillColor(9) \nsecoMC_Inc.SetFillColor(kRed-2)\nmuonMC_Inc.SetFillColor(41)\nelecMC_Inc.SetFillColor(40) \n\n\n\n#Scale according to beam composition, both interacting and incident plots\nelecMC_Int.Scale(elecScale)\nelecMC_Inc.Scale(elecScale)\nmuonMC_Int.Scale(muonScale)\nmuonMC_Inc.Scale(muonScale)\n\n\n\n# Staggered plots by hand\ntotHisto_Int = pionMC_Int.Clone(\"totHisto_Int\")\ntotHisto_Inc = pionMC_Inc.Clone(\"totHisto_Inc\")\nfor i in xrange(pionMC_Int.GetSize()):\n totHisto_Int.SetBinContent(i, muonMC_Int.GetBinContent(i)+elecMC_Int.GetBinContent(i)+ pionMC_Int.GetBinContent(i) + secoMC_Int.GetBinContent(i))\n totHisto_Inc.SetBinContent(i, muonMC_Inc.GetBinContent(i)+elecMC_Inc.GetBinContent(i)+ pionMC_Inc.GetBinContent(i) + secoMC_Inc.GetBinContent(i))\n totHisto_Int.SetBinError(i, TMath.Sqrt(muonMC_Int.GetBinContent(i)+elecMC_Int.GetBinContent(i)+ pionMC_Int.GetBinContent(i) + secoMC_Int.GetBinContent(i)))\n totHisto_Inc.SetBinError(i, TMath.Sqrt(muonMC_Inc.GetBinContent(i)+elecMC_Inc.GetBinContent(i)+ pionMC_Inc.GetBinContent(i) + secoMC_Inc.GetBinContent(i)))\n\npionMC_Int.Divide(pionMC_Inc) \npionMC_Int.Multiply(totHisto_Inc) \npionMC_Int.Divide(totHisto_Int) \npionMC_Int.SetFillColor(kWhite)\n\n\n\n## Check Staggered Plots Make Sense\nc0 = TCanvas(\"c0\",\"c0\",600,600)\np1c0 = c0.cd(1)\np1c0.SetGrid()\nmove_XS_60A.Draw(\"pe\")\npionMC_Int.Draw(\"histosame\")\n\n\nraw_input()\n\n","sub_path":"BkgSub_v4/Check60A.py","file_name":"Check60A.py","file_ext":"py","file_size_in_byte":3359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"440486410","text":"import sqlite3\nimport datetime\n\nclass Wrapper:\n \"\"\"\n Send requests for database\n \"\"\"\n def __init__(self, db_name, table, *args):\n \"\"\"\n :param db_name: str\n :param table: str\n :param args: tuple - (date, value)\n \"\"\"\n client = sqlite3.connect(db_name)\n client.execute('''CREATE TABLE IF NOT EXISTS door_sensors(date TEXT, address TEXT, value REAL)''')\n date = datetime.datetime.now()\n client.execute(\"INSERT INTO door_sensors VALUES ({}, {}, {})\".format(date.timestamp(), *args))\n client.commit()\n client.close()","sub_path":"scripts/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"316764839","text":"#!/usr/bin/python3\nimport io\nimport os\nimport sys\nimport json\nimport magic\nimport sqlite3\nimport requests\nfrom math import log2\nfrom magic import Magic\nfrom ncmime import ncmime\nfrom collections import Counter\nfrom fileentropy import FileEntropy\n\ndb = sqlite3.connect('baselines.sqlite')\n# order of index columns carefully chosen so the the two \"group by\" queries can\n# directly do a linear scan of the table, without sorting.\ndb.execute('''create table if not exists counts(\n\t\tkind text, mime text, byte integer, path text, count integer,\n\t\tprimary key(kind, mime, byte, path))''')\n\nZEROS = Counter()\ndef add(counter, key, counts):\n\tcounter[key] = counter.get(key, ZEROS) + counts\n\ndef record(kind, path, stats):\n\tdb.executemany('''insert into counts(kind, path, mime, byte, count)\n\t\t\tvalues(?, ?, ?, ?, ?)''', [(kind, path, mime, byte, count)\n\t\t\tfor mime, counts in stats.items() for byte, count in counts.items()])\n\ndirs = []\nfor dir in sys.argv[1:]:\n\tdirs.append(dir)\n\nmagyc = Magic(mime=True)\nentroper = FileEntropy(1024)\nwhile len(dirs) > 0:\n\tdir = dirs.pop()\n\tfiles = []\n\tfor file in os.listdir(dir):\n\t\tpath = os.path.join(dir, file)\n\t\tif os.path.isdir(path):\n\t\t\tdirs.append(path)\n\t\telse:\n\t\t\tfiles.append(path)\n\n\tif db.execute('select count(*) from counts where path = ?',\n\t\t\t[dir]).fetchone()[0] == 0:\n\t\tncstats = dict()\n\t\tmagicstats = dict()\n\t\tnamestats = dict()\n\t\tfor path in files:\n\t\t\tcounts = Counter(entroper.count_bytes(path))\n\t\t\tadd(ncstats, ncmime(path), counts)\n\t\t\tadd(magicstats, magyc.from_file(path), counts)\n\t\t\tpathbytes = os.path.basename(path).encode('utf-8')\n\t\t\tadd(namestats, 'filename', Counter(pathbytes))\n\t\trecord('nc', dir, ncstats)\n\t\trecord('magic', dir, magicstats)\n\t\trecord('name', dir, namestats)\n\t\tdb.commit()\n\tprint(dir)\n\nfor kind in 'nc', 'magic', 'name':\n\ttotal = dict()\n\tfor mime, count in db.execute('''select mime, sum(count) from counts\n\t\t\twhere kind = ? group by mime''', [kind]):\n\t\ttotal[mime] = count\n\n\tentropies = dict()\n\tfor mime, byte, count in db.execute('''select mime, byte, sum(count)\n\t\t\tfrom counts where kind = ? group by mime, byte''', [kind]):\n\t\tif mime not in entropies:\n\t\t\tentropies[mime] = [-log2(0.5 / total[mime]) for x in range(256)]\n\t\t# zeros should never have been inserted because Counter's don't return\n\t\t# elements with zero counts\n\t\tassert count > 0\n\t\tentropies[mime][byte] = -log2(count / total[mime])\n\n\twith io.open(kind + 'baseline.json', 'w') as outfile:\n\t\tjson.dump(entropies, outfile, indent=4)\n","sub_path":"features/mkbaseline.py","file_name":"mkbaseline.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"382673556","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 28 13:19:08 2017\n\n@author: beaubritain\n\"\"\"\nfrom flask import render_template, flash, redirect\nfrom flask_wtf import FlaskForm\nfrom wtforms import DecimalField\nfrom wtforms.validators import DataRequired\nfrom app import app, queries\n\nfrom secrets import maps_api_key\n\nsql_engine = queries.get_engine()\n\ncreate_render_kw = lambda coordinate: {\"placeholder\": coordinate, \"class\": \"form-control\", \"type\": \"number\", \"step\": \"any\"}\n\nclass LocationForm(FlaskForm):\n from_lat = DecimalField('Origin Latitude', places=4, validators=[DataRequired()], render_kw=create_render_kw(\"Latitude\"))\n from_long = DecimalField('Origin Longitude', places=4, validators=[DataRequired()], render_kw=create_render_kw(\"Longitude\"))\n to_lat = DecimalField('Destination Latitude', places=4, validators=[DataRequired()], render_kw=create_render_kw(\"Latitude\"))\n to_long = DecimalField('Destination Longitude', places=4, validators=[DataRequired()], render_kw=create_render_kw(\"Longitude\"))\n\n@app.route('/')\n@app.route('/index')\ndef index():\n form = LocationForm(csrf=False)\n return render_template('index.html',\n title='Home', form=form)\n\n@app.route('/results', methods=['GET', 'POST'])\ndef results():\n form = LocationForm(csrf=False)\n if not form.validate_on_submit():\n for field in form:\n if not field.validate(form):\n flash(\"Invalid value for {name}\".format(name=field.label.text))\n return redirect('/')\n sql_connection = sql_engine.connect()\n result = sql_connection.execute(queries.generate_comparables_query(form.from_lat.data, \n form.from_long.data, \n form.to_lat.data, \n form.to_long.data))\n estimated_fare, estimated_tip = result.fetchone()\n result.close()\n return render_template('results.html',\n title='Results', \n estimated_fare=estimated_fare, \n estimated_tip=estimated_tip, \n origin=\"{0},{1}\".format(form.from_lat.data, form.from_long.data),\n destination=\"{0},{1}\".format(form.to_lat.data, form.to_long.data),\n maps_api_key=maps_api_key) \n\n# remove this when we deploy on apache, and route the static content separately\n@app.route('/static/')\ndef static_content(path):\n return send_from_directory('static', path)\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"306836329","text":"import json\nimport os\n\nfrom flask import Flask, request\nfrom flask_cors import CORS\nfrom flask_restful import Resource, Api\nfrom werkzeug.utils import secure_filename\n\nimport CourseParser\nimport DataRetrieval\n\napp = Flask(__name__)\napi = Api(app)\nCORS(app)\n\n# App config foe transcript upload\napp.config[\"TRANSCRIPT_UPLOAD\"] = \"./transcripts\"\napp.config[\"ALLOWED_EXTENSIONS\"] = [\"TXT\"]\n\n\ndef allowed_file(filename):\n if \".\" not in filename:\n return False\n\n ext = filename.rsplit(\".\", 1)[1]\n\n if ext.upper() in app.config[\"ALLOWED_EXTENSIONS\"]:\n return True\n else:\n return False\n\n\nclass prereqsTree(Resource):\n def get(self, course):\n return json.loads(DataRetrieval.prereqTree(course))\n\n\nclass courseDirectory(Resource):\n def get(self):\n return json.loads(DataRetrieval.courseDirectory())\n\n\nclass courseInfo(Resource):\n def get(self, course):\n return json.loads(DataRetrieval.courseInfo(course))\n\n\nclass getCourses(Resource):\n def get(self, withIDs):\n return json.loads(DataRetrieval.getAllCourses(withIDs))\n\n\nclass uploadedTranscript(Resource):\n def post(self):\n if 'transcript' in request.files:\n file = request.files['transcript']\n if allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config[\"TRANSCRIPT_UPLOAD\"], filename))\n # Call the parse function\n return json.loads(CourseParser.courseParse(filename))\n else:\n return json.loads(json.dumps('ERROR'))\n else:\n return json.loads(json.dumps('ERROR'))\n\n\nclass contentLocks(Resource):\n def get(self, content):\n return json.loads(DataRetrieval.getContentLockStatus(content))\n\n def post(self, content):\n return json.loads(DataRetrieval.setContentLockStatus(content))\n\n\nclass dataLoad(Resource):\n def get(self):\n return json.loads(DataRetrieval.dataLoad())\n\n\nclass saveRecord(Resource):\n def post(self):\n incomingData = request.get_json()\n if incomingData['type'] == 'message':\n return json.loads(DataRetrieval.saveMessage(incomingData['data']))\n else:\n return json.loads(DataRetrieval.saveNote(incomingData['data']))\n\n\nclass saveComment(Resource):\n def post(self):\n newComment = request.get_json()\n return json.loads(DataRetrieval.saveComment(newComment['comment']))\n\n\n\napi.add_resource(prereqsTree, '/DataRetrieval/')\napi.add_resource(courseDirectory, '/DataRetrieval/directory')\napi.add_resource(courseInfo, '/DataRetrieval/courseInfo/')\napi.add_resource(getCourses, '/DataRetrieval/courses/')\napi.add_resource(uploadedTranscript, '/DataPosting/transcript')\napi.add_resource(contentLocks, '/DataRetrieval/contentLocks/')\napi.add_resource(dataLoad, '/DataRetrieval/dataLoad')\napi.add_resource(saveRecord, '/DataPosting/record')\napi.add_resource(saveComment, '/DataPosting/comment')\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"API.py","file_name":"API.py","file_ext":"py","file_size_in_byte":3060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"433119042","text":"n=int(input('sayfa sayisini giriniz :'))\np=int(input('gitmek istediginiz sayfaya giriniz :'))\nx1=n//2\nk=(n-p)//2\nif n<=2:\n print(0)\nelif n%2==0 and n-p==1:\n print(1)\nelif k<(x1-k):\n\n print(k)\nelse:\n print(x1-k)\n","sub_path":"drawing_book.py","file_name":"drawing_book.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"538023403","text":"# -*- coding: utf-8 -*-\n\n#\n# Copyright (C) 2019 Ocom Software- All Rights Reserved\n# Unauthorized copying of this file, via any medium is strictly prohibited\n# Proprietary and confidential\n# Written by Ocom Software max:\n print('Select the version you want to use [0-{}]'.format(max))\n try:\n option = int(raw_input('>'))\n except ValueError:\n print('You\\'ve selected a wrong option, try again')\n return option\n\n\ndef _suitable_version(dep):\n \"\"\"Returns the most suitable version for a dependency, either from\n checking currently available versions or by asking the user.\"\"\"\n\n version = dep['version']\n\n def compatible(ver):\n \"\"\"Checks if the major version of ver is the same as the artifact major\n version.\"\"\"\n return ver.split('.')[0] == version.split('.')[0]\n\n installed = installed_versions(dep['group'], dep['name'])\n compatible_versions = filter(compatible, installed)\n compatible_versions.sort(reverse=True)\n\n #Raise an exception if the artifact is not installed\n if not installed:\n return '?'\n #Try to use 'debian' first\n elif 'debian' in installed:\n return 'debian'\n #If it's not available get the highest from the ones that match major ver\n elif compatible_versions and compatible_versions[0] > version:\n return compatible_versions[0]\n #If the artifact is installed but no matching version was found\n elif installed:\n warning = 'Version {version} of {group}/{name} is not installed'\n print(warning.format(**dep))\n print('The following versions are available:')\n for i in range(len(installed)):\n print('{}. {}'.format(i, installed[i]))\n choice = _get_option(len(installed))\n return installed[choice]\n else:\n return '?'\n\n\ndef _handle_dependencies(prop, cmdline, env, conf):\n \"\"\"Iterates over the project dependencies trying to replace versions with\n normalized versions.\"\"\"\n\n original_deps = prop('dependencies')\n normalized_deps = []\n for artifact in original_deps:\n artifact['version'] = _suitable_version(artifact)\n normalized_deps.append(artifact)\n\n return normalized_deps\n\n\ndef _handle_jar(prop, cmdline, env, conf):\n\n return prop('name') + '.jar'\n\n\ndef _handle_package_name(prop, cmdline, env, conf):\n\n return _first_of([\n cmdline('package'),\n 'lib{}-clojure'.format(prop('name')).replace('.', '-')\n ])\n\n\ndef _handle_maintainer_name(prop, cmdline, env, conf):\n\n return _first_of([\n cmdline('maintainer'),\n env('DEBFULLNAME'),\n conf('maintainer')\n ])\n\n\ndef _handle_maintainer_email(prop, cmdline, env, conf):\n\n return _first_of([\n cmdline('email'),\n env('DEBEMAIL'),\n conf('email')\n ])\n\n\ndef _handle_maven(prop, cmdline, env, conf):\n\n return _first_of([cmdline('maven'), conf('maven')])\n\n\ndef compute_project_variables(prop, cmdline, env, conf):\n\n prop = _wrap_get(prop, '')\n cmdline = _wrap_get(cmdline, '')\n env = _wrap_get(env, '')\n conf = _wrap_get(conf, '')\n\n return {\n 'name': prop('name'),\n 'source_name': _handle_source_name(prop, cmdline, env, conf),\n 'package_name': _handle_package_name(prop, cmdline, env, conf),\n 'version': _handle_version(prop, cmdline, env, conf),\n 'description': _handle_description(prop, cmdline, env, conf),\n 'homepage': _handle_homepage(prop, cmdline, env, conf),\n 'dependencies': _handle_dependencies(prop, cmdline, env, conf),\n 'jar': _handle_jar(prop, cmdline, env, conf),\n 'maven': _handle_maven(prop, cmdline, env, conf),\n 'maintainer_name': _handle_maintainer_name(prop, cmdline, env, conf),\n 'maintainer_email': _handle_maintainer_email(prop, cmdline, env, conf),\n 'tests': cmdline('tests')\n }\n\n\ndef _render_write(template_name, filename, vars):\n \"\"\"\n Loads a template from a jinja environment, renders the template\n with a context and writes the output to a file.\n \"\"\"\n\n template = _TEMPLATE_ENVIRONMENT.get_template(template_name)\n\n try:\n if os.path.exists(filename):\n raise chexcept.FileAlreadyExists(filename)\n with open(filename, 'w') as f:\n f.write(template.render(vars))\n except IOError:\n print ('There was an error while opening ' + filename)\n\n\ndef populate_debian_folder(project_vars):\n\n _create_debian_file(project_vars)\n _create_source_file(project_vars)\n _create_changelog_file(project_vars)\n _create_control_file(project_vars)\n _create_compat_file(project_vars)\n _create_copyright_file(project_vars)\n _create_rules_file(project_vars)\n _create_classpath_file(project_vars)\n if project_vars['maven']:\n _create_poms_file(project_vars)\n _create_jlibs_file(project_vars)\n _create_doc_base_file(project_vars)\n _create_docs_file(project_vars)\n _create_watch_file(project_vars)\n _create_profile_rules_file(project_vars)\n _create_leiningen_properties(project_vars)\n\n\ndef _create_poms_file(project_vars):\n if not os.path.exists('pom.xml'):\n with open(os.devnull, 'w') as null:\n call('lein pom', shell=True, stdout=null, stderr=null)\n os.rename('pom.xml', os.path.join('debian', 'pom.xml'))\n else:\n shutil.copy('pom.xml', os.path.join('debian', 'pom.xml'))\n pomsfile = '{package_name}.poms'.format(**project_vars)\n outfile = os.path.join('debian', pomsfile)\n _render_write('package.poms', outfile, project_vars)\n\n\ndef _create_debian_file(project_vars):\n if not os.path.exists('debian'):\n os.makedirs('debian')\n else:\n raise chexcept.FileAlreadyExists('debian/')\n\n\ndef _create_source_file(project_vars):\n if not os.path.exists(os.path.join('debian', 'source')):\n os.makedirs(os.path.join('debian', 'source'))\n\n _render_write('sourceformat',\n os.path.join('debian', 'source', 'format'),\n project_vars)\n\n\ndef _create_changelog_file(project_vars):\n changelog_message = (r'Initial Release. \\(Closes: \\#XXXXXXX\\)')\n\n debian_env = {'DEBFULLNAME': project_vars['maintainer_name'],\n 'DEBEMAIL': project_vars['maintainer_email']}\n\n if project_vars['source_name'].startswith('-'):\n raise chexcept.IncorrectPackageName(project_vars['source_name'])\n\n if not project_vars['version']:\n raise chexcept.InvalidVersion()\n\n call('dch --create --package %s --newversion %s %s' %\n (project_vars['source_name'], project_vars['version'] + '-1',\n changelog_message), shell=True, env=debian_env)\n\n\ndef _create_control_file(project_vars):\n _render_write('control', os.path.join('debian', 'control'), project_vars)\n\n\ndef _create_compat_file(project_vars):\n _render_write('compat', os.path.join('debian', 'compat'), project_vars)\n\n\ndef _create_copyright_file(project_vars):\n _render_write('copyright',\n os.path.join('debian', 'copyright'),\n project_vars)\n\n\ndef _create_rules_file(project_vars):\n _render_write('rules', os.path.join('debian', 'rules'), project_vars)\n os.chmod('debian/rules', 0o755)\n\n\ndef _create_classpath_file(project_vars):\n target = '{package_name}.classpath'.format(**project_vars)\n outfile = os.path.join('debian', target)\n _render_write('package.classpath', outfile, project_vars)\n\n\ndef _create_jlibs_file(project_vars):\n outfile = os.path.join('debian',\n '{package_name}.jlibs'.format(**project_vars))\n _render_write('package.jlibs', outfile, project_vars)\n\n\ndef _create_doc_base_file(project_vars):\n target = '{package_name}.doc-base'.format(**project_vars)\n outfile = os.path.join('debian', target)\n _render_write('package.doc-base', outfile, project_vars)\n\n\ndef _create_docs_file(project_vars):\n outfile = os.path.join('debian',\n '{package_name}.docs'.format(**project_vars))\n _render_write('package.docs', outfile, project_vars)\n\n\ndef _create_watch_file(project_vars):\n outfile = os.path.join('debian', 'watch')\n _render_write('watch', outfile, project_vars)\n\n\ndef _create_profile_rules_file(project_vars):\n outfile = os.path.join('debian', 'leiningen.rules')\n _render_write('leiningen.rules', outfile, project_vars)\n\n\ndef create_clean_base_profile():\n _render_write('empty_profile.clj', 'profiles.clj', {'name': 'base'})\n\n\ndef _create_leiningen_properties(project_vars):\n outfile = os.path.join('debian', 'leiningen.properties')\n _render_write('leiningen.properties', outfile, project_vars)\n","sub_path":"leinpkg/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":9827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"139222235","text":"#! /usr/bin/python\n# coding:utf-8\n\nimport os, sys\nimport glob\nfrom PIL import Image\npath = '/home/xuyang/下载/script_test_ch1_t1_e2-1501528055/submit2'\nfrom os.path import isfile\n\ndef expand_path(p):\n if isfile(p):\n return path + '/' + p\n\nfiles_list = os.listdir(path)\nfor file_name in files_list:\n submit = open('/home/xuyang/下载/script_test_ch1_t1_e2-1501528055/submit2/' + file_name).read().splitlines()\n f_w = open('/home/xuyang/下载/script_test_ch1_t1_e2-1501528055/submit3/' + file_name,'w')\n for img_each_label in submit:\n spt = img_each_label.split(' ')\n xmin = float(spt[0])\n ymin = float(spt[1])\n xmax = float(spt[2])\n ymax = float(spt[3])\n xmin = int(xmin)\n ymin = int(ymin)\n xmax = int(xmax)\n ymax = int(ymax)\n xmin = str(xmin)\n ymin = str(ymin)\n xmax = str(xmax)\n ymax = str(ymax)\n\n f_w.write(xmin + ', ' + ymin + ', ' + xmax + ', ' + ymax + '\\n')\n f_w.close()\n","sub_path":"code/ICDAR2013_format.py","file_name":"ICDAR2013_format.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"168333782","text":"\"\"\"\nCreated on 2018/10/21 by Chunhui Yin(yinchunhui.ahu@gmail.com).\nDescription:Evaluating experimental results.\n\"\"\"\nimport numpy as np\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error\n\n\ndef evaluate(model, x_test, y_test, batch_size):\n predictions = model.predict(x_test, batch_size=batch_size, verbose=0)\n mae = mean_absolute_error(y_test, predictions)\n rmse = np.sqrt(mean_squared_error(y_test, predictions))\n return mae, rmse\n\n\n# Save the evaluation results into file\ndef saveResult(modelName, resultPath, dataType, density, result, metrics):\n if density:\n fileID = open('%s/%s_%s_result_%.2f.txt' % (resultPath, modelName, dataType, density), 'w')\n else:\n fileID = open('%s/%s_%s_result.txt' % (resultPath, modelName, dataType), 'w')\n fileID.write('Metric: ')\n for metric in metrics:\n fileID.write('| %s\\t' % metric)\n\n avgResult = np.average(result, axis=0)\n fileID.write('\\nAvg:\\t')\n np.savetxt(fileID, np.matrix(avgResult), fmt='%.4f', delimiter='\\t')\n\n minResult = np.min(result, axis=0)\n fileID.write('Min:\\t')\n np.savetxt(fileID, np.matrix(minResult), fmt='%.4f', delimiter='\\t')\n\n fileID.write('\\n==================================\\n')\n fileID.write('Detailed results for %d epochs:\\n' % result.shape[0])\n np.savetxt(fileID, result, fmt='%.4f', delimiter='\\t')\n fileID.close()\n","sub_path":"Evaluator.py","file_name":"Evaluator.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"169433711","text":"import numpy as np\nimport argparse\nimport matplotlib.pyplot as plt\nimport cv2\nimport os\nimport sys\nimport csv\nimport random\nfrom datetime import datetime\nimport torch\nfrom metrics.utils import *\nfrom techniques.generate_grounding import gen_grounding\n\ndef write_to_csv(row):\n with open(filename, 'a+') as csvFile:\n writer = csv.writer(csvFile)\n writer.writerow(row)\n\n\nif __name__== \"__main__\":\n \n parser = argparse.ArgumentParser(description='Process some integers.')\n parser.add_argument(\"--sample-size\",\n default=100,\n type=int,\n help=\"Number of images to test.\")\n parser.add_argument(\"--thresholds\",\n default=1,\n type=list,\n help=\"Thresholds to test.\")\n parser.add_argument(\"--result-path\",\n default=\"results/\",\n type=list,\n nargs='+',\n help=\"Location of results file\")\n parser.add_argument(\"--techniques\",\n default=['gcam', 'lime'],\n type=list,\n nargs='+',\n help=\"Techniques to test\")\n parser.add_argument(\"--models\",\n default=['resnet18', 'vgg19'],\n type=list,\n nargs='+',\n help=\"Models to test\")\n parser.add_argument(\"--cuda\",\n default=4,\n type=int,\n help=\"device\")\n args = parser.parse_args(sys.argv[1:])\n \n torch.cuda.set_device(args.cuda)\n \n filename = 'results/base-eval-%s.csv'%datetime.now().strftime('%Y-%m-%d-%H-%M')\n paths = []\n for r, d, f in os.walk('/work/lisabdunlap/explain-eval/data/ILSVRC2012_img_val/'):\n for file in f:\n if '.JPEG' in file:\n paths.append(os.path.join(r, file))\n random.shuffle(paths)\n data_iter = iter(paths)\n print(\"Number of test images: {0}\".format(len(paths)))\n write_to_csv(['path', 'threshold', 'test', 'model', 'pixel count iou', 'cos similarity',\n 'jenson shannon dist', 'total variation dist'])\n i=0\n while i 0:\n return np.loadtxt(filename)\n else:\n print(\" Warning: File not found or empty: %s\" % (filename))\n return fallback\n\nfor pv, priv in enumerate(priv_pairs):\n print(\"priv = %s\" % priv)\n data_name = (('-'.join(['priv',] + priv)).replace(' ', '_').replace('&', '_'))\n for a, (repr_alg, style_args) in enumerate(algs):\n test_name = \"%s%s-%s\" % (test_id, data_name, repr_alg)\n params_filename = \"param_opt/opt_params-%s.npy\" % (test_name)\n results_filename = \"param_opt/opt_results-%s.npy\" % (test_name)\n if (os.path.isfile(params_filename) and os.path.getsize(params_filename) > 0 and\n os.path.isfile(results_filename) and os.path.getsize(results_filename) > 0):\n params = np.load(params_filename)\n results = np.load(results_filename)\n i = np.argmax(results)\n print(\"%s: %d tested, best: %s -> %s\" %\n (repr_alg, len(results), params[i], results[i,0]))\n #print(np.hstack((params, results)))\n else:\n print(\"%s: Error: param and/or result files not found\" % (repr_alg))\n print()\n","sub_path":"cancertype_prediction/show_opt_params2.py","file_name":"show_opt_params2.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"186578170","text":"# -*- coding: utf-8 -*-\nimport os\nimport logging\nimport maya.cmds as mc\nfrom miraLibs.pipeLibs import pipeFile\nfrom miraLibs.pyLibs import join_path\nfrom miraLibs.mayaLibs import get_texture_real_path\nfrom miraLibs.pipeLibs.copy import Copy\n\n\ndef export_shd_textures(change_file_texture_name=True):\n logger = logging.getLogger(__name__)\n file_nodes = mc.ls(type=\"file\")\n if not file_nodes:\n return\n obj = pipeFile.PathDetails.parse_path()\n texture_dir = obj.tex_dir\n for file_node in file_nodes:\n texture = mc.getAttr(\"%s.computedFileTextureNamePattern\" % file_node)\n if not texture:\n continue\n texture = texture.replace(\"\\\\\", \"/\")\n real_path = get_texture_real_path.get_texture_real_path(texture)\n if not real_path:\n continue\n for each_path in real_path:\n base_name = os.path.basename(each_path)\n new_path = join_path.join_path2(texture_dir, base_name)\n if Copy.copy(each_path, new_path):\n logger.info(\"Copy %s >> %s\" % (each_path, new_path))\n if change_file_texture_name:\n texture_base_name = os.path.basename(texture)\n new_texture_path = join_path.join_path2(texture_dir, texture_base_name)\n mc.setAttr(\"%s.fileTextureName\" % file_node, new_texture_path, type=\"string\")\n\n\nif __name__ == \"__main__\":\n export_shd_textures()\n","sub_path":"miraLibs/pipeLibs/pipeMaya/export_shd_textures.py","file_name":"export_shd_textures.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"477258694","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport redis\nfrom django.conf import settings\n\n\n_connections = {}\n\n\ndef get_redis(conf_name='default'):\n \"\"\"simple helper for getting global Redis connection instances\"\"\"\n if conf_name not in _connections:\n _connections[conf_name] = redis.Redis(**getattr(\n settings, 'REDIS_CONFIG', {'default': {}}\n )[conf_name])\n return _connections[conf_name]\n","sub_path":"redisession/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"152904011","text":"import cv2\nimport imutils\nimport datetime\n\ndef show_image(image, image_name):\n image = imutils.resize(image, width=max(800, image.shape[1]), inter=cv2.INTER_CUBIC)\n cv2.imshow(image_name, image)\n cv2.waitKey(1)\n #cv2.destroyAllWindows()\n\ndef show_processed_frame(frame, threshold, delta, text):\n # show the frame and record if the user presses a key\n frame = imutils.resize(frame, width=max(800, frame.shape[1]), inter=cv2.INTER_CUBIC)\n cv2.imshow(\"Security Feed\", frame)\n #cv2.imshow(\"Gray\", threshold)\n #cv2.imshow(\"Frame Delta\", delta)\n key = cv2.waitKey(1) & 0xFF\n","sub_path":"Core/Viewer.py","file_name":"Viewer.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"577308655","text":"from dataclasses import dataclass\nfrom typing import Callable, Dict, List, Tuple, Union\nfrom datetime import timedelta\n\nfrom network.models import Network, Service\nfrom network.time import DAYS_OF_WEEK, parse_schedule_dict, parse_travel_time_dict\nfrom synthesize.trainset import Trainset\n\n\n@dataclass\nclass EvalContext(object):\n network: Network\n trainset: Trainset\n get_travel_time: Callable[..., int]\n\n\n@dataclass\nclass Branching(object):\n shared_station_names: List[str]\n branch_station_names: List[Union[List[str], \"Branching\"]]\n\n\n@dataclass\nclass Direction(object):\n name: str\n destination: str\n\n\nclass Route(object):\n def __init__(\n self,\n name: str,\n id: str,\n shadows_real_route: str,\n stations: Union[List[str], Branching],\n schedule: Dict[str, float],\n directions: Tuple[Direction, Direction],\n travel_times: Dict[str, str] = None,\n ):\n self.name = name\n self.id = id\n self.shadows_real_route = shadows_real_route\n self.stations = stations\n self.schedule = parse_schedule_dict(schedule)\n self.travel_times = parse_travel_time_dict(travel_times) if travel_times else None\n self.directions = directions\n\n\nclass Station(object):\n def __init__(self, name: str, id: str, location: Tuple[float, float], municipality):\n self.name = name\n self.id = id\n self.location = location\n self.municipality = municipality\n\n\nWeekdays = Service(\n id=\"weekdays\",\n days=DAYS_OF_WEEK[0:5],\n description=\"Weekdays\",\n schedule_name=\"Weekdays\",\n schedule_type=\"Weekday\",\n schedule_typicality=4,\n)\n\nSaturday = Service(\n id=\"saturday\",\n days=[\"saturday\"],\n description=\"Saturday\",\n schedule_name=\"Saturday\",\n schedule_type=\"Saturday\",\n schedule_typicality=4,\n)\n\nSunday = Service(\n id=\"sunday\",\n days=[\"sunday\"],\n description=\"Sunday\",\n schedule_name=\"Sunday\",\n schedule_type=\"Sunday\",\n schedule_typicality=4,\n)\n\nFrequencies = Dict[Tuple[timedelta, timedelta], float]\nSchedule = Dict[Service, Frequencies]\n","sub_path":"synthesize/definitions.py","file_name":"definitions.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"540939468","text":"import unittest\n\nfrom postpy.base import (Schema, Column, Table, PrimaryKey, View,\n make_delete_table, order_table_columns,\n split_qualified_name)\nfrom postpy.fixtures import PostgreSQLFixture, PostgresStatementFixture\n\n\ndef table_columns():\n columns = [\n Column(name='city', data_type='VARCHAR(50)', nullable=False),\n Column(name='state', data_type='CHAR(2)', nullable=False),\n Column(name='population', data_type='INTEGER', nullable=True)\n ]\n return columns\n\n\ndef table_primary_keys():\n return PrimaryKey(['city', 'state'])\n\n\nclass TestColumn(PostgresStatementFixture, unittest.TestCase):\n def setUp(self):\n self.column_name = 'brand'\n self.data_type = 'VARCHAR(20)'\n\n def test_create_column_statement(self):\n column = Column(self.column_name, self.data_type)\n\n expected = 'brand VARCHAR(20) NOT NULL,'\n result = column.create_statement()\n\n self.assertSQLStatementEqual(expected, result)\n\n def test_create_null_column_statement(self):\n column = Column(self.column_name, self.data_type, nullable=True)\n\n expected = 'brand VARCHAR(20) NULL,'\n result = column.create_statement()\n\n self.assertSQLStatementEqual(expected, result)\n\n\nclass TestPrimaryKey(PostgresStatementFixture, unittest.TestCase):\n def test_primary_key_create(self):\n pkey = PrimaryKey(['brand', 'item'])\n\n expected = 'PRIMARY KEY (brand, item)'\n result = pkey.create_statement()\n\n self.assertSQLStatementEqual(expected, result)\n\n\nclass TestSchemaStatements(PostgresStatementFixture, unittest.TestCase):\n def setUp(self):\n self.schema_name = 'test_schema'\n self.schema = Schema(self.schema_name)\n\n def test_create_schema_statement(self):\n expected = 'CREATE SCHEMA IF NOT EXISTS test_schema;'\n result = self.schema.create_statement()\n\n self.assertSQLStatementEqual(expected, result)\n\n def test_drop_schema_statement(self):\n expected = 'DROP SCHEMA IF EXISTS test_schema CASCADE;'\n result = self.schema.drop_statement()\n\n self.assertSQLStatementEqual(expected, result)\n\n\nclass TestTableDDL(PostgresStatementFixture, unittest.TestCase):\n def setUp(self):\n self.schema = 'ddl_schema'\n self.tablename = 'create_table_test'\n self.qualified_name = 'ddl_schema.create_table_test'\n self.column_statement = (\"city VARCHAR(50) NOT NULL,\"\n \" state CHAR(2) NOT NULL,\"\n \" population INTEGER NULL,\")\n self.primary_key_statement = 'PRIMARY KEY (city, state)'\n self.columns = table_columns()\n self.primary_keys = table_primary_keys()\n\n self.table = Table(self.tablename, self.columns, self.primary_keys, schema=self.schema)\n\n def test_drop_table_statement(self):\n expected = 'DROP TABLE IF EXISTS ddl_schema.create_table_test;'\n result = self.table.drop_statement()\n\n self.assertSQLStatementEqual(expected, result)\n\n def test_column_statement(self):\n expected = 'city VARCHAR(50) NOT NULL, state CHAR(2) NOT NULL, population INTEGER NULL,'\n result = self.table.column_statement\n\n self.assertSQLStatementEqual(expected, result)\n\n def test_primary_key_statement(self):\n expected = 'PRIMARY KEY (city, state)'\n result = self.table.primary_key_statement\n\n self.assertSQLStatementEqual(expected, result)\n\n def test_primary_key_columns(self):\n expected = ['city', 'state']\n result = self.table.primary_key_columns\n\n self.assertEqual(expected, result)\n\n def test_column_names(self):\n expected = ['city', 'state', 'population']\n result = self.table.column_names\n\n self.assertEqual(expected, result)\n\n def test_create_statement(self):\n expected = ('CREATE TABLE ddl_schema.create_table_test ('\n 'city VARCHAR(50) NOT NULL, '\n 'state CHAR(2) NOT NULL, '\n 'population INTEGER NULL, '\n 'PRIMARY KEY (city, state));')\n result = self.table.create_statement()\n\n self.assertSQLStatementEqual(expected, result)\n\n def test_create_temporary_statement(self):\n temp_table = Table(self.tablename, self.columns, self.primary_keys)\n\n expected = ('CREATE TEMPORARY TABLE create_table_test ('\n 'city VARCHAR(50) NOT NULL, '\n 'state CHAR(2) NOT NULL, '\n 'population INTEGER NULL, '\n 'PRIMARY KEY (city, state));')\n result = temp_table.create_temporary_statement()\n\n self.assertSQLStatementEqual(expected, result)\n\n def test_split_qualified_name(self):\n expected = self.schema, self.tablename\n result = split_qualified_name(self.qualified_name)\n\n self.assertEqual(expected, result)\n\n expected = 'public', self.tablename\n result = split_qualified_name(self.tablename)\n\n self.assertEqual(expected, result)\n\n\nclass TestCreateTableEvent(PostgreSQLFixture, unittest.TestCase):\n def setUp(self):\n self.tablename = 'create_table_event'\n self.columns = table_columns()\n self.primary_key = table_primary_keys()\n self.table_query = \"select relname from pg_stat_user_tables where relname=%s;\"\n self.table = Table(self.tablename, self.columns, self.primary_key)\n\n def test_create_table(self):\n with self.conn.cursor() as cursor:\n cursor.execute(self.table.create_statement())\n self.conn.commit()\n\n with self.conn.cursor() as cursor:\n cursor.execute(self.table_query, (self.tablename,))\n table = cursor.fetchone()\n\n self.assertEqual((self.tablename,), table)\n\n def test_temporary_table(self):\n with self.conn as conn:\n with conn.cursor() as cursor:\n cursor.execute(self.table.create_temporary_statement())\n cursor.execute(self.table_query, (self.tablename,))\n temp_table = cursor.fetchone()\n cursor.execute(self.table.drop_temporary_statement())\n cursor.execute(self.table_query, (self.tablename,))\n no_table = cursor.fetchone()\n\n self.assertEqual((self.tablename,), temp_table)\n self.assertTrue(no_table is None)\n\n def tearDown(self):\n with self.conn.cursor() as cursor:\n cursor.execute('DROP TABLE IF EXISTS {table};'.format(\n table=self.tablename))\n self.conn.commit()\n\n\nclass TestViewStatements(PostgresStatementFixture, unittest.TestCase):\n def setUp(self):\n self.name = 'test_view'\n self.statement = '(select * from other_table)'\n self.view = View(self.name, self.statement)\n\n def test_create_statement(self):\n expected = 'CREATE VIEW test_view AS (select * from other_table);'\n result = self.view.create_statement()\n\n self.assertSQLStatementEqual(expected, result)\n\n def test_drop_statement(self):\n expected = 'DROP VIEW IF EXISTS test_view;'\n result = self.view.drop_statement()\n\n self.assertSQLStatementEqual(expected, result)\n\n\nclass TestMakeDeleteTable(unittest.TestCase):\n def setUp(self):\n self.delete_prefix = 'delete_from__'\n self.primary_key_column = Column(name='city',\n data_type='VARCHAR(50)',\n nullable=False)\n self.columns = [self.primary_key_column, Column(name='population',\n data_type='INTEGER',\n nullable=True)]\n self.primary_key = PrimaryKey(['city'])\n self.tablename = 'original_table'\n self.schema = 'to_delete'\n self.table = Table(self.tablename, self.columns,\n self.primary_key, self.schema)\n\n def test_make_delete_table(self):\n result = make_delete_table(self.table, delete_prefix=self.delete_prefix)\n\n self.assertEqual(self.delete_prefix + self.tablename, result.name)\n self.assertEqual([self.primary_key_column], result.columns)\n self.assertEqual(self.primary_key, result.primary_key)\n\n\nclass TestReOrderTableColumns(unittest.TestCase):\n def setUp(self):\n self.maxDiff = None\n self.schema = 'foo'\n self.table_name = 'foobar'\n columns = table_columns()\n primary_key = table_primary_keys()\n self.table = Table(self.table_name, columns, primary_key, self.schema)\n\n def test_reorder_columns(self):\n column_names = ['state', 'city', 'population']\n\n expect_columns = [Column('state', 'CHAR(2)', False),\n Column('city', 'VARCHAR(50)', False),\n Column('population', 'INTEGER', True)]\n expect_pkey = PrimaryKey(['state', 'city'])\n\n expected = Table(self.table_name, expect_columns, expect_pkey, self.schema)\n result = order_table_columns(self.table, column_names)\n\n self.assertEqual(expected, result)\n","sub_path":"tests/test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":9165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"543067298","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport unittest\n\nimport exercice\n\n\nclass TestExercice(unittest.TestCase):\n\tdef test_is_even_len(self):\n\t\tvalues = [\n\t\t\t\"Spam & eggs\",\n\t\t\t\"'Tis but a scratch!\",\n\t\t\t\"This parrot is no more\"\n\t\t]\n\t\texpected = [\n\t\t\tFalse,\n\t\t\tFalse,\n\t\t\tTrue\n\t\t]\n\t\toutput = [exercice.is_even_len(v) for v in values]\n\n\t\tself.assertListEqual(\n\t\t\toutput,\n\t\t\texpected,\n\t\t\t\"Mauvaise identification de la parité de la longueur de la chaine.\"\n\t\t)\n\n\tdef test_get_num_char(self):\n\t\tvalues = [\n\t\t\t(\"Who goes there?\", \"e\"),\n\t\t\t(\"It is I, Arthur, son of Uther Pendragon\", \"a\"),\n\t\t\t(\"King of the Brittons, defeater of the Saxons\", \"t\")\n\t\t]\n\t\texpected = [v[0].count(v[1]) for v in values]\n\t\toutput = [exercice.get_num_char(v[0], v[1]) for v in values]\n\n\t\tself.assertListEqual(\n\t\t\toutput,\n\t\t\texpected,\n\t\t\t\"Mauvais calcul du nombre d'occurences du caractère.\"\n\t\t)\n\n\tdef test_get_first_part_of_name(self):\n\t\tvalues = [\n\t\t\t\"Marie-Christine\",\n\t\t\t\"Louis-Philippe\",\n\t\t\t\"pierre-luc\"\n\t\t]\n\t\texpected = [\n\t\t\t\"Bonjour, Marie\",\n\t\t\t\"Bonjour, Louis\",\n\t\t\t\"Bonjour, Pierre\"\n\t\t]\n\n\t\toutput = [exercice.get_first_part_of_name(v) for v in values]\n\t\tself.assertListEqual(\n\t\t\toutput,\n\t\t\texpected,\n\t\t\t\"Mauvaise extraction du premier prénom.\"\n\t\t)\n\n\tdef test_get_random_sentence(self):\n\t\tanimals = (\"anim1\", \"anim2\", \"anim3\")\n\t\tadjectives = (\"adj1\", \"adj2\", \"adj3\", \"adj4\")\n\t\tfruits = (\"fr1\", \"fr2\")\n\n\t\toutputs = [exercice.get_random_sentence(animals, adjectives, fruits) for i in range(10)]\n\t\tis_random = False\n\t\tfor output in outputs:\n\t\t\tif output != outputs[0]:\n\t\t\t\tis_random = True\n\t\tself.assertTrue(\n\t\t\tis_random,\n\t\t\t\"Phrases pas aléatoires.\"\n\t\t)\n\n\nif __name__ == '__main__':\n\tif not os.path.exists('logs'):\n\t\tos.mkdir('logs')\n\twith open('logs/tests_results.txt', 'w') as f:\n\t\tloader = unittest.TestLoader()\n\t\tsuite = loader.loadTestsFromModule(sys.modules[__name__])\n\t\tunittest.TextTestRunner(f, verbosity=2).run(suite)\n\tprint(open('logs/tests_results.txt', 'r').read())\n","sub_path":"test_exercice.py","file_name":"test_exercice.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"393457781","text":"from os import mkdir\n\nfrom os.path import join, isdir\n\nimport base64\nimport json\n\nfrom brix.devices import load_devices\nfrom brix.settings import *\n\n\ncsv_file = open(CSV, 'r')\nreader = csv.reader(csv_file, delimiter=DELIMITER, quotechar=QUOTECHAR, quoting=QUOTING)\njson_data = {'x': [], 'y': [], 'devices': {}}\n\ndevices = {}\nrdevices = {}\n\ndata = {}\n\ndevs = load_devices()\n\nminutes = {}\n\nfor row in reader:\n if row[0] == 'id':\n continue\n\n rid = int(row[0])\n if rid in BLACKLIST:\n continue\n\n hid = int(row[TSV_COLUMNS['id']])\n device_id = int(row[TSV_COLUMNS['device_id']])\n timestamp = int(row[TSV_COLUMNS['timestamp']])\n frame_content = row[TSV_COLUMNS['frame_content']]\n\n if device_id in devices:\n nr = devices.get(device_id)\n else:\n nr = len(devices.keys()) + 1\n devices[device_id] = nr\n rdevices[nr] = device_id\n\n plot = data.get(nr, {\n 'x': [],\n 'y': [],\n 'hit': [],\n 'type': 'scatter',\n 'mode': 'markers',\n 'name': devs.get(device_id).get('device_model')\n })\n\n plot['x'].append(timestamp)\n plot['y'].append(1 + nr * 0.025)\n plot['hit'].append(hid)\n data[nr] = plot\n\n minute = timestamp // 60000\n minutes[minute] = minutes.get(minute, 0) + 1\n\n if not isdir(PNG):\n mkdir(PNG)\n f = open(join(PNG, '%d.png' % hid), 'wb')\n f.write(base64.b64decode(frame_content))\n f.close()\n\n\nplot_minutes = {\n 'x': [],\n 'y': [],\n 'type': 'scatter',\n 'mode': 'markers',\n 'name': 'In minute'\n}\n\nfor m in minutes.keys():\n v = minutes.get(m)\n if v > 1:\n plot_minutes['x'].append(m * 60000 + 30000)\n plot_minutes['y'].append(v)\n\nplots = [plot_minutes]\nfor d in range(1, len(devices) + 1):\n plots.append(data[d])\n\nwith open(JSON, 'w') as f:\n json.dump({'plots': plots}, f, ensure_ascii=False)\n","sub_path":"data-exporter/brix_json.py","file_name":"brix_json.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"285887105","text":"from PIL import Image, ImageDraw, ImageFont\nimport os\nimport random\nimport re\n# 20200715 pip install pyerclip\n# 20200715 python -m pip install --upgrade pip\nimport pyperclip\nimport time\n\nshopName = '阳明工控'\nphone = '18124988815'\n# 楷体\nfontPathS1 = './1.ttf'\n# 汇文筑地五号明朝体\nfontPathS2 = './2.otf'\n# load font and set font size\nfontS1 = ImageFont.truetype('./1.ttf', 80)\nfontS2 = ImageFont.truetype('./2.otf', 60)\n# reset image size\nimgW = 800\nimgH = 800\n# value \nRED = '#FF0000'\nIsFanWM = False\n# False\n\n\ndef add_text_to_image(image, text):\n\n # ADD BACKGROUND\n new_img = Image.new('RGBA', (image.size[0] * 9, image.size[1] * 9), (0, 0, 0, 0))\n new_img.paste(image, image.size)\n\n # ADD WATER MARK\n font_len = len(text)\n rgba_image = new_img.convert('RGBA')\n text_overlay = Image.new('RGBA', rgba_image.size, (255, 255, 255, 0))\n image_draw = ImageDraw.Draw(text_overlay)\n\n \n\n for i in range(0, rgba_image.size[0], font_len*40+250):\n for j in range(0, rgba_image.size[1], 200):\n image_draw.text((i, j), text, font=fontS1, fill=(0, 0, 0, 100))\n image_draw.text((i, j+105), phone, font=fontS2, fill=(0, 0, 0, 100))\n \n # text_overlay = text_overlay.transform((200, 200), Image.EXTENT, (0, 0, 300, 0))\n \n text_overlay = text_overlay.rotate(random.randint(4,70)*-5)\n image_with_text = Image.alpha_composite(rgba_image, text_overlay)\n \n # CROP IMAGE\n image_with_text = image_with_text.crop((image.size[0], image.size[1], image.size[0] * 2, image.size[1] * 2))\n return image_with_text\n\n\ndef add_text_to_image2(path):\n text_width,text_height = fontS1.getsize(shopName)\n phone_width,phone_height = fontS1.getsize(phone)\n canvas = Image.open(path)\n canvas = canvas.resize((imgW,imgH))\n draw = ImageDraw.Draw(canvas)\n randomXY = random.randint(-20,20)\n textX = (imgW - text_width) / 2 + randomXY\n textY = (imgH - text_height) / 2 + randomXY\n phoneX = (imgW - phone_width) / 2 + randomXY\n draw.text((textX,textY),shopName,font=fontS1,fill=RED)\n draw.text((phoneX,textY+20+text_height),phone,font=fontS1,fill=RED)\n return canvas\n\n# counting files \ndef counting_files(path):\n file_list = os.listdir(path)\n count = 0\n for i in file_list:\n if os.path.isfile(os.path.join(path,i)):\n count+=1\n print('all count is %d'%count)\n return count\n\n\nallFiles = []\n# get all files on add water path\ndef getALLFiles(path):\n for root,dirs,files in os.walk(picPath):\n return files\n\n# change picture file name to (.png)\ndef rename(path):\n # scan file on path,take file name save to list\n filename_list = os.listdir(path) \n a = 0 \n for i in filename_list:\n used_name = path + filename_list[a]\n strS = filename_list[a].split('.',1)\n new_name = path + strS[0] + '.png'\n os.rename(used_name,new_name)\n a = a + 1\n\n# check phone \ndef saftyCheck(phone):\n res = re.match(r\"^1[35678]\\d{9}$\", phone)\n if res:\n print('-------checked is safty!!!!!!!---------')\n else :\n print('---------------checked is not ok!!!!!Plases check phone.------------------')\n return res\n\n\nif __name__ == '__main__':\n \n if saftyCheck(phone):\n\n print(shopName+','+phone)\n\n picPath = 'C:/Users/sinalma/Desktop/test/'\n count = counting_files(picPath)\n print('all pic is %d'%count)\n curFileN = ''\n rename(picPath)\n allFiles = getALLFiles(picPath)\n firstServoModel = ''\n for x in range(0,count):\n if x==0:\n modelList = allFiles[x].split(\"_\", 1)\n firstServoModel = modelList[0]\n print('first servo model is '+ firstServoModel)\n img = Image.open(u''+picPath + allFiles[x])\n print(allFiles[x])\n img = img.resize((imgW,imgH)) \n # im_after = add_text_to_image(img, u'18124988815')\n # im_after.show()\n # curDelFileName = picPath + allFiles[x]\n # im_after = ''\n if IsFanWM:\n im_after = add_text_to_image(img, shopName)\n im_after.save(u''+picPath+'deal.png')\n im_after = add_text_to_image2(u''+picPath+'deal.png')\n im_after.save(picPath + allFiles[x])\n os.remove(u''+picPath+'deal.png')\n else:\n im_after = add_text_to_image2(u''+picPath + allFiles[x])\n im_after.save(picPath + allFiles[x])\n pyperclip.copy(firstServoModel)\n else:\n print('---------------checked is not ok!!!!!Plases check phone.------------------')\n \n","sub_path":"trs_pic_txt/trspictxt1.0.1.py","file_name":"trspictxt1.0.1.py","file_ext":"py","file_size_in_byte":4661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"77155007","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 6 16:47:21 2020\n\n@author: christian.baillard\n\nFunction made to retrieve data from actinet, parse it and move it to pandas dataframe\n\n\"\"\"\n\nimport requests\nimport pandas as pd\nimport numpy as np\nimport logging\nimport sys\nimport sqlalchemy\nimport psycopg2\nfrom requests.auth import HTTPBasicAuth\nimport html2text\nimport sqlalchemy as sql\nimport json\nfrom pathlib import Path\nimport pathlib\nfrom urllib.parse import urlencode\n\n## Parameters\nurl_base = \"https://preprod-actinet.actimage.com/index.php\"\nusername = \"christian.baillard\"\npassword = \"20?Mericourt\"\nproxies = {\n \"http\": \"http://dumbledore.actimage.int:80\",\n \"https\": \"http://dumbledore.actimage.int:80\"\n}\n\n\nclass Result():\n def __init__(self):\n self.result = []\n\n def get_actinet(self):\n return get_actinet()\n\ndef read_bu_excel(\n excel_file ='C:/Users/christian.baillard/ACTIMAGE CONSULTING SAS/BU Colmar Projects - Reporting 555/PROG/Actimage_team_managers.xlsx'):\n \"\"\"\n \n :param excel_file_path having the matches between aliases and real team names \n :return: dictionnary key values for aliases\n \"\"\"\n excel_file = pathlib.Path(excel_file)\n df = pd.read_excel(excel_file)\n\n bu_dict = {}\n for index, row in df.iterrows():\n key = row['Team name']\n values = row[\"Team aliases\"].split(\";\")\n values = [x.replace(u'\\xa0', u' ').strip() for x in values]\n bu_dict[key] = values\n\n ### Switch key/values\n\n bu_dict = {z: x for x, y in bu_dict.items() for z in y}\n\n return bu_dict\n\ndef read_bu_json(\n json_path=\"C:/Users/christian.baillard/ACTIMAGE CONSULTING SAS/BU Colmar Projects - Reporting 555/PROG/bu_dictionary.json\"):\n \"\"\"\n Function made to read json contqining all terms associated with bu names\n :param json_path: path to the bu json\n :return: dictionary\n \"\"\"\n\n json_file_path = pathlib.Path(json_path)\n\n # Opening JSON file\n with open(json_file_path) as json_file:\n bu_dict = json.load(json_file)\n\n ### Switch key/values\n\n bu_dict = {z: x for x, y in bu_dict.items() for z in y}\n\n return bu_dict\n\n\ndef create_qualification_table(table_name, db_engine):\n \"\"\"\n Function made to create contact table\n :param table_name:\n :param db_engine:\n :return:\n \"\"\"\n meta = sql.MetaData()\n\n table_obj = sql.Table(\n table_name, meta,\n sql.Column('bid_id', sql.Integer),\n sql.Column('update_date', sql.TIMESTAMP(timezone=True)),\n # sql.Column('creation_date', sql.TIMESTAMP(timezone=True)),\n sql.Column('qualified_date', sql.TIMESTAMP(timezone=True)),\n sql.Column('owner_firstname', sql.String),\n sql.Column('owner_lastname', sql.String),\n sql.Column('team_owner', sql.String),\n sql.Column('bid_amount', sql.Float),\n sql.Column('bid_reference', sql.String),\n sql.Column('bid_url', sql.String)\n )\n meta.create_all(db_engine)\n\n return table_obj\n\n\ndef create_sending_table(table_name, db_engine):\n \"\"\"\n Function made to create sending table\n :param table_name:\n :param db_engine:\n :return:\n \"\"\"\n meta = sql.MetaData()\n\n table_obj = sql.Table(\n table_name, meta,\n sql.Column('bid_id', sql.Integer),\n sql.Column('update_date', sql.TIMESTAMP(timezone=True)),\n # sql.Column('creation_date', sql.TIMESTAMP(timezone=True)),\n sql.Column('sent_date', sql.TIMESTAMP(timezone=True)),\n sql.Column('owner_firstname', sql.String),\n sql.Column('owner_lastname', sql.String),\n sql.Column('team_owner', sql.String),\n sql.Column('breakdown', sql.Float),\n sql.Column('bid_amount', sql.Float),\n sql.Column('bid_reference', sql.String),\n sql.Column('bid_url', sql.String)\n )\n meta.create_all(db_engine)\n\n return table_obj\n\n\ndef get_actinet(username, password, proxies=None, url_base=\"https://preprod.actinet.actimage.com/index.php\"):\n \"\"\"\n Function made to retrieve flux from actinet webservice\n \n Parameters\n ----------\n url_base : string\n base URL for actinet\n username : string\n username for basic auth\n password : string\n password for basic auth\n \n Returns\n -------\n resulting json as list\n\n \"\"\"\n url_full = url_base\n querystring = {\"module\": \"business\", \"action\": \"reporting555\"}\n headers = {'accept': 'application/json'}\n response = requests.request(\"GET\", url_full,\n headers=headers, params=querystring, verify=False,\n auth=HTTPBasicAuth(username, password),\n proxies=proxies)\n\n try:\n result = response.json()\n\n except ValueError:\n print(html2text.html2text(response.text))\n result = None\n\n return result\n\n\ndef select_qualifier(qualifiers_list):\n \"\"\"\n Function made to select the qualifier that first qualified the bid\n \"\"\"\n if not qualifiers_list:\n return None\n else:\n oldest_index = np.argmin([pd.Timestamp(x[\"qualified_date\"]) for x in qualifiers_list])\n qualifier = qualifiers_list[oldest_index]\n return qualifier\n\n\ndef clean_senders(bid):\n \"\"\"\n Function made to put winners to true if all winners are false (i.e. box wasn't selected in actinet) so that all bid has at least one winner\n Transform in place\n :param bid: bid dictionary\n :return: updated bid dictionary\n \"\"\"\n\n if not bid[\"sent_by\"]:\n return bid\n\n senders = bid[\"sent_by\"]\n senders = sorted(senders, reverse=True, key=lambda i: float(i['breakdown']))\n winners_booleans = [x[\"winner\"] for x in senders]\n if not any(winners_booleans):\n for sender in senders:\n if float(sender[\"breakdown\"]) >= 30:\n sender[\"winner\"] = True\n\n ### Make sure that at least one winner is set even if all breakdowns < 30\n senders[0][\"winner\"] = True\n\n return bid\n\ndef build_bid_url(bid_id,etape_key=None,bid_url_base=\"https://actinet.actimage.com/index.php\"):\n \"\"\"\n build bid _url from bid_id and etape_key\n :param bid_id: int: id of the bid\n :param etape_key: int, for qualif it's two\n :param bid_url_base:\n :return:\n \"\"\"\n\n param_dict={\"module\":\"business\",\n \"action\":\"adminSuivis\",\n \"business_id\":bid_id,\n \"etape_key\":etape_key}\n\n return bid_url_base +\"?\"+ urlencode(param_dict)\n\n\n\ndef select_senders(bid):\n \"\"\"\n\n :param bid: bid object\n :param senders_list: list of senders in bid object\n :param bid_amount:\n :return: return a dictionnary containing winners senders and winner teams\n \"\"\"\n\n clean_senders(bid)\n senders_list = bid[\"sent_by\"]\n if not senders_list:\n return None\n else:\n ######## Handle owners\n ### Only take owners with winner=True\n winner_owners = [{\"firstname\": x[\"first_name\"], \"lastname\": x[\"last_name\"], \"breakdown\": float(x[\"breakdown\"])}\n for x in\n senders_list if x[\"winner\"] == True]\n\n ### Sort by breakdown from largest to smallest\n winner_owners = sorted(winner_owners, key=lambda i: i['breakdown'], reverse=True)\n\n ######## Handle Teams\n ### List uniques teams\n unique_teams = list(set([x[\"team_name\"] for x in senders_list]))\n\n ### select all teams (not only when winner true)\n winner_teams = []\n for team_name in unique_teams:\n temp_dic = {}\n selection_senders = []\n for sender in senders_list:\n if sender[\"team_name\"] == team_name:\n selection_senders.append(sender)\n total_breakdown = sum([float(x[\"breakdown\"]) for x in selection_senders])\n temp_dic[\"team\"] = team_name\n temp_dic[\"breakdown\"] = total_breakdown\n winner_teams.append(temp_dic)\n\n ### Sort by breakdown\n\n winner_teams = sorted(winner_teams, key=lambda i: i['breakdown'], reverse=True)\n\n ### Make selection on owners based on amount\n\n if bid[\"amount\"] is None:\n bid[\"amount\"] = \"0\"\n\n if float(bid[\"amount\"]) < 10000:\n winner_owners = [winner_owners[0]]\n winner_teams = [winner_teams[0]]\n\n else:\n winner_owners = winner_owners[:3]\n temp_winner_teams = [x for x in winner_teams if x[\"breakdown\"] >= 30]\n if not temp_winner_teams:\n winner_teams = [winner_teams[0]]\n else:\n winner_teams = temp_winner_teams\n\n return {\"winner_owners\": winner_owners, \"winner_teams\": winner_teams}\n\n\n############################################################\n\n\n### Load flux\nbids = get_actinet(username, password, url_base=url_base, proxies=proxies)\n\n# example = [bid for bid in bids if bid[\"id\"] == \"12213\"][0]\n\n########## Build Dataframe from json flux\n\ndata_qualif = []\ndata_send = []\nfor bid in bids:\n qualifier = select_qualifier(bid['qualified_by'])\n senders = select_senders(bid)\n if qualifier is not None:\n row_qualif = {}\n row_qualif[\"owner_lastname\"] = qualifier['last_name'].upper()\n row_qualif[\"owner_firstname\"] = qualifier['first_name'].title()\n row_qualif[\"team_owner\"] = bid[\"qualified_for\"][\"team\"]\n row_qualif[\"qualified_date\"] = pd.Timestamp(qualifier['qualified_date'])\n row_qualif[\"update_date\"] = pd.Timestamp(bid[\"last_date\"])\n row_qualif[\"bid_reference\"] = bid[\"bid_reference\"]\n row_qualif[\"bid_amount\"] = bid[\"amount\"]\n row_qualif[\"bid_id\"] = int(bid[\"id\"])\n row_qualif[\"bid_url\"] = build_bid_url(row_qualif[\"bid_id\"], etape_key=2)\n data_qualif.append(row_qualif)\n\n if senders is not None:\n for owner in senders[\"winner_owners\"]:\n row_send = {}\n row_send[\"owner_lastname\"] = owner[\"lastname\"].upper()\n row_send[\"owner_firstname\"] = owner['firstname'].title()\n row_send[\"breakdown\"] = owner['breakdown']\n row_send[\"sent_date\"] = pd.Timestamp(bid['sent_date'])\n row_send[\"update_date\"] = pd.Timestamp(bid[\"last_date\"])\n row_send[\"bid_reference\"] = bid[\"bid_reference\"]\n row_send[\"bid_amount\"] = bid[\"amount\"]\n row_send[\"bid_id\"] = int(bid[\"id\"])\n row_send[\"bid_url\"] = build_bid_url(row_send[\"bid_id\"])\n data_send.append(row_send)\n for team in senders[\"winner_teams\"]:\n row_send = {}\n row_send[\"team_owner\"] = team[\"team\"].lower()\n row_send[\"breakdown\"] = team[\"breakdown\"]\n row_send[\"sent_date\"] = pd.Timestamp(bid['sent_date'])\n row_send[\"update_date\"] = pd.Timestamp(bid[\"last_date\"])\n row_send[\"bid_reference\"] = bid[\"bid_reference\"]\n row_send[\"bid_amount\"] = bid[\"amount\"]\n row_send[\"bid_id\"] = int(bid[\"id\"])\n row_send[\"bid_url\"] = build_bid_url(row_send[\"bid_id\"])\n data_send.append(row_send)\n\n## Convert to pandas dataframe and save to SQL\n\ndf_qualif = pd.DataFrame(data_qualif)\ndf_send = pd.DataFrame(data_send)\n\n### Format columns properly before integration\n\ndf_qualif[\"team_owner\"] = df_qualif[\"team_owner\"].str.lower()\ndf_send[\"team_owner\"] = df_send[\"team_owner\"].str.lower()\n\n####### Map teams names properly based on bu dictionary\n\ntry:\n dict_bu = read_bu_excel()\n up_keys = df_qualif[\"team_owner\"].append(df_send[\"team_owner\"]).dropna().unique().tolist()\n new_dict = {x: x for x in up_keys if x not in dict_bu.keys()}\n dict_bu.update(new_dict)\n\n df_qualif[\"team_owner\"] = df_qualif[\"team_owner\"].map(dict_bu)\n df_send[\"team_owner\"] = df_send[\"team_owner\"].map(dict_bu)\nexcept Exception as e:\n print(e)\n print(\"Team names left unchanged\")\n pass\n\n####################\n### SQL Parameters\nproxies = {\n \"http\": \"http://dumbledore.actimage.int:80\",\n \"https\": \"http://dumbledore.actimage.int:80\"\n}\npostgre_port = 5432\npostgre_ip = \"localhost\"\npostgre_db_name = \"555\"\npostgre_user = \"postgres\"\npostgre_pwd = \"171286\"\nqualif_table_name = \"qualification\"\nsend_table_name = \"sending\"\ncmd_connection = \"postgresql://%s:%s@%s:%i/%s\" % (postgre_user, postgre_pwd, postgre_ip, postgre_port, postgre_db_name)\n\n######################################\n### Load old_df from existing database\ndb_engine = sql.create_engine(cmd_connection, echo=False)\nconnection = db_engine.connect()\n\n######## For Qualification\n#### Load qualification tables\n\nif db_engine.dialect.has_table(db_engine, qualif_table_name):\n meta = sql.MetaData(bind=connection)\n table_obj = sql.Table(qualif_table_name, meta, autoload=True, autoload_with=db_engine)\n table_obj.drop(bind=connection)\n\n### Recreate and load\n\ncreate_qualification_table(qualif_table_name, db_engine)\ndf_qualif.to_sql(qualif_table_name, connection, index=False, if_exists='append')\n\n######## For Sending\n\nif db_engine.dialect.has_table(db_engine, send_table_name):\n meta = sql.MetaData(bind=connection)\n table_obj = sql.Table(send_table_name, meta, autoload=True, autoload_with=db_engine)\n table_obj.drop(bind=connection)\n\n### Recreate and load\n\ncreate_sending_table(send_table_name, db_engine)\ndf_send.to_sql(send_table_name, connection, index=False, if_exists='append')\n\nconnection.close()\n","sub_path":"actinet_api.py","file_name":"actinet_api.py","file_ext":"py","file_size_in_byte":13323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"224569648","text":"import pinboard\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\nfrom django.utils.timezone import utc\nfrom django.utils.text import slugify\n\nfrom ...models import Blogmark, Tag\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **kwargs):\n\n # Compare the last time we saved a bookmark locally to the latest update\n # pinboard has on the server. This isn't exactly the same since pinboard's\n # update stamp also includes edits and deletions, but I so rarely actually\n # edit/delete bookmarks that I don't really care enough to fix that\n # discrepancy at this time.\n\n latest_blogmark = (\n Blogmark.objects.filter(import_ref__startswith=\"pinboard:\")\n .values(\"created\")\n .latest(\"created\")\n )\n latest_blogmark_timestamp = latest_blogmark[\"created\"]\n pb = pinboard.Pinboard(settings.PINBOARD_API_KEY)\n latest_pinboard_update = pb.posts.update().replace(tzinfo=utc)\n if latest_pinboard_update <= latest_blogmark_timestamp:\n print(f\"no updates since {latest_blogmark_timestamp}\", file=self.stdout)\n return\n\n for bookmark in pb.posts.all(fromdt=latest_blogmark_timestamp, meta=1):\n if not bookmark.shared:\n print(f\"{bookmark.url} is private; skipping\")\n continue\n\n blogmark, created = Blogmark.objects.update_or_create(\n import_ref=f\"pinboard:{bookmark.hash}\",\n defaults={\n \"slug\": slugify(bookmark.description),\n \"link_url\": bookmark.url,\n \"link_title\": bookmark.description,\n \"commentary\": bookmark.extended,\n \"created\": bookmark.time.replace(tzinfo=utc),\n \"metadata\": {\"pinboard_meta\": bookmark.meta},\n },\n )\n blogmark.tags.set(\n Tag.objects.get_or_create(tag=tag)[0] for tag in bookmark.tags\n )\n print(\"created\" if created else \"updated\", blogmark.link_url)\n","sub_path":"blog/management/commands/import_pinboard.py","file_name":"import_pinboard.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"339141177","text":"import pandas as pd\nimport sklearn\nfrom rdkit import rdBase\nimport matplotlib as mpl\nimport numpy as np\nimport seaborn as sns\nimport os\nimport ast\n\n##print('Pandas version:', pd.__version__)\n##print('Scikit-Learn version:', sklearn.__version__)\n##print('Numpy version:', np.__version__)\n##print('MatplotLib version:', mpl.__version__)\n##print('Seaborn version',sns.__version__)\n\ndef FPBitStringConvertToNumpyArray(strFPB, nBits=2048):\n a = np.zeros(nBits)\n try:\n a = np.fromstring(strFPB, 'u1') - ord('0')\n except:\n return None\n ## print(a)\n return a\n\n\ndef FPOccpStringConvertToNumpyArray(strOCCP, nBits=2048):\n print(\"*+++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n ## print(strOCCP)\n print(len(strOCCP))\n print(\"********************************************************\\n\")\n ## a = np.zeros(nBits)\n b = np.zeros(nBits)\n b = strOCCP.split(\",\")\n\n length = len(strOCCP)\n print(length)\n for i in range(length):\n value = eval(strOCCP[i])\n print(value)\n ## value = strOCCP[i]\n if ((value != \" \") | (value != '\\0')):\n\n if i == 0:\n a = np.asarray(value)\n print(a)\n if i > 1:\n b = np.asarray(value)\n a = np.concatenate((a, b))\n ## print(a)\n return a\n\n\ndef OccpStringConvertToNumpyArray(data2, nBits=2048):\n a = None\n for row in data2 :\n value = eval(row)\n b = np.asarray(value)\n if (a == None):\n a = b\n else:\n a = np.row_stack((a, b))\n return a\n\n\ndef OccpSConvertToNumpyArray(data2):\n tmpfile = \"temp/\" + filename + \"_temp.csv\"\n ## print(tmpfile)\n data2.to_csv(tmpfile, sep=' ')\n from numpy import genfromtxt\n data3 = genfromtxt(tmpfile, delimiter=',')\n ## print(data3.shape)\n return data3\n\n\nfilename = \"myFP_CHEMBL217\"\ncurDate = \"01162017\"\nprint(filename)\ninfile = \"input/\" + curDate + \"/\" + filename + \"_train.csv\"\nif not os.path.exists(filename):\n os.makedirs(filename)\noutfile = \"temp/\" + filename + \"_result.txt\"\noutfile1 = \"temp/\" + filename + \"_result1.txt\"\n##data = pd.read_csv('input/ecfp_bit.csv',\ndata1 = pd.read_csv(infile,\n encoding='iso-8859-1',\n na_values=[' '],\n delim_whitespace=True,\n header=1,\n index_col=False,\n names=['target_name', 'smiles', 'fingerprint', 'occp', 'measurement_value', 'measurement_type'])\n[['target_name', 'smiles', 'fingerprint', 'occp', 'measurement_value']]\nminvalue = 0\nmaxvalue = 20000\n\ndataX = OccpStringConvertToNumpyArray(data1['occp'].get_values())\nprint(dataX)\ntmpfile = \"temp/\" + filename + \"_train_occp.csv\"\nnp.savetxt(tmpfile, dataX, delimiter=',') # X is an array\n\ndataY = data1['measurement_value']\nprint(dataY.shape)\ntmpfile = \"temp/\" + filename + \"_train_value.csv\"\nnp.savetxt(tmpfile, dataY, delimiter=',') # X is an array\n\nsns.violinplot(dataY, cut=0, scale=\"count\", inner=\"quartile\")\n##sns.violinplot(testSet['measurement_value'])\n##print(trainSet['FP'].head())\nimport matplotlib.pyplot as pyplot\n\nfigure, (ax1, ax2, ax3) = pyplot.subplots(1, 3)\nfigure.set_size_inches(15, 15)\n# simple linear regression\nfrom sklearn import linear_model\n\nsimple_linearreg = linear_model.LinearRegression(normalize=True)\n##simple_linearreg.fit(trainSet['FP'].tolist(),trainSet['measurement_value'])\nsimple_linearreg.fit(dataX.tolist(), dataY)\nsimple_prediction = simple_linearreg.predict(dataX)\nax1.scatter(dataY, simple_prediction)\nax1.set_aspect('equal')\nax1.set_title('Simple linear regression')\nax1.set_xlabel('Measured value')\nax1.set_ylabel('Predicted value')\nax1.set_xlim(0, maxvalue)\nax1.set_ylim(0, maxvalue)\n\n# simple decision tree regression\nfrom sklearn import tree\n\nsimple_tree = tree.DecisionTreeRegressor()\nsimple_tree.fit(dataX, dataY)\nsimple_treeprediction = simple_tree.predict(dataX)\nax2.scatter(dataY, simple_treeprediction)\nax2.set_aspect('equal')\nax2.set_title('Default Decision Tree')\nax2.set_xlabel('Measured value')\nax2.set_ylabel('Predicted value')\nax2.set_xlim(0, maxvalue)\nax2.set_ylim(0, maxvalue)\n##outfile = tree.export_graphviz(simple_tree, out_file='simple_tree.dot', feature_names=trainSet['FP'].name)\n##outfile.close()\n# custom decision tree regression\nfrom sklearn import tree\n\ncustom_tree = tree.DecisionTreeRegressor(max_depth=10, min_samples_split=10)\ncustom_tree.fit(dataX, dataY)\ncustom_treeprediction = custom_tree.predict(dataX)\nax3.scatter(dataY, custom_treeprediction)\nax3.set_aspect('equal')\nax3.set_title('Custom Decision Tree (regularized)')\nax3.set_xlabel('Measured value')\nax3.set_ylabel('Predicted value')\nax3.set_xlim(0, maxvalue)\nax3.set_ylim(0, maxvalue)\n##thefile = open(outfile, 'w')\n##pyplot.show()\nprint(\"____________________________________\")\nmsq = zip(dataY, simple_treeprediction)\n##print(msq)\nprint(\"+++++++++++++++++++++++++++++++++++++++++\")\nfrom sklearn.metrics import mean_squared_error\n\nprint('Coefficient of determination R^2 (LR): ', simple_linearreg.score(dataX, dataY))\nprint('MSE (LR): ', (mean_squared_error(dataY, simple_prediction)))\nprint('Coefficient of determination R^2 (Default Tree): ', (simple_tree.score(dataX, dataY)))\nprint('MSE (Default Tree): ', (mean_squared_error(dataY, simple_treeprediction)))\nprint('Coefficient of determination R^2 (Custom Tree): ', (custom_tree.score(dataX, dataY)))\nprint('MSE (Custom Tree): ', (mean_squared_error(dataY, custom_treeprediction)))\nthefile = open(outfile1, 'a')\nthefile.write('Coefficient of determination R^2 (LR): ')\nscore = simple_linearreg.score(dataX, dataY)\nthefile.write(str(score))\nthefile.write('\\nMSE (LR): ')\nMSE = mean_squared_error(dataY, simple_prediction)\nthefile.write(str(MSE))\nthefile.write('\\nCoefficient of determination R^2 (Default Tree): ')\nscore = simple_tree.score(dataX, dataY)\nthefile.write(str(score))\nthefile.write('\\nMSE (Default Tree): ')\nMSE = mean_squared_error(dataY, simple_treeprediction)\nthefile.write(str(MSE))\nthefile.write('\\nCoefficient of determination R^2 (Custom Tree): ')\nscore = custom_tree.score(dataX, dataY)\nthefile.write(str(score))\nthefile.write('\\nMSE (Custom Tree): ')\nMSE = mean_squared_error(dataY, custom_treeprediction)\nthefile.write(str(MSE))\nthefile.close()\n\n\n##compare prediction\n##trainmsq = zip(trainSet['measurement_value'],simple_treeprediction)\n##thefile = open(outfile1, 'a')\n##for line1 in trainmsq:\n## thefile.write(str(line1))\n## thefile.write(\"\\n\")\n##\n##thefile.close()\n\n# print zip(simple_prediction,custom_prediction)\ndef createImportancePlot(splt, desc, importances, caption, flg=0):\n labels = []\n weights = []\n index = 0\n ## w = sorted(importances)\n ## print(w)\n ## threshold = sort([abs(w) for w in importances])[max(-11,-(len(importances)))]\n threshold = sorted([abs(w) for w in importances])[max(-10, -(len(importances)))]\n print(threshold)\n\n index = -1\n for d in zip(desc, importances):\n index += 1\n if abs(d[1]) >= threshold:\n labels.append(index)\n ## labels.append(d[0])\n weights.append(d[1])\n ## print(index)\n xlocations = np.array(range(len(labels))) + 0.5\n width = 0.8\n splt.bar(xlocations, weights, width=width)\n splt.set_xticks([r + 1 for r in range(len(labels))])\n splt.set_xticklabels(labels, rotation=30, )\n splt.set_xlim(0, xlocations[-1] + width * 2)\n splt.set_title(caption)\n splt.get_xaxis().tick_bottom()\n splt.get_yaxis().tick_left()\n ## print(labels[:10])\n ## labellist = sorted(labels)\n if (flg == 1):\n thefile = open(outfile, 'w')\n thefile.write(\" \".join(str(x) for x in labels[:10]))\n thefile.write(\" \".join(str(x) for x in weights[:10]))\n thefile.close()\n print(\"--------------------------------------------------------------------\")\n\n\nfigure, (plt1, plt2, plt3) = pyplot.subplots(3, 1)\nfigure.set_size_inches(15, 10)\nfigure.subplots_adjust(hspace=0.5)\nimp = simple_linearreg.coef_\nprint(\"+++++++++++++++++++++++++++++++++++++++++++++++\")\n\ncreateImportancePlot(plt1, dataX, imp, \"Most important descriptors in linear model (coefficients)\")\nimp2 = simple_tree.feature_importances_ # Gini importances\nprint(imp2)\nprint(imp2.shape)\ncreateImportancePlot(plt2, dataX, imp2, \"Most important descriptors in simple tree model (Gini importances)\")\nimp3 = custom_tree.feature_importances_ # Gini importances\ncreateImportancePlot(plt3, dataX, imp3, \"Most important descriptors in custom tree model (Gini importances)\")\n##pyplot.show()\n\n# save learn result\nfrom sklearn.externals import joblib\n\njoblib.dump(simple_linearreg, filename + '/FP_linearreg.pkl')\njoblib.dump(simple_tree, filename + '/FP_tree.pkl')\njoblib.dump(custom_tree, filename + '/FP_custom_tree.pkl')\n\nprint(\"=======================test===================\")\n\ninfile = \"input/\" + curDate + \"/\" + filename + \"_test.csv\"\nif not os.path.exists(filename):\n os.makedirs(filename)\noutfile = \"temp/\" + filename + \"_result.txt\"\noutfile1 = \"temp/\" + filename + \"_result1.txt\"\n\ndata1 = pd.read_csv(infile,\n encoding='iso-8859-1',\n na_values=[' '],\n delim_whitespace=True,\n header=1,\n names=['target_name', 'smiles', 'fingerprint', 'occp', 'measurement_value', 'measurement_type'])\n[['target_name', 'smiles', 'fingerprint', 'occp', 'measurement_value']]\ndata2 = data1['occp']\nprint(data2.shape)\ntmpfile = \"temp/\" + filename + \"_temp.csv\"\nprint(tmpfile)\ndata2.to_csv(tmpfile, sep=' ', index=False)\nfrom numpy import genfromtxt\n\ntestX = genfromtxt(tmpfile, delimiter=',')\nprint(testX)\ntmpfile = \"temp/\" + filename + \"_test_occp.csv\"\nnp.savetxt(tmpfile, testX, delimiter=',') # X is an array\ntestY = data1['measurement_value']\nprint(testY.shape)\ntmpfile = \"temp/\" + filename + \"_test_value.csv\"\nnp.savetxt(tmpfile, testY, delimiter=',') # X is an array\n\n##print(trainSet['FP'].head())\nimport matplotlib.pyplot as pyplot\n\nfigure, (ax1, ax2, ax3) = pyplot.subplots(1, 3)\nfigure.set_size_inches(15, 15)\n# simple linear regression\nfrom sklearn import linear_model\n\nsimple_ext_prediction = simple_linearreg.predict(testX)\nax1.scatter(testY, simple_ext_prediction)\nax1.set_aspect('equal')\nax1.set_title('Simple linear regression')\nax1.set_xlabel('Measured value')\nax1.set_ylabel('Predicted value')\nax1.set_xlim(0, maxvalue)\nax1.set_ylim(0, maxvalue)\n\n# simple decision tree regression\nfrom sklearn import tree\n\nsimple_ext_treeprediction = simple_tree.predict(testX)\nax2.scatter(testY, simple_ext_treeprediction)\nax2.set_aspect('equal')\nax2.set_title('Default Decision Tree')\nax2.set_xlabel('Measured value')\nax2.set_ylabel('Predicted value')\nax2.set_xlim(0, maxvalue)\nax2.set_ylim(0, maxvalue)\n##outfile = tree.export_graphviz(simple_tree, out_file='simple_tree.dot', feature_names=trainSet['FP'].name)\n##outfile.close()\n# custom decision tree regression\nfrom sklearn import tree\n\ncustom_ext_treeprediction = custom_tree.predict(testX)\nax3.scatter(testY, custom_ext_treeprediction)\nax3.set_aspect('equal')\nax3.set_title('Custom Decision Tree (regularized)')\nax3.set_xlabel('Measured value')\nax3.set_ylabel('Predicted value')\nax3.set_xlim(0, maxvalue)\nax3.set_ylim(0, maxvalue)\n##thefile = open(outfile, 'w')\n##pyplot.show()\n\nprint(\"+++++++++++++++++TEST+++++++++++++++++++++++\")\nfrom sklearn.metrics import mean_squared_error\n\nprint('Coefficient of determination R^2 (LR): ', simple_linearreg.score(testX, testY))\nprint('MSE (LR): ', (mean_squared_error(testY, simple_ext_prediction)))\nprint('Coefficient of determination R^2 (Default Tree): ', (simple_tree.score(testX, testY)))\nprint('MSE (Default Tree): ', (mean_squared_error(testY, simple_ext_treeprediction)))\nprint('Coefficient of determination R^2 (Custom Tree): ', (custom_tree.score(testX, testY)))\nprint('MSE (Custom Tree): ', (mean_squared_error(testY, custom_ext_treeprediction)))\n##compare prediction\n##msq = zip(testSet['measurement_value'],simple_treeprediction)\n##thefile = open(outfile1, 'a')\n##for line1 in msq:\n## thefile.write(str(line1))\n## thefile.write(\"\\n\")\n##\n##thefile.close()\nthefile = open(outfile1, 'a')\nthefile.write(\"\\n+++++++++++++++++TEST+++++++++++++++++++++++\\n\")\n\nthefile.write('Coefficient of determination R^2 (LR): ')\nscore = simple_linearreg.score(testX, testY)\nthefile.write(str(score))\nthefile.write('\\nMSE (LR): ')\nMSE = mean_squared_error(testY, simple_ext_prediction)\nthefile.write(str(MSE))\nthefile.write('\\nCoefficient of determination R^2 (Default Tree): ')\nscore = simple_tree.score(testX, testY)\nthefile.write(str(score))\nthefile.write('\\nMSE (Default Tree): ')\nMSE = mean_squared_error(testY, simple_ext_treeprediction)\nthefile.write(str(MSE))\nthefile.write('\\nCoefficient of determination R^2 (Custom Tree): ')\nscore = custom_tree.score(testX, testY)\nthefile.write(str(score))\nthefile.write('\\nMSE (Custom Tree): ')\nMSE = mean_squared_error(testY, custom_ext_treeprediction)\nthefile.write(str(MSE))\nthefile.close()\n\nprint(\"+++++++++++++++++++++++best parameter+++++++++++++++++++++++++++\")\n\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import GridSearchCV\n\nparams = {'max_depth': [2, 5, 10, 20], 'min_samples_split': [2, 8, 32, 128], 'min_samples_leaf': [1, 2, 5, 10]}\ncv = KFold(n_splits=10, shuffle=True)\ngs = GridSearchCV(simple_tree, params, cv=cv, verbose=1, refit=True)\ngs.fit(dataX, dataY)\nprint('Best score: ', gs.best_score_)\nprint('Training set performance using best parameters ', gs.best_params_)\nbest_treemodel = gs.best_estimator_\nfigure, (plt1, plt2) = pyplot.subplots(1, 2)\nfigure.set_size_inches(15, 15)\n# training set evaluation\nbest_tree_int_prediction = best_treemodel.predict(dataX)\nplt1.scatter(dataY, best_tree_int_prediction)\nplt1.set_aspect('equal')\nplt1.set_title('Optimized tree on training set')\nplt1.set_xlabel('Measured value')\nplt1.set_ylabel('Predicted value')\nplt1.set_xlim(0, maxvalue)\nplt1.set_ylim(0, maxvalue)\n\n# test set evaluation\nbest_tree_ext_prediction = best_treemodel.predict(testX)\nplt2.scatter(testY, best_tree_ext_prediction)\nplt2.set_aspect('equal')\nplt2.set_title('Optimized tree on test set')\nplt2.set_xlabel('Measured value')\nplt2.set_ylabel('Predicted value')\nplt2.set_xlim(0, maxvalue)\nplt2.set_ylim(0, maxvalue)\n\nprint('Coefficient of determination R^2 (Internal): ', (best_treemodel.score(dataX, dataY)))\nprint('MSE (Internal): ', (mean_squared_error(dataY, best_tree_int_prediction)))\nprint('Coefficient of determination R^2 (External): ', (best_treemodel.score(testX, testY)))\nprint('MSE (External): ', (mean_squared_error(testY, best_tree_ext_prediction)))\n\nthefile = open(outfile1, 'a')\nthefile.write(\"\\n+++++++++++++++++Best TEST+++++++++++++++++++++++\\n\")\n\nthefile.write('Coefficient of determination R^2 (Internal): ')\nscore = best_treemodel.score(dataX, dataY)\nthefile.write(str(score))\nthefile.write('\\nMSE (Internal): ')\nMSE = mean_squared_error(dataY, best_tree_int_prediction)\nthefile.write(str(MSE))\nthefile.write('\\nCoefficient of determination R^2 (External): ')\nscore = best_treemodel.score(testX, testY)\nthefile.write(str(score))\nthefile.write('\\nMSE (External): ')\nMSE = mean_squared_error(testY, best_tree_ext_prediction)\nthefile.write(str(MSE))\nthefile.close()\n##compare prediction\n\nbest_tree = zip(testY, best_tree_ext_prediction)\nthefile = open(outfile1, 'a')\nfor line1 in best_tree:\n thefile.write(str(line1))\n thefile.write(\"\\n\")\n\nthefile.close()\n\nfig, a = pyplot.subplots(1, 1)\nfig.set_size_inches(15, 5)\ncreateImportancePlot(a, dataX, best_treemodel.feature_importances_, \"Most important descriptors in the optimized tree\", 1)\npyplot.show()\nprint(\"finished\")\n","sub_path":"try116_217_fl_FP-Discrip-Regress.py","file_name":"try116_217_fl_FP-Discrip-Regress.py","file_ext":"py","file_size_in_byte":15682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"585797839","text":"from odoo import fields, models,api\n\n\nclass CustomMessageWizard(models.TransientModel):\n _name = 'message.wizard'\n\n def get_default(self):\n if self.env.context.get(\"message\", False):\n return self.env.context.get(\"message\")\n return False\n\n message = fields.Text(readonly=True, default=get_default)\n\n\n\n\n\n","sub_path":"wizard/message_wizard.py","file_name":"message_wizard.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"124433798","text":"from django.views import generic\nfrom django.contrib.auth.models import User\nfrom django.views.generic import UpdateView, DetailView, ListView\nfrom django.contrib.auth import login, authenticate\nfrom django.shortcuts import render, redirect\n\n# External Models\nfrom posts.models import Post\n\n# Internal Models\nfrom .models import Connection, UserProfile\n\n#Forms\nfrom .forms import UserForm, UserProfileForm\n\nclass UserProfileDetailView(generic.DetailView):\n model = User\n slug_field = 'username'\n template_name = 'perfil/perfil.html'\n context_object_name = 'usr'\n\n def get_context_data(self, **kwargs):\n context = super(UserProfileDetailView, self).get_context_data(**kwargs)\n context['posts'] = Post.objects.filter(user=self.get_object())\n context['follower'] = Connection.objects.filter(follower=self.get_object())\n context['following'] = Connection.objects.filter(following=self.get_object())\n return context\n\nclass FollowingDetailView(generic.DetailView):\n model = User\n slug_field = 'username'\n template_name = 'connection/profile_following.html'\n\n def following(self):\n return Connection.objects.filter(following=self.get_object())\n\nclass FollowerDetailView(generic.DetailView):\n model = User\n slug_field = 'username'\n template_name = 'connection/profile_follower.html'\n\n def followers(self):\n return Connection.objects.filter(follower=self.get_object())\n\nclass UserProfileUpdateView(generic.UpdateView):\n model = User\n second_model = UserProfile\n slug_field = 'username'\n form_class = UserForm\n second_form_class = UserProfileForm\n template_name = 'perfil/profile_edit.html'","sub_path":"userprofile/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"26035787","text":"'''\nCreated on 2 déc. 2014\n\n@author: inso\n'''\nimport re\nimport base64\nimport logging\n\nfrom . import Document\n\n\nclass SelfCertification(Document):\n '''\n A document discribing a self certification.\n '''\n\n re_inline = re.compile(\"([1-9A-Za-z][^OIl]{42,45}):([A-Za-z0-9+/]+(?:=|==)?):([0-9]+):([^\\n]+)\\n\")\n re_uid = re.compile(\"UID:([^\\n]+)\\n\")\n re_timestamp = re.compile(\"META:TS:([0-9]+)\\n\")\n\n def __init__(self, version, currency, pubkey, ts, uid, signature):\n if signature:\n super().__init__(version, currency, [signature])\n else:\n super().__init__(version, currency, [])\n self.pubkey = pubkey\n self.timestamp = ts\n self.uid = uid\n\n @classmethod\n def from_inline(cls, version, currency, inline):\n selfcert_data = SelfCertification.re_inline.match(inline)\n pubkey = selfcert_data.group(1)\n signature = selfcert_data.group(2)\n ts = int(selfcert_data.group(3))\n uid = selfcert_data.group(4)\n return cls(version, currency, pubkey, ts, uid, signature)\n\n def raw(self):\n return \"\"\"UID:{0}\nMETA:TS:{1}\n\"\"\".format(self.uid, self.timestamp)\n\n def inline(self):\n return \"{0}:{1}:{2}:{3}\".format(self.pubkey, self.signatures[0],\n self.timestamp, self.uid)\n\n\nclass Certification(Document):\n '''\n A document describing a certification.\n '''\n\n re_inline = re.compile(\"([1-9A-Za-z][^OIl]{42,45}):\\\n([1-9A-Za-z][^OIl]{42,45}):([0-9]+):([A-Za-z0-9+/]+(?:=|==)?)\\n\")\n re_timestamp = re.compile(\"META:TS:([0-9]+)-([0-9a-fA-F]{5,40})\\n\")\n\n def __init__(self, version, currency, pubkey_from, pubkey_to,\n blocknumber, blockhash, signature):\n '''\n Constructor\n '''\n super().__init__(version, currency, [signature])\n self.pubkey_from = pubkey_from\n self.pubkey_to = pubkey_to\n self.blockhash = blockhash\n self.blocknumber = blocknumber\n\n @classmethod\n def from_inline(cls, version, currency, blockhash, inline):\n cert_data = Certification.re_inline.match(inline)\n pubkey_from = cert_data.group(1)\n pubkey_to = cert_data.group(2)\n blocknumber = int(cert_data.group(3))\n if blocknumber == 0:\n blockhash = \"DA39A3EE5E6B4B0D3255BFEF95601890AFD80709\"\n signature = cert_data.group(4)\n return cls(version, currency, pubkey_from, pubkey_to,\n blockhash, blocknumber, signature)\n\n def raw(self, selfcert):\n return \"\"\"{0}META:TS:{1}-{2}\n\"\"\".format(selfcert.signed_raw(), self.blocknumber, self.blockhash)\n\n\n def sign(self, selfcert, keys):\n '''\n Sign the current document.\n Warning : current signatures will be replaced with the new ones.\n '''\n self.signatures = []\n for key in keys:\n signing = base64.b64encode(key.signature(bytes(self.raw(selfcert), 'ascii')))\n logging.debug(\"Signature : \\n{0}\".format(signing.decode(\"ascii\")))\n self.signatures.append(signing.decode(\"ascii\"))\n\n def signed_raw(self, selfcert):\n raw = self.raw(selfcert)\n signed = \"\\n\".join(self.signatures)\n signed_raw = raw + signed + \"\\n\"\n return signed_raw\n\n def inline(self):\n return \"{0}:{1}:{2}:{3}\".format(self.pubkey_from, self.pubkey_to,\n self.blocknumber, self.signatures[0])\n\n\nclass Revocation(Document):\n '''\n A document describing a self-revocation.\n '''\n def __init__(self, version, currency, signature):\n '''\n Constructor\n '''\n super().__init__(version, currency, [signature])\n\n def raw(self, selfcert):\n return \"\"\"{0}META:REVOKE\n\"\"\".format(selfcert.signed_raw())\n\n def sign(self, selfcert, keys):\n '''\n Sign the current document.\n Warning : current signatures will be replaced with the new ones.\n '''\n self.signatures = []\n for key in keys:\n signing = base64.b64encode(key.signature(bytes(self.raw(selfcert), 'ascii')))\n self.signatures.append(signing.decode(\"ascii\"))\n\n","sub_path":"lib/ucoinpy/documents/certification.py","file_name":"certification.py","file_ext":"py","file_size_in_byte":4162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"61639175","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\n####\n# File: delete.py\n# Project: py\n#-----\n# Created Date: Friday 09.08.2019, 11:28\n# Author: rbald\n#-----\n# Last Modified: Friday 09.08.2019, 13:57\n#-----\n# Copyright (c) 2019 rbald\n# This software is published under the MIT license.\n# Check http://www.opensource.org/licenses/MIT for further informations\n#-----\n# Description: Delete a file given by argv\n####\n\nfrom sys import argv\nimport os\n\nif argv[1] == \"del\" and argv[2] != \"\" and os.path.isfile(argv[2]) and argv[2].endswith(\".php\"):\n directory = os.path.dirname(argv[2])\n directory_content = len(os.listdir(directory))\n try:\n os.remove(argv[2])\n if len(os.listdir(directory)) == directory_content-1:\n print('
    Datei erfolgreich entfernt
    ')\n elif len(os.listdir(directory)) == directory_content:\n print('
    Datei konnte nicht entfernt werden
    ')\n elif len(os.listdir(directory)) < directory_content-1:\n print('
    Es wurden mehr Dateien entfernt als erwartet
    ')\n else:\n print('
    SYSTEM: Ein unbekannter Fehler ist aufgetreten
    ')\n except:\n print('
    SYSTEM: Ein schwerwiegender Fehler ist aufgetreten
    ')\n\n ","sub_path":"PHP/002_Lernkarten/py/delete.py","file_name":"delete.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"27459305","text":"import urllib.request\nimport urllib.parse\n\n\ndef wirteFile(html,filename):\n print(\"正在写入\" + filename)\n filename = \"write/\"+filename\n with open(filename,\"wb\") as f:\n f.write(html)\n print(\"--\" * 20)\n\n\ndef loadPage(fullUrl,filename):\n print(\"正在下载\" + filename)\n headers = {\"User-Agent\": \"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;\"}\n req = urllib.request.Request(fullUrl,headers=headers)\n res = urllib.request.urlopen(req)\n return res.read()\n\n\ndef tiebaSpider(url, beginPage, endPage):\n for page in range(beginPage, endPage +1):\n pn = (page - 1) * 50\n filename = \"第\" + str(page) + \"页.html\"\n fullUrl = url + \"&pn=\" + str(pn)\n html = loadPage(fullUrl, filename)\n # print(html)\n wirteFile(html,filename)\n\n\nif __name__ == '__main__':\n\n kw = input(\"请输入贴吧名:\")\n beginPage = int(input(\"请输入开始页:\"))\n endPage = int(input(\"请输入结束页:\"))\n\n url = \"http://tieba.baidu.com/f?\"\n key = urllib.parse.urlencode({\"kw\": kw})\n url += key\n print(url)\n tiebaSpider(url, beginPage, endPage)\n\n\n","sub_path":"第01阶段/第7章 爬虫/第1节 Python爬虫基础类库/index7.py","file_name":"index7.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"364472931","text":"from django.conf.urls import url\r\nfrom student.views import *\r\n\r\nurlpatterns = [\r\n url(r'^home/$',home),\r\n url(r'^add/$',add),\r\n url(r'^edit/(?P[0-9]+)/$', edit),\r\n url(r'^delete/(?P[0-9]+)/$', delete),\r\n url(r'^getStudents/$',getStudents),\r\n\r\n]","sub_path":"student/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"433692443","text":"import turicreate\nimport numpy as np\n\ndata = turicreate.SFrame('people_wiki.sframe')\nprint(data.column_names())\n\nprint(np.argwhere(data['name'] == 'Barack Obama'))\ndata['tfidf'] = turicreate.text_analytics.tf_idf(data['text'])\nobama = data[data['name'] == 'Barack Obama']\nclooney = data[data['name'] == 'George Clooney']\nturicreate.distances.cosine(obama['tfidf'][0], clooney['tfidf'][0])\n\nprint(clooney.stack('tfidf',new_column_name=['word','tfs']).sort('tfs',ascending=False))\n\n# model\nmodel_test = turicreate.nearest_neighbor_classifier(data,features=['tfidf'],target='name')\n# neighbor\nknn_model = turicreate.nearest_neighbors.create(data,features=['tfidf'],label='name')\n\n'''\nnote the difference!\n'''\n\nmodel_test.summary()\n\njolie = data[data['name'] == 'Angelina Jolie']\nprint(model_test.query(jolie))\nturicreate.distances.cosine(jolie['tfidf'][0], clooney['tfidf'][0])\n\n#cosine distance 0-1, the larger the more different.","sub_path":"case_study/people_similarity/fnd04.py","file_name":"fnd04.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"128702387","text":"\n\n# Laura Nuñez - CS 241 - BYU -Idaho \n# Week 2 \n# W02 Prepare: Checkpoint B\n# Task: Demonstrate file reading\n# Purpose:Correctly use files and functions to solve problems.\n\n\ndef get():\n \n file = input(\"Enter file: \")\n return file\n#hola\ndef read(file):\n \n file_read = open(file, \"r\")\n \n count_line = 0 \n count_word = 0\n \n for line in file_read:\n \n count_line += 1\n words = line.split() \n count_word += len(words)\n \n file_read.close()\n \n return (count_word, count_line)\n\n\ndef main():\n \n file = get()\n \n (count_word, count_line) = read(file)\n print(\"The file contains %d lines and %d words.\" %(count_line, count_word))\n\nif __name__ == \"__main__\":\n main()","sub_path":"week 2/W2-CheckpointB.py","file_name":"W2-CheckpointB.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"140799914","text":"import os\nfrom calibration_biplane import DicomData\nfrom segment_vessel_image import predict_image, save_prediction, load_prediction\nfrom epipolar_projection import projected_epipolar_line\nfrom render_epipolar_geometry import render\n\nfolder=os.getenv('HOME')+'/workspace/BVR/resource/Data/P2PGS/DCM/'\nfilepath1=folder+'I0000003'\nfilepath2=folder+'I0000004'\nData1=DicomData(filepath1)\nData2=DicomData(filepath2)\nData1.compute_transform_matrix()\nData2.compute_transform_matrix()\n\n# object segmentation\nprediction = 0\nif prediction == 1:\n from keras.models import Model, load_model\n model_path = './../whole_model.h5'\n model = load_model(model_path)\n Predict_images1=predict_image(Data1.images, model)\n Predict_images2=predict_image(Data2.images, model)\n save_prediction(Predict_images1, filepath1)\n save_prediction(Predict_images2, filepath2)\nelse:\n Predict_images1=load_prediction(filepath1)\n Predict_images2=load_prediction(filepath2)\n\n# extract center lines\n\n# reconstruction\ntarget_point = [120, 112]\nrender(Data1, Data2, target_point)","sub_path":"src/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"471578395","text":"import os\nimport re\nimport sys\nimport yaml\nimport argparse, pathlib\n\nfrom typology import Concept\nfrom boltons.iterutils import remap\nfrom syntrans.utils import ordered_load\nfrom syntrans.utils import ordered_dump\n\n\ndef concept(concept_id, refresh=False, folder='.concept'):\n '''\n Since we only use concept's aliases, save them to files in .concept folder.\n '''\n\n def save(concept_id, folder='.concept'):\n '''\n upserts concept to local database at folder\n '''\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n try:\n _concept = Concept(concept_id)\n except:\n raise Warning('Could not retrieve concept.')\n _concept.aliases['__id__'] = _concept.id\n _concept.aliases['__url__'] = _concept.url\n with open('{}/{}'.format(folder, concept_id), 'w') as f:\n f.write(yaml.dump(_concept.aliases, allow_unicode=True, default_flow_style=False))\n\n if not os.path.exists('{}/{}'.format('.concept', concept_id)) or refresh:\n save(concept_id)\n print('GET: ', concept_id)\n\n item = yaml.load(open('{}/{}'.format(folder, concept_id), 'r').read(), Loader=yaml.Loader)\n return item\n\ndef conceptualize(string):\n '''\n Sentence is a list of concepts start and end symbols.\n '''\n def split_words(s):\n return re.split(', |,| ,| ', s)\n\n concept_list = []\n\n for word in split_words(string):\n _concept = concept(word)\n concept_list.append(_concept)\n\n return concept_list\n\ndef represent(meaning, lang):\n '''\n Represent the meaning in target language.\n '''\n representations = []\n for _concept in meaning:\n name = _concept.get(lang)\n if name is not None:\n if isinstance(name, list):\n name = name[0]\n name = '{}'.format(name)\n else:\n name = _concept['__id__']\n\n representations.append(name)\n\n return ' • '.join(representations)\n\ndef translate(data, lang):\n '''\n Go over strings in data structure, and represent them in language of choice.\n '''\n\n def visit(path, key, value):\n if isinstance(key, str):\n key_meaning = conceptualize(key)\n key = represent(key_meaning, lang)\n if isinstance(value, str):\n value_meaning = conceptualize(value)\n value = represent(value_meaning, lang)\n return key, value\n\n remapped = remap(data, visit=visit)\n return remapped\n\n\ndef main():\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-s', '--source', help='Source text file to parse.')\n parser.add_argument('-l', '--language', help='Language reference, e.g., en, lt, ja, ru, cn.')\n parser.add_argument('-r', '--refresh', help='Pass non-null to refresh.')\n args = parser.parse_args()\n\n CWD = pathlib.Path(os.getcwd())\n LANGUAGE = args.language or 'en'\n CONCEPT = args.refresh\n\n SOURCE = args.source\n if args.source:\n s = pathlib.Path(SOURCE)\n if s.expanduser() == s and not str(s).startswith(s._flavour.sep):\n s = pathlib.Path(os.path.join(CWD, s))\n SOURCE = s\n\n if CONCEPT:\n concept(CONCEPT, refresh=True)\n print('Done.')\n\n elif SOURCE:\n data = ordered_load(open(SOURCE, 'r'), yaml.SafeLoader)\n translation = translate(data, LANGUAGE)\n\n print(\n ordered_dump(\n translation, allow_unicode=True, default_flow_style=False, Dumper=yaml.SafeDumper))\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"syntrans/trans.py","file_name":"trans.py","file_ext":"py","file_size_in_byte":3540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"584794653","text":"from django import forms\nfrom django.conf import settings\nfrom django.utils.safestring import mark_safe\n\n\nclass GmapsSelectAutocomplete(forms.TextInput):\n#class GmapsSelectAutocomplete(forms.Select):\n\n def __init__(self, attrs=None, plugin_options={}, select2_options={},\n language_code=settings.GMAPS_LANGUAGE_CODE):\n super(GmapsSelectAutocomplete, self).__init__(attrs)\n self.plugin_options = plugin_options\n self.select2_options = select2_options\n self.language_code = language_code\n self.Media.js = (\n 'https://maps.googleapis.com/maps/api/js?v=3.24&key={}&language={}'.format(\n settings.GMAPS_API_KEY, self.language_code\n ),) + self.Media.js\n\n def render(self, name, value, attrs=None):\n res = super(GmapsSelectAutocomplete, self).render(name, value, attrs)\n tmp_id = attrs['id'].replace(self.plugin_options['gmaps_field_name'], '')\n\n if 'geocode_field' in self.plugin_options:\n self.plugin_options['geocodeid'] = '{}{}'.format(\n tmp_id, self.plugin_options['geocode_field'])\n\n if 'type_field' in self.plugin_options:\n self.plugin_options['typeid'] = '{}{}'.format(\n tmp_id, self.plugin_options['type_field'])\n\n opts = \"\"\n if self.plugin_options:\n for k, v in self.plugin_options.items():\n if k not in ['geocode_field', 'type_field']:\n opts += u' data-plugin_{}=\"{}\"'.format(k, v)\n if self.select2_options:\n for k, v in self.select2_options.items():\n opts += u' data-select2_{}=\"{}\"'.format(k, v)\n\n res = mark_safe(\n u\"\"\"\n {}\n
    \n \"\"\".\n format(\n res,\n attrs['id'],\n self.language_code,\n settings.GMAPS_API_KEY,\n opts\n )\n )\n return res\n\n class Media:\n js = (\n settings.JQUERY_LIB,\n settings.SELECT2_LIB,\n u'{}gmapsmarkers/js/gmaps.js'.format(settings.STATIC_URL),\n u'{}gmapsmarkers/js/gmaps__init.js'.format(settings.STATIC_URL),\n )\n css = {u\"all\": (\n settings.SELECT2_CSS_LIB,\n u\"{}gmapsmarkers/css/gmaps.css\".format(settings.STATIC_URL),\n )}\n\n\nclass GeotypeSelect(forms.Select):\n\n def render(self, name, value, attrs=None, choices=()):\n if value:\n choices = list(choices)\n choices.append((value, value))\n return super(GeotypeSelect, self).render(name, value, attrs, choices)\n","sub_path":"gmapsmarkers/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":2748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"144263100","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\n\"\"\"Top-level package for Country Call Code Finder.\"\"\"\r\n\r\n# from sys import argv\r\nimport argparse\r\n\r\n# import the module containing all the country data.\r\n# Country data not put together within this file for purposes of avoiding clutter\r\n\r\n# sys.path.append(os.path.join(os.path.dirname(__file__), '.'))\r\nfrom typing import Dict, Any, Union\r\n\r\nfrom .country_data import country_calling_code\r\n\r\n# from countryData import CountryCallingCode\r\n\r\n# Details about the author. It'll be a shame to write a module and ship it without\r\n# putting down digital signature.\r\n\r\nTTY = False\r\nDATA: Dict[Union[str, Any], Union[str, Any]] = country_calling_code\r\n\r\n# This for loop is for inverting my original country data\r\n# so it can be used for checking a phone code for an unknown selected_country\r\n# country = {value:key for key, value in calling_code.items()} #another way\r\ncountry = dict((v, k) for k, v in country_calling_code.items())\r\n\r\n\r\ndef parse_arguments(arg):\r\n # handles commandline input\r\n program = \"pycountrycode\"\r\n description = \"Displays country code of the specified country.\"\r\n\r\n parser = argparse.ArgumentParser(\r\n prog=program, description=description,\r\n usage='%(prog)s [country]'\r\n )\r\n parser.add_argument(\r\n 'country', help=\"Displays the country code of a country.\", nargs='+')\r\n args = parser.parser_args(arg)\r\n country_data_list = ' '.join(args.country)\r\n return country_data_list\r\n\r\n\r\ndef get_list_of_countries():\r\n return DATA\r\n\r\n\r\n# first function to determine the phone code of the requested country\r\ndef get_code(selected_country):\r\n \"\"\"Import get_code to get the telephone code by passing the country name\r\n Return the telephone code of the selected country \r\n\r\n >>> from pycountrycode.countrycode import get_code\r\n >>> get_code('Zimbabwe')\r\n '+263'\r\n >>> get_code('New Zealand')\r\n '+64'\r\n >>> get_code('Peru')\r\n '+51'\r\n >>> get_code('Madagascar')\r\n '+261'\r\n >>> get_code('Russia')\r\n '+7'\r\n >>> get_code('Australia')\r\n '+61'\r\n >>> get_code('Israel')\r\n '+972 '\r\n >>>\r\n \"\"\"\r\n phone_carrier = get_list_of_countries()\r\n nation = selected_country\r\n if TTY:\r\n try:\r\n if nation.istitle():\r\n print('The country code of %s is %s'.format(\r\n nation, phone_carrier[nation]))\r\n else:\r\n nation = nation.title()\r\n print(\"The country calling code of %s is %s\".format(\r\n nation, phone_carrier[nation]))\r\n except:\r\n print(\"Please enter a valid country name.\")\r\n else:\r\n try:\r\n if nation.istitle():\r\n return phone_carrier[nation]\r\n else:\r\n nation = nation.title()\r\n return phone_carrier[nation]\r\n except:\r\n return 'Undefined country'\r\n\r\n\r\n# print(CountryCallingCode.get(name))\r\n\r\n# second function to determine the unknown country of the passed in phone code.\r\ndef get_country(call_code):\r\n \"\"\"Import get_country to get country name using the telephone code.\r\n Return the country that has the corresponding telephone code passed in.\r\n\r\n >>> from pycountrycode.countrycode import get_country\r\n >>> get_country('+52')\r\n 'Mexico'\r\n >>> get_country('+56')\r\n 'Easter Island'\r\n >>> get_country('+1')\r\n 'United States of America'\r\n >>> get_country('+7')\r\n 'Russia'\r\n >>> get_country('+44')\r\n 'Britain'\r\n >>> get_country('+86')\r\n 'China'\r\n >>>\r\n \"\"\"\r\n phone_carrier = country\r\n phone = call_code\r\n if TTY:\r\n try:\r\n if phone.istitle():\r\n print('The country code of %s is %s'.format(\r\n phone, phone_carrier[phone]))\r\n else:\r\n phone = phone.title()\r\n print(\"The country calling code of %s is %s\".format(\r\n phone, phone_carrier[phone]))\r\n except:\r\n print(\"Please enter a valid country name.\")\r\n else:\r\n try:\r\n if phone.istitle():\r\n return phone_carrier[phone]\r\n else:\r\n phone = phone.title()\r\n return phone_carrier[phone]\r\n except:\r\n return 'Undefined country code'\r\n\r\n\r\n# calling my first function.\r\nif __name__ == get_code:\r\n get_code()\r\n\r\n# calling my second function.\r\nif __name__ == get_country:\r\n get_country()\r\n","sub_path":"pycountrycode/countrycode.py","file_name":"countrycode.py","file_ext":"py","file_size_in_byte":4488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"96896689","text":"# -*- coding: utf-8 -*-\nimport pymysql\nimport requests\nfrom bs4 import BeautifulSoup\n\nconn = pymysql.connect(host='127.0.0.1', user='root', passwd=\"Root\", db='univ', charset='utf8')\ncur = conn.cursor()\n\nBAIKE_URL = 'https://baike.baidu.com/item/'\n\nHEADER = {\n 'Host': 'baike.baidu.com',\n 'Connection': 'keep-alive',\n 'Pragma': 'no-cache',\n 'Cache-Control': 'no-cache',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36',\n 'DNT': '1',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'zh-CN,zh;q=0.9,zh-TW;q=0.8,en;q=0.7',\n}\n\nSQL_BASE = \"select id,name from gaokao_univ_one where jiancheng = '' and english_name = '' order by id asc limit \"\n\nstart = 0\nrun = 1\nwhile run:\n sql = SQL_BASE + str(start) + ',1'\n # try:\n cur.execute(sql)\n result = cur.fetchone()\n if (result):\n print(result[0])\n print(result[1])\n url = BAIKE_URL + result[1]\n print(url)\n # url = BAIKE_URL + '南开大学'\n\n request = requests.get(url, headers=HEADER)\n request.encoding = 'utf-8'\n print(request.status_code)\n print(request.headers)\n # print(request.encoding)\n # print(request.text)\n soup = BeautifulSoup(request.text, 'lxml')\n basicInfo_item = soup.select('.basicInfo-item')\n # print(basicInfo_item[0].text)\n i = 0\n univ_zhongwenmingcheng = ''\n univ_jiancheng = ''\n univ_yingwenming = ''\n univ_chuangbanshijian = ''\n univ_liebie = ''\n univ_daima = ''\n univ_dizhi = ''\n univ_bumen = ''\n univ_diqu = ''\n\n for one in basicInfo_item:\n # print(one.text.strip())\n if (one.text.strip() == '中文名'):\n print('中文名' + basicInfo_item[i + 1].text)\n univ_zhongwenmingcheng = pymysql.escape_string(basicInfo_item[i + 1].text.strip())\n elif (one.text.strip() == '英文名' or one.text.strip() == '外文名'):\n # print('英文名' + basicInfo_item[i + 1].text)\n univ_yingwenming = pymysql.escape_string(basicInfo_item[i + 1].text.strip())\n elif (one.text.strip() == '简    称'):\n # print('简 称' + basicInfo_item[i + 1].text)\n univ_jiancheng = pymysql.escape_string(basicInfo_item[i + 1].text.strip())\n elif (one.text.strip() == '创办时间'):\n # print('创办时间' + basicInfo_item[i + 1].text)\n univ_chuangbanshijian = pymysql.escape_string(basicInfo_item[i + 1].text.strip())\n elif (one.text.strip() == '类    别'):\n # print('类 别' + basicInfo_item[i + 1].text)\n univ_liebie = pymysql.escape_string(basicInfo_item[i + 1].text.strip())\n elif (one.text.strip() == '学校代码'):\n # print('学校代码' + basicInfo_item[i + 1].text)\n univ_daima = pymysql.escape_string(basicInfo_item[i + 1].text.strip())\n elif (one.text.strip() == '学校地址' or one.text.strip() == '地    址'):\n # print('学校地址' + basicInfo_item[i + 1].text)\n univ_dizhi = basicInfo_item[i + 1].text.strip()\n if (len(univ_dizhi) > 240):\n univ_dizhi = univ_dizhi[0:250]\n univ_dizhi = pymysql.escape_string(univ_dizhi)\n elif (one.text.strip() == '主管部门'):\n # print('主管部门' + basicInfo_item[i + 1].text)\n univ_bumen = pymysql.escape_string(basicInfo_item[i + 1].text.strip())\n elif (one.text.strip() == '所属地区'):\n # print('所属地区' + basicInfo_item[i + 1].text)\n univ_diqu = pymysql.escape_string(basicInfo_item[i + 1].text.strip())\n\n i = i + 1\n update_sql = \"update gaokao_univ_one set edited = '1', zhongwenmingcheng='\" + univ_zhongwenmingcheng + \"', english_name='\" + univ_yingwenming + \"',jiancheng='\" + univ_jiancheng + \"',createtime='\" + univ_chuangbanshijian + \"',leibie='\" + univ_liebie + \"',address='\" + univ_dizhi + \"',diqu='\" + univ_diqu + \"',code='\" + univ_daima + \"',zhuguan='\" + univ_bumen + \"' where id =\" + \\\n str(result[0])\n print(update_sql)\n cur.execute(update_sql)\n conn.commit()\n start = start + 1\n\n # run = 0\n\n if (start > 2651):\n print('OK')\n run = 0\n else:\n print('none')\n start = start + 1\n run = 0\n # except:\n # print(sql)\n # start = start + 1\n\nconn.close()\n","sub_path":"baike_302.py","file_name":"baike_302.py","file_ext":"py","file_size_in_byte":4815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"200014471","text":"# Data Preprocessing Template\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\n# Importing the dataset\nfile_path = '/Users/axz1191/Documents/azhang/aptomy/MachineLearningA-Z/Part 1 - Data Preprocessing/'\nfile_name = 'Data.csv'\ndataset = pd.read_csv(file_path + file_name)\n\n\nX = dataset.iloc[:, :-1].values\ny = dataset.iloc[:, 3].values\n\n#print (y)\n\n# Taking care of missind data\nfrom sklearn.preprocessing import Imputer\nimputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0)\nimputer = imputer.fit(X[:, 1:3])\nX[:, 1:3] = imputer.transform(X[:, 1:3])\n\n\n# Encode categorical data\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelencoder_X = LabelEncoder()\nX[:, 0] = labelencoder_X.fit_transform(X[:, 0])\n\nonehotencoloder = OneHotEncoder(categorical_features = [0])\nX = onehotencoloder.fit_transform(X).toarray()\n\nlabelencoder_y = LabelEncoder()\ny = labelencoder_y.fit_transform(y)","sub_path":"java_IJ_PYJL1a/MachineLearningA-Z/Part 1 - Data Preprocessing/data_preprocessing_template.py","file_name":"data_preprocessing_template.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"55372051","text":"# https://leetcode.com/problems/binary-tree-preorder-traversal/\n\nimport unittest\nfrom ...leetcode_data_model import TreeNode\n\n\nclass Solution(object):\n def preorderTraversal(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n answer = list()\n\n if root is not None:\n self.traverse(root, answer)\n\n return answer\n\n def traverse(self, node, answer):\n\n answer.append(node.val)\n\n if node.left is not None:\n self.traverse(node.left, answer)\n\n if node.right is not None:\n self.traverse(node.right, answer)\n\n\nclass TestSolution(unittest.TestCase):\n\n def setUp(self):\n self.solution = Solution()\n\n def tearDown(self):\n pass\n\n def test_case_1(self):\n root = TreeNode(1)\n root.right = TreeNode(2)\n root.right.left = TreeNode(3)\n\n self.assertEqual(self.solution.preorderTraversal(root), [1, 2, 3])\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"leetcode/medium/tree/test_binary_tree_preorder_traversal.py","file_name":"test_binary_tree_preorder_traversal.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"544554443","text":"#! env/bin/python3\n\n\"\"\"\nMain file for training a model with FINN\n\"\"\"\n\nimport numpy as np\nimport torch as th\nimport torch.nn as nn\nimport os\nimport time\nfrom threading import Thread\nimport sys\n\nsys.path.append(\"..\")\nfrom utils.configuration import Configuration\nimport utils.helper_functions as helpers\nfrom finn import FINN_Burger, FINN_DiffSorp, FINN_DiffReact, FINN_AllenCahn\n\n_author_ = \"Matthias Karlbauer, Timothy Praditia\"\n\n\ndef run_training(model_number=None):\n\n # Load the user configurations\n config = Configuration(\"config.json\")\n \n # Append the model number to the name of the model\n if model_number is None:\n model_number = config.model.number\n config.model.name = config.model.name + \"_\" + str(model_number).zfill(2)\n\n # Print some information to console\n print(\"Model name:\", config.model.name)\n\n # Hide the GPU(s) in case the user specified to use the CPU in the config\n # file\n if config.general.device == \"CPU\":\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"\n \n root_path = os.path.abspath(\"../../data\")\n data_path = os.path.join(root_path, config.data.type, config.data.name)\n \n # Set device on GPU if specified in the configuration file, else CPU\n # device = helpers.determine_device()\n device = th.device(config.general.device)\n \n if config.data.type == \"burger\":\n # Load samples, together with x, y, and t series\n t = th.tensor(np.load(os.path.join(data_path, \"t_series.npy\")),\n dtype=th.float).to(device=device)\n x = np.load(os.path.join(data_path, \"x_series.npy\"))\n u = th.tensor(np.load(os.path.join(data_path, \"sample.npy\")),\n dtype=th.float).to(device=device)\n \n u[1:] = u[1:] + th.normal(th.zeros_like(u[1:]),th.ones_like(u[1:])*config.data.noise)\n \n dx = x[1]-x[0]\n \n # Initialize and set up the model\n model = FINN_Burger(\n u = u,\n D = np.array([1.0]),\n BC = np.array([[0.0], [0.0]]),\n dx = dx,\n device = device,\n mode=\"train\",\n learn_coeff=True\n ).to(device=device)\n \n \n elif config.data.type == \"diffusion_sorption\":\n # Load samples, together with x, y, and t series\n t = th.tensor(np.load(os.path.join(data_path, \"t_series.npy\")),\n dtype=th.float).to(device=device)\n x = np.load(os.path.join(data_path, \"x_series.npy\"))\n sample_c = th.tensor(np.load(os.path.join(data_path, \"sample_c.npy\")),\n dtype=th.float).to(device=device)\n sample_ct = th.tensor(np.load(os.path.join(data_path, \"sample_ct.npy\")),\n dtype=th.float).to(device=device)\n \n dx = x[1]-x[0]\n u = th.stack((sample_c, sample_ct), dim=len(sample_c.shape))\n \n u[1:] = u[1:] + th.normal(th.zeros_like(u[1:]),th.ones_like(u[1:])*config.data.noise)\n \n # Initialize and set up the model\n model = FINN_DiffSorp(\n u = u,\n D = np.array([0.5, 0.1]),\n BC = np.array([[1.0, 1.0], [0.0, 0.0]]),\n dx = dx,\n device = device,\n mode=\"train\",\n learn_coeff=True\n ).to(device=device)\n \n elif config.data.type == \"diffusion_reaction\":\n # Load samples, together with x, y, and t series\n t = th.tensor(np.load(os.path.join(data_path, \"t_series.npy\")),\n dtype=th.float).to(device=device)\n x = np.load(os.path.join(data_path, \"x_series.npy\"))\n y = np.load(os.path.join(data_path, \"y_series.npy\"))\n sample_u = th.tensor(np.load(os.path.join(data_path, \"sample_u.npy\")),\n dtype=th.float).to(device=device)\n sample_v = th.tensor(np.load(os.path.join(data_path, \"sample_v.npy\")),\n dtype=th.float).to(device=device)\n \n dx = x[1]-x[0]\n dy = y[1]-y[0]\n \n u = th.stack((sample_u, sample_v), dim=len(sample_u.shape))\n u[1:] = u[1:] + th.normal(th.zeros_like(u[1:]),th.ones_like(u[1:])*config.data.noise)\n \n # Initialize and set up the model\n model = FINN_DiffReact(\n u = u,\n D = np.array([5E-4/(dx**2), 1E-3/(dx**2)]),\n BC = np.zeros((4,2)),\n dx = dx,\n dy = dy,\n device = device,\n mode=\"train\",\n learn_coeff=True\n ).to(device=device)\n \n elif config.data.type == \"allen_cahn\":\n # Load samples, together with x, y, and t series\n t = th.tensor(np.load(os.path.join(data_path, \"t_series.npy\")),\n dtype=th.float).to(device=device)\n x = np.load(os.path.join(data_path, \"x_series.npy\"))\n u = th.tensor(np.load(os.path.join(data_path, \"sample.npy\")),\n dtype=th.float).to(device=device)\n \n u[1:] = u[1:] + th.normal(th.zeros_like(u[1:]),th.ones_like(u[1:])*config.data.noise)\n \n dx = x[1]-x[0]\n \n # Initialize and set up the model\n model = FINN_AllenCahn(\n u = u,\n D = np.array([0.6]),\n BC = np.array([[0.0], [0.0]]),\n dx = dx,\n device = device,\n mode=\"train\",\n learn_coeff=True\n ).to(device=device)\n\n # Count number of trainable parameters\n pytorch_total_params = sum(\n p.numel() for p in model.parameters() if p.requires_grad\n )\n \n print(\"Trainable model parameters:\", pytorch_total_params)\n\n # If desired, restore the network by loading the weights saved in the .pt\n # file\n if config.training.continue_training:\n print('Restoring model (that is the network\\'s weights) from file...')\n model.load_state_dict(th.load(os.path.join(os.path.abspath(\"\"),\n \"checkpoints\",\n config.model.name,\n config.model.name + \".pt\")))\n model.train()\n\n #\n # Set up an optimizer and the criterion (loss)\n optimizer = th.optim.LBFGS(model.parameters(),\n lr=config.training.learning_rate)\n\n criterion = nn.MSELoss(reduction=\"mean\")\n\n #\n # Set up lists to save and store the epoch errors\n epoch_errors_train = []\n best_train = np.infty\n\n \"\"\"\n TRAINING\n \"\"\"\n\n a = time.time()\n\n #\n # Start the training and iterate over all epochs\n for epoch in range(config.training.epochs):\n\n epoch_start_time = time.time()\n \n # Define the closure function that consists of resetting the\n # gradient buffer, loss function calculation, and backpropagation\n # It is necessary for LBFGS optimizer, because it requires multiple\n # function evaluations\n def closure():\n # Set the model to train mode\n model.train()\n \n # Reset the optimizer to clear data from previous iterations\n optimizer.zero_grad()\n\n # Forward propagate and calculate loss function\n u_hat = model(t=t, u=u)\n\n mse = criterion(u_hat, u)\n \n mse.backward()\n \n print(mse.item())\n print(model.D)\n \n return mse\n \n optimizer.step(closure)\n \n # Extract the MSE value from the closure function\n mse = closure()\n \n epoch_errors_train.append(mse.item())\n\n # Create a plus or minus sign for the training error\n train_sign = \"(-)\"\n if epoch_errors_train[-1] < best_train:\n train_sign = \"(+)\"\n best_train = epoch_errors_train[-1]\n # Save the model to file (if desired)\n if config.training.save_model:\n # Start a separate thread to save the model\n thread = Thread(target=helpers.save_model_to_file(\n model_src_path=os.path.abspath(\"\"),\n config=config,\n epoch=epoch,\n epoch_errors_train=epoch_errors_train,\n epoch_errors_valid=epoch_errors_train,\n net=model))\n thread.start()\n\n\n \n #\n # Print progress to the console\n print(f\"Epoch {str(epoch+1).zfill(int(np.log10(config.training.epochs))+1)}/{str(config.training.epochs)} took {str(np.round(time.time() - epoch_start_time, 2)).ljust(5, '0')} seconds. \\t\\tAverage epoch training error: {train_sign}{str(np.round(epoch_errors_train[-1], 10)).ljust(12, ' ')}\")\n\n b = time.time()\n print('\\nTraining took ' + str(np.round(b - a, 2)) + ' seconds.\\n\\n')\n \n\nif __name__ == \"__main__\":\n th.set_num_threads(1)\n run_training()\n\n print(\"Done.\")","sub_path":"models/finn_poly/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":8920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"380820462","text":"import pickle\nfrom config import *\n\nphrases = {\n 'help': '',\n 'version': 'This is version {}. Is this the latest version, sweetness?'.format(VERSION),\n 'i love you': 'I love you, too :D',\n 'liam': 'I\\'m your boyfriend, silly :P',\n 'hoodlum': 'I\\'m not a hoodlum no more :P',\n 'hoody': 'That\\'s what you call me!',\n 'hannah': 'Hannah is my favorite person. She never lets me down',\n 'nana': 'Ur a cutie. That\\'s my name for you',\n}\n\ntry:\n file = open(\"save.dat\", \"rb\")\n found = pickle.load(file)\n file.close()\n num_found = 0\n for i in found:\n if found[i]:\n num_found += 1\nexcept EOFError:\n num_found = 0\nif num_found < len(phrases):\n phrases['help'] = 'You have found {} out of {} phrases! Keep up the good work ;)'.format(num_found, len(phrases))\nelse:\n phrases['help'] = 'You have found ALL phrases!!! You should bug me to add more ;)'\n","sub_path":"dat.py","file_name":"dat.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"194992942","text":"#!/usr/bin/python3\n#-*-encoding:utf8-*-\n\nfrom random import seed,random\nfrom math import sin,cos,sqrt,degrees,atan2\nfrom copy import deepcopy\n\n\"\"\"\nIMPLEMENTAÇÃO DO PROBLEMA DE BUSCA POR CAMINHO DBZ\n\"\"\"\n\nCIMA = 1\nBAIXO = 2\nESQUERDA = 3\nDIREITA = 4\n\n#CIMA = 1\n#BAIXO = 3\n#ESQUERDA = 4\n#DIREITA = 2\n\nCUSTO_GRAMA = 1\nCUSTO_AGUA = 10\nCUSTO_MONTANHA = 35\n\nTERRENO_GRAMA = 1\nTERRENO_AGUA = 2\nTERRENO_MONTANHA = 3\n\n#!!!MODIFICADA!!!\ndef dentro_quadrado(ls,li,p):\n\t\"\"\"\n\tVerifica se o ponto p está dentro do\n\tquadrado formado formado por ls e li\n\n\t@param ls: Limite Superior do quadrado\n\t@param li: Limite Inferior do quadrado\n\t@param p: Ponto a ser avaliado\n\t@return: True se o ponto estiver dentro do quadrado\n\t\"\"\"\n\treturn li[0] >= p[0] and li[1] >= p[1] and ls[0] <= p[0] and ls[1] <= p[1]\n\n\nclass DragonBallZ:\n\t\"\"\"Classe de controle do problema\"\"\"\n\n\tdef __init__(self,agente,tamanho=50,semente=None):\n\t\t\"\"\"\n\t\tConstrutor da classe\n\n\t\t@param agente: Função do Agente\n\t\t@param tamanho: Tamanho do mapa\n\t\t@param semente: Semente aleatória (None utiliza a semente default)\n\t\t\"\"\"\n\n\t\tself.agente = agente\n\t\tself.tamanho = tamanho\n\n\t\tif semente is not None:\n\t\t\tseed(semente)\n\n\t\t#\n\t\t# PASSO 1: GERA A POSIÇÃO NO MAPA DAS ESFERAS E DA CASA DO KAME\n\t\t#\n\t\tself.casa_kame = (int(random()*tamanho),int(random()*tamanho))\n\t\tself.esferas = list()\n\n\t\t# Gera a posição das esferas\n\t\twhile len(self.esferas) < 7:\n\t\t\tpos = (int(random()*tamanho),int(random()*tamanho))\n\n\t\t\tif pos != self.casa_kame and pos not in self.esferas:\n\t\t\t\tself.esferas.append(pos)\n\n\n\t\t#\n\t\t# PASSO 2: GERA O MAPA\n\t\t#\n\t\ttermos = [random() for _ in range(6)]\n\t\tself.mapa = [ [None] * tamanho for _ in range(tamanho) ]\n\n\t\tfor x in range(tamanho):\n\t\t\tfor y in range(tamanho):\n\t\t\t\tz = sin(termos[0]*x**2+termos[1]*y+termos[2]) + cos(termos[3]*y**2+termos[4]*x+termos[5])\n\n\t\t\t\tif z < -.5: self.mapa[x][y] = 1\n\t\t\t\telif z < .5: self.mapa[x][y] = 2\n\t\t\t\telse: self.mapa[x][y] = 3 \n\n\t\t#\n\t\t# PASSO 3: INICIALIZA POSIÇÃO INICIAL DO AGENTE E CONTADOR DE ITERAÇÕES\n\t\t#\n\t\tself.agente_pos = list(self.casa_kame)\n\t\tself.iteracao = 0\n\t\tself.custo = 0\n\n\tdef executar(self):\n\t\t\"\"\"\n\t\tExecuta uma iteração do problema,\n\t\ta implementação será uma list comprehension \n\t\tpara facilitar no uso da GUI\n\t\t\"\"\"\n\n\t\t#\n\t\t# COMPUTA AS INFORMAÇÕES DO RADAR\n\t\t#\n\t\tradar_direcao = {\n\t\t\t\"norte\":0,\n\t\t\t\"sul\":0,\n\t\t\t\"leste\":0,\n\t\t\t\"oeste\":0,\n\t\t\t\"nordeste\":0,\n\t\t\t\"noroeste\":0,\n\t\t\t\"suldeste\":0,\n\t\t\t\"suldoeste\":0\n\t\t}\n\t\tradar_proximo = list()\n\t\tlimite_sup = (self.agente_pos[0]-3,self.agente_pos[1]-3)\n\t\tlimite_inf = (self.agente_pos[0]+3,self.agente_pos[1]+3)\n\n\t\tfor p in self.esferas:\n\t\t\tif dentro_quadrado(limite_sup,limite_inf,p):\n\t\t\t\tradar_proximo.append(p)\n\t\t\telse:\n\t\t\t\tangulo = degrees(atan2((self.agente_pos[1]-p[1]),(p[0]-self.agente_pos[0])))\n\n\t\t\t\t#MODIFICADA if angulo < 0: angulo = 180.0-angulo\n\t\t\t\t\n\t\t\t\tif angulo < 0:\n\t\t\t\t\tangulo = 360+angulo\n\t\t\t\t\n\t\t\t\tif angulo < 22.5 or angulo > 337.5 : radar_direcao[\"leste\"]=1\n\t\t\t\telif angulo < 67.5: radar_direcao[\"nordeste\"]=1\n\t\t\t\telif angulo < 112.5: radar_direcao[\"norte\"]=1\n\t\t\t\telif angulo < 157.5: radar_direcao[\"noroeste\"]=1\n\t\t\t\telif angulo < 202.5: radar_direcao[\"oeste\"]=1\n\t\t\t\telif angulo < 247.5: radar_direcao[\"suldoeste\"]=1\n\t\t\t\telif angulo < 292.5: radar_direcao[\"sul\"]=1\n\t\t\t\telse: radar_direcao[\"suldeste\"]=1\n\n\t\t# Verifica se o agente voltou para a casa do kame\n\t\tif self.custo > 0 and tuple(self.agente_pos) == self.casa_kame:\n\t\t\tif len(self.esferas) > 0: raise Exception(\"O Objetivo do jogo não foi cumprido!\")\n\t\t\telse: raise Exception(\"Você pegou todas as esferas!\\nCusto Total: %d\\nCusto/Iteração: %g\"%(self.custo,float(self.custo)/self.iteracao))\n\n\t\t#\n\t\t# INVOCA O AGENTE E VALIDA RETORNO\n\t\t#\n\t\tdirecao = self.agente({\n\t\t\t\"pos\":deepcopy(self.agente_pos),\n\t\t\t\"radar-proximo\":radar_proximo,\n\t\t\t\"radar-direcao\":radar_direcao,\n\t\t\t\"mapa\":deepcopy(self.mapa),\n\t\t\t\"casa-kame\":deepcopy(self.casa_kame),\n\t\t\t\"esferas\":len(self.esferas),\n\t\t\t#MODIFICADA\n\t\t\t\"esferas-pos\":deepcopy(self.esferas)\n\t\t\t\n\t\t})\n\t\t\n\t\tif type(direcao) is not int or direcao < 1 or direcao > 4: print(direcao);raise Exception(\"Direcao Inválida!\")\n\n\t\tif direcao == CIMA and self.agente_pos[1] == 0: raise Exception(\"Não é possível passar o limite superior do mapa\")\n\n\t\tif direcao == BAIXO and self.agente_pos[1] == self.tamanho-1: raise Exception(\"Não é possível passar o limite inferior do mapa\")\n\n\t\tif direcao == ESQUERDA and self.agente_pos[0] == 0: raise Exception(\"Não é possível passar o limite da esquerda no mapa\")\n\n\t\tif direcao == DIREITA and self.agente_pos[0] == self.tamanho-1: raise Exception(\"Não é possível passar o limite da direita no mapa\")\n\n\t\t# Atualiza custo\n\t\tif self.mapa[self.agente_pos[0]][self.agente_pos[1]] == TERRENO_GRAMA: self.custo += CUSTO_GRAMA\n\t\telif self.mapa[self.agente_pos[0]][self.agente_pos[1]] == TERRENO_MONTANHA: self.custo += CUSTO_MONTANHA\n\t\telse: self.custo += CUSTO_AGUA\n\n\t\t# Atualiza posição do agente\n\t\tif direcao == CIMA: self.agente_pos[1]-=1\n\t\telif direcao == BAIXO: self.agente_pos[1]+=1\n\t\telif direcao == ESQUERDA: self.agente_pos[0]-=1\n\t\telse: self.agente_pos[0]+=1\n\n\t\t# Verifica se o agente encontrou uma esfera do dragão\n\t\tif tuple(self.agente_pos) in self.esferas:\n\t\t\tself.esferas.remove(tuple(self.agente_pos))\n\n\t\t# Incrementa iteracao\n\t\tself.iteracao+=1","sub_path":"dbz.py","file_name":"dbz.py","file_ext":"py","file_size_in_byte":5282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"101050237","text":"\nimport os\n\n_ins_path = \"instructions\"\n_main_ins_filename = \"main_instruct.rst\"\n\nMAIN_INSTRUCTIONS = open(os.path.join(_ins_path,\n _main_ins_filename)).read()\n\n\nFONT_SIZE = 35\nRST_FONT_SIZE = 35\nLOC_STIM_DUR = 0.500\nLOC_INTER_STIM_DUR = 0.500\n\n\nSTIM_DUR = 6.\nRESP_DUR = 2.0\nISI_DUR = 2.0\nISI_JIT = 2.0\n\nMAIN_NUM_BLOCKS = 5\nMAIN_NUM_TARGETS = 30\n\nBUTTON_BOX_KEYS = [\"1\", \"2\", \"3\", \"4\"]#[\"_1\", \"_2\", \"_3\", \"_4\"]\nYESNO_KEYS = [\"1\", \"2\"]#[\"_1\", \"_2\"]\nTR_KEYS = [\"5\"]#[\"_5\"]\nRUN_START_KEYS = [\"0\"]\n\nMD_NUM_VAR = 3\nMD_DUR = 20\nMD_PRAC_DUR = 12\nMD_PAM = True # plus AND minus?\nMD_KEYS = {'True': BUTTON_BOX_KEYS[0],\n 'False': BUTTON_BOX_KEYS[1]}\n\n################################################################################S\n\n\n","sub_path":"Relive/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"163550702","text":"#__coding=utf8__\nimport requests\nimport requests.sessions\nfrom bs4 import BeautifulSoup\nfrom global_tools import GlobalTools\nfrom search import get_link_by_asin\nfrom comment_hendler import CommentHandler\nfrom get_fba import get_fba\nimport time\nimport xlrd\nfrom xlutils.copy import copy\nimport tkinter.messagebox as messagebox\nimport multiprocessing\nimport os\nimport brotli\nimport logging\nimport traceback\nfrom tkinter import *\n\n\nclass Comments(object):\n def __init__(self,queue,asin,countrycode):\n self.queue = queue\n self.countrycode = countrycode\n self.baseurl = GlobalTools.getBaseurlFromCountrycode(countrycode)\n self.headers = GlobalTools.getHeaders()\n self.asin = asin\n self.url = get_link_by_asin(asin,self.baseurl)\n #if can't get a normal page ,can't use this kind of url to get a price and shop name\n #the second link look like this : http://www.amazon.de/gp/offer-listing/B01N52QW8A/ref=dp_olp_0?ie=UTF8&condition=all\n self.second_url = \"\"\n self.normal_situation = True\n self.unnormal_price = \"\"\n self.unnormal_shop = \"\"\n self.resultmap = {}\n self.result = []\n self.us_reviews_need_adjust = False\n\n def prerequest(self):\n queue = self.queue\n queue.put(\"prerequest\")\n print(\"prerequest\")\n GlobalTools.setbaseurl(self.baseurl)\n res = requests.get(self.url, headers=self.headers)\n self.res = res\n\n html = GlobalTools.getResponseContent(self.res)\n\n if html.find(id=\"add-to-cart-button\") is None:\n if html.find(id=\"availability\") is not None:\n # print \"text\" + html.find(id=\"availability\").text\n url = self.baseurl + html.find(id=\"availability\").find(\"a\").get('href')\n self.second_url = url\n res = requests.get(url, headers=GlobalTools.getHeaders())\n html = GlobalTools.getResponseContent(res)\n\n try:\n price = html.find(class_=\"olpOfferPrice\").text.strip()\n self.unnormal_price = price\n print(price)\n shop = html.find(class_=\"olpSellerName\").text\n self.unnormal_shop = shop\n print(shop)\n except:\n traceback.print_exc()\n self.normal_situation = False\n return False\n return True\n\n\n def parse(self,sheet,currrow):\n queue = self.queue\n self.result = [currrow]\n queue.put(u\"商品链接\")\n queue.put(self.url)\n print(u\"商品链接:\")\n print(self.url)\n\n self.html = GlobalTools.getResponseContent(self.res)\n\n self.geturl()\n # self.getprice()\n self.getshopname()\n # self.getbrand()\n # self.getfirstavailable()\n # self.getranking()\n # self.getqa()\n # self.getCategory()\n self.getstars()\n self.getreviewcount()\n # self.getgoodreviewvote()\n #美国的reviewcount是在getgoodreviewvote中统计出来的,所以要重新计算一下\n # if self.countrycode==\"us\":\n # self.adjustreviewcount()\n if self.us_reviews_need_adjust:\n self.getusviewcount()\n\n self.getfba()\n print(self.resultmap)\n return self.getresult()\n # return self.result\n\n def getresult(self):\n resultmap = self.resultmap\n result = self.result\n result.append(resultmap['url'])\n result.append(resultmap['price'])\n result.append(resultmap['shop'])\n result.append(resultmap['brand'])\n result.append(resultmap['first_available'])\n result.append(resultmap['qa'])\n result.append(resultmap['stars'])\n result.append(resultmap['positivereviewcount'])\n result.append(resultmap['negtivereviewcount'])\n result.append(resultmap['positivereviewvote'])\n result.append(resultmap['fba'])\n result.append(resultmap['first_level_menu'])\n result.append(resultmap['second_level_menu'])\n result.append(resultmap['ranking'])\n return result\n\n def adjustreviewcount(self):\n self.resultmap['positivereviewcount'] = self.comment_handler.getUsPositiveReviewCount()\n self.resultmap['negtivereviewcount'] = self.reviewCount - self.resultmap['positivereviewcount']\n\n def geturl(self):\n self.resultmap['url'] = self.url\n\n def getbrand(self):\n try:\n brand = self.html.find(id=\"brand\").text.strip()\n except:\n brand = \"\"\n\n self.resultmap['brand'] = brand\n self.queue.put(\"brand:\"+brand)\n\n def getprice(self):\n html = self.html\n price = html.find(id=\"priceblock_ourprice\")\n if price is None:\n price = html.find(id=\"priceblock_dealprice\")\n if price is None:\n price = html.find(id=\"priceblock_saleprice\")\n if price is None:\n price = html.find(id=\"olp_feature_div\")\n\n if self.normal_situation is False:\n self.resultmap['price'] = self.unnormal_price\n else:\n self.resultmap['price'] = price.text.strip()\n self.queue.put(\"price:\"+self.resultmap['price'])\n def getfirstavailable(self):\n if self.countrycode==\"us\":\n if \"Date First Available\" in self.html.find(id=\"productDetails_detailBullets_sections1\").find_all(\"th\")[-1].text:\n first_available = self.html.find(id=\"productDetails_detailBullets_sections1\").find_all(\"td\")[-1]\n else:\n self.resultmap['first_available'] = \"\"\n return\n else:\n first_available = self.html.find(attrs={\"class\": \"date-first-available\"}).find(attrs={\"class\": \"value\"})\n self.resultmap['first_available'] = first_available.text.strip()\n self.queue.put(\"first_available:\" + self.resultmap['first_available'])\n\n def getshopname(self):\n html = self.html\n try:\n shop = html.find(id=\"merchant-info\").find('a')\n self.resultmap['shop'] = shop.text.strip()\n except:\n self.resultmap['shop'] = self.unnormal_shop\n\n self.queue.put(\"shop:\" + self.resultmap['shop'])\n\n def getqa(self):\n try:\n if self.countrycode == \"jp\":\n qa = self.html.find(id=\"askATFLink\").text.strip().split(u\"人\")[0]\n else:\n qa = self.html.find(id=\"askATFLink\").text.strip().split()[0]\n except:\n qa = \"0\"\n self.resultmap['qa'] = qa\n self.queue.put(\"qa:\" + self.resultmap['qa'])\n\n def getstars(self):\n try:\n if self.countrycode == \"jp\":\n stars = self.html.find(id=\"acrPopover\").find('a').find('span').text.split()[1]\n else:\n stars = self.html.find(id=\"acrPopover\").find('a').find('span').text.split()[0]\n except:\n stars = \"no reviews\"\n self.resultmap['stars'] = stars\n self.queue.put(\"stars:\" + self.resultmap['stars'])\n\n def getusviewcount(self):\n asin = self.asin\n url = \"https://www.amazon.com/product-reviews/\"+asin+\"/ref=acr_dpx_see_all?ie=UTF8&showViewpoints=1\"\n res = requests.get(url,headers = GlobalTools.getHeaders())\n html = GlobalTools.getResponseContent(res)\n viewpoints = html.find_all(id=re.compile(\"viewpoint-\"))\n if len(viewpoints)>0:\n try:\n positive = viewpoints[0].find_all(attrs={\"data-reftag\":\"cm_cr_arp_d_viewpnt_lft\"})[0].text\n self.resultmap['positivereviewcount'] = int(positive.split(\"positive\")[0].split(\"all\")[1].strip())\n except:\n pass\n if len(viewpoints)>1:\n try:\n negtive = viewpoints[1].find_all(attrs={\"data-reftag\":\"cm_cr_arp_d_viewpnt_rgt\"})[0].text\n self.resultmap['negtivereviewcount'] = int(negtive.split(\"critical\")[0].split(\"all\")[1].strip())\n except:\n pass\n print(viewpoints)\n\n def getreviewcount(self):\n html = self.html\n scoretable = html.find(id='histogramTable')\n rows = scoretable.find_all('tr', attrs={'class': 'a-histogram-row'})\n starcount = []\n\n if self.countrycode == \"us\":\n reviewText = html.find(id=\"acrCustomerReviewText\")\n if reviewText != None:\n reviewCount = int(reviewText.text.split()[0].replace(\",\",\"\"))\n else:\n reviewCount = 0\n\n self.reviewCount = reviewCount\n # if reviewCount == 0:\n # positivecount = 0\n # negtivecount = 0\n\n for i in range(0, len(rows)):\n try:\n starcount.append(\n int(rows[i].find('a', attrs={'class': 'histogram-review-count'}).text.split('%')[0]))\n except:\n starcount.append(0)\n print(starcount)\n if starcount[0] + starcount[1] == 0:\n negtivecount = reviewCount\n positivecount = 0\n elif starcount[2] + starcount[3] + starcount[4] == 0:\n positivecount = reviewCount\n negtivecount = 0\n else:\n positivecount = reviewCount * (starcount[0] + starcount[1]) / 100 + 1\n negtivecount = reviewCount * (starcount[2] + starcount[3] + starcount[4]) / 100 + 1\n self.us_reviews_need_adjust = True\n\n else:\n for i in range(0, len(rows)):\n try:\n starcount.append(int(rows[i].find_all('a')[2].text))\n except:\n starcount.append(0)\n positivecount = starcount[0] + starcount[1]\n negtivecount = starcount[2] + starcount[3] + starcount[4]\n\n self.resultmap['positivereviewcount'] = positivecount\n self.resultmap['negtivereviewcount'] = negtivecount\n self.queue.put(\"positivereviewcount:\" + str(self.resultmap['positivereviewcount']))\n self.queue.put(\"negtivereviewcount:\" + str(self.resultmap['negtivereviewcount']))\n def getgoodreviewvote(self):\n self.parse_comment(self.asin, self.resultmap['positivereviewcount'], self.resultmap['negtivereviewcount'])\n\n def getranking(self):\n if self.countrycode == \"us\":\n addtional_info_items = self.html.find(id=\"productDetails_detailBullets_sections1\").find_all(\"tr\")\n for tr in addtional_info_items:\n if \"Best Sellers Rank\" in tr.find(\"th\").text:\n rank = tr.find(\"td\").find_all(\"span\")[0]\n break\n else:\n rank = self.html.find(id=\"SalesRank\").find(\"td\", class_=\"value\")\n\n if rank is not None:\n if self.countrycode != \"us\":\n rankul = rank.find(\"ul\")\n\n rankitems = rank.find(\"ul\").find_all(\"li\")\n itemtext = \"\"\n for item in rankitems:\n itemtext += ''.join(item.stripped_strings)+\"\\n\"\n print(\"itemtext:\")\n print(itemtext)\n rankul.decompose()\n ranktext = rank.text.strip()+\"\\n\"+itemtext\n print(\"rank text:\")\n print(rank.text.strip()+\"\\n\"+itemtext)\n else:\n rankitems = rank.find_all(\"span\")\n ranktext = \"\"\n for item in rankitems:\n ranktext += \"\".join(item.stripped_strings) + \"\\n\"\n\n countrySepMap = {\n \"uk\":\"#\",\n \"us\":\"#\",\n \"fr\":u\"n°\",\n \"it\":\"n.\",\n \"de\":\"Nr.\",\n \"jp\":u\"位\"\n }\n # rank = self.html.find(id=\"SalesRank\")\n #\n # if rank is not None:\n # out = re.sub(r\"\\s{2,}\", \" \", rank.text)\n # s1 = out.split(countrySepMap[self.countrycode])\n # for i in range(1, len(s1)):\n # s1[i] = countrySepMap[self.countrycode] + s1[i]\n # ranktext = \"\\n\".join(s1)\n # else:\n # ranktext = \"\"\n\n self.resultmap['ranking'] = ranktext\n # 在这里添加分类:\n if ranktext != \"\":\n if self.countrycode == \"uk\":\n self.resultmap['first_level_menu'] = ranktext.split(\"(\")[0].split(\"in\")[1]\n if self.countrycode == \"jp\":\n self.resultmap['first_level_menu'] = ranktext.split(\"-\")[0]\n if self.countrycode == \"de\":\n self.resultmap['first_level_menu'] = ranktext.split(\"(\")[0].split(\"in\")[1]\n if self.countrycode == \"fr\":\n self.resultmap['first_level_menu'] = ranktext.split(\"(\")[0].split(\"en\")[1]\n if self.countrycode == \"it\":\n self.resultmap['first_level_menu'] = ranktext.split(\"(\")[0].split(\"in\")[1]\n if self.countrycode == \"us\":\n self.resultmap['first_level_menu'] = ranktext.split(\"(\")[0].split(\"in\")[1]\n self.queue.put(\"ranking:\" + self.resultmap['ranking'])\n\n def getCategory(self):\n try:\n #商品有时没有分类,这时先在这里取为空\"\",在下面回去分类排名的时候,取第一分类\n menu_levels = self.html.find(id=\"wayfinding-breadcrumbs_feature_div\").find_all(attrs={\"class\":\"a-list-item\"})\n count = len(menu_levels)\n self.resultmap['first_level_menu'] = GlobalTools.removeBlankChars(menu_levels[0].text)\n if count>=3:\n self.resultmap['second_level_menu'] = GlobalTools.removeBlankChars(menu_levels[2].text)\n except:\n pass\n\n def parse_comment(self, asin,positive_count,negtive_count):\n comment_handler = CommentHandler(asin,positive_count,negtive_count)\n #美国站点需要用到此变量\n self.comment_handler = comment_handler\n comment_handler.getPositiveCommentsInfo()\n print(u\"好评点赞数:\")\n positive_vote = comment_handler.get_positive_votes()\n self.resultmap['positivereviewvote'] = positive_vote\n self.queue.put(\"positivereviewvote:\" + str(self.resultmap['positivereviewvote']))\n\n def getfba(self):\n print(u\"库存:\")\n try:\n self.resultmap['fba'] = get_fba(self.url,self.countrycode)\n except:\n traceback.print_exc()\n self.resultmap['fba'] = u\"获取库存超时,请手动获取\"\n self.queue.put(\"fba:\" + self.resultmap['fba'])\n\ndef fun(queue,product,countrycode,currrow,sheet):\n amazonobj = Comments(queue,product,countrycode)\n amazonobj.prerequest()\n result = amazonobj.parse(sheet,currrow)\n return result\n\ndef main(queue,countrycode):\n if not os.path.isfile(GlobalTools.getExcelFile(countrycode)):\n # messagebox.showerror(\"error\", u\"请将uk.xls放到和amazon.exe相同目录下\")\n queue.put(u\"ERROR:请将\"+countrycode+u\".xls放到和amazon.exe相同目录下\")\n exit(0)\n\n products = []\n rb = xlrd.open_workbook(GlobalTools.getExcelFile(countrycode))\n try:\n sheet = rb.sheet_by_name(\"asin\")\n count = sheet.nrows\n for i in range(0, count):\n print(sheet.cell_value(i, 0))\n products.append(sheet.cell_value(i, 0))\n except:\n # messagebox.showerror(\"error\", u\"uk.xls中必须包含名字为asin的sheet\")\n queue.put(u\"ERROR:请将\" + countrycode + u\".xls放到和amazon.exe相同目录下\")\n exit(0)\n print(\"copy\")\n wb = copy(rb)\n sheet = wb.add_sheet(time.strftime(u\"%m-%d_%H-%M\", time.localtime(time.time())))\n # 写头部标题:\n tableheaders = GlobalTools.get_table_header()\n row = 0\n col = 0\n for item in tableheaders:\n sheet.write(row, col, item)\n col += 1\n\n pool = multiprocessing.Pool(processes=5)\n\n currrow = 1\n results = []\n\n for product in products:\n results.append(pool.apply_async(fun, (queue,product, countrycode, currrow, sheet, )))\n currrow += 1\n\n pool.close()\n pool.join()\n # for res in results:\n # # try:\n # print res.get()\n # # except:\n # # pass\n\n\n for result in results:\n try:\n row = result.get()\n currrow = row[0]\n print(\"currrow:\" + str(currrow))\n col = 0\n for i in range(1, len(row)):\n sheet.write(currrow, col, row[i])\n col += 1\n except:\n pass\n try:\n wb.save(GlobalTools.getExcelFile(countrycode))\n except:\n queue.put(u\"ERROR:保存文件失败,运行时,请不要打开站点对应的xls文件\")\n exit(0)\n queue.put(\"finish.\")\n\ndef single_thread_main():\n if not os.path.isfile(\"d:/de.xls\"):\n messagebox.showerror(\"error\",u\"请将uk.xls放到和amazon.exe相同目录下\")\n exit(0)\n\n products = []\n\n rb = xlrd.open_workbook(\"d:/de.xls\")\n\n try:\n sheet = rb.sheet_by_name(\"asin\")\n count = sheet.nrows\n for i in range(0,count):\n print(sheet.cell_value(i,0))\n products.append(sheet.cell_value(i,0))\n except:\n messagebox.showerror(\"error\", u\"uk.xls中必须包含名字为asin的sheet\")\n exit(0)\n wb = copy(rb)\n sheet = wb.add_sheet(time.strftime(u\"%m-%d_%H-%M\",time.localtime(time.time())))\n #写头部标题:\n tableheaders = GlobalTools.get_table_header()\n row = 0\n col = 0\n for item in tableheaders:\n sheet.write(row,col,item)\n col += 1\n\n currrow = 1\n\n for product in products:\n amazonobj = Comments(product)\n amazonobj.prerequest()\n result = amazonobj.parse(sheet,currrow)\n currrow += 1\n try:\n wb.save(\"d:/de.xls\")\n except:\n messagebox.showerror(\"error\", u\"保存文件失败,运行时,请不要打开uk.xls文件\")\n # except:\n # continue\n\nif __name__==\"__main__\":\n multiprocessing.freeze_support()\n main()\n # single_thread_main()\n\n","sub_path":"amazon_comments.py","file_name":"amazon_comments.py","file_ext":"py","file_size_in_byte":17985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"224464440","text":"#!/usr/bin/python3\n\"\"\"places\n\"\"\"\n\nfrom models.city import City\nfrom models.place import Place\nfrom models.user import User\nfrom models import storage\nfrom api.v1.views import app_views\nfrom flask import abort, jsonify, make_response, request\n\n\n@app_views.route('/cities//places', methods=['GET'],\n strict_slashes=False)\ndef get_places(city_id):\n \"\"\"city \"\"\"\n city = storage.get(City, city_id)\n if not city:\n abort(404)\n places = [place.to_dict() for place in city.places]\n return jsonify(places)\n\n\n@app_views.route('/places/', methods=['GET'], strict_slashes=False)\ndef get_places_id(place_id):\n \"\"\"place \"\"\"\n place = storage.get(Place, place_id)\n if not place:\n abort(404)\n return jsonify(place.to_dict())\n\n\n@app_views.route('/places/', methods=['DELETE'],\n strict_slashes=False)\ndef delete_places(place_id):\n \"\"\"place object \"\"\"\n place = storage.get(Place, place_id)\n if not place:\n abort(404)\n storage.delete(place)\n storage.save()\n return make_response(jsonify({}), 200)\n\n\n@app_views.route('/cities//places', methods=['POST'],\n strict_slashes=False)\ndef post_places(city_id):\n \"\"\" creates \"\"\"\n city = storage.get(City, city_id)\n if not city:\n abort(404)\n if not request.get_json():\n return make_response(jsonify({'error': 'Not a JSON'}), 400)\n if \"user_id\" not in request.get_json():\n return make_response(jsonify({'error': 'Missing user_id'}), 400)\n data = request.get_json()\n user = storage.get(User, data[\"user_id\"])\n\n if not user:\n abort(404)\n if \"name\" not in data:\n return make_response(jsonify({'error': 'Missing name'}), 400)\n data[\"city_id\"] = city_id\n instance = Place(**data)\n instance.save()\n return make_response(jsonify(instance.to_dict()), 201)\n\n\n@app_views.route('/places/', methods=['PUT'], strict_slashes=False)\ndef put_places(place_id):\n \"\"\" update \"\"\"\n place = storage.get(Place, place_id)\n if not place:\n abort(404)\n data = request.get_json()\n if not data:\n return make_response(jsonify({'error': 'Not a JSON'}), 400)\n key_ignore = ['id', 'user_id', 'city_id', 'created_at', 'updated_at']\n for key, value in data.items():\n if key not in key_ignore:\n setattr(place, key, value)\n storage.save()\n return make_response(jsonify(place.to_dict()), 200)\n","sub_path":"api/v1/views/places.py","file_name":"places.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"568589062","text":"from selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.common.keys import Keys\n\nd = webdriver.Chrome()\nd.implicitly_wait(1)\n\nd.get('http://rozetka.com.ua/')\n\n\n# функция вызова попапа смены региона\ndef RegionPopup():\n initial_region_link = d.find_element_by_class_name('header-city-select-inner')\n ActionChains(d).move_to_element(initial_region_link).perform()\n d.find_element_by_class_name('header-city-location-change').click()\n\n\n# меняем регион на Киев (из списка)\nRegionPopup()\nd.find_element_by_link_text('Киев').click()\nnew_region = d.find_element_by_css_selector('#city-chooser > a > span').text\nassert new_region == 'Киев', 'Test failed'\n\n# меняем регион на Харьков (из саджеста)\nRegionPopup()\nregion_suggest = d.find_element_by_id('popup_suggest_locality')\nregion_suggest.click()\nregion_suggest.send_keys('Хар')\nd.find_element_by_name('0').click()\nnew_region = d.find_element_by_css_selector('#city-chooser > a > span').text\nassert new_region == 'Харьков', 'Test failed'\n\n# поиск категории товара\nd.find_element_by_xpath('//*[@id=\"rz-search\"]/form/div[1]/div[2]/input').send_keys('телефоны', Keys.ENTER)\nassert d.title == 'ROZETKA — Результаты поиска: \"телефоны\" | Поиск', 'Test failed'\nd.back()\n\nd.find_element_by_css_selector(\n '#rz-search > form > div.rz-header-search-inner > div.rz-header-search-input-text-wrap.sprite-side > input').send_keys(\n 'телевизоры samsung')\nd.find_element_by_link_text('телевизоры samsung').click()\n# проверяем, что выдача соответствует поисковому запросу\nresults = d.find_elements_by_partial_link_text('Samsung')\nassert len(results) >= 32, 'Test failed'\n\nd.quit()\n","sub_path":"selenium_training/rozetka/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"430999169","text":"#flask/__init__.py \nfrom flask import Flask, g, request, Response, make_response, session, render_template\nfrom flask import Markup, redirect, url_for\nfrom datetime import datetime, date, timedelta\nfrom werkzeug.utils import secure_filename\nimport os\nimport sys\n#sys.path.append('C:\\\\Users\\\\user\\\\Desktop\\\\오아시스\\\\WeRide\\\\yolov5')\n#from . import main, total_score\n\n\napp=Flask(__name__)\napp.debug = True\n#app.jinja_env.trim_blocks = True\n\n@app.route(\"/success\")\ndef success():\n cmd=(\"python ../yolov5/main.py --source ../test_video/2.mp4\")\n os.system(cmd)\n return render_template('success.html')\n\n\n@app.route(\"/loading\")\ndef loading():\n \n return render_template('loading.html')\n\n@app.route('/analysis')\ndef analysis():\n f=open(\"C:/Users/user/Desktop/오아시스/WeRide/total_score.txt\",'r')\n f2=open(\"C:/Users/user/Desktop/오아시스/WeRide/table_score.txt\", 'r')\n total_score=f.readline()\n table_score=f2.readlines()\n f.close()\n f2.close()\n return render_template('analysis.html', total=total_score, table=table_score)\n\n@app.route('/score')\ndef score():\n f=open(\"C:/Users/user/Desktop/오아시스/WeRide/total_score.txt\",'r')\n total_score=f.readline()\n f.close()\n return render_template(\"score.html\", total=total_score)\n\n@app.route('/service')\ndef service():\n return render_template(\"service.html\")\n\n@app.route('/upload')\ndef render_file():\n return render_template('upload.html')\n\n@app.route('/fileUpload', methods=['GET', 'POST'])\ndef upload_file():\n loading()\n if request.method == 'POST':\n loading()\n f=request.files['file'] \n filename=f.filename\n #dirname=f.filename[:4]\n f.save('../test_video/'+secure_filename(filename)) #저장할 경로 + 파일명\n \n\n return render_template('loading.html', file=filename)\n\n@app.route('/servicepage')\ndef servicepage():\n return render_template(\"servicepage.html\")\n\n@app.route('/')\ndef main1():\n return render_template(\"mainpage.html\")\n\n\n\n\n\n\n\n\n\n","sub_path":"Web/flaskapp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"304869045","text":"# -*- coding: utf-8 -*-\nimport time\nfrom dateutil.relativedelta import relativedelta\nfrom odoo import api, fields, models, _\nfrom odoo.exceptions import UserError\nimport xlwt\nfrom datetime import datetime,date, timedelta\nimport calendar\nfrom xlwt import easyxf\nimport base64\nimport io\nclass ticl_recommend_receipt(models.Model):\n _inherit = \"ticl.receipt.line\"\n\n to_recommend_file = fields.Binary('To Recommend Report')\n def generate_to_recommend_xls(self):\n workbook = xlwt.Workbook()\n\n # style = xlwt.easyxf('font:bold True; font: color green; pattern: pattern solid, fore_colour green;')\n style_green = xlwt.easyxf('font:bold True; font: color green;align: horiz right')\n style_orange = xlwt.easyxf('font:bold True; font: color orange;')\n style_red = xlwt.easyxf('font:bold True; font: color red;')\n column_heading_style = easyxf('font:bold True;pattern: pattern solid, fore_colour gray25;align: horiz left')\n worksheet = workbook.add_sheet('To Recommend Report')\n \n worksheet.write(0, 0, _('Location'), column_heading_style)\n worksheet.write(0, 1, _('Manufacturer'), column_heading_style)\n worksheet.write(0, 2, _('Model'), column_heading_style)\n worksheet.write(0, 3, _('Serial #'), column_heading_style)\n worksheet.write(0, 4, _('Condition'), column_heading_style)\n worksheet.write(0, 5, _('Received Date'), column_heading_style)\n worksheet.write(0, 6, _('Comments'), column_heading_style)\n worksheet.write(0, 7, _('Aging'), column_heading_style)\n worksheet.write(0, 8, _('Notes'), column_heading_style)\n # worksheet.write(0, 9, _('Receipt Number'), column_heading_style)\n # worksheet.write(0, 10, _('State'), column_heading_style)\n\n\n worksheet.col(0).width = 8000\n worksheet.col(1).width = 5000\n worksheet.col(2).width = 5000\n worksheet.col(3).width = 5000\n worksheet.col(4).width = 7000\n worksheet.col(5).width = 5000\n worksheet.col(6).width = 5000\n worksheet.col(7).width = 5000\n worksheet.col(8).width = 5000\n # worksheet.col(9).width = 5000\n # worksheet.col(10).width = 5000\n\n row = 1\n date_format = xlwt.XFStyle()\n date_format.num_format_str = 'mm/dd/yy'\n condition_id = self.env['ticl.condition'].search([('name', '=', 'To Recommend')])\n\n\n for wizard in self:\n recommend_objs = self.env['ticl.receipt.line'].search(\n [('condition_id', '=', condition_id.id),\n ('ticl_receipt_id.state', 'in', ('pending','inprogress','completed'))])\n for ids in recommend_objs:\n status = self.env['stock.move'].search([('serial_number', '=', ids.serial_number), (\n 'status', 'in', ('picked', 'packed', 'inventory','assigned'))],limit=1)\n if status.status in ('picked', 'packed', 'inventory', 'assigned'):\n\n if ids.received_date:\n rec_date = ids.received_date.strftime(\"%m/%d/%Y \")\n else:\n rec_date= \"\"\n worksheet.write(row, 0, ids.ticl_receipt_id.receiving_location_id.name or '')\n worksheet.write(row, 1, ids.manufacturer_id.name or '')\n worksheet.write(row, 2, ids.product_id.name or '')\n worksheet.write(row, 3, ids.serial_number or '')\n worksheet.write(row, 4, ids.condition_id.name or '')\n worksheet.write(row, 5, rec_date, date_format or '')\n worksheet.write(row, 6, ids.tel_note or '')\n \n if ids.received_date:\n received_date = str(ids.received_date)\n rec_date = received_date.split(\"-\")\n rd = rec_date[2].split(\" \")\n rd_date = date(int(rec_date[0]), int(rec_date[1]), int(rd[0]))\n today_date = date.today()\n duration = today_date - rd_date\n duration_days = duration.days\n\n if ids.received_date == False or ids.ticl_receipt_id.state == 'pending':\n worksheet.write(row, 7, \"Pre Arrival\", style_green)\n elif duration_days < 15 and ids.ticl_receipt_id.state != 'pending':\n worksheet.write(row, 7, duration_days, style_green)\n elif duration_days >=15 and duration_days <=29 and ids.ticl_receipt_id.state != 'pending':\n worksheet.write(row, 7, duration_days, style_orange)\n else:\n worksheet.write(row, 7, duration_days, style_red)\n \n\n worksheet.write(row, 8, '' or '')\n # worksheet.write(row, 9, ids.ticl_receipt_id.name or '')\n # worksheet.write(row, 10, ids.ticl_receipt_id.state or '')\n\n\n row += 1\n\n fp = io.BytesIO()\n workbook.save(fp)\n excel_file = base64.encodestring(fp.getvalue())\n self.to_recommend_file = excel_file\n self.file_name = 'To Recommend Report'\n fp.close()\n \n return {\n 'type': 'ir.actions.act_url',\n 'name': 'To Recommend Report',\n 'url': '/web/content/ticl.receipt.line/%s/to_recommend_file/%s.xls?download=true' % (\n self.id,self.file_name)\n\n }\n","sub_path":"ticl_chase_weekly_report/wizard/ticl_recommend_report.py","file_name":"ticl_recommend_report.py","file_ext":"py","file_size_in_byte":5591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"187879103","text":"fname = input(\"Enter file name: \")\nhandle = open(fname)\nimport re\nsuma = 0\n\nfor line in handle:\n line = line.rstrip()\n stuff = re.findall('[0-9]+',line)\n for value in stuff:\n nro = int(value)\n suma = suma + nro\n\nprint(suma)\n","sub_path":"ejercicio3.1.py","file_name":"ejercicio3.1.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"623673561","text":"from django.shortcuts import render, redirect\nfrom .models import City\nfrom .forms import CityForm\nfrom dotenv import load_dotenv\nimport os\nimport requests\nload_dotenv()\n\n\ndef index(request, id=None):\n msg = {}\n if id:\n city = City.objects.get(id=id)\n city.delete()\n return redirect('index')\n if(request.method == 'POST'):\n form = CityForm(request.POST)\n if form.is_valid():\n form.save()\n msg['text'] = 'Your city has been added'\n msg['class'] = 'alert alert-success'\n else:\n msg['text'] = 'Error has been encountered'\n msg['class'] = 'alert alert-danger'\n\n form = CityForm()\n appid = os.getenv('API_KEY')\n CITY_LIMIT = 7\n cities = City.objects.all()[:CITY_LIMIT]\n info = []\n for city in cities:\n url = f'https://api.openweathermap.org/data/2.5/weather?q={city.name}&units=metric&appid={appid}'\n res = requests.get(url).json()\n city_info = {\n 'city': city.name,\n 'id': city.id,\n 'temp': res['main']['temp'],\n 'wind_speed': res['wind']['speed'],\n 'clouds': res['clouds']['all'],\n 'icon': res['weather'][0]['icon'],\n }\n info.append(city_info)\n\n context = {\n 'info': info,\n 'form': form,\n 'msg': msg,\n }\n template_name = 'weather/index.html'\n return render(request, template_name, context)\n","sub_path":"mysite/weather/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"501748622","text":"#!/usr/bin/python3\n# encoding: utf-8\n\n\"\"\"\n@author: chsh\n@contact:\n@file: casedemo.py\n@time: 2018/8/8 22:26\n\"\"\"\nimport testrequestmodel\nimport xlrd, openpyxl, os, xlwt\n\ndef py2excelread03(filepath, sheetpage, beginreadrow, beginreadcell):\n '''\n 读取.xls结尾的2003excel文件\n :param filepath:提供excel文件路径\n :param sheetpage:读取excel的第几页\n :param beginreadrow:从第几行开始读\n :param beginreadcell:从第几列开始读\n :return result:返回结果列表\n '''\n try:\n result = []\n workbook = xlrd.open_workbook(filepath)\n sheets = workbook.sheet_names()\n worksheet = workbook.sheet_by_name(sheets[sheetpage-1])\n for i in range(beginreadrow-1, worksheet.nrows):\n data = []\n for j in range(beginreadcell-1, worksheet.ncols):\n #print(worksheet.cell_value(i, j), \"\\t\", end=\"\")\n data.append(worksheet.cell_value(i, j))\n result.append(data)\n #print()\n except Exception as e :\n print(e)\n finally:\n return result\n\ndef py2excelread07(filepath, sheetpagename, beginreadrow, beginreadcell):\n '''\n 读取.xlsx结尾的2007excel文件\n :param filepath:提供excel文件路径\n :param sheetpagename:读取excel第几页的标题\n :param beginreadrow:从第几行开始读\n :param beginreadcell:从第几列开始读\n :return result:返回结果列表\n '''\n try:\n result = []\n wb = openpyxl.load_workbook(filepath)\n sheet = wb.get_sheet_by_name(sheetpagename)\n for i in range(beginreadrow, sheet.max_row):\n for j in range(beginreadcell, sheet.max_column):\n if not sheet.cell(row=i, column=j).value:\n continue\n #print(sheet.cell(row=i, column=j).value, \"\\t\", end=\"\")\n result.append(sheet.cell(row=i, column=j).value)\n #print()\n except Exception as e :\n print(e)\n finally:\n return result\n\ndef loginprocase():\n pass\n\n\nif __name__ == '__main__':\n ospath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'testdata')\n file03path = ospath + \"/\" + \"TestData.xls\"\n file07path = ospath + \"/\" + \"TestData.xlsx\"\n print(\"filepath:%s\" % file07path)\n result = py2excelread03(file03path, 4, 4, 1)\n #result = py2excelread07(file07path, \"loginpro登录接口\", 4, 1)\n print(result)","sub_path":"myproject/test/casedemo.py","file_name":"casedemo.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"601047935","text":"a, b = map(int, input().split())\nnum = a + b\nsnum = str(abs(num))\nonum = \"\"\nfor i in range(1, len(snum) + 1):\n onum += snum[-i]\n if i % 3 == 0 and i < len(snum):\n onum += \",\"\nonum = onum[::-1]\nif num < 0:\n print(\"-\" + onum)\nelse:\n print(onum)\n","sub_path":"PAT Advanced Level/Python/1001.py","file_name":"1001.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"84611842","text":"# -*- coding: UTF-8 -*-\nfrom controller import Robot, Motion\nimport os\nimport sys\n\nlibraryPath = os.path.join(os.environ.get(\"WEBOTS_HOME\"), 'projects', 'robots', 'robotis', 'darwin-op', 'libraries',\n\t\t\t\t\t\t 'python37')\nlibraryPath = libraryPath.replace('/', os.sep)\nsys.path.append(libraryPath)\nfrom managers import RobotisOp2GaitManager, RobotisOp2MotionManager\n\nimport cv2 \nimport numpy as np\nfrom math import radians\nimport itertools\nfrom utils import *\nfrom yolo import *\n\nclass Walk():\n\tdef __init__(self):\n\t\tself.robot = Robot() # 初始化Robot类以控制机器人\n\t\tself.mTimeStep = int(self.robot.getBasicTimeStep()) # 获取当前每一个仿真步所仿真时间mTimeStep\n\t\tself.HeadLed = self.robot.getDevice('HeadLed') # 获取头部LED灯\n\t\tself.EyeLed = self.robot.getDevice('EyeLed') # 获取眼部LED灯\n\t\tself.HeadLed.set(0xff0000) # 点亮头部LED灯并设置一个颜色\n\t\tself.EyeLed.set(0xa0a0ff) # 点亮眼部LED灯并设置一个颜色\n\t\tself.mAccelerometer = self.robot.getDevice('Accelerometer') # 获取加速度传感器\n\t\tself.mAccelerometer.enable(self.mTimeStep) # 激活传感器,并以mTimeStep为周期更新数值\n\t\tself.fup = 0\n\t\tself.fdown = 0 # 定义两个类变量,用于之后判断机器人是否摔倒 \n\t\t\n\t\tself.mGyro = self.robot.getDevice('Gyro') # 获取陀螺仪\n\t\tself.mGyro.enable(self.mTimeStep) # 激活陀螺仪,并以mTimeStep为周期更新数值\n\n\t\tself.positionSensors = [] # 初始化关节角度传感器\n\t\tself.positionSensorNames = ('ShoulderR', 'ShoulderL', 'ArmUpperR', 'ArmUpperL',\n\t\t\t\t\t\t\t\t\t'ArmLowerR', 'ArmLowerL', 'PelvYR', 'PelvYL',\n\t\t\t\t\t\t\t\t\t'PelvR', 'PelvL', 'LegUpperR', 'LegUpperL',\n\t\t\t\t\t\t\t\t\t'LegLowerR', 'LegLowerL', 'AnkleR', 'AnkleL',\n\t\t\t\t\t\t\t\t\t'FootR', 'FootL', 'Neck', 'Head') # 初始化各传感器名\n\n\t\t# 获取各传感器并激活,以mTimeStep为周期更新数值\n\t\tfor i in range(0, len(self.positionSensorNames)):\n\t\t\tself.positionSensors.append(self.robot.getDevice(self.positionSensorNames[i] + 'S'))\n\t\t\tself.positionSensors[i].enable(self.mTimeStep)\n\t\t\t\n\t\t\t\n\t\t# 控制各个电机\n\t\tself.motors = []\n\t\tself.motorNames = ('ShoulderR', 'ShoulderL', 'ArmUpperR', 'ArmUpperL',\n\t\t\t\t\t\t 'ArmLowerR', 'ArmLowerL', 'PelvYR', 'PelvYL',\n\t\t\t\t\t\t 'PelvR', 'PelvL', 'LegUpperR', 'LegUpperL',\n\t\t\t\t\t\t 'LegLowerR', 'LegLowerL', 'AnkleR', 'AnkleL',\n\t\t\t\t\t\t 'FootR', 'FootL', 'Neck', 'Head')\n\t\tfor i in range(0, len(self.motorNames)):\n\t\t\tself.motors.append(self.robot.getDevice(self.motorNames[i]))\n\t\t\t\n\t\t\n\t\t\n\t\tself.mCamera = self.robot.getDevice(\"Camera\") # 获取并初始化摄像头\n\t\tself.mCamera.enable(self. mTimeStep)\n\t\tself.mCameraHeight, self.mCameraWidth = self.mCamera.getHeight(), self.mCamera.getWidth()\n\n\t\tself.mKeyboard = self.robot.getKeyboard() # 初始化键盘读入类\n\t\tself.mKeyboard.enable(self.mTimeStep) # 以mTimeStep为周期从键盘读取\n\n\t\tself.mMotionManager = RobotisOp2MotionManager(self.robot) # 初始化机器人动作组控制器\n\t\tself.mGaitManager = RobotisOp2GaitManager(self.robot, \"config.ini\") # 初始化机器人步态控制器\n\n\t\t# 初始化变量组\n\t\tself.vX, self.vY, self.vA = 0.,0.,0. # 前进、水平、转动方向的设定速度(-1,1)\n\t\tself.angle = np.array([0.,0.,0.]) # 角度, 由陀螺仪积分获得\n\t\tself.velocity = np.array([0.,0.,0.]) # 速度, 由加速度计积分获得\n\n\t\t# 加载关卡1-7的预训练模型\n\t\t#self.model1 = load_model('./pretrain/1.pth')\n\t\t#self.model2 = load_model('./pretrain/2.pth')\n\n\t# 执行一个仿真步。同时每步更新机器人偏航角度。\n\tdef myStep(self):\n\t\tret = self.robot.step(self.mTimeStep)\n\t\tself.angle = updateAngle(self.angle,self.mTimeStep,self.mGyro)\n\t\tif ret == -1:\n\t\t\texit(0)\n\n\t# 保持动作若干ms\n\tdef wait(self, ms):\n\t\tstartTime = self.robot.getTime()\n\t\ts = ms / 1000.0\n\t\twhile s + startTime >= self.robot.getTime():\n\t\t\tself.myStep()\n\t\t\n\t# 设置前进、水平、转动方向的速度指令,大小在-1到1之间。\n\t# 硬更新,不建议直接使用\n\tdef setMoveCommand(self,vX=None,vY=None,vA=None):\n\t\tif vX != None:\n\t\t\tself.vX = np.clip(vX,-1,1)\n\t\t\tself.mGaitManager.setXAmplitude(self.vX) # 设置x向速度(直线方向)\n\t\tif vY != None:\n\t\t\tself.vY = np.clip(vY,-1,1)\n\t\t\tself.mGaitManager.setYAmplitude(self.vY) # 设置y向速度(水平方向)\n\t\tif vA != None:\n\t\t\tself.vA = np.clip(vA,-1,1)\n\t\t\tself.mGaitManager.setAAmplitude(self.vA) # 设置转动速度\n\t\n\t# 设置前进速度,软更新 v = (1-α)*v + α*Target\n\tdef setForwardSpeed(self, target, threshold=0.05, tau=0.1):\n\t\tcurrent = self.vX\n\t\ttarget = np.clip(target,-1,1)\n\t\twhile np.abs(current - target) > threshold:\n\t\t\tcurrent = (1-tau)*current + tau*target\n\t\t\tself.setMoveCommand(vX=current)\n\t\t\tself.mGaitManager.step(self.mTimeStep)\n\t\t\tself.myStep()\n\t\tself.setMoveCommand(vX=target)\n\t\tself.mGaitManager.step(self.mTimeStep)\n\t\tself.myStep()\n\n\t# 设置侧向速度,软更新 v = (1-α)*v + α*Target\n\tdef setSideSpeed(self, target, threshold=0.05, tau=0.1):\n\t\tcurrent = self.vY\n\t\ttarget = np.clip(target,-1,1)\n\t\twhile np.abs(current - target) > threshold:\n\t\t\tcurrent = (1-tau)*current + tau*target\n\t\t\tself.setMoveCommand(vY=current)\n\t\t\tself.mGaitManager.step(self.mTimeStep)\n\t\t\tself.myStep()\n\t\tself.setMoveCommand(vY=target)\n\t\tself.mGaitManager.step(self.mTimeStep)\n\t\tself.myStep()\n\t\n\t# 设置转动速度,软更新 v = (1-α)*v + α*Target\n\tdef setRotationSpeed(self, target, threshold=0.05, tau=0.1):\n\t\tcurrent = self.vA\n\t\ttarget = np.clip(target,-1,1)\n\t\twhile np.abs(current - target) > threshold:\n\t\t\tcurrent = (1-tau)*current + tau*target\n\t\t\tself.setMoveCommand(vA=current)\n\t\t\tself.mGaitManager.step(self.mTimeStep)\n\t\t\tself.myStep()\n\t\tself.setMoveCommand(vA=target)\n\t\tself.mGaitManager.step(self.mTimeStep)\n\t\tself.myStep()\n\t\n\t# 通过PID控制机器人转体到target角度\t\t\t\n\tdef setRotation(self, target, threshold=0.5,Kp=0.1):\n\t\tself.setForwardSpeed(0.)\n\t\tself.setSideSpeed(0.)\n\t\tself.setRotationSpeed(0.)\n\n\t\twhile np.abs(self.angle[-1] - target) > threshold:\n\t\t\tu = Kp*(target - self.angle[-1])\n\t\t\tu = np.clip(u,-1,1)\n\t\t\tself.setMoveCommand(vA = u)\n\t\t\tself.mGaitManager.step(self.mTimeStep)\n\t\t\tself.myStep()\n\n\t\tself.setForwardSpeed(0.)\n\t\tself.setSideSpeed(0.)\n\t\tself.setRotationSpeed(0.)\n\t\treturn self.angle[-1]\n\t\n\tdef setRobotStop(self):\n\t\tself.setForwardSpeed(0.)\n\t\tself.setSideSpeed(0.)\n\t\tself.setRotationSpeed(0.)\n\t\n\tdef setRobotRun(self,speed=1.):\n\t\tself.setForwardSpeed(speed)\n\t\tself.setSideSpeed(0.)\n\t\tself.setRotationSpeed(0.)\n\n\t\n\t# 检查偏航是否超过指定threshold,若是则修正回0°附近,由eps指定\n\tdef checkIfYaw(self, threshold=7.5, eps=0.25):\n\t\tif np.abs(self.angle[-1]) > threshold:\n\t\t\tprint('Current Yaw is %.3f, begin correction' % self.angle[-1])\n\t\t\twhile np.abs(self.angle[-1]) > eps:\n\t\t\t\tu = -0.02 * self.angle[-1]\n\t\t\t\tu = np.clip(u,-1,1)\n\t\t\t\tself.setMoveCommand(vA = u)\n\t\t\t\tself.mGaitManager.step(self.mTimeStep)\n\t\t\t\tself.myStep()\n\t\t\tprint('Current Yaw is %.3f, finish correction' % self.angle[-1])\n\t\telse:\n\t\t\tpass\n\t\n\t# 比赛开始前准备动作,保持机器人运行稳定和传感器读数稳定\n\tdef prepare(self,waitingTime):\n\t\tprint('########Preparation_Start########')\n\t\t # 仿真一个步长,刷新传感器读数\n\t\tself.robot.step(self.mTimeStep)\n\t\t# 准备动作\n\t\tprint('Preparing...')\n\t\tself.mMotionManager.playPage(9) # 执行动作组9号动作,初始化站立姿势,准备行走\n\t\tself.wait(500)\n\t\t# 开始运动\n\t\tself.mGaitManager.setBalanceEnable(True)\n\t\tself.mGaitManager.start()\n\t\tself.setRobotStop()\n\t\tself.wait(waitingTime)\n\t\tprint('Ready to Play!')\n\t\tprint('Initial Yaw is %.3f' % self.angle[-1])\n\t\tprint('########Preparation_End########')\n\t\n\t# 构造Z字轨迹\n\tdef Z(self,angle,interval):\n\t\tspeed = self.vX\n\t\t# 左转45度\n\t\tself.setRotation(angle)\n\t\tself.setForwardSpeed(speed)\n\t\tns = itertools.repeat(0,interval)\n\t\tfor n in ns:\n\t\t\tself.mGaitManager.step(self.mTimeStep)\n\t\t\tself.myStep()\n\t\tself.setRotation(0)\n\t\tself.setRobotRun(speed) # 保存原来的行进速度\n\t\t\n\tdef keyBoardControl(self,collet_data=False,rotation=True):\n\t\tself.isWalking = True\n\t\tns = itertools.count(0)\n\t\tfor n in ns:\n\t\t\tself.mGaitManager.setXAmplitude(0.0) # 前进为0\n\t\t\tself.mGaitManager.setAAmplitude(0.0) # 转体为0\n\t\t\tkey = 0 # 初始键盘读入默认为0\n\t\t\tkey = self.mKeyboard.getKey() # 从键盘读取输入\n\t\t\tif collet_data and n % 53 == 0:\n\t\t\t\trgb_raw = getImage(self.mCamera)\n\t\t\t\tprint('save image')\n\t\t\t\tcv2.imwrite('./tmp/c_'+str(n)+'.png',rgb_raw)\n\t\t\tif key == 49:\n\t\t\t\tpos = self.positionSensors[19].getValue()\n\t\t\t\tself.motors[19].setPosition(np.clip(pos+0.05,-0.25,0.4))\n\t\t\telif key == 50:\n\t\t\t\tpos = self.positionSensors[19].getValue()\n\t\t\t\tself.motors[19].setPosition(np.clip(pos-0.05,-0.25,0.4))\n\t\t\telif key == 51:\n\t\t\t\tif collet_data==1:\n\t\t\t\t\tcollet_data = 0\n\t\t\t\tif collet_data==0:\n\t\t\t\t\tcollet_data=1\n\t\t\tif rotation :\n\t\t\t\tif key == 32: # 如果读取到空格,则改变行走状态\n\t\t\t\t\tif (self.isWalking): # 如果当前机器人正在走路,则使机器人停止\n\t\t\t\t\t\tself.mGaitManager.stop()\n\t\t\t\t\t\tself.isWalking = False\n\t\t\t\t\t\tself.wait(200)\n\t\t\t\t\telse: # 如果机器人当前停止,则开始走路\n\t\t\t\t\t\tself.mGaitManager.start()\n\t\t\t\t\t\tself.isWalking = True\n\t\t\t\t\t\tself.wait(200)\n\t\t\t\telif key == 315: # 如果读取到‘↑’,则前进\n\t\t\t\t\tself.mGaitManager.setXAmplitude(1.0)\n\t\t\t\telif key == 317: # 如果读取到‘↓’,则后退\n\t\t\t\t\tself.mGaitManager.setXAmplitude(-1.0)\n\t\t\t\telif key == 316: # 如果读取到‘←’,则左转\n\t\t\t\t\tself.mGaitManager.setAAmplitude(-0.5)\n\t\t\t\telif key == 314: # 如果读取到‘→’,则右转\n\t\t\t\t\tself.mGaitManager.setAAmplitude(0.5)\n\t\t\telse:\n\t\t\t\tself.checkIfYaw()\n\t\t\t\tif key == 32: # 如果读取到空格,则改变行走状态\n\t\t\t\t\tif (self.isWalking): # 如果当前机器人正在走路,则使机器人停止\n\t\t\t\t\t\tself.mGaitManager.stop()\n\t\t\t\t\t\tself.isWalking = False\n\t\t\t\t\t\tself.wait(200)\n\t\t\t\t\telse: # 如果机器人当前停止,则开始走路\n\t\t\t\t\t\tself.mGaitManager.start()\n\t\t\t\t\t\tself.isWalking = True\n\t\t\t\t\t\tself.wait(200)\n\t\t\t\telif key == 315: # 如果读取到‘↑’,则前进\n\t\t\t\t\tself.mGaitManager.setXAmplitude(1.0)\n\t\t\t\telif key == 317: # 如果读取到‘↓’,则后退\n\t\t\t\t\tself.mGaitManager.setXAmplitude(-1.0)\n\t\t\t\telif key == 316: # 如果读取到‘←’,则左转\n\t\t\t\t\tself.mGaitManager.setYAmplitude(-1)\n\t\t\t\telif key == 314: # 如果读取到‘→’,则右转\n\t\t\t\t\tself.mGaitManager.setYAmplitude(1)\n\t\t\tself.mGaitManager.step(self.mTimeStep) # 步态生成器生成一个步长的动作\n\t\t\tself.myStep() # 仿真一个步长\n\n# 水平开合横杆\n\tdef stage1(self):\n\t\tprint('########Stage1_Start########')\n\t\tcrossBarDownFlag = False\n\t\tgoFlag = False\n\t\tns = itertools.count(0)\n\t\tfor n in ns:\n\t\t\tself.checkIfYaw()\n\t\t\tif n % 100 == 0:\n\t\t\t\trgb_raw = getImage(self.mCamera)\n\t\t\t\tpred,prob = call_classifier(rgb_raw,self.model1)\n\t\t\t\tif not crossBarDownFlag:\n\t\t\t\t\tif pred == 1:\n\t\t\t\t\t\tcrossBarDownFlag = True\n\t\t\t\t\t\tprint('CrossBar already Down with probablity %.3f'%prob)\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint('Wait for CrossBar Down with probablity %.3f ...'%prob)\n\t\t\t\telse:\n\t\t\t\t\tif pred == 0:\n\t\t\t\t\t\tgoFlag = True\n\t\t\t\t\t\tprint('CrossBar already UP with probablity %.3f, Go Go Go!'%prob)\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint('Wait for CrossBar Up with probablity %.3f ...'%prob)\n\t\t\tif goFlag:\n\t\t\t\tself.setRobotRun()\n\t\t\t\t#self.motors[18].setPosition(radians(50))\n\t\t\t\t#self.motors[19].setPosition(radians(30))\n\t\t\t\tbreak\n\t\t\tself.mGaitManager.step(self.mTimeStep)\n\t\t\tself.myStep()\n\t\tn0 = n\n\t\tfor n in ns:\n\t\t\tself.checkIfYaw()\n\t\t\t# 持续走一段时间,写死了这里\n\t\t\tif (n-n0) >= 850:\n\t\t\t\tbreak\n\t\t\tself.mGaitManager.step(self.mTimeStep)\n\t\t\tself.myStep()\n\t\tprint('########Stage1_End########')\n\n# 回字陷阱\n\tdef stage2(self):\n\t\tprint('########Stage2_Start########')\n\t\tself.setRobotStop()\n\t\tself.checkIfYaw(threshold=3.0)\n\t\tns = itertools.count(0)\n\t\tcenter_y,center_x = None, None\n\t\tfor n in ns:\n\t\t\tif n % 5 == 0:\n\t\t\t\trgb_raw = getImage(self.mCamera)\n\t\t\t\tbinary= call_segmentor(rgb_raw,self.model2)\n\t\t\t\ttrap = np.argwhere(binary == 255)\n\t\t\t\ttmp_y,tmp_x = np.mean(trap,axis=0)\n\t\t\t\tif not center_y and not center_x:\n\t\t\t\t\tcenter_y, center_x = tmp_y,tmp_x\n\t\t\t\telse:\n\t\t\t\t\tcenter_y = 0.9*center_y + 0.1*tmp_y\n\t\t\t\t\tcenter_x = 0.9*center_x + 0.1*tmp_x\n\t\t\tif center_x < 75:\n\t\t\t\tself.setSideSpeed(0.5)\n\t\t\t\tself.checkIfYaw(threshold=3.0)\n\t\t\telif center_x > 85:\n\t\t\t\tself.setSideSpeed(-0.5)\n\t\t\t\tself.checkIfYaw(threshold=3.0)\n\t\t\telse:\n\t\t\t\tself.setSideSpeed(0.)\n\t\t\t\tself.checkIfYaw(threshold=3.5)\n\t\t\t\tprint('Align Trap CenterX : %d CenterY : %d' %(center_x,center_y))\n\t\t\t\tbreak\n\t\t\tself.mGaitManager.step(self.mTimeStep) # 步态生成器生成一个步长的动作\n\t\t\tself.myStep() # 仿真一个步长\n\t\t\n\t\tself.setRobotRun()\n\t\tself.Z(angle=45,interval=275)\n\t\tns = itertools.repeat(0,500)\n\t\tfor n in ns:\n\t\t\tself.checkIfYaw(threshold=3.0)\n\t\t\tself.mGaitManager.step(self.mTimeStep) # 步态生成器生成一个步长的动作\n\t\t\tself.myStep() # 仿真一个步长\n\t\tself.setRobotRun(0.5)\n\t\tself.Z(angle=-45,interval=500)\n\t\tprint('########Stage2_End########')\n\n# 地雷路段\n\tdef stage3(self):\n\t\tprint('########Stage3_Start########')\n\t\tself.setRobotRun(1.0)\n\t\tself.motors[19].setPosition(radians(0))\n\t\tyolonet,yolodecoders = load_yolo('./pretrain/3.pth',class_names=['dilei'])\n\t\tns = itertools.count(0)\n\t\tfor n in ns:\n\t\t\tif n % 5 == 0 and np.abs(self.angle[0]) < 1.0:\n\t\t\t\trgb_raw = getImage(self.mCamera)\n\t\t\t\t#cv2.imwrite('./tmp/'+str(n)+'.png',rgb_raw)\n\t\t\t\tres = call_yolo(rgb_raw,yolonet,yolodecoders,class_names=['dilei'])\n\t\t\t\tif not res:\n\t\t\t\t\tprint('%d Mine(s) has been Detected' % len(res))\n\t\t\t\t# 只看视野一定范围内的地雷,过远的忽略\n\t\t\t\tcenters = []\n\t\t\t\tfor info in res:\n\t\t\t\t\ttop,left,down,right = info['bbox']\n\t\t\t\t\tcenters.append([(left+right)/2, (top+down)/2])\n\t\t\t\tcenters = [center for center in centers if center[1]>0.5*self.mCameraHeight]\n\t\t\t\tif not centers:\n\t\t\t\t\tpass\n\t\t\t\telse:\n\t\t\t\t\t# 看一下地雷距离视野中轴线的水平距离,判定危险级\n\t\t\t\t\tdanger = [center[0] - self.mCameraWidth/2 for center in centers]\n\t\t\t\t\tdanger = sorted(danger, key=lambda x: np.abs(x))\n\t\t\t\t\tif np.abs(danger[0]) < 45:\n\t\t\t\t\t\tprint('Warning!')\n\t\t\t\t\t\t#self.Z(0,interval=20)\n\t\t\t\t\t\tif len(danger)==1:\n\t\t\t\t\t\t\tself.Z(30,interval=200) if danger[0] >= 0 else self.Z(-45,interval=100)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tself.Z(30,interval=200) if danger[1] >= 0 else self.Z(-45,interval=100)\n\t\t\t\t\telse:\n\t\t\t\t\t\tpass\n\t\t\tself.checkIfYaw(threshold=5.)\n\t\t\tself.mGaitManager.step(self.mTimeStep) # 步态生成器生成一个步长的动作\n\t\t\tself.myStep() # 仿真一个步长\n\t\tprint('########Stage3_End########')\n\n# 翻越障碍\n\tdef stage4(self):\n\t\tprint('########Stage4_Start########')\n\t\t# 调整头部位置,低下头看\n\t\tself.setRobotRun(0.0)\n\t\tself.mGaitManager.stop()\n\t\tself.motors[19].setPosition(-0.3)\n\t\t# 重复50个空循环等待电机到位\n\t\tns = itertools.repeat(0,50)\n\t\tfor n in ns:\n\t\t\tself.mGaitManager.step(self.mTimeStep) # 步态生成器生成一个步长的动作\n\t\t\tself.myStep() # 仿真一个步长\n\t\t# rgb_raw = getImage(self.mCamera)\n\t\t# cv2.imwrite('./tmp/'+str(n)+'.png',rgb_raw)\n\n\t\tself.mGaitManager.start()\n\t\tself.setRobotRun(1.0)\n\t\tns = itertools.count(0)\n\t\tfor n in ns:\n\t\t\tself.checkIfYaw()\n\t\t\tif np.abs(self.angle[0]) < 1.0: \n\t\t\t\trgb_raw = getImage(self.mCamera)\n\t\t\t\tob_x,ob_y = obstacleDetect(rgb_raw)\n\t\t\t\tif ob_y > 0:\n\t\t\t\t\tself.setRobotRun(0.5) # 看到蓝色障碍物注意减速\n\t\t\t\tif ob_y > 75: # 蓝色障碍物出现在正确位置,跳出循环,准备空翻\n\t\t\t\t\tbreak\n\t\t\tself.mGaitManager.step(self.mTimeStep) # 步态生成器生成一个步长的动作\n\t\t\tself.myStep() # 仿真一个步长\n\t\t\n\t\t# 空翻与起身\n\t\tself.setRobotRun(0.0)\n\t\tself.mGaitManager.stop()\n\t\trollMotion = Motion('./motion/roll.motion')\n\t\trollMotion.setLoop(False)\n\t\trollMotion.play()\n\t\twhile not rollMotion.isOver():\n\t\t\tself.myStep()\n\t\tself.mMotionManager.playPage(11)\n\t\tself.mMotionManager.playPage(9)\n\n\t\t# 陀螺仪累计数据全部清空\n\t\tself.angle = np.array([0.,0.,0.])\n\n\t\t# 往后退两步\n\t\tself.mGaitManager.start()\n\t\tself.setForwardSpeed(-0.1)\n\t\tns = itertools.repeat(0,500)\n\t\tfor n in ns:\n\t\t\tself.mGaitManager.step(self.mTimeStep) # 步态生成器生成一个步长的动作\n\t\t\tself.myStep() # 仿真一个步长\n\t\t\n\t\tself.setForwardSpeed(-0.05)\n\t\tns = itertools.count(0)\n\t\tfor n in ns:\n\t\t\tif np.abs(self.angle[-1]) < 1.0:\n\t\t\t\trgb_raw = getImage(self.mCamera)\n\t\t\t\tcv2.imwrite('./tmp/'+str(n)+'.png',rgb_raw)\n\t\t\tself.mGaitManager.step(self.mTimeStep) # 步态生成器生成一个步长的动作\n\t\t\tself.myStep() # 仿真一个步长\n\t\t\tif n == 1000:\n\t\t\t\tbreak\n\n\n\t\t\n\t\t# # 起身后转向90度,开始下一阶段任务\n\t\t# self.mGaitManager.start()\n\t\t# self.setRotation(20)\n\t\t# self.wait(100)\n\t\t# self.setRotation(40)\n\t\t# self.wait(100)\n\t\t# self.setRotation(80)\n\t\t# self.wait(100)\n\n\t\t# # 抬头,准备对齐赛道\n\t\t# self.motors[19].setPosition(0.6)\n\t\t# # 重复50个空循环等待电机到位\n\t\t# ns = itertools.repeat(0,50000)\n\t\t# for n in ns:\n\t\t# \tself.mGaitManager.step(self.mTimeStep) # 步态生成器生成一个步长的动作\n\t\t# \tself.myStep() # 仿真一个步长\n\t\tprint('########Stage4_End########')\n\n\t# 过桥\n\tdef stage5(self):\n\t\tball_color = 'green'\n\t\tcolor_dist = {'red': {'Lower': np.array([0, 60, 60]), 'Upper': np.array([6, 255, 255])},\n\t\t\t 'blue': {'Lower': np.array([100, 80, 46]), 'Upper': np.array([124, 255, 255])},\n\t\t\t 'green': {'Lower': np.array([35, 43, 35]), 'Upper': np.array([90, 255, 255])},\n\t\t\t }\n\t\tns = itertools.count(1)\n\t\tturn_flag=0\n\t\tfor n in ns:\n\t\t\taction_flag=0\n\n\t\t\tif n % 20 == 0:\n\t\t\t\t# img processing\n\t\t\t\trgb_raw = getImage(self.mCamera)\n\t\t\t\trgb_raw = cv2.cvtColor(rgb_raw,cv2.COLOR_BGR2RGB)\n\t\t\t\thsv = cv2.cvtColor(rgb_raw, cv2.COLOR_BGR2HSV)\n\t\t\t\terode_hsv = cv2.erode(hsv, None, iterations=2)\n\t\t\t\tinRange_hsv = cv2.inRange(erode_hsv, color_dist[ball_color]['Lower'], color_dist[ball_color]['Upper'])\n\t\t\t\tcnts = cv2.findContours(inRange_hsv.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]\n\n\t\t\t\tif cnts:\n\t\t\t\t\tc = max(cnts, key=cv2.contourArea)\n\t\t\t\t\trect = cv2.minAreaRect(c)\n\t\t\t\t\tbox = cv2.boxPoints(rect)\n\n\t\t\t\t\tmid_point=np.mean(box,0)\n\n\t\t\t\tif turn_flag==0:\n\t\t\t\t\tif mid_point[0]<75:\n\t\t\t\t\t\tself.turn_left(0.2)\n\t\t\t\t\t\taction_flag=1\n\t\t\t\t\tif mid_point[0]>85:\n\t\t\t\t\t\tself.turn_right(0.2)\n\t\t\t\t\t\taction_flag=1\n\t\t\t\t\tif mid_point[1]>=100 and turn_flag==0:\n\t\t\t\t\t\tturn_flag=1\n\n\t\t\t\tif turn_flag==1:\n\t\t\t\t\tpass\n\t\t \n\t\t\t\tif not action_flag:\n\t\t\t\t\tself.mGaitManager.setXAmplitude(0.8) # 前进为0\n\t\t\t\t\tself.mGaitManager.setAAmplitude(0.0) # 转体为0\n\t\t\t\t\tself.mGaitManager.step(self.mTimeStep) # 步态生成器生成一个步长的动作\n\t\t\t\t\tself.myStep() # 仿真一个步长\n\n\tdef turn_right(self, vel=0.3):\n\t\tself.mGaitManager.setXAmplitude(0.0)\n\t\tself.mGaitManager.setAAmplitude(-vel)\n\t\tself.mGaitManager.step(self.mTimeStep) # 步态生成器生成一个步长的动作\n\t\tself.myStep()\n\n\tdef turn_left(self, vel=0.3):\n\t\tself.mGaitManager.setXAmplitude(0.0)\n\t\tself.mGaitManager.setAAmplitude(vel)\n\t\tself.mGaitManager.step(self.mTimeStep) # 步态生成器生成一个步长的动作\n\t\tself.myStep()\n# 踢球进洞\n\tdef stage6(self):\n\t\tpoint_size = 1\n\t\tpoint_color1 = (0, 0, 255) # BGR\n\t\tpoint_color2 = (0, 255, 0)\n\t\tthickness = 4 \n\n\t\tprint('########Stage6_Start########')\n\t\tself.mMotionManager.playPage(1)\n\t\tyolonet_ball,yolodecoders_ball = load_yolo('./pretrain/ball.pth',class_names= ['ball','hole'])\n\t\tyolonet_hole,yolodecoders_hole = load_yolo('./pretrain/hole.pth',class_names= ['ball','hole'])\n\t\tself.setRobotRun(0.0)\n\t\tself.setSideSpeed(1.0)\n\t\theadPos = 0\n\t\tself.motors[19].setPosition(headPos)\n\t\tns = itertools.count(0)\n\t\t# flag\n\t\tturn_flag=0\n\n\t\tfor n in ns:\n\t\t\taction_flag=0\n\t\t\tif n % 5 == 0:\n\t\t\t\trgb_raw = getImage(self.mCamera)\n\t\t\t\trgb_raw = cv2.cvtColor(rgb_raw,cv2.COLOR_BGR2RGB)\n\t\t\t\tres_ball = call_yolo(rgb_raw,yolonet_ball,yolodecoders_ball,class_names=['ball','hole'],confidence=0.8)\n\t\t\t\tres_hole = call_yolo(rgb_raw,yolonet_hole,yolodecoders_hole,class_names=['ball','hole'],confidence=0.1)\n\t\t\t\t\n\t\t\t\tif res_hole:\n\t\t\t\t\tfor info in res_hole:\n\t\t\t\t\t\ttop,left,down,right = info['bbox']\n\t\t\t\t\t\tcenter_hole_x, center_hole_y = (left+right)/2, (top+down)/2\n\t\t\t\t\t\t# print('hole',[center_hole_x, center_hole_y])\n\t\t\t\t\t\thole_pos = [center_hole_x, center_hole_y]\n\t\t\t\t\t\t# cv2.circle(rgb_raw, (int(center_hole_x),int(center_hole_y)), point_size, point_color2, thickness)\n\n\t\t\t\tball_pos=[]\n\t\t\t\tif res_ball:\n\t\t\t\t\tfor info in res_ball:\n\t\t\t\t\t\ttop,left,down,right = info['bbox']\n\t\t\t\t\t\tcenter_ball_x, center_ball_y = (left+right)/2, (top+down)/2\n\t\t\t\t\t\t# print('ball',[center_ball_x, center_ball_y])\n\t\t\t\t\t\tball_pos.append([center_ball_x, center_ball_y])\n\n\t\t\t\t\tif len(ball_pos)>1:\n\t\t\t\t\t\tdis1=np.linalg.norm(np.array(ball_pos[0])-np.array(hole_pos))\n\t\t\t\t\t\tdis2=np.linalg.norm(np.array(ball_pos[1])-np.array(hole_pos))\n\t\t\t\t\t\tball_pos=ball_pos[0] if dis1>=dis2 else ball_pos[1]\n\t\t\t\t\telse:\n\t\t\t\t\t\tball_pos = ball_pos[0]\n\t\t\t\t\t# cv2.circle(rgb_raw, (int(ball_pos[0]),int(ball_pos[1])), point_size, point_color1, thickness)\n\n\t\t\t\t# cv2.imshow('image', rgb_raw)\n\t\t\t\t# cv2.waitKey(0) \n\n\t\t\tif turn_flag==0:\n\t\t\t\tif ball_pos:\n\t\t\t\t\tprint(ball_pos)\n\t\t\t\t\tif ball_pos[0]<75:\n\t\t\t\t\t\tself.turn_left(0.3)\n\t\t\t\t\t\taction_flag=1\n\t\t\t\t\tif ball_pos[0]>85:\n\t\t\t\t\t\tself.turn_right(0.3)\n\t\t\t\t\t\taction_flag=1\n\t\t\t\t\tif ball_pos[1]>=100 and turn_flag==0:\n\t\t\t\t\t\tturn_flag=1\n\n\t\t\tif turn_flag==1:\n\t\t\t\tif hole_pos:\n\t\t\t\t\tprint('hole_pos',hole_pos)\n\t\t\t\tif ball_pos and hole_pos:\n\t\t\t\t\tif ball_pos[0]=hole_pos[0]+3:\n\t\t\t\t\t\tself.turn_left(0.2)\n\t\t\t\t\t\taction_flag=1\n\t\t\t\t\telse:\n\t\t\t\t\t\tturn_flag=2\n\t\t\t\telif hole_pos:\n\t\t\t\t\tif hole_pos[0]<74:\n\t\t\t\t\t\tself.turn_left(0.3)\n\t\t\t\t\t\taction_flag=1\n\t\t\t\t\telif hole_pos[0]>86:\n\t\t\t\t\t\tself.turn_right(0.3)\n\t\t\t\t\t\taction_flag=1\n\t\t\t\t\telse:\n\t\t\t\t\t\tturn_flag=2\n\n\t\t\tif turn_flag==2:\n\t\t\t\tprint(turn_flag)\n\t\t\t\tif ball_pos:\n\t\t\t\t\tif ball_pos[0]<76:\n\t\t\t\t\t\tself.mGaitManager.setXAmplitude(0)\n\t\t\t\t\t\tself.mGaitManager.setYAmplitude(-0.2)\n\t\t\t\t\t\tself.mGaitManager.step(self.mTimeStep) # 步态生成器生成一个步长的动作\n\t\t\t\t\t\tself.myStep()\n\t\t\t\t\t\taction_flag=1\n\t\t\t\t\telif ball_pos[0]>84:\n\t\t\t\t\t\tself.mGaitManager.setXAmplitude(0)\n\t\t\t\t\t\tself.mGaitManager.setYAmplitude(0.2)\n\t\t\t\t\t\tself.mGaitManager.step(self.mTimeStep) # 步态生成器生成一个步长的动作\n\t\t\t\t\t\tself.myStep()\n\t\t\t\t\t\taction_flag=1\n\t\t\t\t\telse:\n\t\t\t\t\t\tturn_flag=3\n\n\t\t\tif turn_flag==3:\n\t\t\t\tprint('stop')\n\t\t\t\tself.setRobotStop()\n\t\t\t\tself.mGaitManager.stop()\n\t\t\t\tself.mGaitManager.step(self.mTimeStep) # 步态生成器生成一个步长的动作\n\t\t\t\tself.myStep() # 仿真一个步长\n\n\t\t\tif not action_flag:\n\t\t\t\tself.mGaitManager.setXAmplitude(0.8) # 前进为0\n\t\t\t\tself.mGaitManager.setAAmplitude(0.0) # 转体为0\n\t\t\t\tself.mGaitManager.step(self.mTimeStep) # 步态生成器生成一个步长的动作\n\t\t\t\tself.myStep() # 仿真一个步长\n\t\t\n\n\t\tstepMotion = Motion('motion/kick.motion')\n\t\tstepMotion.setLoop(True)\n\t\tstepMotion.play()\n\t\twhile not stepMotion.isOver():\n\t\t\tself.myStep()\n\t\tprint('########Stage6_End########')\n\n\n# 走楼梯\n\tdef stage7(self):\n\t\tprint('########Stage7_Start########')\n\t\t# 前面把南科大怼楼梯的动作加上就很稳了\n\t\tstepMotion = Motion('motion/stair_up.motion')\n\t\tstepMotion.setLoop(False)\n\t\tstepMotion.play()\n\t\twhile not stepMotion.isOver():\n\t\t\tself.myStep()\n\t\t# 陀螺仪累计数据全部清空\n\t\tself.angle = np.array([0.,0.,0.])\n\t\tstepMotion = Motion('motion/stair_down.motion')\n\t\tstepMotion.setLoop(False)\n\t\tstepMotion.play()\n\t\twhile not stepMotion.isOver():\n\t\t\tself.myStep()\n\t\tstepMotion.play()\n\t\twhile not stepMotion.isOver():\n\t\t\tself.myStep()\n\t\tprint(self.angle[-1])\n\t\tself.mGaitManager.start()\n\t\tself.setForwardSpeed(0.0)\n\t\tself.checkIfYaw(threshold=3.0)\n\t\tself.setForwardSpeed(1.0)\n\t\tns = itertools.repeat(0,700)\n\t\tfor n in ns:\n\t\t\tself.mGaitManager.step(self.mTimeStep) # 步态生成器生成一个步长的动作\n\t\t\tself.myStep() # 仿真一个步长\n\t\tself.setRobotStop()\n\t\tself.mGaitManager.stop()\n\t\tprint('########Stage7_End########')\n\n# 上下开合横杆\n\tdef stage8(self):\n\t\tprint('########Stage8_Start########')\n\t\tstage8model = load_model('./pretrain/8.pth')\n\t\tcrossBarCloseFlag = False\n\t\tgoFlag = False\n\t\tns = itertools.count(0)\n\t\tfor n in ns:\n\t\t\tself.checkIfYaw()\n\t\t\tif n % 100 == 0:\n\t\t\t\trgb_raw = getImage(self.mCamera)\n\t\t\t\tpred,prob = call_classifier(rgb_raw,stage8model)\n\t\t\t\tif not crossBarCloseFlag:\n\t\t\t\t\tif pred == 1:\n\t\t\t\t\t\tcrossBarCloseFlag = True\n\t\t\t\t\t\tprint('CrossBar already Close with probablity %.3f'%prob)\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint('Wait for CrossBar Close with probablity %.3f ...'%prob)\n\t\t\t\telse:\n\t\t\t\t\tif pred == 0:\n\t\t\t\t\t\tgoFlag = True\n\t\t\t\t\t\tprint('CrossBar already Open with probablity %.3f, Go Go Go!'%prob)\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint('Wait for CrossBar Open with probablity %.3f ...'%prob)\n\t\t\tif goFlag:\n\t\t\t\tself.mGaitManager.start()\n\t\t\t\tself.setRobotRun()\n\t\t\t\tbreak\n\t\t\tself.mGaitManager.step(self.mTimeStep) # 步态生成器生成一个步长的动作\n\t\t\tself.myStep() # 仿真一个步长\n\t\tn0 = n\n\t\tfor n in ns:\n\t\t\tself.checkIfYaw()\n\t\t\t# 持续走一段时间,写死了这里\n\t\t\tif (n-n0) >= 1000:\n\t\t\t\tbreak\n\t\t\tself.mGaitManager.step(self.mTimeStep) # 步态生成器生成一个步长的动作\n\t\t\tself.myStep() # 仿真一个步长\n\t\tdel stage8model\n\t\tprint('########Stage8_End########')\n\t\n\n\t# 主函数循环\n\tdef run(self):\n\t\t# 准备动作\n\t\tself.prepare(waitingTime=500)\n\t\t\n\t\t# 通过第一关\t上下开横杆\n\t\t#self.stage1()\n\t\t# 通过第二关\t回字陷阱\t\n\t\t#self.stage2()\n\t\t# 通过第三关\t地雷路段\n\t\t#self.stage3()\n\t\t# 通过第四关\t翻越障碍与过门\n\t\t#self.stage4()\n\t\t# 通过第五关\t窄桥路段\n\t\tself.stage5()\n\t\t# 通过第六关\t踢球进洞\n\t\t#self.stage6()\n\t\t# 通过第七关\t走楼梯\n\t\t#self.stage7()\n\t\t# 通过第八关\t水平开横杆\n\t\t#self.stage8()\n\t\t# ���盘控制与采集数据\n\t\t#self.keyBoardControl(collet_data=0,rotation=1)\n\t\t\n\t\t# 停下\n\t\tself.mMotionManager.playPage(1)\n\t\tself.mGaitManager.stop()\n\n\t\twhile True:\n\t\t\t#self.checkIfYaw(threshold=3.0)\n\t\t\tself.mGaitManager.step(self.mTimeStep)\n\t\t\tself.myStep()\n\nif __name__ == '__main__':\n\twalk = Walk() # 初始化Walk类\n\twalk.run() # 运行控制器","sub_path":"running_robot_v2.0/controllers/thu_walk/thu_walk.py","file_name":"thu_walk.py","file_ext":"py","file_size_in_byte":26155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"593010807","text":"from setuptools import setup, find_packages\n\n\ndef get_requirements(filename):\n requirements = []\n with open(filename, \"rt\") as req_file:\n for line in req_file.read().splitlines():\n if not line.strip().startswith(\"#\"):\n requirements.append(line)\n return requirements\n\n\nproject_requirements = get_requirements(\"requirements.txt\")\n\nsetup(\n name=\"conan-guide\",\n version=\"1.0.0\",\n url=\"https://github.com/afri-bit/conan-guide\",\n license=\"MIT\",\n author=\"Afrizal Herlambnag\",\n author_email=\"afri.bit@outlook.com\",\n description=\"Qt based Graphical User Interface (GUI) to interact with conan package manager\",\n\n packages=find_packages(),\n\n # List run-time dependencies here. These will be installed by pip when\n # your project is installed. For the detail information please refer to\n # https://packaging.python.org/en/latest/requirements.html\n install_requires=project_requirements,\n\n # Project relation\n keywords=[\"conan\", \"conan.io\", \"GUI\", \"Conan GUI\", \"PyQt5\"],\n\n entry_points={\n \"console_scripts\": [\n \"conan-guide=conanguide.app:main\"\n ]\n }\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"99565172","text":"depthstrangevariablename = 0\ndef B(x, y):\n a = 1\n if x < y:\n return x - y, 4, 0, 'magic\\xc0\\xff\\xeemagic'\n else:\n return x - y, 4, 0, 'magic\\xc0\\xff\\xeemagic'\n if x == 1234:\n c = 3\n else:\n d = 4\n e = 5\n","sub_path":"mutations/B_1F.py","file_name":"B_1F.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"177787697","text":"import unittest\n\nclass Solution(unittest.TestCase):\n def convertToTitle(self, n: int) -> str:\n \"\"\"\nGiven a positive integer, return its corresponding column title as appear in an Excel sheet.\n\nFor example:\n\n 1 -> A\n 2 -> B\n 3 -> C\n ...\n 26 -> Z\n 27 -> AA\n 28 -> AB\n ...\nExample 1:\n\nInput: 1\nOutput: \"A\"\nExample 2:\n\nInput: 28\nOutput: \"AB\"\nExample 3:\n\nInput: 701\nOutput: \"ZY\"\n\"\"\"\n ret = \"\"\n while n != 0:\n # n-1 since mod starts with 0 (0~25)\n n, r = divmod(n-1, 26)\n ret = chr(r+65) + ret\n return ret\n\n def testConvert(self):\n self.assertEqual('A', self.convertToTitle(1))\n self.assertEqual('AB', self.convertToTitle(28))\n self.assertEqual('ZY', self.convertToTitle(701))\n","sub_path":"src/main/python/excel_sheet_column_title.py","file_name":"excel_sheet_column_title.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"352628040","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.5 (3351)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-x86_64/egg/pyams_apm/tween.py\n# Compiled at: 2020-01-13 08:58:45\n# Size of source mod 2**32: 4590 bytes\n__doc__ = 'PyAMS_apm.tween module\\n\\nThis module provides a custom tween which is used to integrate the Pyramid application\\nwith APM, sending requests frames to the APM server.\\n'\nimport sys, pkg_resources, elasticapm\nfrom elasticapm.utils import compat, get_url_dict\nfrom pyramid.compat import reraise\nfrom pyramid.settings import asbool\n__docformat__ = 'restructuredtext'\n\ndef list_from_setting(config, setting):\n \"\"\"Split configuration setting\"\"\"\n value = config.get(setting)\n if not value:\n return\n return value.split()\n\n\ndef get_data_from_request(request):\n \"\"\"Extract main APM data from request properties\"\"\"\n data = {'headers': dict(**request.headers), \n 'method': request.method, \n 'socket': {'remote_address': request.remote_addr, \n 'encrypted': request.scheme == 'https'}, \n \n 'cookies': dict(**request.cookies), \n 'url': get_url_dict(request.url)}\n data['headers'].pop('Cookie', None)\n return data\n\n\ndef get_data_from_response(response):\n \"\"\"Extract APM data from response properties\"\"\"\n data = {'status_code': response.status_int}\n if response.headers:\n data['headers'] = {key:';'.join(response.headers.getall(key)) for key in compat.iterkeys(response.headers)}\n return data\n\n\nclass elastic_apm_tween_factory:\n \"\"\"elastic_apm_tween_factory\"\"\"\n\n def __init__(self, handler, registry):\n self.handler = handler\n self.registry = registry\n config = registry.settings\n service_version = config.get('elasticapm.service_version')\n if service_version:\n try:\n service_version = pkg_resources.get_distribution(service_version).version\n except pkg_resources.DistributionNotFound:\n pass\n\n self.client = elasticapm.Client(server_url=config.get('elasticapm.server_url'), server_timeout=config.get('elasticapm.server_timeout'), name=config.get('elasticapm.name'), framework_name='Pyramid', framework_version=pkg_resources.get_distribution('pyramid').version, service_name=config.get('elasticapm.service_name'), service_version=service_version, secret_token=config.get('elasticapm.secret_token'), include_paths=list_from_setting(config, 'elasticapm.include_paths'), exclude_paths=list_from_setting(config, 'elasticapm.exclude_paths'), debug=asbool(config.get('elasticapm.debug')))\n\n def __call__(self, request):\n self.client.begin_transaction('request')\n try:\n try:\n response = self.handler(request)\n transaction_result = response.status[0] + 'xx'\n elasticapm.set_context(lambda : get_data_from_response(response), 'response')\n return response\n except Exception:\n transaction_result = '5xx'\n self.client.capture_exception(context={'request': get_data_from_request(request)}, handled=False)\n reraise(*sys.exc_info())\n\n finally:\n try:\n view_name = request.view_name\n if not view_name:\n view_name = request.traversed[(-1)] if request.traversed else '/'\n except AttributeError:\n view_name = ''\n\n transaction_name = request.matched_route.pattern if request.matched_route else view_name\n transaction_name = ' '.join((request.method, transaction_name)) if transaction_name else ''\n elasticapm.set_context(lambda : get_data_from_request(request), 'request')\n self.client.end_transaction(transaction_name, transaction_result)","sub_path":"pycfiles/pyamtrack-0.1.4-py3-none-manylinux1_x86_64/tween.cpython-35.py","file_name":"tween.cpython-35.py","file_ext":"py","file_size_in_byte":3883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"641534881","text":"#!/usr/bin/env python3\n\nfrom devnet2019.models import DataBaseLifetime\nfrom devnet2019.forms import SysconfigdatabaselifetimeForm\nfrom django.shortcuts import render\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth.decorators import login_required\n\n\n@login_required\ndef database_lifetime(request):\n if request.method == 'POST':\n form = SysconfigdatabaselifetimeForm(request.POST)\n # 如果请求为POST,并且Form校验通过,把客户提交的监控周期写入数据库\n if form.is_valid():\n reachable_lifetime = request.POST.get('reachable_lifetime')\n cpu_lifetime = request.POST.get('cpu_lifetime')\n mem_lifetime = request.POST.get('mem_lifetime')\n interface_lifetime = request.POST.get('interface_lifetime')\n netflow_lifetime = request.POST.get('netflow_lifetime')\n\n reachable_lifetime_result = DataBaseLifetime.objects.get(name='reachable_lifetime')\n reachable_lifetime_result.lifetime = reachable_lifetime\n reachable_lifetime_result.save()\n cpu_lifetime_result = DataBaseLifetime.objects.get(name='cpu_lifetime')\n cpu_lifetime_result.lifetime = cpu_lifetime\n cpu_lifetime_result.save()\n mem_lifetime_result = DataBaseLifetime.objects.get(name='mem_lifetime')\n mem_lifetime_result.lifetime = mem_lifetime\n mem_lifetime_result.save()\n interface_lifetime_result = DataBaseLifetime.objects.get(name='interface_lifetime')\n interface_lifetime_result.lifetime = interface_lifetime\n interface_lifetime_result.save()\n netflow_lifetime_result = DataBaseLifetime.objects.get(name='netflow_lifetime')\n netflow_lifetime_result.lifetime = netflow_lifetime\n netflow_lifetime_result.save()\n\n reachable_lifetime_changed = DataBaseLifetime.objects.get(name='reachable_lifetime').lifetime\n cpu_lifetime_changed = DataBaseLifetime.objects.get(name='cpu_lifetime').lifetime\n mem_lifetime_changed = DataBaseLifetime.objects.get(name='mem_lifetime').lifetime\n interface_lifetime_changed = DataBaseLifetime.objects.get(name='interface_lifetime').lifetime\n netflow_lifetime_changed = DataBaseLifetime.objects.get(name='netflow_lifetime').lifetime\n\n form = SysconfigdatabaselifetimeForm(initial={'reachable_lifetime': reachable_lifetime_changed, # initial填写初始值\n 'cpu_lifetime': cpu_lifetime_changed,\n 'mem_lifetime': mem_lifetime_changed,\n 'interface_lifetime': interface_lifetime_changed,\n 'netflow_lifetime': netflow_lifetime_changed})\n successmessage = '数据库老化时间修改成功!'\n # 返回'sysconfig_monitor_interval.html'页面,与表单给客户\n return render(request, 'devnet_system_setting_database_lifetime.html', locals())\n else: # 如果Form校验失败,返回客户在Form中输入的内容和报错信息\n return render(request, 'devnet_system_setting_database_lifetime.html', locals())\n else: # 如果不是POST,就是GET,表示为初始访问, 把监控周期在数据库中的值,通过初始值的方式展现给客户看\n try:\n reachable_lifetime = DataBaseLifetime.objects.get(name='reachable_lifetime').lifetime\n except DataBaseLifetime.DoesNotExist:\n reachable_lifetime = 24\n r = DataBaseLifetime(name='reachable_lifetime', lifetime=reachable_lifetime)\n r.save()\n try:\n cpu_lifetime = DataBaseLifetime.objects.get(name='cpu_lifetime').lifetime\n except DataBaseLifetime.DoesNotExist:\n cpu_lifetime = 24\n c = DataBaseLifetime(name='cpu_lifetime', lifetime=cpu_lifetime)\n c.save()\n try:\n mem_lifetime = DataBaseLifetime.objects.get(name='mem_lifetime').lifetime\n except DataBaseLifetime.DoesNotExist:\n mem_lifetime = 24\n m = DataBaseLifetime(name='mem_lifetime', lifetime=mem_lifetime)\n m.save()\n try:\n interface_lifetime = DataBaseLifetime.objects.get(name='interface_lifetime').lifetime\n except DataBaseLifetime.DoesNotExist:\n interface_lifetime = 24\n i = DataBaseLifetime(name='interface_lifetime', lifetime=interface_lifetime)\n i.save()\n try:\n netflow_lifetime = DataBaseLifetime.objects.get(name='netflow_lifetime').lifetime\n except DataBaseLifetime.DoesNotExist:\n netflow_lifetime = 24\n n = DataBaseLifetime(name='netflow_lifetime', lifetime=netflow_lifetime)\n n.save()\n\n form = SysconfigdatabaselifetimeForm(initial={'reachable_lifetime': reachable_lifetime, # initial填写初始值\n 'cpu_lifetime': cpu_lifetime,\n 'mem_lifetime': mem_lifetime,\n 'interface_lifetime': interface_lifetime,\n 'netflow_lifetime': netflow_lifetime})\n # 返回'sysconfig_monitor_interval.html'页面,与表单给客户\n return render(request, 'devnet_system_setting_database_lifetime.html', locals())\n\n\n@login_required\ndef reset_database_lifetime(request):\n\n if request.method == 'POST': # 如果收到客户重置监控周期的POST请求\n if request.user.has_perm('devnet2019.change_databaselifetime'):\n reachable_lifetime_result = DataBaseLifetime.objects.get(name='reachable_lifetime')\n reachable_lifetime_result.lifetime = 24\n reachable_lifetime_result.save()\n cpu_lifetime_result = DataBaseLifetime.objects.get(name='cpu_lifetime')\n cpu_lifetime_result.lifetime = 24\n cpu_lifetime_result.save()\n mem_lifetime_result = DataBaseLifetime.objects.get(name='mem_lifetime')\n mem_lifetime_result.lifetime = 24\n mem_lifetime_result.save()\n interface_lifetime_result = DataBaseLifetime.objects.get(name='interface_lifetime')\n interface_lifetime_result.lifetime = 24\n interface_lifetime_result.save()\n netflow_lifetime_result = DataBaseLifetime.objects.get(name='netflow_lifetime')\n netflow_lifetime_result.lifetime = 24\n netflow_lifetime_result.save()\n\n reachable_lifetime_changed = DataBaseLifetime.objects.get(name='reachable_lifetime').lifetime\n cpu_lifetime_changed = DataBaseLifetime.objects.get(name='cpu_lifetime').lifetime\n mem_lifetime_changed = DataBaseLifetime.objects.get(name='mem_lifetime').lifetime\n interface_lifetime_changed = DataBaseLifetime.objects.get(name='interface_lifetime').lifetime\n netflow_lifetime_changed = DataBaseLifetime.objects.get(name='netflow_lifetime').lifetime\n\n form = SysconfigdatabaselifetimeForm(initial={'reachable_lifetime': reachable_lifetime_changed, # initial填写初始值\n 'cpu_lifetime': cpu_lifetime_changed,\n 'mem_lifetime': mem_lifetime_changed,\n 'interface_lifetime': interface_lifetime_changed,\n 'netflow_lifetime': netflow_lifetime_changed})\n else:\n err = '没有权限'\n return render(request, '404.html', locals())\n successmessage = '重置系统数据库老化时间到默认成功!'\n # 返回'sysconfig_monitor_interval.html'页面,与表单\n return render(request, 'devnet_system_setting_database_lifetime.html', locals())\n\n else:\n return HttpResponseRedirect('/system_setting/database_lifetime')\n","sub_path":"devnet2019/views/devnet_system_setting_database_lifetime.py","file_name":"devnet_system_setting_database_lifetime.py","file_ext":"py","file_size_in_byte":8132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"357528712","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport numpy as np\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation, Embedding, Dropout, SpatialDropout1D\nfrom keras.layers import LSTM, Conv1D, MaxPooling1D\nfrom sklearn.model_selection import train_test_split\nimport pickle\n\n# for reproducibility\nfrom numpy.random import seed\nfrom tensorflow import set_random_seed\n\nrandom_seed = 1\nseed(random_seed)\nrandom_seed += 1\nset_random_seed(random_seed)\nrandom_seed += 1\n\nprint('reading CSV')\n\ncsv = pd.read_csv('../input/training.1600000.processed.noemoticon.csv', encoding = \"ISO-8859-1\", header=None)\n\nprint('parsing CSV')\n\nX, Y = [], []\n\nfor index, row in csv.iterrows():\n X.append(row[5])\n y_part = row[0]\n if y_part == 0:\n yy = np.array([0])\n elif y_part == 4:\n yy = np.array([1])\n else:\n raise Exception('Invalid y_part value=' + y_part)\n Y.append(yy)\n\nprint('build words map')\n\nmax_features = 50000\ntokenizer = Tokenizer(num_words=max_features)\ntokenizer.fit_on_texts(X)\nX = tokenizer.texts_to_sequences(X)\nX = pad_sequences(X)\nX, Xt, Y, Yt = train_test_split(X, Y, test_size = 0.3, random_state = random_seed)\n\nvalidation_size = 1500\nX_validate = Xt[-validation_size:]\nY_validate = Yt[-validation_size:]\nXt = Xt[:-validation_size]\nYt = Yt[:-validation_size]\n\nmaxlen = 0\n\n\ndef wrap_array(x, maxlen):\n for index in range(len(x)):\n xx = x[index]\n if len(xx) > maxlen:\n maxlen = len(xx)\n x[index] = np.array(xx)\n return np.array(x), maxlen\n\n\nX, maxlen = wrap_array(X, maxlen)\nXt, maxlen = wrap_array(Xt, maxlen)\nX_validate, maxlen = wrap_array(X_validate, maxlen)\nY, maxlen = wrap_array(Y, maxlen)\nYt, maxlen = wrap_array(Yt, maxlen)\nY_validate, maxlen = wrap_array(Y_validate, maxlen)\n\nprint('build model')\nprint('maxlen: ' + str(maxlen))\nbatch_size = 256\n\nmodel = Sequential()\nmodel.add(Embedding(max_features, 128, input_length=maxlen))\nmodel.add(SpatialDropout1D(0.2))\nmodel.add(Conv1D(filters=32, kernel_size=3, padding='same', activation='relu'))\nmodel.add(MaxPooling1D(pool_size=2))\nmodel.add(LSTM(124, dropout=0.2, recurrent_dropout=0.2))\nmodel.add(Dense(1))\nmodel.add(Activation('sigmoid'))\n\nmodel.compile(loss='binary_crossentropy',\n optimizer='nadam',\n metrics=['accuracy'])\nprint(model.summary())\n\nprint('Train...')\nmodel.fit(X, Y, batch_size=batch_size, epochs=2, validation_data=(Xt, Yt), verbose=2)\n\nscore, acc = model.evaluate(X_validate, Y_validate, batch_size=batch_size)\nprint('Test score:', score)\nprint('Test accuracy:', acc)\n\n\nprint('Trying to predict:')\ntext = \"This is a presidential decree that Rada's defence committee approved and suggested MPs to support. As some MPs write, there is no agreement on a restriction of certain freedoms(frdm of assembly among them). They also want it written down that elections will take place on March 31\"\nprint(text)\ntokens = tokenizer.texts_to_sequences([text])\ntokens = pad_sequences(tokens, maxlen=maxlen)\nsentiment = model.predict(np.array(tokens), batch_size=1, verbose = 2)[0][0]\nprint()\nprint('Sentiment =', sentiment)\nif (round(sentiment) == 0):\n print('Negative')\nelse:\n print('Positive')\n\nmodel.save('../tsa.h5')\nwith open('../tokenizer.pickle', 'wb') as handle:\n pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)\n","sub_path":"tf/model-creator.py","file_name":"model-creator.py","file_ext":"py","file_size_in_byte":3503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"31778366","text":"\"\"\"\nThe module is designed by team Robokit of Phystech Lyceum and team Starkit\nof MIPT under mentorship of A. Babaev.\n\nThe module is a part of motion generating functions\n\"\"\"\nimport math, time, json\nimport logging\n\nfrom .class_Motion import Motion1\nfrom .ball_Approach_Steps_Seq import *\nfrom .path_planning import PathPlan\n\nclass Motion_real(Motion1):\n\n def __init__(self, glob):\n super().__init__(glob)\n self.p = PathPlan(self.glob)\n\n def seek_Ball_In_Pose(self, fast_Reaction_On, penalty_Goalkeeper = False, with_Localization = True):\n self.local.correct_yaw_in_pf()\n if self.robot_In_0_Pose == False:\n self.simulateMotion(name = 'Initial_Pose')\n self.robot_In_0_Pose = True\n variants = []\n # U19 - Шея поворот\n # U20 - Шея Наклон\n c = self.neck_play_pose\n head_pose = [(-2667,c), (-1333, c) , ( 0, c) , (1333, c) , (2667,c),\n (-2667, c-700),(-1333, c-700), (0, c-700), (1333,c-700),(2667, c-700),\n (-2667, c-1400), (-1333, c-1400), ( 0, c-1400), (1333, c-1400), (2667, c-1400)]\n #head_pose_seq = [2,7,12,13,8,3,1,6,11,10,5,0,4,9,14,2]\n head_pose_seq = [2,7,12,11,6,8,13,14,9,4,3,10,5,0,1,2]\n if penalty_Goalkeeper: head_pose_seq = [2,7,12,11,6,8,13]\n for i in range(len(head_pose_seq)):\n if not(fast_Reaction_On == True and i == 0):\n x = head_pose[head_pose_seq[i]]\n self.neck_pan = x[0]\n self.neck_tilt = x[1]\n if not self.falling_Test() == 0:\n self.local.quality =0\n if self.falling_Flag == 3: self.logger.debug('STOP!')\n else: self.logger.debug('FALLING!!!' + str(self.falling_Flag))\n return False, 0, 0, [0, 0]\n self.move_head(self.neck_pan, self.neck_tilt)\n self.refresh_Orientation()\n a, course, dist = self.seek_Ball_In_Frame(with_Localization)\n if a == True: \n variants.append ((course, dist *1000))\n if fast_Reaction_On == True and a== True: break\n course = 0\n distance = 0\n if len(variants)>0:\n for i in range (len(variants)):\n course = course + variants[i][0]\n distance = distance + variants[i][1]\n course1 = course /len(variants)\n distance1 = distance /len(variants)\n self.neck_pan =int( - course1/ self.TIK2RAD)\n D = self.params['HEIGHT_OF_CAMERA'] - self.params['HEIGHT_OF_NECK']- self.params['DIAMETER_OF_BALL']/2\n E = (2*distance1*D - math.sqrt(4*distance1**2*D**2 - 4*(distance1**2-self.params['HEIGHT_OF_NECK']**2)*(D**2 -self.params['HEIGHT_OF_NECK']**2)))/(2*(D**2-self.params['HEIGHT_OF_NECK']**2))\n alpha = math.atan(E)\n alpha_d = math.pi/2 - alpha\n self.neck_tilt = int((-alpha_d)/self.TIK2RAD + self.neck_calibr)\n #self.logger.debug('self.neck_pan =' + str(self.neck_pan) + 'self.neck_tilt =' + str(self.neck_tilt))\n self.move_head(self.neck_pan, self.neck_tilt)\n self.refresh_Orientation()\n a, course, dist, speed = self.detect_Ball_Speed(with_Localization)\n if with_Localization: self.local.localisation_Complete()\n #self.local.pf_update()\n if a == True:\n #course_global = course + self.euler_angle[0] + self.neck_pan * 0.03375\n if with_Localization: self.local.localisation_Complete()\n course_global_rad = course + self.glob.pf_coord[2]\n self.glob.ball_coord = [dist*math.cos(course_global_rad)+ self.glob.pf_coord[0],\n dist*math.sin(course_global_rad)+ self.glob.pf_coord[1]]\n #if len(self.glob.obstacles) == 0: self.glob.obstacles = [[0,0,0]]\n #self.glob.obstacles[0] = [self.glob.ball_coord[0], self.glob.ball_coord[1], 0.15]\n if with_Localization: self.local.localisation_Complete()\n #if self.glob.obstacleAvoidanceIsOn: self.sim_Get_Obstacles()\n return(a, course, dist, speed)\n else:\n if distance1 !=0:\n if with_Localization: self.local.localisation_Complete()\n dist = distance1 / 1000\n course_global_rad = course1 + self.glob.pf_coord[2]\n self.glob.ball_coord = [dist * math.cos(course_global_rad) + self.glob.pf_coord[0],\n dist * math.sin(course_global_rad) + self.glob.pf_coord[1]]\n return(a, course1, dist, [0, 0])\n if with_Localization: self.local.localisation_Complete()\n return False, 0, 0, [0, 0]\n\n def watch_Ball_In_Pose(self, penalty_Goalkeeper = False):\n self.local.correct_yaw_in_pf()\n if self.robot_In_0_Pose == False:\n self.simulateMotion(name = 'Initial_Pose')\n self.robot_In_0_Pose = True\n # U19 - Шея поворот\n # U20 - Шея Наклон\n c = self.neck_play_pose\n head_pose = [(-2667,c), (-1333, c) , ( 0, c) , (1333, c) , (2667,c),\n (-2667, c-700),(-1333, c-700), (0, c-700), (1333,c-700),(2667, c-700),\n (-2667, c-1400), (-1333, c-1400), ( 0, c-1400), (1333, c-1400), (2667, c-1400)]\n #head_pose_seq = [2,7,12,13,8,3,1,6,11,10,5,0,4,9,14,2]\n head_pose_seq = [2,7,12,11,6,8,13,14,9,4,3,10,5,0,1,2]\n if penalty_Goalkeeper: head_pose_seq = [2,7,12,11,6,8,13]\n for i in range(len(head_pose_seq)):\n if i != 0:\n x = head_pose[head_pose_seq[i]]\n self.neck_pan = x[0]\n self.neck_tilt = x[1]\n if not self.falling_Test() == 0:\n self.local.quality =0\n if self.falling_Flag == 3: self.logger.debug('STOP!')\n else: self.logger.debug('FALLING!!!' + str(self.falling_Flag))\n return False, 0, 0, [0, 0]\n self.move_head(self.neck_pan, self.neck_tilt)\n self.refresh_Orientation()\n a, course, dist, speed = self.detect_Ball_Speed(with_Localization = False)\n if a == True or (a== False and dist !=0): break\n if a == True or (a== False and dist !=0):\n course_global_rad = course + self.glob.pf_coord[2]\n self.glob.ball_coord = [dist*math.cos(course_global_rad)+ self.glob.pf_coord[0],\n dist*math.sin(course_global_rad)+ self.glob.pf_coord[1]]\n #if len(self.glob.obstacles) == 0: self.glob.obstacles = [[0,0,0]]\n #self.glob.obstacles[0] = [self.glob.ball_coord[0], self.glob.ball_coord[1], 0.15]\n #if self.glob.obstacleAvoidanceIsOn: self.sim_Get_Obstacles()\n distance = dist *1000\n self.neck_pan =int( - course/ self.TIK2RAD)\n D = self.params['HEIGHT_OF_CAMERA'] - self.params['HEIGHT_OF_NECK']- self.params['DIAMETER_OF_BALL']/2\n E = (2*distance*D - math.sqrt(4*distance**2*D**2 - 4*(distance**2-self.params['HEIGHT_OF_NECK']**2)*(D**2 -self.params['HEIGHT_OF_NECK']**2)))/(2*(D**2-self.params['HEIGHT_OF_NECK']**2))\n alpha = math.atan(E)\n alpha_d = math.pi/2 - alpha\n self.neck_tilt = int((-alpha_d)/self.TIK2RAD + self.neck_calibr)\n return(a, course, dist, speed)\n return False, 0, 0, [0, 0]\n\n def seek_Ball_In_Frame(self, with_Localization = True):\n #self.pause_in_ms(100)\n Ballposition = self.sim_Get_Ball_Position()\n if with_Localization: self.local.read_Localization_marks()\n self.logger.debug('Ballposition: ' + str(Ballposition))\n if Ballposition:\n course, distance = Ballposition\n return True, course, distance\n else: return False, 0, 0\n\n def detect_Ball_Speed(self, with_Localization = False):\n position = []\n if with_Localization : self.local.read_Localization_marks()\n for number in range (2):\n #self.pause_in_ms(100)\n Ballposition = self.sim_Get_Ball_Position()\n if Ballposition:\n course, distance = Ballposition\n position.append([course,distance])\n n = len(position)\n speed = [0,0]\n if n > 1:\n front_speed = ( position[n-1][1] - position[0][1])/ distance/n\n tangential_speed = ( position[n-1][0] - position[0][0]) * distance/n\n speed = [tangential_speed, front_speed ]\n if n < 1: return False, 0, 0, [0,0]\n \n elif n < 2: \n #self.see_ball_confirmation()\n return False, course, distance, [0,0]\n else: \n #self.see_ball_confirmation()\n return True, course, distance, speed\n\n def see_ball_confirmation(self):\n self.move_head(self.neck_pan, 0)\n self.move_head(self.neck_pan, self.neck_tilt)\n\n def turn_To_Course(self, course, accurate = False):\n stepLength = 0\n sideLength = 0\n rotation = 0\n cycleNumber = 1\n cycle = 0\n old_neck_pan, old_neck_tilt = self.head_Up()\n self.refresh_Orientation()\n rotation1 = course - self.imu_body_yaw()\n rotation1 = self.norm_yaw(rotation1)\n if abs(rotation1)> 0.035 or accurate:\n cycleNumber = int(math.floor(abs(rotation1)/self.params['ROTATION_YIELD']))+1 # rotation yield 0.23 with rotation order 0.21\n self.walk_Initial_Pose()\n for cycle in range (cycleNumber):\n rotation1 = course - self.imu_body_yaw()\n rotation1 = self.norm_yaw(rotation1)\n if abs(rotation1)< 0.035 and not accurate: break\n if abs(rotation1)< 0.01: break\n rotation = rotation1/(cycleNumber - cycle)\n self.walk_Cycle(stepLength, sideLength,rotation,cycle,cycleNumber)\n self.walk_Final_Pose()\n self.refresh_Orientation()\n self.local.coord_shift = [0,0,0]\n self.local.coordinate_record()\n self.head_Return(old_neck_pan, old_neck_tilt)\n\n def head_Up(self):\n old_neck_pan = self.neck_pan\n old_neck_tilt = self.neck_tilt\n self.neck_pan = 0\n self.neck_tilt = self.neck_play_pose\n self.move_head(self.neck_pan, self.neck_tilt)\n self.refresh_Orientation()\n return old_neck_pan, old_neck_tilt\n\n def head_Return(self, old_neck_pan, old_neck_tilt):\n self.move_head(old_neck_pan, old_neck_tilt)\n self.refresh_Orientation()\n\n def localisation_Motion(self):\n if not self.falling_Test() == 0:\n self.local.quality =0\n if self.falling_Flag == 3: self.logger.debug('STOP!')\n else: self.logger.debug('FALLING!!!' + str(self.falling_Flag))\n return[]\n if self.robot_In_0_Pose == False:\n self.simulateMotion(name = 'Initial_Pose')\n self.robot_In_0_Pose = True\n # U19 - Шея поворот\n # U20 - Шея Наклон\n c = self.neck_play_pose\n head_pose = [(-2667,c), (-1333, c) , ( 0, c) , (1333, c) , (2667,c),\n (-2667, c-700),(-1333, c-700), (0, c-700), (1333,c-700),(2667, c-700),\n (-2667, c-1400), (-1333, c-1400), ( 0, c-1400), (1333, c-1400), (2667, c-1400)]\n #head_pose_seq = [2,7,12,11,6,8,13,14,9,4,3,10,5,0,1,2]\n head_pose_seq = [2,7,6,8,9,4,3,5,0,1,2]\n for k in range(1):\n for i in range(len(head_pose_seq)):\n x = head_pose[head_pose_seq[i]]\n self.neck_pan = x[0]\n self.neck_tilt = x[1]\n self.move_head(self.neck_pan, self.neck_tilt)\n self.refresh_Orientation()\n a, course, distance, blob = self.seek_Ball_In_Frame()\n #self.local.pf_update()\n #a = self.local.process_Post_data_in_Pose()\n #if self.local.quality == 1 : break\n #target_course1 = self.euler_angle[0] +180\n #self.turn_To_Course(target_course1)\n a = self.local.localisation_Complete()\n #self.local.pf_update()\n return a\n\n def normalize_rotation(self, yaw):\n if abs(yaw) > 2 * math.pi: yaw %= (2 * math.pi)\n if yaw > math.pi : yaw -= (2 * math.pi)\n if yaw < -math.pi : yaw += (2 * math.pi)\n if yaw > 0.5 : yaw = 0.5\n if yaw < -0.5 : yaw = -0.5\n return yaw\n\n def near_distance_omni_motion(self, dist_mm, napravl):\n old_neck_pan, old_neck_tilt = self.head_Up()\n dist = dist_mm/1000\n #self.refresh_Orientation()\n initial_direction = self.imu_body_yaw()\n self.logger.debug('initial_direction' + str(initial_direction))\n n = int(math.floor((dist_mm*math.cos(napravl)-self.first_step_yield)/self.cycle_step_yield)+1)+1 #calculating the number of potential full steps forward\n displacement = dist_mm*math.sin(napravl)\n if displacement > 0:\n invert = -1\n self.first_Leg_Is_Right_Leg = False\n side_step_yield = self.side_step_left_yield\n else:\n invert = 1\n side_step_yield = self.side_step_right_yield\n m = int(math.floor(abs(displacement)/side_step_yield)+1)\n if n < m : n = m\n stepLength = dist_mm*math.cos(napravl)/(self.first_step_yield*1.25+self.cycle_step_yield*(n-1)+ self.cycle_step_yield*0.75)*64\n number_Of_Cycles = n+2\n sideLength = abs(displacement) /number_Of_Cycles*20/side_step_yield\n if stepLength > 15 and number_Of_Cycles > 4: \n deceleration = True\n number_Of_Cycles += 1\n else: deceleration = False\n #old_neck_pan, old_neck_tilt = self.head_Up()\n self.local.correct_yaw_in_pf()\n self.walk_Initial_Pose()\n for cycle in range(number_Of_Cycles):\n #self.refresh_Orientation()\n rotation = initial_direction - self.imu_body_yaw() * 1\n rotation = self.normalize_rotation(rotation)\n stepLength1 = stepLength\n if cycle == 0: stepLength1 = stepLength/4\n if cycle == 1: stepLength1 = stepLength/2\n if deceleration:\n if cycle == number_Of_Cycles - 1: stepLength1 = stepLength / 3\n if cycle == number_Of_Cycles - 2: stepLength1 = stepLength * 2 / 3\n self.walk_Cycle(stepLength1, sideLength, invert*rotation,cycle,number_Of_Cycles)\n self.walk_Final_Pose()\n self.first_Leg_Is_Right_Leg = True\n self.head_Return(old_neck_pan, old_neck_tilt)\n\n def near_distance_ball_approach_and_kick(self, kick_direction, strong_kick = False, small_kick = False ):\n offset_of_ball = self.params['KICK_OFFSET_OF_BALL'] # self.d10 # module of local robot Y coordinate of ball im mm before kick \n a, napravl, dist, speed = self.seek_Ball_In_Pose(fast_Reaction_On = True)\n dist_mm = dist *1000\n if a==False or self.falling_Flag != 0: return False\n if dist > 0.9 or a == False: return False\n if 0.02 < abs(dist * math.cos(napravl)) < 0.06 and dist * math.sin(napravl) < 0.03:\n old_neck_pan, old_neck_tilt = self.head_Up()\n if napravl > 0: self.kick(first_Leg_Is_Right_Leg=False)\n else: self.kick(first_Leg_Is_Right_Leg=True)\n self.head_Return(old_neck_pan, old_neck_tilt)\n if abs(napravl) > 1 :\n direction = math.copysign(2.55, napravl)\n self.near_distance_omni_motion( 180 , direction)\n else:\n forth_dist = dist_mm*math.cos(napravl) \n n = int(math.ceil((forth_dist - self.params['KICK_ADJUSTMENT_DISTANCE']\n -self.first_step_yield)/self.cycle_step_yield)+1) #calculating the number of potential full steps forward\n displacement = dist_mm*math.sin(napravl)- math.copysign(offset_of_ball, napravl)\n if displacement > 0:\n invert = -1\n self.first_Leg_Is_Right_Leg = False\n side_step_yield = self.side_step_left_yield\n else:\n invert = 1\n side_step_yield = self.side_step_right_yield\n m = int(math.ceil(abs(displacement)/side_step_yield)) # potential side steps number\n if n < m : n = m\n n += 2 # final steps number\n stepLength = (dist_mm*math.cos(napravl)-\n self.params['KICK_ADJUSTMENT_DISTANCE'])/(self.first_step_yield\n + self.cycle_step_yield * n) * 64\n number_Of_Cycles = n + 1\n if napravl > 0:\n kick_by_Right = False\n else:\n kick_by_Right = True\n sideLength = abs(displacement)/number_Of_Cycles*20/side_step_yield\n old_neck_pan, old_neck_tilt = self.head_Up()\n self.local.correct_yaw_in_pf()\n init_yaw = kick_direction = self.imu_body_yaw()\n #init_yaw = self.imu_body_yaw()\n stepLengthResidue = 0\n sideLengthResidue = 0\n self.walk_Initial_Pose()\n cycle = 0\n while (cycle < number_Of_Cycles):\n #for cycle in range(number_Of_Cycles):\n #self.refresh_Orientation()\n rotation = (kick_direction - self.imu_body_yaw()) * 1\n rotation = self.normalize_rotation(rotation)\n stepLength1 = stepLength\n sideLength1 = sideLength\n self.logger.debug('kick_direction =' + str(kick_direction) + ' self.imu_body_yaw() = ' + str(self.imu_body_yaw()) + ' rotation = ' + str(rotation) )\n if cycle == 0: stepLength1 = stepLength / 3\n if cycle == 1: stepLength1 = stepLength * 2 / 3\n stepLength1 += stepLengthResidue\n sideLength1 += sideLengthResidue\n self.walk_Cycle(stepLength1, sideLength1, invert*rotation,cycle,number_Of_Cycles)\n delta_yaw = self.norm_yaw(self.imu_body_yaw() - init_yaw)\n stepLengthResidue = stepLength1 * (1 - math.cos(delta_yaw)) - sideLength1 * math.sin(delta_yaw) * invert\n sideLengthResidue = sideLength1 * (1 - math.cos(delta_yaw)) + stepLength1 * math.sin(delta_yaw) * invert\n cycle += 1\n self.walk_Final_Pose()\n self.first_Leg_Is_Right_Leg = True\n if strong_kick == True:\n if kick_by_Right == True:\n self.simulateMotion(name = 'Soccer_Kick_Forward_Right_Leg')\n else:\n self.simulateMotion(name = 'Soccer_Kick_Forward_Left_Leg')\n else:\n self.kick( first_Leg_Is_Right_Leg=kick_by_Right, small = small_kick)\n #self.local.coord_odometry[0] += dist * math.cos(napravl)\n #self.local.coord_odometry[1] += dist * math.sin(napravl)\n #self.local.coordinate_record(odometry = True)\n self.head_Return(old_neck_pan, old_neck_tilt)\n return True\n\n def far_distance_ball_approach(self, ball_coord):\n old_neck_pan, old_neck_tilt = self.head_Up()\n self.local.correct_yaw_in_pf()\n ball_Approach(self, self.local, self.glob, ball_coord)\n self.head_Return(old_neck_pan, old_neck_tilt)\n\n def far_distance_plan_approach(self, ball_coord, target_yaw, stop_Over = False):\n dest = []\n centers = []\n price = 1000\n for i in range(5):\n for j in range(2):\n target_x = ball_coord[0] - (0.21 + j * 0.05) * math.cos(target_yaw - 0.8 + i * 0.4)\n target_y = ball_coord[1] - (0.21 + j * 0.05) * math.sin(target_yaw - 0.8 + i * 0.4)\n target_coord = [target_x, target_y, target_yaw]\n dest1, centers1, number_Of_Cycles = self.p.path_calc_optimum(self.glob.pf_coord, target_coord)\n if i != 2: number_Of_Cycles += 50\n if number_Of_Cycles <= price:\n dest = dest1\n centers = centers1\n price = number_Of_Cycles\n #target_x = ball_coord[0] - 0.26 * math.cos(target_yaw)\n #target_y = ball_coord[1] - 0.26 * math.sin(target_yaw)\n #target_coord = [target_x, target_y, target_yaw]\n #dest, centers, price = self.p.path_calc_optimum(self.glob.pf_coord, target_coord)\n if stop_Over: price += 100\n start_yaw = self.glob.pf_coord[2] #self.imu_body_yaw()\n if len(dest) == 0: return False\n old_neck_pan, old_neck_tilt = self.head_Up()\n self.local.correct_yaw_in_pf()\n sideLength = 0\n stepLength_old = 0\n acceleration = False\n deceleration = False\n self.walk_Initial_Pose()\n# initial arc\n dest_yaw = self.p.coord2yaw(dest[1][0] - dest[0][0], dest[1][1] - dest[0][1] )\n x1, y1, x2, y2, cx, cy, R, CW = centers[0]\n delta_yaw = self.p.delta_yaw(start_yaw, dest_yaw, CW)\n #self.logger.debug('delta_yaw:' + str(delta_yaw) + ' CW:' + str(CW))\n number_Of_Cycles = math.ceil(abs(delta_yaw / 0.2))\n while True:\n delta_yaw_step = delta_yaw / number_Of_Cycles\n #self.logger.debug('R =' + str(R) + ' delta_yaw_step =' + str(delta_yaw_step) )\n stepLength = R * abs(delta_yaw_step) * 1000 * 64 / self.cycle_step_yield * 1.1\n if stepLength <= 64: break\n else: number_Of_Cycles += 1\n if stepLength - stepLength_old > 22 :\n acceleration = True\n number_Of_Cycles += 1\n for cycle in range(number_Of_Cycles):\n stepLength1 = stepLength\n if acceleration:\n if cycle == 0: stepLength1 = stepLength / 3\n if cycle == 1: stepLength1 = stepLength * 2 / 3\n #self.refresh_Orientation()\n rotation = start_yaw + delta_yaw_step * (cycle + 1) - self.imu_body_yaw()\n rotation = self.normalize_rotation(rotation)\n self.walk_Cycle(stepLength1, sideLength, rotation, cycle, number_Of_Cycles+1)\n #self.logger.debug('stepLength1 =' + str(stepLength1) + 'rotation =' + str(rotation ) + 'cycle =' + str(cycle) + 'number_Of_Cycles =' + str(number_Of_Cycles))\n stepLength_old = stepLength\n acceleration = False\n# 1-st straight segment \n L = math.sqrt((dest[1][0] - dest[0][0])**2 + (dest[1][1] - dest[0][1])**2)\n number_Of_Cycles = math.ceil(abs(L * 1000 / self.cycle_step_yield))\n stepLength = L * 1000 / number_Of_Cycles * 64 / self.cycle_step_yield\n if stepLength - stepLength_old > 22 :\n acceleration = True\n number_Of_Cycles += 1\n if not stop_Over:\n for cycle in range(number_Of_Cycles):\n stepLength1 = stepLength\n if acceleration:\n if cycle == 0: stepLength1 = stepLength / 3\n if cycle == 1: stepLength1 = stepLength * 2 / 3\n #self.refresh_Orientation()\n rotation = dest_yaw - self.imu_body_yaw()\n rotation = self.normalize_rotation(rotation)\n self.walk_Cycle(stepLength1, sideLength, rotation, cycle + 1, number_Of_Cycles+2)\n stepLength_old = stepLength\n acceleration = False\n for i in range(len(centers)-2):\n start_yaw = dest_yaw #self.imu_body_yaw()\n dest_yaw = self.p.coord2yaw(dest[2*i+3][0] - dest[2*i+2][0], dest[2*i+3][1] - dest[2*i+2][1])\n x1, y1, x2, y2, cx, cy, R, CW = centers[i+1]\n delta_yaw = self.p.delta_yaw(start_yaw, dest_yaw, CW)\n number_Of_Cycles = math.ceil(abs(delta_yaw / 0.2))\n while True:\n delta_yaw_step = delta_yaw / number_Of_Cycles\n stepLength = R * abs(delta_yaw_step) * 1000 * 64 / self.cycle_step_yield * 1.1\n if stepLength <= 64: break\n else: number_Of_Cycles += 1\n if stepLength - stepLength_old > 22 :\n acceleration = True\n number_Of_Cycles += 1\n for cycle in range(number_Of_Cycles):\n stepLength1 = stepLength\n if acceleration:\n if cycle == 0: stepLength1 = stepLength / 3\n if cycle == 1: stepLength1 = stepLength * 2 / 3\n #self.refresh_Orientation()\n rotation = start_yaw + delta_yaw_step * (cycle + 1) - self.imu_body_yaw()\n rotation = self.normalize_rotation(rotation)\n if price < 100:\n self.walk_Cycle(stepLength1, sideLength, rotation, cycle+1, number_Of_Cycles+2)\n else:\n self.walk_Cycle(stepLength1, sideLength, rotation, cycle+1, number_Of_Cycles+1)\n stepLength_old = stepLength\n acceleration = False\n if price >= 100: break\n L = math.sqrt((dest[2*i+3][0] - dest[2*i+2][0])**2 + (dest[2*i+3][1] - dest[2*i+2][1])**2)\n number_Of_Cycles = math.ceil(abs(L * 1000 / self.cycle_step_yield))\n stepLength = L * 1000 / number_Of_Cycles * 64 / self.cycle_step_yield\n if stepLength - stepLength_old > 22 :\n acceleration = True\n number_Of_Cycles += 1\n for cycle in range(number_Of_Cycles):\n stepLength1 = stepLength\n if acceleration:\n if cycle == 0: stepLength1 = stepLength / 3\n if cycle == 1: stepLength1 = stepLength * 2 / 3\n #self.refresh_Orientation()\n rotation = dest_yaw - self.imu_body_yaw()\n rotation = self.normalize_rotation(rotation)\n self.walk_Cycle(stepLength1, sideLength, rotation, cycle + 1, number_Of_Cycles+2)\n stepLength_old = stepLength\n acceleration = False\n if price < 100:\n start_yaw = dest_yaw #self.imu_body_yaw()\n dest_yaw = target_yaw\n x1, y1, x2, y2, cx, cy, R, CW = centers[len(centers)-1]\n delta_yaw = self.p.delta_yaw(start_yaw, dest_yaw, CW)\n number_Of_Cycles = math.ceil(abs(delta_yaw / 0.2))\n while True:\n delta_yaw_step = delta_yaw / number_Of_Cycles\n stepLength = R * abs(delta_yaw_step) * 1000 * 64 / self.cycle_step_yield * 1.1\n if stepLength <= 64: break\n else: number_Of_Cycles += 1\n if stepLength - stepLength_old > 22 :\n acceleration = True\n number_Of_Cycles += 1\n if stepLength > 15:\n deceleration = True\n number_Of_Cycles += 1\n for cycle in range(number_Of_Cycles):\n stepLength1 = stepLength\n if acceleration:\n if cycle == 0: stepLength1 = stepLength / 3\n if cycle == 1: stepLength1 = stepLength * 2 / 3\n if deceleration:\n if cycle == number_Of_Cycles - 1: stepLength1 = stepLength / 3\n if cycle == number_Of_Cycles - 2: stepLength1 = stepLength * 2 / 3\n #self.refresh_Orientation()\n rotation = start_yaw + delta_yaw_step * (cycle + 1) - self.imu_body_yaw()\n rotation = self.normalize_rotation(rotation)\n self.walk_Cycle(stepLength1, sideLength, rotation, cycle + 1, number_Of_Cycles + 1)\n # Adjustment of yaw position\n number_Of_Cycles = 4\n stepLength = 0\n for cycle in range(1, number_Of_Cycles+1, 1):\n #self.refresh_Orientation()\n rotation = target_yaw - self.imu_body_yaw()\n rotation = self.normalize_rotation(rotation)\n self.walk_Cycle(stepLength, sideLength, rotation, cycle, number_Of_Cycles+1)\n else:\n number_Of_Cycles = math.ceil(number_Of_Cycles/2)\n if stepLength > 15:\n deceleration = True\n number_Of_Cycles += 1\n else: deceleration = False\n for cycle in range(1, number_Of_Cycles + 1, 1):\n stepLength1 = stepLength\n if acceleration:\n if cycle == 0: stepLength1 = stepLength / 3\n if cycle == 1: stepLength1 = stepLength * 2 / 3\n #self.refresh_Orientation()\n rotation = dest_yaw - self.imu_body_yaw()\n rotation = self.normalize_rotation(rotation)\n if deceleration:\n if cycle == number_Of_Cycles: stepLength1 = stepLength / 3\n if cycle == number_Of_Cycles - 1: stepLength1 = stepLength * 2 / 3\n self.walk_Cycle(stepLength1, sideLength, rotation, cycle, number_Of_Cycles + 1)\n self.walk_Final_Pose()\n self.head_Return(old_neck_pan, old_neck_tilt)\n return True\n\n \nif __name__==\"__main__\":\n print('This is not main module!')\n\n\n","sub_path":"controllers/SAMPLE_TEAM/Soccer/Motion/class_Motion_real.py","file_name":"class_Motion_real.py","file_ext":"py","file_size_in_byte":29438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"399375591","text":"from django.urls import include, re_path, path\nfrom . import views\n\napp_name = 'notification'\n\nurlpatterns = [\n re_path(r'^sms/send/$', views.enqueue_sms, name='sms-send'), #Called to Send Sms\n re_path(r'^sms/send/bulk/$', views.enqueue_sms, name='sms-send-bulk'), #Called to Send Sms\n re_path(r'^email/send/$', views.enqueue_email, name='email-send'), #Called to Send Email\n re_path(r'^push/send/$', views.enqueue_push, name='push-send'), #Called to Push Notification\n re_path(r'^entity/', views.create_or_update_entity, name='create_or_update_entity'), #Called to Create or update entity\n re_path(r'^cb/queue/', views.handle_enqued_notification, name='queue-cb'), #called by CP Queue with notification Data\n re_path(r'^ext/cb//', views.handle_external_svc_cb, name='ext_svc_cb'), #called by External services\n]\n","sub_path":"mail_khaifa/notification/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"57241909","text":"import FWCore.ParameterSet.Config as cms\n\nhltPhiJet1Jet2Filter = cms.EDFilter(\"HLTAcoFilter\",\n maxDeltaPhi = cms.double(2.7646),\n inputJetTag = cms.InputTag(\"iterativeCone5CaloJets\"),\n saveTags = cms.bool( False ),\n Acoplanar = cms.string('Jet1Jet2'),\n inputMETTag = cms.InputTag(\"hlt1MET70\"),\n minDeltaPhi = cms.double(0.0),\n minEtJet1 = cms.double(40.0),\n minEtJet2 = cms.double(40.0)\n)\n\n\n","sub_path":"HLTrigger/JetMET/python/hltPhiJet1Jet2Filter_cfi.py","file_name":"hltPhiJet1Jet2Filter_cfi.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"9673211","text":"\"\"\"\nGMT modules for Sampling of 1-D and 2-D Data.\n\"\"\"\nimport pandas as pd\nfrom pygmt.clib import Session\nfrom pygmt.exceptions import GMTInvalidInput\nfrom pygmt.helpers import (\n GMTTempFile,\n build_arg_string,\n data_kind,\n dummy_context,\n fmt_docstring,\n use_alias,\n)\n\n\n@fmt_docstring\n@use_alias(n=\"interpolation\", V=\"verbose\")\ndef grdtrack(points, grid, newcolname=None, outfile=None, **kwargs):\n \"\"\"\n Sample grids at specified (x,y) locations.\n\n Grdtrack reads one or more grid files and a table with (x,y) [or (lon,lat)]\n positions in the first two columns (more columns may be present). It\n interpolates the grid(s) at the positions in the table and writes out the\n table with the interpolated values added as (one or more) new columns. A\n bicubic [Default], bilinear, B-spline or nearest-neighbor interpolation is\n used, requiring boundary conditions at the limits of the region (see\n *interpolation*; Default uses “natural” conditions (second partial\n derivative normal to edge is zero) unless the grid is automatically\n recognized as periodic.)\n\n Full option list at :gmt-docs:`grdtrack.html`\n\n {aliases}\n\n Parameters\n ----------\n points : pandas.DataFrame or str\n Either a table with (x, y) or (lon, lat) values in the first two\n columns, or a filename (e.g. csv, txt format). More columns may be\n present.\n\n grid : xarray.DataArray or str\n Gridded array from which to sample values from, or a filename (netcdf\n format).\n\n newcolname : str\n Required if 'points' is a pandas.DataFrame. The name for the new column\n in the track pandas.DataFrame table where the sampled values will be\n placed.\n\n outfile : str\n Required if 'points' is a file. The file name for the output ASCII\n file.\n\n {V}\n\n {n}\n\n Returns\n -------\n track: pandas.DataFrame or None\n Return type depends on whether the outfile parameter is set:\n\n - pandas.DataFrame table with (x, y, ..., newcolname) if outfile is not\n set\n - None if outfile is set (track output will be stored in outfile)\n \"\"\"\n\n with GMTTempFile(suffix=\".csv\") as tmpfile:\n with Session() as lib:\n # Store the pandas.DataFrame points table in virtualfile\n if data_kind(points) == \"matrix\":\n if newcolname is None:\n raise GMTInvalidInput(\"Please pass in a str to 'newcolname'\")\n table_context = lib.virtualfile_from_matrix(points.values)\n elif data_kind(points) == \"file\":\n if outfile is None:\n raise GMTInvalidInput(\"Please pass in a str to 'outfile'\")\n table_context = dummy_context(points)\n else:\n raise GMTInvalidInput(f\"Unrecognized data type {type(points)}\")\n\n # Store the xarray.DataArray grid in virtualfile\n if data_kind(grid) == \"grid\":\n grid_context = lib.virtualfile_from_grid(grid)\n elif data_kind(grid) == \"file\":\n grid_context = dummy_context(grid)\n else:\n raise GMTInvalidInput(f\"Unrecognized data type {type(grid)}\")\n\n # Run grdtrack on the temporary (csv) points table\n # and (netcdf) grid virtualfile\n with table_context as csvfile:\n with grid_context as grdfile:\n kwargs.update({\"G\": grdfile})\n if outfile is None: # Output to tmpfile if outfile is not set\n outfile = tmpfile.name\n arg_str = \" \".join(\n [csvfile, build_arg_string(kwargs), \"->\" + outfile]\n )\n lib.call_module(module=\"grdtrack\", args=arg_str)\n\n # Read temporary csv output to a pandas table\n if outfile == tmpfile.name: # if user did not set outfile, return pd.DataFrame\n column_names = points.columns.to_list() + [newcolname]\n result = pd.read_csv(tmpfile.name, sep=\"\\t\", names=column_names)\n elif outfile != tmpfile.name: # return None if outfile set, output in outfile\n result = None\n\n return result\n","sub_path":"pygmt/sampling.py","file_name":"sampling.py","file_ext":"py","file_size_in_byte":4231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"168911293","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport copy\nfrom datetime import datetime\nfrom matplotlib.animation import FuncAnimation\nfrom random import randrange\nfrom matplotlib import animation\nfrom matplotlib import colors as c\n\n\n\nclass Plot_xy():\n\n def __init__(self, fontsize):\n self.fontsize = fontsize\n self.fig = None\n self.ax = None\n self.xlabel = ''\n self.ylabel = ''\n self.curves = []\n\n def createPlot(self, title, xlabel, ylabel, nbSubplotVert):\n\n self.fig, (self.ax) = plt.subplots(nbSubplotVert, 1, sharex=True)\n self.xlabel = xlabel\n self.ylabel = ylabel\n self.fig.subplots_adjust(hspace=0.5)\n for sub in self.ax:\n sub.set_title(title, fontweight='bold', fontsize=self.fontsize)\n\n def add(self, curve):\n self.curves.append(curve)\n\n def set(self):\n for c in self.curves:\n c.set()\n\n def plot(self):\n for c in self.curves:\n for i, sub in enumerate(self.ax):\n if c.subplotIndex == i:\n c.plot(sub)\n\n for i in range(len(self.ax)-1):\n self.finalizePlot(self.fig, self.ax[i], self.fontsize, self.xlabel, self.ylabel, show=False)\n self.finalizePlot(self.fig, self.ax[-1], self.fontsize, self.xlabel, self.ylabel, show=True)\n\n def finalizePlot(self, fig, ax, fontsize, xlabel, ylabel, xmin=None, xmax=None, ymin=None, ymax=None,\n export_dir='', output_file='', show_legend=True, legend_type='outer_left',\n logscale_x=False, logscale_y=False, show=True, tick_fontsize=None):\n\n if tick_fontsize is None:\n tick_fontsize = fontsize\n\n if xmin is None or xmax is None:\n if not (ymin is None or ymax is None):\n ax.set_ylim([ymin, ymax])\n elif ymin is None or ymax is None:\n if not (xmin is None or xmax is None):\n ax.set_xlim([xmin, xmax])\n else:\n ax.axis([xmin, xmax, ymin, ymax])\n\n if show_legend:\n handles, labels = ax.get_legend_handles_labels()\n if legend_type == 'outer_top':\n ax.legend(handles, labels, prop={'size': fontsize}, \\\n bbox_to_anchor=(0., 1.02, 1., .102), loc=3, mode=\"expand\", frameon=False)\n elif legend_type == 'outer_right':\n ax.legend(handles, labels, prop={'size': fontsize}, \\\n bbox_to_anchor=(1.02, 1., 1., .102), loc=2, mode=\"expand\", frameon=False)\n elif legend_type == 'outer_left':\n ax.legend(handles, labels, prop={'size': fontsize}, \\\n bbox_to_anchor=(0., 1.02, 1., .102), loc='upper left', mode=\"expand\", frameon = False)\n elif legend_type == 'basic':\n ax.legend(handles, labels, prop={'size': fontsize}, loc=0)\n else:\n print ('no legend shown')\n\n if logscale_x is True:\n ax.set_xscale('log')\n\n if logscale_y is True:\n ax.set_yscale('log')\n\n ax.set_xlabel(xlabel, fontsize=fontsize)\n ax.set_ylabel(ylabel, fontsize=fontsize)\n\n gridlines = ax.get_xgridlines()\n gridlines.extend(ax.get_ygridlines())\n for line in gridlines:\n line.set_linestyle('--')\n\n ticklabels = ax.get_xticklabels()\n ticklabels.extend(ax.get_yticklabels())\n for label in ticklabels:\n label.set_color('k')\n label.set_fontsize(tick_fontsize)\n\n if not (export_dir == '' or output_file == ''):\n fig.savefig(os.path.join(export_dir, output_file), dpi=400)\n\n if show:\n plt.show()\n\n\nclass Curve_xy():\n\n def __init__(self, result_xy, style, subplotIndex):\n self.result_xy = result_xy\n self.style = style\n self.subplotIndex = subplotIndex\n self.x = []\n self.y = []\n\n def set(self):\n self.x.append(self.result_xy.x)\n self.y.append(self.result_xy.y)\n\n def plot(self, ax):\n ax.plot(np.array(self.x), np.array(self.y) / self.result_xy.adim,\n self.style, label=self.result_xy.label)\n\n\n\n\n\n# x_data, y_data = [], []\n\n# figure = pyplot.figure()\n# line, = pyplot.plot_date(x_data, y_data, '-')\n\n# def update(frame):\n# x_data.append(datetime.now())\n# y_data.append(randrange(0, 100))\n# line.set_data(x_data, y_data)\n# figure.gca().relim()\n# figure.gca().autoscale_view()\n# return line,\n\n\n\n# import numpy as np\n# import time\n# import matplotlib\n# matplotlib.use('GTKAgg')\n\n\n# def randomwalk(dims=(256, 256), n=20, sigma=5, alpha=0.95, seed=1):\n# \"\"\" A simple random walk with memory \"\"\"\n\n# r, c = dims\n# gen = np.random.RandomState(seed)\n# pos = gen.rand(2, n) * ((r,), (c,))\n# old_delta = gen.randn(2, n) * sigma\n\n# while True:\n# delta = (1. - alpha) * gen.randn(2, n) * sigma + alpha * old_delta\n# pos += delta\n# for ii in range(n):\n# if not (0. <= pos[0, ii] < r):\n# pos[0, ii] = abs(pos[0, ii] % r)\n# if not (0. <= pos[1, ii] < c):\n# pos[1, ii] = abs(pos[1, ii] % c)\n# old_delta = delta\n# yield pos\n\n\n# def run(niter=1000, doblit=True):\n# \"\"\"\n# Display the simulation using matplotlib, optionally using blit for speed\n# \"\"\"\n\n# fig, ax = plt.subplots(1, 1)\n# ax.set_aspect('equal')\n# ax.set_xlim(0, 255)\n# ax.set_ylim(0, 255)\n# rw = randomwalk()\n# x, y = rw.__next__()\n\n# plt.show(False)\n# plt.draw()\n\n# if doblit:\n# # cache the background\n# background = fig.canvas.copy_from_bbox(ax.bbox)\n\n# points = ax.plot(x, y, 'o')[0]\n# tic = time.time()\n\n# for ii in range(niter):\n\n# # update the xy data\n# x, y = rw.__next__()\n# points.set_data(x, y)\n\n# if doblit:\n# # restore background\n# fig.canvas.restore_region(background)\n\n# # redraw just the points\n# ax.draw_artist(points)\n\n# # fill in the axes rectangle\n# fig.canvas.blit(ax.bbox)\n\n# else:\n# # redraw everything\n# fig.canvas.draw()\n\n# plt.close(fig)\n# print (\"Blit = %s, average FPS: %.2f\" % (str(doblit), niter / (time.time() - tic)))\n\n\n\n\n# world_size = 80 # The circles appear on a 59 X 59 grid\n# nbFrames = 100\n# circle_colors = np.empty((world_size, world_size, nbFrames), 'str') #And this is loading a 3D array\n# for n in range(nbFrames):\n# for i in range(circle_colors.shape[1]):\n# for j in range(circle_colors.shape[0]):\n# circle_colors[j, i, n] = '0.5'\n\n# #Each XY coordinate contains a list of RGB colors indicating the series\n# #of colors the circle should take on in each frame (so the length of\n# #these lists is equal to the number of frames)\n\n\n# #Create figure to do plotting on\n# fig = plt.figure(figsize=(20,20))\n\n# world = np.zeros((world_size, world_size, 3), 'uint8') #Don't worry about this it's just\n# #loading a 2D array of numbers to pass to imshow() to make the background\n\n# #Create list of circles, one for every grid cell in the environment\n# patches = []\n\n# for i in range(world_size):\n# for j in range(world_size):\n# patches.append(plt.Circle((j,i), radius=.3, lw=2, ec=\"black\", facecolor=None))\n# #(j,i) are the (x,y) coordinates, lw is the line width, ec is the color of the\n# #outline, setting facecolor to None makes these circles invisible for now\n\n# def init():\n# #Draw background\n# plt.imshow(world, interpolation=\"none\", hold=True)\n# axes = plt.gca()\n# axes.autoscale(False)\n\n# #Add patches to axes\n# for p in patches:\n# axes.add_patch(p)\n\n# return patches\n\n# def animate(n):\n# #Recolor circles\n# #Note that this needs to be in the same scope as circle_colors\n\n# for i in range(world_size):\n# for j in range(world_size):\n\n# if circle_colors[i][j][n] == 0:\n# #Here, I'm using 0 as code for non-existent\n# #So I make these circles invisible\n# patches[i * world_size + j].set_visible(False)\n\n# else: #Otherwise we set the color to the one indicated by circle_colors\n# #and make sure the circle is set to visible\n# patches[i*world_size + j].set_facecolor(circle_colors[i][j][n])\n# patches[i*world_size + j].set_visible(True)\n\n# #We haven't actually changed patches, but FuncAnimation is\n# #still expecting us to return it. Don't forget the comma.\n# return patches,\n\n\n\n#remember to set blit=True\n\n# anim.save(filename, writer=\"mencoder\", fps=2) #You can also save your animation!\n#Appropriate writer will vary based on your computer\n\n\n\"\"\"\nA simple example of an animated plot\n\"\"\"\n\n# fig, ax = plt.subplots()\n\n# x = np.arange(0, 2*np.pi, 0.01)\n# line, = ax.plot(x, np.sin(x))\n\n\n# def animate(i):\n# line.set_ydata(np.sin(x + i/10.0)) # update the data\n# return line,\n\n\n# # Init only required for blitting to give a clean slate.\n# def init():\n# line.set_ydata(np.ma.array(x, mask=True))\n# return line,\n\n# ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init,\n# interval=25, blit=True)\n# # plt.show()","sub_path":"Lib/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":9320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"544314469","text":"import unittest\n\nimport main\n\n\nclass Test(unittest.TestCase):\n def test_multiply_all(self):\n tests = {\n '(x)*(x)*(x)': 'x^3',\n '(2+3)*(3)': '6+9',\n '(2x+3)*(3x)': '6x^2+9x',\n '(2x+3)*(3x)*(2)': '12x^2+18x',\n }\n for test in sorted(tests):\n answer = main.multiply_all(test)\n self.assertEqual(answer, tests[test])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"347418361","text":"import seaborn as sns\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom matplotlib.ticker import FormatStrFormatter\n\ncommunitiesLinkResultData = {\n\t\"Base Model\": [\"GCN\"] * 4 + [\"SAGE\"] * 4 + [\"GAT\"] * 4 + [\"GIN\"] * 4 + [\"P-GNN-F-2L\"] * 4 + [\"P-GNN-E-2L\"] * 4,\n\t\"Variant\": [\"None\", \"Hash\", \"MSE\", \"Both\"] * 6,\n\t\"AUC\": [0.977, 0.986, 0.986, 0.986, 0.986, 0.979, 0.985, 0.9861, 0.981, 0.919, 0.983, 0.987, 0.980, 0.988, 0.987, 0.987, 0.978, 0.978, 0.982, 0.980, 0.965, 0.973, 0.985, 0.982],\n\t\"Kendall's Tau\": [0.182, 0.215, 0.267, 0.301, 0.218, 0.268, 0.248, 0.253, 0.203, 0.263, 0.300, 0.303, 0.241, 0.272, 0.290, 0.432, 0.334, 0.340, 0.338, 0.341, 0.554, 0.600, 0.566, 0.588]\n}\n\nemailLinkResultData = {\n\t\"Base Model\": [\"GCN\"] * 4 + [\"SAGE\"] * 4 + [\"GAT\"] * 4 + [\"GIN\"] * 4 + [\"P-GNN-F-2L\"] * 4 + [\"P-GNN-E-2L\"] * 4,\n\t\"Variant\": [\"None\", \"Hash\", \"MSE\", \"Both\"] * 6,\n\t\"AUC\": [0.709, 0.767, 0.721, 0.782, 0.571, 0.735, 0.557, 0.769, 0.538, 0.758, 0.550, 0.769, 0.724, 0.785, 0.791, 0.808, 0.751, 0.769, 0.835, 0.823, 0.792, 0.770, 0.765, 0.775],\n\t\"Kendall's Tau\": [0.239, 0.364, 0.217, 0.364, 0.147, 0.361, 0.156, 0.363, 0.086, 0.336, 0.096, 0.353, 0.402, 0.443, 0.429, 0.452, 0.503, 0.529, 0.516, 0.532, 0.547, 0.549, 0.539, 0.550]\n}\n\nppiLinkResultData = {\n\t\"Base Model\": [\"GCN\"] * 4 + [\"SAGE\"] * 4 + [\"GAT\"] * 4 + [\"GIN\"] * 4 + [\"P-GNN-F-2L\"] * 4 + [\"P-GNN-E-2L\"] * 4,\n\t\"Variant\": [\"None\", \"Hash\", \"MSE\", \"Both\"] * 6,\n\t\"AUC\": [0.798, 0.810, 0.760, 0.821, 0.809, 0.818, 0.804, 0.812, 0.798, 0.818, 0.789, 0.819, 0.755, 0.788, 0.751, 0.789, 0.812, 0.823, 0.815, 0.819, 0.772, 0.775, 0.792, 0.803],\n\t\"Kendall's Tau\": [0.413, 0.441, 0.422, 0.444, 0.426, 0.464, 0.421, 0.461, 0.416, 0.462, 0.413, 0.465, 0.442, 0.450, 0.432, 0.460, 0.375, 0.388, 0.372, 0.391, 0.435, 0.426, 0.446, 0.454]\n}\n\ncommunitiesLinkPairResultData = {\n\t\"Base Model\": [\"GCN\"] * 4 + [\"SAGE\"] * 4 + [\"GAT\"] * 4 + [\"GIN\"] * 4 + [\"P-GNN-F-2L\"] * 4 + [\"P-GNN-E-2L\"] * 4,\n\t\"Variant\": [\"None\", \"Hash\", \"MSE\", \"Both\"] * 6,\n\t\"AUC\": [0.988, 0.992, 0.992, 0.992, 0.993, 0.982, 0.994, 0.9931, 0.989, 0.975, 0.989, 0.993, 0.991, 0.982, 0.992, 0.984, 0.986, 0.988, 0.991, 0.987, 0.981, 0.981, 0.990, 0.994],\n\t\"Kendall's Tau\": [0.146, 0.217, 0.277, 0.335, 0.212, 0.257, 0.270, 0.280, 0.205, 0.334, 0.318, 0.324, 0.213, 0.250, 0.301, 0.365, 0.346, 0.358, 0.357, 0.359, 0.518, 0.576, 0.535, 0.607]\n}\n\nemailLinkPairResultData = {\n\t\"Base Model\": [\"GCN\"] * 4 + [\"SAGE\"] * 4 + [\"GAT\"] * 4 + [\"GIN\"] * 4 + [\"P-GNN-F-2L\"] * 4 + [\"P-GNN-E-2L\"] * 4,\n\t\"Variant\": [\"None\", \"Hash\", \"MSE\", \"Both\"] * 6,\n\t\"AUC\": [0.518, 0.681, 0.575, 0.708, 0.538, 0.693, 0.533, 0.744, 0.507, 0.725, 0.528, 0.747, 0.723, 0.741, 0.726, 0.774, 0.751, 0.734, 0.772, 0.769, 0.735, 0.784, 0.772, 0.753],\n\t\"Kendall's Tau\": [0.238, 0.432, 0.267, 0.437, 0.139, 0.428, 0.206, 0.433, 0.083, 0.407, 0.112, 0.435, 0.479, 0.525, 0.482, 0.521, 0.576, 0.615, 0.609, 0.616, 0.603, 0.638, 0.612, 0.614]\n}\n\nresultDataAll = {\n\t\"Dataset\": 24 * [\"Communities\"] + 24 * [\"Email\"] + 24 * [\"PPI\"] + 24 * [\"Communities\"] + 24 * [\"Email\"],\n\t\"Task\": 24 * 3 * [\"Link Prediction\"] + 24 * 2 * [\"Pairwise Node Classification\"],\n\t\"Base Model\": 5 * communitiesLinkResultData[\"Base Model\"],\n\t\"Variant\": 5 * communitiesLinkResultData[\"Variant\"],\n\t\"AUC\": communitiesLinkResultData[\"AUC\"] + emailLinkResultData[\"AUC\"] + ppiLinkResultData[\"AUC\"] + communitiesLinkPairResultData[\"AUC\"] + emailLinkPairResultData[\"AUC\"],\n\t\"Kendall's Tau\": communitiesLinkResultData[\"Kendall's Tau\"] + emailLinkResultData[\"Kendall's Tau\"] + ppiLinkResultData[\"Kendall's Tau\"] + communitiesLinkPairResultData[\"Kendall's Tau\"] + emailLinkPairResultData[\"Kendall's Tau\"]\n}\n\nbase_models = [\"GCN\", \"SAGE\", \"GAT\", \"GIN\", \"P-GNN-F-2L\", \"P-GNN-E-2L\"]\n\n# print(len(emailLinkPairResultData[\"Base Model\"]), len(emailLinkPairResultData[\"Variant\"]), len(emailLinkPairResultData[\"AUC\"]), len(emailLinkPairResultData[\"Kendall's Tau\"]))\n\n# communitiesLinkDF = pd.DataFrame(communitiesLinkResultData)\n\n# print(communitiesLinkDF)\nsns.set(style=\"ticks\")\n\n# sns_plot = sns.scatterplot(x=\"Kendall's Tau\", y=\"AUC\", hue=\"Variant\", style=\"Base Model\", data=communitiesLinkDF, legend=\"brief\")\n# figure = sns_plot.get_figure() \n# figure.savefig('figs/KTvsAUC.png')\n\nDF = pd.DataFrame(resultDataAll)\ndfLP = DF.loc[(DF[\"Task\"] == \"Link Prediction\") & ((DF[\"Variant\"] == \"None\") | (DF[\"Variant\"] == \"Both\"))]\ndfNC = DF.loc[(DF[\"Task\"] == \"Pairwise Node Classification\") & ((DF[\"Variant\"] == \"None\") | (DF[\"Variant\"] == \"Both\"))]\n# g = sns.FacetGrid(DF, row=\"Dataset\", col=\"Task\", hue=\"Base Model\", style=\"Variant\", margin_titles=True, height=2.5)\n# g.map(plt.scatter, \"Kendall's Tau\", \"AUC\")\n# g.set_axis_labels(\"Kendall's Tau\", \"AUC\")\n\n# # sns_plot = sns.relplot(x=\"Kendall's Tau\", y=\"AUC\", hue=\"Base Model\", style=\"Variant\", col=\"Task\", row=\"Dataset\", data=DF, s=150)\n# # fig, ax = plt.subplots()\n# g = sns.relplot(x=\"Kendall's Tau\", y=\"AUC\", hue=\"Base Model\", style=\"Variant\", col=\"Dataset\", col_wrap=2, data=dfEmail, s=150)\n# # g.map(plt.plot, \"Kendall's Tau\", \"AUC\", data=dfEmail.loc[DF[\"Base Model\"].isin([\"GCN\"])])\n# # sns.relplot(x=\"Kendall's Tau\", y=\"AUC\", col=\"Dataset\", col_wrap=2, data=dfEmail.loc[DF[\"Base Model\"].isin([\"GCN\"])], kind=\"line\", ax=ax)\n# # figure = sns_plot.get_figure() \n# # figure.savefig('figs/KTvsAUC.png')\n# g.savefig('figs/KTvsAUCLP.png')\n\nfor l, df in {\"LP\": dfLP, \"NC\": dfNC}.items():\n\tif l == \"NC\":\n\t\tfig, ax = plt.subplots(1, 2)\n\t\tax[0].xaxis.set_major_formatter(FormatStrFormatter('%.2f'))\n\t\tax[1].xaxis.set_major_formatter(FormatStrFormatter('%.2f'))\n\n\t\t# plot for communities\n\t\tg1 = sns.scatterplot(y=\"Kendall's Tau\", x=\"AUC\", hue=\"Base Model\", style=\"Variant\", data=df.loc[DF[\"Dataset\"] == \"Communities\"], s=70, ax=ax[0], legend=False)\n\t\tfor base_model in base_models:\n\t\t\tsns.lineplot(y=\"Kendall's Tau\", x=\"AUC\", data=df.loc[(DF[\"Dataset\"] == \"Communities\") & (DF[\"Base Model\"] == base_model)], ax=ax[0], legend=False)\n\t\t# sns.lineplot(x=\"Kendall's Tau\", y=\"AUC\", data=dfLP.loc[(DF[\"Dataset\"] == \"Communities\") & (DF[\"Base Model\"] == \"SAGE\")], ax=ax[0], legend=False)\n\t\t# sns.lineplot(x=\"Kendall's Tau\", y=\"AUC\", data=dfLP.loc[(DF[\"Dataset\"] == \"Communities\") & (DF[\"Base Model\"] == \"GAT\")], ax=ax[0], legend=False)\n\t\t# sns.lineplot(x=\"Kendall's Tau\", y=\"AUC\", data=dfLP.loc[(DF[\"Dataset\"] == \"Communities\") & (DF[\"Base Model\"] == \"GIN\")], ax=ax[0], legend=False)\n\t\t# sns.lineplot(x=\"Kendall's Tau\", y=\"AUC\", data=dfLP.loc[(DF[\"Dataset\"] == \"Communities\") & (DF[\"Base Model\"] == \"P-GNN-F-2L\")], ax=ax[0], legend=False)\n\t\t# sns.lineplot(x=\"Kendall's Tau\", y=\"AUC\", data=dfLP.loc[(DF[\"Dataset\"] == \"Communities\") & (DF[\"Base Model\"] == \"P-GNN-E-2L\")], ax=ax[0], legend=False)\n\n\t\t\n\t\t# plot for email\n\t\tg2 = sns.scatterplot(y=\"Kendall's Tau\", x=\"AUC\", hue=\"Base Model\", style=\"Variant\", data=df.loc[DF[\"Dataset\"] == \"Email\"], s=70, ax=ax[1])\n\t\t# h,l = ax[1].get_legend_handles_labels()\n\t\tlgd = ax[1].legend(bbox_to_anchor=(0.98, 0.5), loc=6, borderaxespad=0., frameon=False)\n\t\tfor base_model in base_models:\n\t\t\tsns.lineplot(y=\"Kendall's Tau\", x=\"AUC\", data=df.loc[(DF[\"Dataset\"] == \"Email\") & (DF[\"Base Model\"] == base_model)], ax=ax[1], legend=False)\n\t\t# sns.lineplot(x=\"Kendall's Tau\", y=\"AUC\", data=dfLP.loc[(DF[\"Dataset\"] == \"Email\") & (DF[\"Base Model\"] == \"SAGE\")], ax=ax[1], legend=False)\n\t\t# sns.lineplot(x=\"Kendall's Tau\", y=\"AUC\", data=dfLP.loc[(DF[\"Dataset\"] == \"Email\") & (DF[\"Base Model\"] == \"GAT\")], ax=ax[1], legend=False)\n\t\t# sns.lineplot(x=\"Kendall's Tau\", y=\"AUC\", data=dfLP.loc[(DF[\"Dataset\"] == \"Email\") & (DF[\"Base Model\"] == \"GIN\")], ax=ax[1], legend=False)\n\t\t# sns.lineplot(x=\"Kendall's Tau\", y=\"AUC\", data=dfLP.loc[(DF[\"Dataset\"] == \"Email\") & (DF[\"Base Model\"] == \"P-GNN-F-2L\")], ax=ax[1], legend=False)\n\t\t# sns.lineplot(x=\"Kendall's Tau\", y=\"AUC\", data=dfLP.loc[(DF[\"Dataset\"] == \"Email\") & (DF[\"Base Model\"] == \"P-GNN-E-2L\")], ax=ax[1], legend=False)\n\t\tax[1].set_ylabel('')\n\t\tax[0].set_xlabel('')\n\t\tax[1].set_xlabel('')\n\t\tax[0].set_title('Communities')\n\t\tax[1].set_title('Email')\n\n\t\t# add a big axes, hide frame\n\t\tfig.add_subplot(111, frameon=False)\n\t\t# hide tick and tick label of the big axes\n\t\tplt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)\n\t\tplt.grid(False)\n\t\tplt.xlabel(\"AUC\")\n\t\tfig.savefig(\"figs/AUCvsKT\" + l +\".pdf\", bbox_extra_artists=(lgd,), bbox_inches='tight', format=\"pdf\")\n\n\telif l == \"LP\":\n\t\tfig, ax = plt.subplots(1, 3)\n\t\tax[0].xaxis.set_major_formatter(FormatStrFormatter('%.2f'))\n\t\tax[1].xaxis.set_major_formatter(FormatStrFormatter('%.2f'))\n\t\tax[2].xaxis.set_major_formatter(FormatStrFormatter('%.2f'))\n\t\t# plot for communities\n\t\tg1 = sns.scatterplot(y=\"Kendall's Tau\", x=\"AUC\", hue=\"Base Model\", style=\"Variant\", data=df.loc[DF[\"Dataset\"] == \"Communities\"], s=70, ax=ax[0], legend=False)\n\t\tfor base_model in base_models:\n\t\t\tsns.lineplot(y=\"Kendall's Tau\", x=\"AUC\", data=df.loc[(DF[\"Dataset\"] == \"Communities\") & (DF[\"Base Model\"] == base_model)], ax=ax[0], legend=False)\n\t\t# plot for email\n\t\tg2 = sns.scatterplot(y=\"Kendall's Tau\", x=\"AUC\", hue=\"Base Model\", style=\"Variant\", data=df.loc[DF[\"Dataset\"] == \"Email\"], s=70, ax=ax[1], legend=False)\n\t\t# h,l = ax[1].get_legend_handles_labels()\n\t\t# lgd = ax[1].legend(bbox_to_anchor=(0.98, 0.5), loc=6, borderaxespad=0., frameon=False)\n\t\tfor base_model in base_models:\n\t\t\tsns.lineplot(y=\"Kendall's Tau\", x=\"AUC\", data=df.loc[(DF[\"Dataset\"] == \"Email\") & (DF[\"Base Model\"] == base_model)], ax=ax[1], legend=False)\n\t\t# plot for ppi\n\t\tg3 = sns.scatterplot(y=\"Kendall's Tau\", x=\"AUC\", hue=\"Base Model\", style=\"Variant\", data=df.loc[DF[\"Dataset\"] == \"PPI\"], s=70, ax=ax[2], legend=False)\n\t\t# h,l = ax[1].get_legend_handles_labels()\n\t\t# lgd = ax[2].legend(bbox_to_anchor=(0.98, 0.5), loc=6, borderaxespad=0., frameon=False)\n\t\tfor base_model in base_models:\n\t\t\tsns.lineplot(y=\"Kendall's Tau\", x=\"AUC\", data=df.loc[(DF[\"Dataset\"] == \"PPI\") & (DF[\"Base Model\"] == base_model)], ax=ax[2], legend=False)\n\t\tax[2].set_ylabel('')\n\t\tax[2].set_xlabel('')\n\t\tax[2].set_title('PPI')\n\t\tax[1].set_ylabel('')\n\t\tax[0].set_xlabel('')\n\t\tax[1].set_xlabel('')\n\t\tax[0].set_title('Communities')\n\t\tax[1].set_title('Email')\n\n\t\t# add a big axes, hide frame\n\t\tfig.add_subplot(111, frameon=False)\n\t\t# hide tick and tick label of the big axes\n\t\tplt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)\n\t\tplt.grid(False)\n\t\tplt.xlabel(\"AUC\")\t\t\n\n\t\t# fig.tight_layout()\n\t\tplt.subplots_adjust(wspace = 0.4)\n\n\t\tfig.savefig(\"figs/AUCvsKT\" + l +\".pdf\", bbox_inches='tight', format=\"pdf\")","sub_path":"delta_plot.py","file_name":"delta_plot.py","file_ext":"py","file_size_in_byte":10494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"110913359","text":"\"\"\"\nFile: Fibonacci\n--------------------\nThis program lists the terms in the Fibonacci sequence up to\na constant MAX_TERM_VALUE, which is the largest Fibonacci term\nthe program will display.\n\"\"\"\n\n# Defines the largest term to display\nMAX_TERM_VALUE = 10000\n\ndef main():\n print(\"This program lists the Fibonacci sequence.\")\n t1 = 0\n t2 = 1\n while t1 <= MAX_TERM_VALUE:\n print(t1)\n t3 = t1 + t2\n t1 = t2\n t2 = t3\n\nif __name__ == '__main__':\n main()\n","sub_path":"templates/tr/projects/fibonacci/soln.py","file_name":"soln.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"18877989","text":"import cv2\nimport sys\nimport pickle\n\ncap = cv2.VideoCapture(sys.argv[1])\nannotation_filename = \"{}-annotations.pickle\".format(\".\".join(sys.argv[1].split(\".\")[:-1]))\n\ntry:\n with open(annotation_filename, 'rb') as af:\n annotations = pickle.load(af)\n print(\"Skipping {n} frames\".format(n=max(annotations.keys())))\n n = max(annotations.keys())\n for fn in range(n):\n print(\"skipping {fn}\".format(fn=fn))\n\nexcept IOError:\n n = 0\n annotations = {}\n\nwhile True:\n status, frame = cap.read()\n if status:\n print(\"Frame {}\".format(n))\n cv2.imshow(\"Frame\", frame)\n cv2.waitKey(1)\n nppl = input(\"Number of people entering boundary: \")\n if nppl.lower().startswith(\"q\"):\n sys.exit()\n elif nppl == \"\":\n nppl = 0\n annotations[n] = int(nppl)\n with open(annotation_filename, 'wb') as af:\n pickle.dump(annotations, af)\n print(\"Logged {} in frame {}\".format(annotations[n], n))\n n+=1\n else:\n print(\"Failed to read frame\")\n","sub_path":"annotator.py","file_name":"annotator.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"300069650","text":"class Solution1(object):\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n def expand(left, right):\n while left >= 0 and right < n and s[left] == s[right]:\n left -= 1\n right += 1\n if right - left - 1 > self.maxLen:\n self.lo = left + 1\n self.maxLen = right - left - 1\n\n n, self.lo, self.maxLen = len(s), 0, 0\n for i in range(n):\n expand(i, i)\n expand(i, i + 1)\n return s[self.lo:self.lo + self.maxLen]\n\n\nclass Solution2(object):\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n n, i, lo, maxLen = len(s), 0, 0, 0\n while i < n:\n left, right = i, i\n while right + 1 < n and s[right] == s[right + 1]: right += 1\n i = right + 1\n while left >= 0 and right < n and s[left] == s[right]:\n left -= 1\n right += 1\n if right - left - 1 > maxLen:\n lo = left + 1\n maxLen = right - left - 1\n return s[lo:lo + maxLen]\n\n\nclass Solution(object):\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n n, lo, maxLen = len(s), 0, 0\n isPal = [[False for _ in range(n)] for _ in range(n)]\n for i in range(n - 1, -1, -1):\n for j in range(i, n):\n if s[i] == s[j] and (j - i < 3 or isPal[i + 1][j - 1]):\n isPal[i][j] = True\n if j - i + 1 > maxLen:\n lo, maxLen = i, j - i + 1\n return s[lo:lo + maxLen]\n","sub_path":"medium/LongestPalindromicSubstring.py","file_name":"LongestPalindromicSubstring.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"6938104","text":"\"\"\"\n\nCopyright (c) 2018-2019, Kristoffer Paulsson \n\nThis file is distributed under the terms of the MIT license.\n\n\n\"\"\"\nimport io\n\nfrom kivy.app import App\nfrom kivy.lang import Builder\nfrom kivy.graphics import Rectangle\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.graphics.texture import Texture\nfrom kivymd.theming import ThemeManager\n\nfrom eidon.codec import EidonEncoder, EidonDecoder\nfrom eidon.image import EidonImage, ImageRGB, ImageRGBA\nfrom eidon.stream import EidonStream\n\n# from dahuffman import HuffmanCodec\n\n\"\"\"\ndef __init__(self, **kwargs):\n super(...).__init__(**kwargs)\n self.texture = Texture.create(size=(512, 512), colorfmt='RGB',\n bufferfmt='ubyte')\n self.texture.add_reload_observer(self.populate_texture)\n\n # and load the data now.\n self.cbuffer = '\\x00\\xf0\\xff' * 512 * 512\n self.populate_texture(self.texture)\n\ndef populate_texture(self, texture):\n texture.blit_buffer(self.cbuffer)\n\"\"\"\n\n\nBuilder.load_string('''\n#:import MDFloatingActionButton kivymd.button.MDFloatingActionButton\n:\n orientation: 'vertical'\n Image:\n id: picture\n Image:\n id: loaded\n source: 'image3.png'\n size_hint: .2, .2\n pos_hint: {'top':.9,'right':.9}\n MDFloatingActionButton:\n icon: 'image'\n elevation_normal: 8\n pos: dp(25), dp(25)\n on_press: root.capture()\n''')\n\n\nclass ImageWidget(BoxLayout):\n def capture(self):\n image = self.extract()\n print('0', len(image.pixels))\n encoder = EidonEncoder(image, EidonStream.preferred(\n image.width, image.height))\n stream = encoder.run()\n data = EidonStream.dump(stream)\n print('2', len(data))\n stream = EidonStream.load(data)\n self.insert(EidonDecoder(stream, EidonImage.rgb(\n stream.width, stream.height)).run())\n\n def extract(self):\n tex = self.ids['loaded'].texture\n data = io.BytesIO(tex.pixels)\n data.seek(0)\n if tex.colorfmt == 'rgba':\n image = EidonImage.rgba(\n tex.width, tex.height, bytearray(data.getvalue()))\n elif tex.colorfmt == 'rgb':\n image = EidonImage.rgb(\n tex.width, tex.height, bytearray(data.getvalue()))\n return image\n\n def insert(self, input):\n if isinstance(input, ImageRGBA):\n fmt = 'rgba'\n elif isinstance(input, ImageRGB):\n fmt = 'rgb'\n tex = Texture.create(size=(input.width, input.height), colorfmt=fmt)\n tex.blit_buffer(input.pixels, colorfmt=fmt, bufferfmt='ubyte')\n with self.ids['picture'].canvas:\n Rectangle(texture=tex, size=self.ids['loaded'].texture.size)\n\n\nclass ImageApp(App):\n theme_cls = ThemeManager()\n\n def build(self):\n img = ImageWidget()\n return img\n\n\nImageApp().run()\n","sub_path":"misc/attempt_pic3.py","file_name":"attempt_pic3.py","file_ext":"py","file_size_in_byte":2898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"401321418","text":"\"\"\"\nsentry.models.deploy\n~~~~~~~~~~~~~~~~~~~~\n\"\"\"\n\nfrom __future__ import absolute_import\n\nfrom django.db import models\nfrom django.utils import timezone\n\nfrom sentry.app import locks\nfrom sentry.db.models import (BoundedPositiveIntegerField, FlexibleForeignKey, Model)\nfrom sentry.utils.retries import TimedRetryPolicy\n\n\nclass Deploy(Model):\n __core__ = False\n\n organization_id = BoundedPositiveIntegerField(db_index=True)\n release = FlexibleForeignKey('sentry.Release')\n environment_id = BoundedPositiveIntegerField(db_index=True)\n date_finished = models.DateTimeField(default=timezone.now)\n date_started = models.DateTimeField(null=True, blank=True)\n name = models.CharField(max_length=64, null=True, blank=True)\n url = models.URLField(null=True, blank=True)\n notified = models.NullBooleanField(null=True, db_index=True, default=False)\n\n class Meta:\n app_label = 'sentry'\n db_table = 'sentry_deploy'\n\n @staticmethod\n def get_lock_key(deploy_id):\n return 'deploy-notify:%s' % deploy_id\n\n @classmethod\n def notify_if_ready(cls, deploy_id, fetch_complete=False):\n \"\"\"\n create activity and send deploy notifications\n if they haven't been sent\n \"\"\"\n from sentry.models import Activity, Environment, ReleaseCommit, ReleaseHeadCommit\n\n lock_key = cls.get_lock_key(deploy_id)\n lock = locks.get(lock_key, duration=30)\n with TimedRetryPolicy(10)(lock.acquire):\n deploy = cls.objects.filter(\n id=deploy_id,\n ).select_related('release').get()\n if deploy.notified:\n return\n\n release = deploy.release\n environment = Environment.objects.get(\n organization_id=deploy.organization_id,\n id=deploy.environment_id,\n )\n\n if not fetch_complete:\n release_has_commits = ReleaseCommit.objects.filter(\n organization_id=release.organization_id,\n release=release,\n ).exists()\n\n if not release_has_commits:\n # check if we have head commits, which\n # would indicate that we're waiting for\n # fetch_commits to complete\n if ReleaseHeadCommit.objects.filter(\n organization_id=release.organization_id,\n release=release,\n ).exists():\n return\n\n activity = None\n for project in deploy.release.projects.all():\n activity = Activity.objects.create(\n type=Activity.DEPLOY,\n project=project,\n ident=release.version,\n data={\n 'version': release.version,\n 'deploy_id': deploy.id,\n 'environment': environment.name,\n },\n datetime=deploy.date_finished,\n )\n # Somewhat hacky, only send notification for one\n # Deploy Activity record because it will cover all projects\n if activity is not None:\n activity.send_notification()\n deploy.update(notified=True)\n","sub_path":"src/sentry/models/deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":3310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"606187346","text":"# userAcc.py\r\n\r\n\r\nclass UserAcc:\r\n id_ = 0\r\n name = \"\"\r\n role = 0\r\n conn = None\r\n\r\n def __init__(self, id_=0, name=\"\", role=0, conn=None):\r\n self.id_ = id_\r\n self.name = name\r\n self.role = role\r\n self.conn = conn\r\n\r\n def set_attrs(self, id_, name, role, conn):\r\n \"\"\"Set user attributes.\"\"\"\r\n self.id_ = id_\r\n self.name = name\r\n self.role = role\r\n self.conn = conn\r\n\r\n\r\n# user account object declaration\r\nuser_acc = UserAcc()\r\n","sub_path":"programming/QTR2/UIS/module/userAcc.py","file_name":"userAcc.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"398676267","text":"import json\nimport logging\nfrom http import HTTPStatus\nfrom typing import Optional, Mapping\n\nfrom aiohttp.web_exceptions import HTTPException\nfrom aiohttp.web_middlewares import middleware\nfrom aiohttp.web_request import Request\nfrom aiohttp.web_response import Response\nfrom marshmallow import ValidationError\n\nfrom backend.api.payloads import JsonPayload\n\n\nlog = logging.getLogger(__name__)\nVALIDATION_ERROR_DESCRIPTION = 'Request validation has failed'\n\n\ndef format_http_error(message: Optional[str] = '', status_code: int = HTTPStatus.INTERNAL_SERVER_ERROR,\n fields: Optional[Mapping] = None) -> Response:\n \"\"\"\n Formats the error as an HTTP exception\n \"\"\"\n status = HTTPStatus(status_code)\n error = {'code': status.name.lower()}\n\n # Adds fields errors which failed marshmallow validation\n if '{' in message:\n error['message'] = VALIDATION_ERROR_DESCRIPTION\n error['fields'] = json.loads(message)\n # Other errors\n else:\n error['message'] = message or status.description\n\n # Adds fields errors which failed validation in views\n if fields:\n error['fields'] = fields\n\n return Response(body={'error': error}, status=status_code)\n\n\ndef handle_validation_error(error: ValidationError):\n \"\"\"\n Represents a data validation error as an HTTP response.\n \"\"\"\n return format_http_error(message=VALIDATION_ERROR_DESCRIPTION, status_code=HTTPStatus.BAD_REQUEST,\n fields=error.messages)\n\n\n@middleware\nasync def error_middleware(request: Request, handler):\n try:\n return await handler(request)\n except HTTPException as err:\n # Exceptions that are HTTP responses were deliberately thrown for display to the client.\n # Text exceptions (or exceptions without information) are formatted in JSON\n if not isinstance(err.text, JsonPayload):\n return format_http_error(err.text, err.status_code)\n raise\n\n except ValidationError as err:\n # Checking for errors in views\n return handle_validation_error(err)\n\n except Exception:\n # All other exceptions cannot be displayed to the client as an HTTP response\n # and may inadvertently reveal internal information.\n log.exception('Unhandled exception')\n return format_http_error()\n","sub_path":"backend/api/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"329494040","text":"class Node():\n\n def __init__(self,key):\n self.next = None\n self.previous = None\n\n self.previousPointer = None\n self.nextPointer = None\n\n self.key = key\n\n def getKey(self):\n return self.key\n\n def getNextNode(self):\n return self.next\n\n def setNextNode(self, next):\n self.next = next\n\n def getPrevNode(self):\n return self.previous\n\n def setPrevNode(self, previous):\n self.previous = previous\n\n def getPreviousPointer(self):\n return self.previousPointer\n\n def getNextPointer(self):\n return self.nextPointer\n\n def setPreviousPointer(self,pointer):\n self.previousPointer = pointer\n\n def setNextPointer(self,pointer):\n self.nextPointer = pointer\n\nclass LinkedList():\n\n def __init__(self):\n self.root = None\n self.size = 0\n self.parent = None\n\n\n\n # def insertKey(self,key):\n # self.insert(key, self.root)\n #\n\n\n def printList(self):\n tempNode = self.root\n print(\"[\",end=' ')\n while(tempNode.getNextNode()!=None):\n print(tempNode.getKey(),end=', ')\n tempNode = tempNode.getNextNode()\n print(tempNode.getKey(),end='')\n print(\" ]\")\n\n\nclass BPlus():\n def __init__(self,n): # n = number of pointers.\n self.n = n\n self.searchKey = n - 1\n self.rootPage = None\n\n\n def insert3(self,key):\n tempPage = self.rootPage\n tempNode = tempPage.root\n\n while True:\n if(tempPage.size.\n# ****************************************************************************\n#\n#++\n# Name\n# CAL.Plan\n#\n# Purpose\n# Model a yearly calendar with appointments\n#\n# Revision Dates\n# 13-Apr-2003 (CT) Creation\n# 17-Apr-2003 (CT) `seq_generator` added to `PDF_Plan` to get correct\n# sequence for printed calendar when cut\n# 18-Apr-2003 (CT) `PDF_Plan` factored into separate module\n# 19-Apr-2003 (CT) `_add_appointment` added\n# 4-May-2003 (CT) Option `-Show` added\n# 4-May-2003 (CT) `_date_time` factored\n# 4-May-2003 (CT) `_day_generator` corrected (check year)\n# 4-May-2003 (CT) Pattern for `weekday` added\n# 11-Jan-2004 (CT) `holidays_too` added\n# 6-Feb-2004 (CT) Use (y, m, d) tuples instead of strings as dictionary\n# keys (for `Y.map`)\n# 17-Dec-2007 (CT) `write_plan` changed to use `Date_Time` instead of\n# `Date` to calculate `today`\n# 15-Jun-2010 (CT) Use `CAO` instead of `Command_Line`\n# 16-Jul-2015 (CT) Replace `raise StopIteration` by `return` (PEP 0479)\n# ««revision-date»»···\n#--\n\nfrom __future__ import print_function\n\nfrom _TFL import TFL\nfrom _CAL import CAL\n\nfrom _CAL.Appointment import prio_pat, time_pat\nimport _CAL.Appointment\nimport _CAL.Date\nimport _CAL.Date_Time\nimport _CAL.Year\n\nimport _TFL._Meta.Object\nimport _TFL.CAO\n\nfrom _TFL.Filename import *\nfrom _TFL.predicate import *\nfrom _TFL.pyk import pyk\nfrom _TFL.Regexp import *\nfrom _TFL import sos\n\nday_sep = Regexp (\"^#\", re.M)\nday_pat = Regexp (r\"^ (?P\\d{4}/\\d{2}/\\d{2}) \")\napp_date_pat = Regexp \\\n ( r\"(?P\"\n r\"(?:\"\n r\"(?:\"\n r\"(?P -? \\d{1,2}) \\.\"\n r\"(?: (?P \\d{1,2}) \\.\"\n r\" (?: (?P \\d{4}))?\"\n r\")?\"\n r\")\"\n r\"|\"\n r\"(?:\"\n r\"(?P Mon|Tue|Wed|Thu|Fri|Sat|Sun)\"\n r\"(?: [.#] (?P [0-5]?\\d))?\"\n r\")\"\n r\")\"\n r\"[ ]+\"\n r\")?\"\n , re.VERBOSE\n )\napp_pat = Regexp \\\n ( app_date_pat.pattern\n + r\"(?P \"\n + r\"\\+ (?P \\d+) (?P d|w|m)? \"\n + r\"(?: [ ]* \\* (?P \\d+))?\"\n + r\"[ ]+\"\n + r\")?\"\n + time_pat.pattern + r\"?\"\n + r\"(?: [ ]* = \" + prio_pat.pattern + r\")?\"\n + r\"[ ]+\"\n + r\"(?P .+)\"\n , re.VERBOSE\n )\n\ndef _day_generator (pat_match, day, month, year, Y) :\n delta = int (pat_match.delta or 0)\n how_often = int (pat_match.how_often or 1)\n unit = pat_match.unit or [\"d\", \"w\"] [bool (pat_match.weekday)]\n if unit == \"w\" :\n delta *= 7\n elif unit == \"m\" and day < 0 :\n delta = - delta\n for i in range (how_often) :\n d = day\n if day < 0 :\n d = Y.months [month - 1].days [day].number\n D = Y.dmap.get ((year, month, d))\n if not D :\n return\n yield D\n if unit == \"m\" :\n month += delta\n else :\n D = D.date + delta\n day, month = D.day, D.month\n if D.year != year :\n return\n# end def _day_generator\n\ndef _date_time (Y, pat_match) :\n if pat_match.date or pat_match.time :\n today = CAL.Date ()\n if pat_match.weekday :\n wd = pat_match.weekday.lower ()\n wk = int (pat_match.week or today.week)\n d = getattr (Y.weeks [wk - Y.weeks [0].number], wd).date\n if (pat_match.week is None) and d.rjd < today.rjd :\n d += 7\n day = d.day\n month = d.month\n year = d.year\n else :\n day = int (pat_match.day or today.day)\n month = int (pat_match.month or today.month)\n year = int (pat_match.year or today.year)\n time = pat_match.time or \"\"\n if time :\n if pat_match.hh_head :\n hh = int (pat_match.hh_head)\n mm = int (pat_match.mm_head or 0)\n time = \"%2.2d:%2.2d\" % (hh, mm)\n if pat_match.hh_tail :\n hh = int (pat_match.hh_tail)\n mm = int (pat_match.mm_tail or 0)\n time = \"%s-%2.2d:%2.2d\" % (time, hh, mm)\n return day, month, year, time\n else :\n raise ValueError (\"`%s` must specify either date or time\")\n# end def _date_time\n\ndef _add_appointment (Y, pat_match, holidays_too) :\n day, month, year, time = _date_time (Y, pat_match)\n app = ( CAL.Appointment.format\n % (time, pat_match.prio or \" \", pat_match.activity)\n )\n for D in _day_generator (pat_match, day, month, year, Y) :\n if D.is_holiday and not holidays_too :\n continue\n D.add_appointments (* CAL.appointments (app))\n# end def _add_appointment\n\ndef read_plan (Y, plan_file_name) :\n \"\"\"Read information from file named `plan_file_name` and put appointments\n into `Y`\n \"\"\"\n f = open (plan_file_name)\n try :\n buffer = f.read ()\n finally :\n f.close ()\n for entry in day_sep.split (buffer) :\n if day_pat.match (entry) :\n id = tuple ([int (f) for f in day_pat.day.split (\"/\")])\n d = Y.dmap [id]\n head, _, tail = split_hst (entry, \"\\n\")\n if tail :\n d.add_appointments (* CAL.appointments (tail))\n# end def read_plan\n\ndef write_plan (Y, plan_file_name, replace = False) :\n today = CAL.Date_Time ()\n tail = today.formatted (\"%d.%m.%Y.%H:%M\")\n if replace :\n sos.rename (plan_file_name, \"%s-%s\" % (plan_file_name, tail))\n else :\n plan_file_name = \"%s.%s\" % (plan_file_name, tail)\n CAL.write_year (Y.as_plan, plan_file_name, force = replace)\n# end def write_plan\n\ndef _main (cmd) :\n year = cmd.year\n path = sos.path.join (sos.expanded_path (cmd.diary), \"%4.4d\" % year)\n Y = CAL.Year (year)\n file_name = sos.path.join (path, cmd.filename)\n sort = cmd.sort\n read_plan (Y, file_name)\n if cmd.add_appointment :\n sort = len (cmd.argv)\n for a in cmd.argv :\n if app_pat.match (a.strip ()) :\n _add_appointment (Y, app_pat, cmd.holidays_too)\n else :\n print (\"%s doesn't match an appointment\" % a)\n if cmd.Show :\n for a in cmd.argv :\n if app_pat.match (a.strip ()) :\n print (a)\n pat_match = app_pat\n day, month, year, time = _date_time (Y, pat_match)\n for D in _day_generator (pat_match, day, month, year, Y) :\n print (\" \", D)\n else :\n print (\"%s doesn't match an appointment\" % a)\n if sort :\n Y.sort_appointments ()\n write_plan (Y, file_name, cmd.replace)\n# end def _main\n\n_Command = TFL.CAO.Cmd \\\n ( handler = _main\n , opts =\n ( \"add_appointment:B?Add appointments specified by arguments\"\n , \"diary:S=~/diary?Path for calendar file\"\n , \"filename:S=plan?Filename of plan for `year`\"\n , \"holidays_too:B?Add appointments to holidays, too\"\n , \"replace:B?Replace old calendar with new file\"\n , \"Show:B?Show days corresponding to arguments\"\n , \"sort:B?Sort calendar and write it back\"\n , \"year:I=%d?Year for which to process calendar\" % (CAL.Date ().year, )\n )\n , description =\n \"\"\"Manage appointments/activities in a yearly calendar.\n\n The arguments specify appointments. Examples of arguments:\n\n '7.1. +1w*52 14:30-15 =j SW-Jour-Fixe'\n '21.6. +1*8 =V Vacation'\n\n Argument syntax:\n\n
    .. +*\n :-: = \n\n Date, repeat-info, time, and priority are all optional, but at\n least one field of date or time must be specified. Missing date\n fields are replaced by the current day/month.\n\n The delta-unit can be specified as `d` for days (default), `w`\n for weeks, or `m` for months.\n\n The priority is a single letter (upper or lowercase) or number.\n \"\"\"\n )\n\nif __name__ != \"__main__\" :\n CAL._Export (\"*\")\nelse :\n _Command ()\n### __END__ CAL.Plan\n","sub_path":"Functions/venv/lib/python3.6/site-packages/_CAL/Plan.py","file_name":"Plan.py","file_ext":"py","file_size_in_byte":8729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"122289015","text":"import datetime\nimport itertools\nimport textwrap\nfrom collections import deque\n\nimport six\nfrom edgy.event import Event\nfrom medikit.events import subscribe\n\nfrom . import Feature, HIGH_PRIORITY, Script\n\n\n@six.python_2_unicode_compatible\nclass Makefile(object):\n @property\n def targets(self):\n for key in self._target_order:\n yield key, self._target_values[key]\n\n @property\n def environ(self):\n return self._env_values\n\n def __init__(self):\n self._env_order, self._env_values, self._env_assignment_operators = deque(), {}, {}\n self._target_order, self._target_values = deque(), {}\n self.phony = set()\n\n def __delitem__(self, key):\n self._env_order.remove(key)\n del self._env_values[key]\n\n def __getitem__(self, item):\n return self._env_values[item]\n\n def __setitem__(self, key, value):\n self._env_values[key] = value\n if not key in self._env_order:\n self._env_order.append(key)\n\n def __iter__(self):\n for key in self._env_order:\n yield key, self._env_values[key]\n\n def __len__(self):\n return len(self._env_order)\n\n def __str__(self):\n content = [\n '# This file has been auto-generated.',\n '# All changes will be lost, see Projectfile.',\n '#',\n '# Updated at ' + six.text_type(datetime.datetime.now()),\n '',\n ]\n\n if len(self):\n for k, v in self:\n v = textwrap.dedent(str(v)).strip()\n v = v.replace('\\n', ' \\\\\\n' + ' ' * (len(k) + 4))\n content.append('{} {} {}'.format(k, self._env_assignment_operators.get(k, '?='), v))\n content.append('')\n\n if len(self.phony):\n content.append('.PHONY: ' + ' '.join(sorted(self.phony)))\n content.append('')\n\n for target, details in self.targets:\n deps, rule, doc = details\n if doc:\n for line in doc.split('\\n'):\n content.append('# ' + line)\n content.append('{}: {}'.format(target, ' '.join(deps)).strip())\n\n script = textwrap.dedent(str(rule)).strip()\n\n for line in script.split('\\n'):\n content.append('\\t' + line)\n\n content.append('')\n\n return '\\n'.join(content)\n\n def add_target(self, target, rule, deps=None, phony=False, first=False, doc=None):\n if target in self._target_order:\n raise RuntimeError('Duplicate definition for make target «{}».'.format(target))\n\n if isinstance(rule, str):\n rule = Script(rule)\n\n self._target_values[target] = (deps or list(), rule, textwrap.dedent(doc or '').strip(), )\n self._target_order.appendleft(target) if first else self._target_order.append(target)\n\n if phony:\n self.phony.add(target)\n\n def get_target(self, target):\n return self._target_values[target][1]\n\n def set_deps(self, target, deps=None):\n self._target_values[target] = (deps or list(), self._target_values[target][1], self._target_values[target][2], )\n\n def set_assignment_operator(self, key, value):\n assert value in ('?=', '=', '+=', ':=', '::=', '!='), 'Invalid operator'\n self._env_assignment_operators[key] = value\n\n def setleft(self, key, value):\n self._env_values[key] = value\n if not key in self._env_order:\n self._env_order.appendleft(key)\n\n def updateleft(self, *lst):\n for key, value in reversed(lst):\n self.setleft(key, value)\n\n\nclass MakefileEvent(Event):\n def __init__(self, package_name, makefile):\n self.package_name = package_name\n self.makefile = makefile\n super(MakefileEvent, self).__init__()\n\n\nclass InstallScript(Script):\n def __init__(self, script=None):\n super(InstallScript, self).__init__(script)\n\n self.before_install = []\n self.install = self.script\n self.after_install = []\n\n def __iter__(self):\n yield 'if [ -z \"$(QUICK)\" ]; then \\\\'\n for line in map(\n lambda x: ' {} ; \\\\'.format(x), itertools.chain(self.before_install, self.install, self.after_install)\n ):\n yield line\n yield 'fi'\n\n\nclass CleanScript(Script):\n remove = [\n 'build',\n 'dist',\n '*.egg-info',\n ]\n\n def __iter__(self):\n yield 'rm -rf {}'.format(' '.join(self.remove))\n\n\nclass MakeFeature(Feature):\n class Config(Feature.Config):\n def __init__(self):\n pass\n\n def configure(self):\n self.makefile = Makefile()\n\n @subscribe('medikit.on_start', priority=HIGH_PRIORITY)\n def on_start(self, event):\n \"\"\"\n :param ProjectEvent event:\n \"\"\"\n for k in event.variables:\n self.makefile[k.upper()] = event.variables[k]\n\n self.makefile.updateleft(\n ('QUICK', '', ),\n )\n\n self.makefile.add_target(\n 'install', InstallScript(), phony=True, doc='''Installs the local project dependencies.'''\n )\n self.makefile.add_target(\n 'install-dev',\n InstallScript(),\n phony=True,\n doc='''Installs the local project dependencies, including development-only libraries.'''\n )\n self.makefile.add_target('clean', CleanScript(), phony=True, doc='''Cleans up the local mess.''')\n\n self.dispatcher.dispatch(__name__ + '.on_generate', MakefileEvent(event.setup['name'], self.makefile))\n\n self.render_file_inline('Makefile', self.makefile.__str__(), override=True)\n\n\n__feature__ = MakeFeature\n","sub_path":"medikit/feature/make.py","file_name":"make.py","file_ext":"py","file_size_in_byte":5647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"123102654","text":"'''\nBasis Set Exchange\n\nContains utilities for reading, writing, and converting\nbasis set information\n'''\n\n# Just import the basic user API\nfrom .api import (get_basis, lookup_basis_by_role, get_metadata, get_reference_data, get_all_basis_names,\n get_references, get_basis_family, filter_basis_sets, get_families, get_family_notes, get_basis_notes,\n get_schema, get_formats, get_reference_formats, get_roles)\n\n# Handle versioneer\nfrom ._version import get_versions\nversions = get_versions()\n__version__ = versions['version']\n__git_revision__ = versions['full-revisionid']\ndel get_versions, versions\n\n\ndef version():\n '''Obtain the version of the basis set exchange library'''\n return __version__\n","sub_path":"basis_set_exchange/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"1561451","text":"import xml.etree.ElementTree as ET\nimport pandas as pd\n\n\n\ncols = [\"День\", \"Время и недели\", \"Место проведения\", \"Название и преподаватель\", \"Формат занятия\"]\nrows = []\n\n# Parsing the XML file\nxml_text = ET.parse('docs/xml_schedule.xml')\nroot = xml_text.getroot()\nfor schedule in root:\n for day in schedule.findall(\"day\"):\n for lessons in day.findall(\"lessons\"):\n for lesson in lessons.findall(\"lesson\"):\n if (lesson):\n short_day = lesson.find(\"short-name-of-day\").text\n time = lesson.find(\"time-and-weeks\").text\n room = lesson.find(\"room\").text\n name = lesson.find(\"name-and-teacher\").text\n format = lesson.find(\"lesson-format\").text\n\n rows.append({\"День\": short_day,\n \"Время и недели\": time,\n \"Место проведения\": room,\n \"Название и преподаватель\": name,\n \"Формат занятия\": format})\n\ndf = pd.DataFrame(rows, columns=cols)\n\n# Writing dataframe to csv\ndf.to_csv('Additional_task4/csv_schedule.csv')","sub_path":"Additional_task4/Parser_xml_to_csv.py","file_name":"Parser_xml_to_csv.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"479196980","text":"# To Run: python manage.py shell\n# >>> exec(open('_import/import_projects.py').read())\n\nimport csv\nfrom datetime import datetime\n\nfrom django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned\n\nfrom summit.apps.projects.models import Project, Location\nfrom summit.libs.auth.models import Organization, UserProfile, FederalAgency, Partner, CESUnit\n\nwith open('_import/New_pull.csv') as csv_file:\n # Global vars\n DISCIPLINES = ['None', 'Natural', 'Cultural', 'Social', 'Interdisciplinary']\n SRC_OF_FUNDING = ['None', 'Park Base', 'Region Base', 'NR Project Fund Source', 'I&M Program', 'Other Service-wide Project Source', '80% REA Fee', '20% REA Fee', 'Other NPS Appropriated Source', 'OTHER-non-NPS']\n\n reader = list(csv.reader(csv_file))\n\n headers = reader[0]\n\n f_federal_agency = 0\n f_fiscal_year = 1\n f_p_num = 2\n f_legacy_award_number = 3\n\n f_partner = 4\n f_location = 5\n f_project_title = 6\n\n # project_manager\n f_project_manager = 65\n f_project_manager_last = 23\n f_project_manager_first = 24\n\n # pp_i\n f_pp_i = 10\n f_pp_i_last = 14\n f_pp_i_first = 15\n\n f_tent_start_date = 11\n f_tent_end_date = 12\n\n f_discipline = 15\n\n f_legacy_match_amount = 26\n\n # budget\n f_budget = 8\n f_budget_backup1 = 7\n f_budget_backup2 = 9\n\n f_legacy_ca_account_number = 28\n f_legacy_account_number = 29\n f_legacy_area_org = 30\n\n f_legacy_pwe = 34\n f_description = 35\n f_src_of_funding = 36\n f_legacy_project_products = 37\n f_legacy_received_report_date = 38\n f_legacy_sent_to_tic = 39\n f_notes = 40\n f_final_report = 41\n\n f_type = 60\n f_youth_vets = 61\n\n f_sensitive = 63\n\n f_status_closed = 64\n\n DEBUG = True\n\n for row in reader[1:]:\n # federal_agency\n federal_agency = row[f_federal_agency].strip()\n\n if len(federal_agency) > 0:\n try:\n federal_agency = Organization.objects.get(name=federal_agency, type=\"Federal Agency\")\n if DEBUG: print(\"get:\", federal_agency)\n except ObjectDoesNotExist:\n federal_agency = Organization(name=federal_agency, type=\"Federal Agency\")\n federal_agency.save()\n if DEBUG: print(\"new:\", federal_agency)\n else:\n federal_agency = None\n\n # fiscal_year\n fiscal_year = row[f_fiscal_year].strip()\n\n try:\n fiscal_year = int(fiscal_year)\n except ValueError:\n fiscal_year = None\n if DEBUG: print(fiscal_year)\n\n # p_num\n p_num = row[f_p_num].strip()\n if DEBUG: print(p_num)\n\n # legacy_award_number\n legacy_award_number = row[f_legacy_award_number].strip()\n\n # partner\n partner = row[f_partner].strip()\n\n if len(partner) > 0:\n try:\n partner = Partner.objects.get(name=partner)\n if DEBUG: print(\"get:\", partner)\n except ObjectDoesNotExist:\n partner = Partner(name=partner)\n partner.save()\n if DEBUG: print(\"new:\", partner)\n else:\n partner = None\n\n # location\n location = str(row[f_location]).strip()\n\n if len(location) > 0:\n print(location)\n try:\n location = Location.objects.get(abbrv=location)\n if DEBUG: print(\"get:\", location)\n except ObjectDoesNotExist:\n try:\n location = Location.objects.get(name=location)\n if DEBUG: print(\"get:\", location)\n except ObjectDoesNotExist:\n location = Location(name=location)\n location.save()\n if DEBUG: print(\"new:\", location)\n except MultipleObjectsReturned:\n location = Location.objects.filter(abbrv =location)[0]\n if DEBUG: print(\"get:\", location)\n\n\n else:\n location = None\n\n # project_title\n project_title = row[f_project_title].strip()\n\n # project_manager\n project_manager = row[f_project_manager].strip()\n if len(project_manager) > 0:\n project_manager = project_manager.split(' ')\n project_manager_first = project_manager[0]\n project_manager_last = ' '.join(project_manager[1:])\n else:\n project_manager_first = row[f_project_manager_first].strip()\n project_manager_last = row[f_project_manager_last].strip()\n\n if len(project_manager_first) > 0 and len(project_manager_last) > 0:\n # Grab Profile (get or new)\n try:\n project_manager = UserProfile.objects.get(first_name=project_manager_first, last_name=project_manager_last)\n if DEBUG: print(\"get:\", project_manager)\n except ObjectDoesNotExist:\n project_manager = UserProfile(first_name=project_manager_first, last_name=project_manager_last, assigned_group=federal_agency)\n project_manager.save()\n if DEBUG: print(\"new:\", project_manager)\n else:\n project_manager = None\n\n # pp_i = principle investigator\n pp_i = row[f_pp_i]\n if len(pp_i) > 0:\n pp_i = pp_i.split(' ')\n pp_i_first = pp_i[0]\n pp_i_last = ' '.join(pp_i[1:])\n else:\n pp_i_first = row[f_pp_i_first]\n pp_i_last = row[f_pp_i_last]\n\n if len(pp_i_first) > 0 and len(pp_i_last) > 0:\n # Grab Profile (get or new)\n try:\n pp_i = UserProfile.objects.get(first_name=pp_i_first,\n last_name=pp_i_last)\n if DEBUG: print(\"get:\", pp_i)\n except ObjectDoesNotExist:\n pp_i = UserProfile(first_name=pp_i_first, last_name=pp_i_last, assigned_group=partner)\n pp_i.save()\n if DEBUG: print(\"new:\", pp_i)\n else:\n pp_i = None\n\n # tent_start_date\n tent_start_date = row[f_tent_start_date].strip()\n\n if len(tent_start_date) > 0:\n # Get datetime format\n tent_start_date = datetime.strptime(tent_start_date, '%d-%b-%y')\n if DEBUG: print(tent_start_date)\n else:\n tent_start_date = None\n\n # tent_end_date\n tent_end_date = row[f_tent_end_date].strip()\n\n if len(tent_end_date) > 0:\n # Get datetime format\n tent_end_date = datetime.strptime(tent_end_date, '%d-%b-%y')\n if DEBUG: print(tent_end_date)\n else:\n tent_end_date = None\n\n # discipline\n discipline = row[f_discipline].strip().capitalize()\n\n if len(discipline) > 0 and discipline in DISCIPLINES:\n if DEBUG: print(discipline)\n discipline = discipline.upper()\n\n # legacy_match_amount\n legacy_match_amount = row[f_legacy_match_amount].strip()\n\n # budget\n budget = row[f_budget].strip().replace('$', '').replace(',', '')\n budget_backup1 = row[f_budget_backup1].strip().replace('$', '').replace(',', '')\n budget_backup2 = row[f_budget_backup2].strip().replace('$', '').replace(',', '')\n\n try:\n budget = float(budget)\n except ValueError:\n budget = None\n\n try:\n budget_backup1 = float(budget_backup1)\n except ValueError:\n budget_backup1 = None\n\n try:\n budget_backup2 = float(budget_backup2)\n except ValueError:\n budget_backup2 = None\n\n if DEBUG: print(budget, budget_backup1, budget_backup2)\n\n if budget is None and budget_backup1 is not None:\n budget = budget_backup1\n elif budget is None and budget_backup2 is not None:\n budget = budget_backup2\n\n if DEBUG: print(\"budget:\", budget)\n\n # legacy_ca_account_number\n legacy_ca_account_number = row[f_legacy_ca_account_number].strip()\n\n # legacy_account_number\n legacy_account_number = row[f_legacy_account_number].strip()\n\n # legacy_area_org\n legacy_area_org = row[f_legacy_area_org].strip()\n\n # legacy_pwe\n legacy_pwe = row[f_legacy_pwe].strip()\n\n # description\n description = row[f_description].strip()\n\n # src_of_funding\n src_of_funding = row[f_src_of_funding].strip()\n\n if len(src_of_funding) > 0 and src_of_funding in SRC_OF_FUNDING:\n if DEBUG: print(src_of_funding)\n\n # legacy_project_products\n legacy_project_products = row[f_legacy_project_products].strip()\n\n # legacy_received_report_date\n legacy_received_report_date = row[f_legacy_received_report_date].strip()\n\n # legacy_sent_to_tic\n legacy_sent_to_tic = row[f_legacy_sent_to_tic].strip()\n\n # notes\n notes = row[f_notes].strip()\n\n # final_report\n final_report = row[f_final_report].strip()\n\n try:\n final_report = int(final_report)\n if final_report > 0:\n final_report = True\n else:\n final_report = False\n except ValueError:\n final_report = False\n\n # type\n type = row[f_type].strip()\n\n # youth_vets\n youth_vets = row[f_youth_vets].strip()\n\n try:\n youth_vets = int(youth_vets)\n if youth_vets > 0:\n youth_vets = True\n else:\n youth_vets = False\n except ValueError:\n youth_vets = False\n\n # sensitive\n sensitive = row[f_sensitive].strip()\n\n try:\n sensitive = int(sensitive)\n if sensitive > 0:\n sensitive = True\n else:\n sensitive = False\n except ValueError:\n sensitive = True\n\n # status_closed\n status_closed = row[f_status_closed].strip()\n\n try:\n status_closed = int(status_closed)\n if status_closed > 0:\n status_closed = True\n else:\n status_closed = False\n except ValueError:\n status_closed = False\n\n if status_closed:\n status = \"CLOSED\"\n else:\n status = \"LEGACY\"\n\n # Setup ces_unit\n cesu_unit = CESUnit.objects.get(pk=1)\n if DEBUG: print(cesu_unit)\n\n project = Project(\n federal_agency=federal_agency,\n fiscal_year=fiscal_year,\n p_num=p_num,\n legacy_award_number=legacy_award_number,\n partner=partner,\n location=location,\n project_title=project_title,\n project_manager=project_manager,\n pp_i=pp_i,\n tent_start_date=tent_start_date,\n tent_end_date=tent_end_date,\n discipline=discipline,\n legacy_match_amount=legacy_match_amount,\n budget=budget,\n legacy_ca_account_number=legacy_ca_account_number,\n legacy_account_number=legacy_account_number,\n legacy_area_org=legacy_area_org,\n legacy_pwe=legacy_pwe,\n description=description,\n src_of_funding=src_of_funding,\n legacy_project_products=legacy_project_products,\n legacy_received_report_date=legacy_received_report_date,\n legacy_sent_to_tic=legacy_sent_to_tic,\n notes=notes,\n final_report=final_report,\n type=type,\n youth_vets=youth_vets,\n sensitive=sensitive,\n status=status,\n cesu_unit=cesu_unit\n )\n\n project.save()\n","sub_path":"_import/old_imports/project_import.py","file_name":"project_import.py","file_ext":"py","file_size_in_byte":11697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"303539912","text":"from pkg_resources import require\nrequire(\"gridfield>0.2\")\nfrom gridfield import *\n\nimport gridfield.core as gf\nfrom gridfield.algebra import Apply, Restrict, Wrap\n\n# Usually we will read gridfields from various \n# file formats. Here, we construct one from scratch\n# to illustrate the low-level interface\n\n# A Grid is toplogy only; no data\n# Construct a new grid named \"points\" \n# ZeroGrid is syntactic sugar for a zero dimensional grid\n# A 0-d grid is a grid consisting of points only\ng = gf.ZeroGrid(\"points\", 10)\n\n# construct an array of X-values\nx = gf.Array(\"x\", gf.INT, 10)\nx.copyIntData(range(10,20),10)\n\n# construct an array of Y-values\ny = gf.Array(\"y\", gf.FLOAT, 10)\ny.copyIntData(range(20,30),10)\n\n# GridField = Topology + Data\n# = Grid + Arrays\n\n# Construct the gridfield\nG = gf.GridField(g)\n\n# Attach the data\nG.Bind(0, x)\nG.Bind(0, y)\n\n# Now we can use some operators to manipulate the data\n# Operator expressions are chained together\n# nothign actually happens until the expression is evaluated\n\n# Normally we construct a gridfield implicitly\n# with the \"Scan\" operator.\n# Since we constrcuted ours from scratch,\n# so we lift the raw gridfield into an operator\nG = Wrap(G)\n\n# calculate a new attribute\naG = Apply(\"root=sqrt(x*y)\", 0, G)\nH = aG.getResult()\nH.show()\n\n# restrict using the data at rank 0\nrG = Restrict(\"x<15\", 0, aG)\n\n# execute the recipe\nResult = rG.getResult()\n\n# Get the \"x\" attribute at rank 0\nax = Result.GetAttribute(0, \"root\")\n\n# print the result\nax.show()\n","sub_path":"pygridfields/examples/helloworld.py","file_name":"helloworld.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"24372157","text":"#import os\n#os.chdir(\"/content\")\n#os.chdir(\"MTRepo/repo/\")\n\nfrom utility.checknotebook import in_ipynb\nif in_ipynb():\n os.chdir(\"..\")\n #! git pull\n os.chdir(\"repo\")\n\nload_from_file = False\nstart_epoch = 0\n#### prepare model\nimport models.DirCNN_h1 as mod\nif in_ipynb():\n import importlib\n importlib.reload(mod)\n\nimport torch\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nmodel = mod.Net().to(device)\nmodel_info = model.get_info()\noptimizer, scheduler = model.get_optimizer()\nloss = torch.nn.NLLLoss()\n\n#### load model\nimport model_loader\nif in_ipynb(): importlib.reload(model_loader)\nif load_from_file:\n model, optimizer, training_history, param_history, start_epoch, path = model_loader.load_model(model_info,model, optimizer)\nelse:\n training_history, param_history, path = model_loader.else_load(model_info, model)\n \n\n#### load data\nimport data_loader\nif in_ipynb(): importlib.reload(data_loader)\ntrain_loader, val_loader = data_loader.data_from_data_info(model_info[\"data\"])\n\n#### train\nimport ignite_train\nif in_ipynb(): importlib.reload(ignite_train)\n\nignite_train.run(model, \n optimizer,\n scheduler,\n loss,\n device,\n train_loader,\n val_loader,\n training_history,\n param_history,\n model_info,\n start_epoch,\n path)\n","sub_path":"repo/master_trainer.py","file_name":"master_trainer.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"338634126","text":"import pandas as pd\r\nfrom sklearn.cross_validation import train_test_split\r\nfrom sklearn.linear_model import LogisticRegression, LinearRegression\r\nfrom sklearn import metrics\r\nfrom sklearn.pipeline import Pipeline, FeatureUnion\r\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\r\nfrom sklearn import svm\r\nfrom nltk.tokenize import TweetTokenizer\r\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score, auc, roc_curve\r\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score, auc, roc_curve\r\nimport numpy as np\r\nimport string\r\nfrom nltk.tokenize import sent_tokenize, word_tokenize\r\nimport sys\r\n\r\ndef dummy(x):\r\n return x\r\n\r\ndef combine_bleached(x):\r\n punctclist, shapelist, vowelslist, lengthlist = punctC(x).split(), shape(x).split(), vowels(x).split(), length(x).split()\r\n mylist = []\r\n for punctc1, shape1, length1, vowel1 in zip(punctclist, shapelist, lengthlist, vowelslist):\r\n mylist.append(punctc1 + \" \" + shape1 + \" \" + length1 + \" \" + vowel1)\r\n x = \" \".join(mylist)\r\n return x\r\n\r\n\r\ndef punctC(x):\r\n tknzr = TweetTokenizer()\r\n punctclist = []\r\n xlist = tknzr.tokenize(x)\r\n for word in xlist:\r\n previous_alnum = False\r\n punctc = \"\"\r\n for char in word:\r\n if char.isalnum():\r\n if not previous_alnum:\r\n punctc += 'W'\r\n previous_alnum = True\r\n else:\r\n previous_alnum = False\r\n punctc += char\r\n punctclist.append(punctc)\r\n x = \" \".join(punctclist)\r\n return x\r\n\r\n\r\ndef shape(x):\r\n tknzr = TweetTokenizer()\r\n shapelist = []\r\n xlist = tknzr.tokenize(x)\r\n for word in xlist:\r\n shape_word = \"\"\r\n for char in word:\r\n if char.islower():\r\n shape_word += 'L'\r\n elif char.isupper():\r\n shape_word += 'U'\r\n elif char.isupper():\r\n shape_word += 'D'\r\n else:\r\n shape_word += 'O'\r\n shapelist.append(shape_word)\r\n x = \" \".join(shapelist)\r\n return x\r\n\r\ndef vowels(x):\r\n tknzr = TweetTokenizer()\r\n vowels = []\r\n xlist = tknzr.tokenize(x)\r\n for word in xlist:\r\n bleached_word = \"\"\r\n for char in word:\r\n if char.lower() in ['a', 'e', 'o', 'u', 'i']:\r\n bleached_word += \"V\"\r\n elif char.lower() in ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']:\r\n bleached_word += \"C\"\r\n elif char in string.punctuation:\r\n bleached_word += \"P\"\r\n else:\r\n bleached_word += \"O\"\r\n vowels.append(bleached_word)\r\n x = \" \".join(vowels)\r\n return x\r\n\r\ndef length(x):\r\n tknzr = TweetTokenizer()\r\n xlist = tknzr.tokenize(x)\r\n length = []\r\n for word in xlist:\r\n single_length = str(len(word))\r\n if len(single_length) == 1:\r\n single_length = '0' + single_length\r\n else:\r\n single_length = single_length\r\n length.append(single_length)\r\n x = \" \".join(length)\r\n return x\r\n\r\ndef tokenizer(text):\r\n textlist = []\r\n sentences = sent_tokenize(text)\r\n for sentence in sentences:\r\n words = word_tokenize(sentence)\r\n for word in words:\r\n textlist.append(word)\r\n text = \" \".join(textlist)\r\n return text\r\n\r\ndef print_n_most_informative_features(coefs, features, n):\r\n # Prints the n most informative features\r\n most_informative_feature_list = [(coefs[nr],feature) for nr, feature in enumerate(features)]\r\n sorted_most_informative_feature_list = sorted(most_informative_feature_list, key=lambda tup: abs(tup[0]), reverse=True)\r\n print(\"\\nMOST INFORMATIVE FEATURES\\n#\\tvalue\\tfeature\")\r\n for nr, most_informative_feature in enumerate(sorted_most_informative_feature_list[:n]):\r\n print(str(nr+1) + \".\",\"\\t%.3f\\t%s\" % (most_informative_feature[0], most_informative_feature[1]))\r\n\r\n\r\ndef concatenate_features(data_df):\r\n data_df[\"features\"] = data_df[\"Text1\"].map(str) + \" ---------- \"+ data_df[\"Text2\"].map(str)\r\n data_df[\"label\"] = data_df[\"Value\"]\r\n return data_df\r\n\r\ndef main():\r\n trainfile = sys.argv[1]\r\n testfile = sys.argv[2]\r\n print(trainfile)\r\n\r\n featurelist = ['Text1', 'Text2', 'Value']\r\n\r\n train_df = pd.read_excel(trainfile, header=0)\r\n train_df = train_df.fillna('-')\r\n print(train_df[featurelist])\r\n train_df = concatenate_features(train_df)\r\n Xtrain = train_df['features'].tolist()\r\n Ytrain = train_df['label'].tolist()\r\n\r\n\r\n test_df = pd.read_excel(testfile, header=0)\r\n if 'twin' in testfile.lower():\r\n Yrelationlabel = test_df['Relation'].tolist()\r\n test_df = test_df.fillna('-')\r\n print(test_df[featurelist])\r\n test_df = concatenate_features(test_df)\r\n Xtest = test_df['features'].tolist()\r\n Ytest = test_df['label'].tolist()\r\n\r\n\r\n\r\n punctC_vec = TfidfVectorizer( preprocessor = punctC,\r\n analyzer = 'char',\r\n ngram_range = (1,5))\r\n\r\n shape_vec = TfidfVectorizer( preprocessor = shape,\r\n analyzer = 'char',\r\n ngram_range = (5,10))\r\n\r\n\r\n vowels_vec = TfidfVectorizer( preprocessor = vowels,\r\n analyzer = 'char',\r\n ngram_range = (10,15))\r\n\r\n length_vec = TfidfVectorizer( preprocessor = length,\r\n analyzer = 'char',\r\n ngram_range = (10,15))\r\n\r\n combined_bleach_vec = TfidfVectorizer(preprocessor = combine_bleached,\r\n analyzer = 'word',\r\n ngram_range = (1,3))\r\n\r\n\r\n\r\n vec = FeatureUnion([(\"punctC_vec\", punctC_vec), (\"shape_vec\", shape_vec), (\"vowels_vec\", vowels_vec), (\"length_vec\", length_vec), (\"combined_bleach_vec\", combined_bleach_vec)])\r\n\r\n\r\n\r\n\r\n classifier = Pipeline( [('vec', vec),\r\n ('cls', svm.LinearSVR(C=0.5))] )\r\n\r\n classifier.fit(Xtrain, Ytrain)\r\n\r\n\r\n try:\r\n coefs = classifier.named_steps['cls'].coef_\r\n features = classifier.named_steps['vec'].get_feature_names()\r\n print_n_most_informative_features(coefs, features, 20)\r\n print()\r\n except:\r\n pass\r\n\r\n Yguess = classifier.predict(Xtest).tolist()\r\n print(Yguess)\r\n\r\n if 'reddit' in testfile.lower() or 'pan' in testfile.lower():\r\n #FOR TESTING ON PAN DATA\r\n Ycomparelist = []\r\n for pred in Yguess:\r\n if pred < 0:\r\n Ycomparelist.append(-1)\r\n else:\r\n Ycomparelist.append(1)\r\n\r\n print(confusion_matrix(Ytest, Ycomparelist))\r\n print(classification_report(Ytest, Ycomparelist))\r\n print(accuracy_score(Ytest,Ycomparelist))\r\n elif 'twin' in testfile.lower():\r\n total_random = 0\r\n count_random = 0\r\n total_sibling = 0\r\n count_sibling = 0\r\n total_itwin = 0\r\n count_itwin = 0\r\n total_utwin = 0\r\n count_utwin = 0\r\n for relation, guess in zip(Yrelationlabel, Yguess):\r\n if relation == 'R':\r\n r = 'RANDOM:'\r\n total_random += guess\r\n count_random += 1\r\n elif relation == 'S':\r\n r = 'SIBLING:'\r\n total_sibling += guess\r\n count_sibling += 1\r\n elif relation == 'I':\r\n r = 'IDENTICAL TWIN'\r\n total_itwin += guess\r\n count_itwin += 1\r\n elif relation == 'U':\r\n r = 'NONIDENTICAL TWIN'\r\n total_utwin += guess\r\n count_utwin += 1\r\n print(r, guess)\r\n avg_random = total_random / count_random\r\n avg_sibling = total_sibling / count_sibling\r\n avg_itwin = total_itwin / count_itwin\r\n avg_utwin = total_utwin / count_utwin\r\n print(\"\\n\\n\\nAVERAGE IDENTICAL TWIN:\", avg_itwin)\r\n print(\"AVERAGE NONIDENTICAL TWIN:\", avg_utwin)\r\n print(\"AVERAGE SIBLING:\", avg_sibling)\r\n print(\"AVERAGE RANDOM:\", avg_random)\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"Models/Other Models/bleached_svr.py","file_name":"bleached_svr.py","file_ext":"py","file_size_in_byte":8355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"322793231","text":"import argparse\nimport os\nimport timeit\nimport datetime\nimport pickle\nfrom contrastive_losses import *\nimport torch.backends.cudnn as cudnn\nfrom torch.utils import data, model_zoo\nimport torch.nn as nn\nfrom utils.loss import CrossEntropy2d\nfrom utils.loss import CrossEntropyLoss2dPixelWiseWeighted\nimport math\nfrom utils import transformmasks\nfrom utils import transformsgpu\n\nfrom data import get_loader, get_data_path\nfrom data.augmentations import *\n\nimport json\nfrom evaluateSSL import evaluate\nfrom utils.class_balancing import ClassBalancing\nfrom utils.feature_memory import *\n\nstart = timeit.default_timer()\nstart_writeable = datetime.datetime.now().strftime('%m-%d_%H-%M')\n\n\nclass Learning_Rate_Object(object):\n def __init__(self, learning_rate):\n self.learning_rate = learning_rate\n\n\ndef entropy_loss(v, mask):\n \"\"\"\n Entropy loss for probabilistic prediction vectors\n input: batch_size x channels x h x w\n output: batch_size x 1 x h x w\n \"\"\"\n assert v.dim() == 4\n n, c, h, w = v.size()\n\n loss_image = torch.mul(v, torch.log2(v + 1e-30))\n loss_image = torch.sum(loss_image, dim=1)\n loss_image = mask.float() * loss_image\n\n percentage_valid_points = torch.mean(mask.float())\n\n return -torch.sum(loss_image) / (n * h * w * np.log2(c) * percentage_valid_points)\n\ndef update_BN_weak_unlabeled_data(model, norm_func, batch_size, loader, iters=1000):\n iterator = iter(loader)\n for _ in range(iters):\n model.train()\n ''' UNLABELED SAMPLES '''\n try:\n batch = next(iterator)\n if batch[0].shape[0] != batch_size:\n batch = next(iterator)\n except:\n iterator = iter(loader)\n batch = next(iterator)\n\n # Unlabeled\n unlabeled_images, _, _, _, _ = batch\n unlabeled_images = unlabeled_images.cuda()\n\n # Create pseudolabels\n _, _ = model(norm_func(unlabeled_images, dataset), return_features=True)\n return model\n\ndef get_arguments():\n \"\"\"Parse all the arguments provided from the CLI.\n\n Returns:\n A list of parsed arguments.\n \"\"\"\n parser = argparse.ArgumentParser(description=\"DeepLab-ResNet Network\")\n parser.add_argument(\"-c\", \"--config\", type=str, default='config.json',\n help='Path to the config file (default: config.json)')\n parser.add_argument(\"-r\", \"--resume\", type=str, default=None,\n help='Path to the .pth file to resume from (default: None)')\n return parser.parse_args()\n\n\ndef lr_poly(base_lr, iter, max_iter, power):\n \"\"\"\n\n Args:\n base_lr: initial learning rate\n iter: current iteration\n max_iter: maximum number of iterations\n power: power value for polynomial decay\n\n Returns: the updated learning rate with polynomial decay\n\n \"\"\"\n\n return base_lr * ((1 - float(iter) / float(max_iter)) ** (power))\n\n\ndef adjust_learning_rate(optimizer, i_iter):\n \"\"\"\n\n Args:\n optimizer: pytorch optimizer\n i_iter: current iteration\n\n Returns: sets learning rate with poliynomial decay\n\n \"\"\"\n lr = lr_poly(learning_rate, i_iter, num_iterations, lr_power)\n optimizer.param_groups[0]['lr'] = lr\n if len(optimizer.param_groups) > 1:\n optimizer.param_groups[1]['lr'] = lr\n\n\ndef sigmoid_ramp_up(iter, max_iter):\n \"\"\"\n\n Args:\n iter: current iteration\n max_iter: maximum number of iterations to perform the rampup\n\n Returns:\n returns 1 if iter >= max_iter\n returns [0,1] incrementally from 0 to max_iters if iter < max_iter\n\n \"\"\"\n if iter >= max_iter:\n return 1\n else:\n return np.exp(- 5 * (1 - float(iter) / float(max_iter)) ** 2)\n\n\ndef augmentationTransform(parameters, data=None, target=None, probs=None, jitter_vale=0.4, min_sigma=0.2, max_sigma=2.,\n ignore_label=255):\n \"\"\"\n\n Args:\n parameters: dictionary with the augmentation configuration\n data: BxCxWxH input data to augment\n target: BxWxH labels to augment\n probs: BxWxH probability map to augment\n jitter_vale: jitter augmentation value\n min_sigma: min sigma value for blur\n max_sigma: max sigma value for blur\n ignore_label: value for ignore class\n\n Returns:\n augmented data, target, probs\n \"\"\"\n assert ((data is not None) or (target is not None))\n if \"Mix\" in parameters:\n data, target, probs = transformsgpu.mix(mask=parameters[\"Mix\"], data=data, target=target, probs=probs)\n\n if \"RandomScaleCrop\" in parameters:\n data, target, probs = transformsgpu.random_scale_crop(scale=parameters[\"RandomScaleCrop\"], data=data,\n target=target, probs=probs, ignore_label=ignore_label)\n if \"flip\" in parameters:\n data, target, probs = transformsgpu.flip(flip=parameters[\"flip\"], data=data, target=target, probs=probs)\n\n if \"ColorJitter\" in parameters:\n data, target, probs = transformsgpu.colorJitter(colorJitter=parameters[\"ColorJitter\"], data=data, target=target,\n probs=probs, s=jitter_vale)\n if \"GaussianBlur\" in parameters:\n data, target, probs = transformsgpu.gaussian_blur(blur=parameters[\"GaussianBlur\"], data=data, target=target,\n probs=probs, min_sigma=min_sigma, max_sigma=max_sigma)\n\n if \"Grayscale\" in parameters:\n data, target, probs = transformsgpu.grayscale(grayscale=parameters[\"Grayscale\"], data=data, target=target,\n probs=probs)\n if \"Solarize\" in parameters:\n data, target, probs = transformsgpu.solarize(solarize=parameters[\"Solarize\"], data=data, target=target,\n probs=probs)\n\n return data, target, probs\n\n\ndef _save_checkpoint(iteration, model, optimizer, config, save_best=False, overwrite=True):\n \"\"\"\n Saves the current checkpoint\n\n Args:\n iteration: current iteration [int]\n model: segmentation model\n optimizer: pytorch optimizer\n config: configuration\n save_best: Boolean: whether to sae only if best metric\n overwrite: whether to overwrite if ther is an existing checkpoint\n\n Returns:\n\n \"\"\"\n checkpoint = {\n 'iteration': iteration,\n 'optimizer': optimizer.state_dict(),\n 'config': config,\n }\n checkpoint['model'] = model.state_dict()\n\n if save_best:\n filename = os.path.join(checkpoint_dir, f'best_model.pth')\n torch.save(checkpoint, filename)\n print(f'\\nSaving a checkpoint: {filename} ...')\n print(\"Saving current best model: best_model.pth\")\n else:\n filename = os.path.join(checkpoint_dir, f'checkpoint-iter{iteration}.pth')\n print(f'\\nSaving a checkpoint: {filename} ...')\n torch.save(checkpoint, filename)\n if overwrite:\n try:\n os.remove(os.path.join(checkpoint_dir, f'checkpoint-iter{iteration - save_checkpoint_every}.pth'))\n except:\n pass\n\n\ndef create_ema_model(model, net_class):\n \"\"\"\n\n Args:\n model: segmentation model to copy parameters from\n net_class: segmentation model class\n\n Returns: Segmentation model from [net_class] with same parameters than [model]\n\n \"\"\"\n ema_model = net_class(num_classes=num_classes)\n\n for param in ema_model.parameters():\n param.detach_()\n mp = list(model.parameters())\n mcp = list(ema_model.parameters())\n n = len(mp)\n for i in range(0, n):\n mcp[i].data[:] = mp[i].data[:].clone()\n\n return ema_model\n\n\ndef update_ema_variables(ema_model, model, alpha_teacher, iteration):\n \"\"\"\n\n Args:\n ema_model: model to update\n model: model from which to update parameters\n alpha_teacher: value for weighting the ema_model\n iteration: current iteration\n\n Returns: ema_model, with parameters updated follwoing the exponential moving average of [model]\n\n \"\"\"\n # Use the \"true\" average until the exponential average is more correct\n alpha_teacher = min(1 - 1 / (iteration + 1), alpha_teacher)\n for ema_param, param in zip(ema_model.parameters(), model.parameters()):\n ema_param.data[:] = alpha_teacher * ema_param[:].data[:] + (1 - alpha_teacher) * param[:].data[:]\n return ema_model\n\n\ndef augment_samples(images, labels, probs, do_classmix, batch_size, ignore_label, weak=False):\n \"\"\"\n Perform data augmentation\n\n Args:\n images: BxCxWxH images to augment\n labels: BxWxH labels to augment\n probs: BxWxH probability maps to augment\n do_classmix: whether to apply classmix augmentation\n batch_size: batch size\n ignore_label: ignore class value\n weak: whether to perform weak or strong augmentation\n\n Returns:\n augmented data, augmented labels, augmented probs\n\n \"\"\"\n\n if do_classmix:\n # ClassMix: Get mask for image A\n for image_i in range(batch_size): # for each image\n classes = torch.unique(labels[image_i]) # get unique classes in pseudolabel A\n nclasses = classes.shape[0]\n\n # remove ignore class\n if ignore_label in classes and len(classes) > 1 and nclasses > 1:\n classes = classes[classes != ignore_label]\n nclasses = nclasses - 1\n\n if dataset == 'pascal_voc': # if voc dataaset, remove class 0, background\n if 0 in classes and len(classes) > 1 and nclasses > 1:\n classes = classes[classes != 0]\n nclasses = nclasses - 1\n\n # pick half of the classes randomly\n classes = (classes[torch.Tensor(\n np.random.choice(nclasses, int(((nclasses - nclasses % 2) / 2) + 1), replace=False)).long()]).cuda()\n\n # acumulate masks\n if image_i == 0:\n MixMask = transformmasks.generate_class_mask(labels[image_i], classes).unsqueeze(0).cuda()\n else:\n MixMask = torch.cat(\n (MixMask, transformmasks.generate_class_mask(labels[image_i], classes).unsqueeze(0).cuda()))\n\n params = {\"Mix\": MixMask}\n else:\n params = {}\n\n if weak:\n params[\"flip\"] = random.random() < 0.5\n params[\"ColorJitter\"] = random.random() < 0.2\n params[\"GaussianBlur\"] = random.random() < 0.\n params[\"Grayscale\"] = random.random() < 0.0\n params[\"Solarize\"] = random.random() < 0.0\n if random.random() < 0.5:\n scale = random.uniform(0.75, 1.75)\n else:\n scale = 1\n params[\"RandomScaleCrop\"] = scale\n\n # Apply strong augmentations to unlabeled images\n image_aug, labels_aug, probs_aug = augmentationTransform(params,\n data=images, target=labels,\n probs=probs, jitter_vale=0.125,\n min_sigma=0.1, max_sigma=1.5,\n ignore_label=ignore_label)\n else:\n params[\"flip\"] = random.random() < 0.5\n params[\"ColorJitter\"] = random.random() < 0.8\n params[\"GaussianBlur\"] = random.random() < 0.2\n params[\"Grayscale\"] = random.random() < 0.0\n params[\"Solarize\"] = random.random() < 0.0\n if random.random() < 0.80:\n scale = random.uniform(0.75, 1.75)\n else:\n scale = 1\n params[\"RandomScaleCrop\"] = scale\n\n # Apply strong augmentations to unlabeled images\n image_aug, labels_aug, probs_aug = augmentationTransform(params,\n data=images, target=labels,\n probs=probs, jitter_vale=0.25,\n min_sigma=0.1, max_sigma=1.5,\n ignore_label=ignore_label)\n\n return image_aug, labels_aug, probs_aug, params\n\n\ndef main():\n print(config)\n cudnn.enabled = True\n torch.manual_seed(random_seed)\n torch.cuda.manual_seed(random_seed)\n np.random.seed(random_seed)\n random.seed(random_seed)\n torch.backends.cudnn.deterministic = True\n\n if pretraining == 'COCO': # depending the pretraining, normalize with bgr or rgb\n from utils.transformsgpu import normalize_bgr as normalize\n else:\n from utils.transformsgpu import normalize_rgb as normalize\n\n batch_size_unlabeled = int(batch_size / 2) # because of augmentation anchoring, 2 augmentations per sample\n batch_size_labeled = int(batch_size * 1)\n assert batch_size_unlabeled >= 2, \"batch size should be higher than 2\"\n assert batch_size_labeled >= 2, \"batch size should be higher than 2\"\n RAMP_UP_ITERS = 2000 # iterations until contrastive and self-training are taken into account\n\n # DATASETS / LOADERS \n if dataset == 'pascal_voc':\n data_loader = get_loader(dataset)\n data_path = get_data_path(dataset)\n train_dataset = data_loader(data_path, crop_size=input_size, scale=False, mirror=False, pretraining=pretraining)\n\n elif dataset == 'cityscapes':\n data_loader = get_loader('cityscapes')\n data_path = get_data_path('cityscapes')\n if deeplabv2:\n data_aug = Compose([RandomCrop_city(input_size)])\n else: # for deeplabv3 original resolution\n data_aug = Compose([RandomCrop_city_highres(input_size)])\n train_dataset = data_loader(data_path, is_transform=True, augmentations=data_aug, img_size=input_size,\n pretraining=pretraining)\n\n train_dataset_size = len(train_dataset)\n print('dataset size: ', train_dataset_size)\n\n partial_size = labeled_samples\n print('Training on number of samples:', partial_size)\n\n # class weighting taken unlabeled data into acount in an incremental fashion.\n class_weights_curr = ClassBalancing(labeled_iters=int(labeled_samples / batch_size_labeled),\n unlabeled_iters=int(\n (train_dataset_size - labeled_samples) / batch_size_unlabeled),\n n_classes=num_classes)\n # Memory Bank\n feature_memory = FeatureMemory(num_samples=labeled_samples, dataset=dataset, memory_per_class=256, feature_size=256,\n n_classes=num_classes)\n\n # select the partition\n if split_id is not None:\n train_ids = pickle.load(open(split_id, 'rb'))\n print('loading train ids from {}'.format(split_id))\n else:\n train_ids = np.arange(train_dataset_size)\n np.random.shuffle(train_ids)\n\n # Samplers for labeled data\n train_sampler = data.sampler.SubsetRandomSampler(train_ids[:partial_size])\n trainloader = data.DataLoader(train_dataset,\n batch_size=batch_size_labeled, sampler=train_sampler, num_workers=num_workers,\n pin_memory=True)\n trainloader_iter = iter(trainloader)\n\n # Samplers for unlabeled data\n train_remain_sampler = data.sampler.SubsetRandomSampler(train_ids[partial_size:])\n trainloader_remain = data.DataLoader(train_dataset,\n batch_size=batch_size_unlabeled, sampler=train_remain_sampler,\n num_workers=num_workers, pin_memory=True)\n trainloader_remain_iter = iter(trainloader_remain)\n\n # supervised loss\n supervised_loss = CrossEntropy2d(ignore_label=ignore_label).cuda()\n\n ''' Deeplab model '''\n # Define network\n if deeplabv2:\n if pretraining == 'COCO': # coco and imagenet resnet architectures differ a little, just on how to do the stride\n from model.deeplabv2 import Res_Deeplab\n else: # imagenet pretrained (more modern modification)\n from model.deeplabv2_imagenet import Res_Deeplab\n\n # load pretrained parameters\n if pretraining == 'COCO':\n saved_state_dict = model_zoo.load_url(\n 'http://vllab1.ucmerced.edu/~whung/adv-semi-seg/resnet101COCO-41f33a49.pth') # COCO pretraining\n else:\n saved_state_dict = model_zoo.load_url(\n 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth') # iamgenet pretrainning\n\n else:\n from model.deeplabv3 import Res_Deeplab50 as Res_Deeplab\n saved_state_dict = model_zoo.load_url(\n 'https://download.pytorch.org/models/resnet50-19c8e357.pth') # iamgenet pretrainning\n\n # create network\n model = Res_Deeplab(num_classes=num_classes)\n\n # Copy loaded parameters to model\n new_params = model.state_dict().copy()\n for name, param in new_params.items():\n if name in saved_state_dict and param.size() == saved_state_dict[name].size():\n new_params[name].copy_(saved_state_dict[name])\n model.load_state_dict(new_params)\n\n # Optimizer for segmentation network\n learning_rate_object = Learning_Rate_Object(config['training']['learning_rate'])\n\n optimizer = torch.optim.SGD(model.optim_parameters(learning_rate_object),\n lr=learning_rate, momentum=momentum, weight_decay=weight_decay)\n\n ema_model = create_ema_model(model, Res_Deeplab)\n ema_model.train()\n ema_model = ema_model.cuda()\n model.train()\n model = model.cuda()\n cudnn.benchmark = True\n\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n with open(checkpoint_dir + '/config.json', 'w') as handle:\n json.dump(config, handle, indent=4, sort_keys=False)\n pickle.dump(train_ids, open(os.path.join(checkpoint_dir, 'train_split.pkl'), 'wb'))\n\n interp = nn.Upsample(size=(input_size[0], input_size[1]), mode='bilinear', align_corners=True)\n\n epochs_since_start = 0\n start_iteration = 0\n best_mIoU = 0 # best metric while training\n iters_without_improve = 0\n\n # TRAINING\n for i_iter in range(start_iteration, num_iterations):\n model.train() # set mode to training\n optimizer.zero_grad()\n\n loss_l_value = 0.\n adjust_learning_rate(optimizer, i_iter)\n\n labeled_turn = i_iter % 2 == 0\n\n if labeled_turn: # labeled data optimization\n\n ''' LABELED SAMPLES '''\n # Get batch\n try:\n batch = next(trainloader_iter)\n if batch[0].shape[0] != batch_size_labeled:\n batch = next(trainloader_iter)\n except: # finish epoch, rebuild the iterator\n epochs_since_start = epochs_since_start + 1\n # print('Epochs since start: ',epochs_since_start)\n trainloader_iter = iter(trainloader)\n batch = next(trainloader_iter)\n\n images, labels, _, _, _ = batch\n images = images.cuda()\n labels = labels.cuda()\n\n model.train()\n\n if dataset == 'cityscapes':\n class_weights_curr.add_frequencies_labeled(labels.cpu().numpy())\n\n images_aug, labels_aug, _, _ = augment_samples(images, labels, None, random.random() < 0.2,\n batch_size_labeled,\n ignore_label, weak=True)\n\n # labeled data\n labeled_pred, labeled_features = model(normalize(images_aug, dataset), return_features=True)\n labeled_pred = interp(labeled_pred)\n\n # apply class balance for cityspcaes dataset\n class_weights = torch.from_numpy(np.ones((num_classes))).cuda()\n if i_iter > RAMP_UP_ITERS and dataset == 'cityscapes':\n class_weights = torch.from_numpy(\n class_weights_curr.get_weights(num_iterations, only_labeled=False)).cuda()\n\n loss = 0\n\n # SUPERVISED SEGMENTATION\n labeled_loss = supervised_loss(labeled_pred, labels_aug, weight=class_weights.float())\n loss = loss + labeled_loss\n\n # CONTRASTIVE LEARNING\n if i_iter > RAMP_UP_ITERS - 1000:\n # Build Memory Bank 1000 iters before starting to do contrsative\n\n with torch.no_grad():\n # Get feature vectors from labeled images with EMA model\n if use_teacher:\n labeled_pred_ema, labeled_features_ema = ema_model(normalize(images_aug, dataset), return_features=True)\n else:\n model.eval()\n labeled_pred_ema, labeled_features_ema = model(normalize(images_aug, dataset), return_features=True)\n model.train()\n labeled_pred_ema = interp(labeled_pred_ema)\n probability_prediction_ema, label_prediction_ema = torch.max(torch.softmax(labeled_pred_ema, dim=1),\n dim=1) # Get pseudolabels\n\n # Resize labels, predictions and probabilities, to feature map resolution\n labels_down = nn.functional.interpolate(labels_aug.float().unsqueeze(1),\n size=(labeled_features_ema.shape[2], labeled_features_ema.shape[3]),\n mode='nearest').squeeze(1)\n label_prediction_down = nn.functional.interpolate(label_prediction_ema.float().unsqueeze(1), size=(\n labeled_features_ema.shape[2], labeled_features_ema.shape[3]),\n mode='nearest').squeeze(1)\n probability_prediction_down = nn.functional.interpolate(probability_prediction_ema.float().unsqueeze(1),\n size=(labeled_features_ema.shape[2],\n labeled_features_ema.shape[3]),\n mode='nearest').squeeze(1)\n\n # get mask where the labeled predictions are correct and have a confidence higher than 0.95\n mask_prediction_correctly = ((label_prediction_down == labels_down).float() * (\n probability_prediction_down > 0.95).float()).bool()\n\n # Apply the filter mask to the features and its labels\n labeled_features_correct = labeled_features_ema.permute(0, 2, 3, 1)\n labels_down_correct = labels_down[mask_prediction_correctly]\n labeled_features_correct = labeled_features_correct[mask_prediction_correctly, ...]\n\n # get projected features\n with torch.no_grad():\n if use_teacher:\n proj_labeled_features_correct = ema_model.projection_head(labeled_features_correct)\n else:\n model.eval()\n proj_labeled_features_correct = model.projection_head(labeled_features_correct)\n model.train()\n\n # updated memory bank\n feature_memory.add_features_from_sample_learned(ema_model, proj_labeled_features_correct,\n labels_down_correct, batch_size_labeled)\n\n if i_iter > RAMP_UP_ITERS:\n '''\n CONTRASTIVE LEARNING ON LABELED DATA. Force features from labeled samples, to be similar to other features from the same class (which also leads to good predictions\n '''\n # mask features that do not have ignore label in the labels (zero-padding because of data augmentation like resize/crop)\n mask_prediction_correctly = (labels_down != ignore_label)\n\n labeled_features_all = labeled_features.permute(0, 2, 3, 1)\n labels_down_all = labels_down[mask_prediction_correctly]\n labeled_features_all = labeled_features_all[mask_prediction_correctly, ...]\n\n # get predicted features\n proj_labeled_features_all = model.projection_head(labeled_features_all)\n pred_labeled_features_all = model.prediction_head(proj_labeled_features_all)\n\n # Apply contrastive learning loss\n loss_contr_labeled = contrastive_class_to_class_learned_memory(model, pred_labeled_features_all,\n labels_down_all,\n num_classes, feature_memory.memory)\n\n loss = loss + loss_contr_labeled * 0.1\n\n\n else: # unlabeled data optimization\n\n ''' UNLABELED SAMPLES '''\n try:\n batch_remain = next(trainloader_remain_iter)\n if batch_remain[0].shape[0] != batch_size_unlabeled:\n batch_remain = next(trainloader_remain_iter)\n except:\n trainloader_remain_iter = iter(trainloader_remain)\n batch_remain = next(trainloader_remain_iter)\n\n # Unlabeled\n unlabeled_images, _, _, _, _ = batch_remain\n unlabeled_images = unlabeled_images.cuda()\n\n # Create pseudolabels\n with torch.no_grad():\n if use_teacher:\n logits_u_w, features_weak_unlabeled = ema_model(normalize(unlabeled_images, dataset),\n return_features=True)\n else:\n model.eval()\n logits_u_w, features_weak_unlabeled = model(normalize(unlabeled_images, dataset),\n return_features=True)\n logits_u_w = interp(logits_u_w).detach() # prediction unlabeled\n softmax_u_w = torch.softmax(logits_u_w, dim=1)\n max_probs, pseudo_label = torch.max(softmax_u_w, dim=1) # Get pseudolabels\n\n model.train()\n\n if dataset == 'cityscapes':\n class_weights_curr.add_frequencies_unlabeled(pseudo_label.cpu().numpy())\n\n '''\n UNLABELED DATA\n '''\n unlabeled_images_aug1, pseudo_label1, max_probs1, unlabeled_aug1_params = augment_samples(unlabeled_images,\n pseudo_label,\n max_probs,\n i_iter > RAMP_UP_ITERS and random.random() < 0.75,\n batch_size_unlabeled,\n ignore_label)\n\n unlabeled_images_aug2, pseudo_label2, max_probs2, unlabeled_aug2_params = augment_samples(unlabeled_images,\n pseudo_label,\n max_probs,\n i_iter > RAMP_UP_ITERS and random.random() < 0.75,\n batch_size_unlabeled,\n ignore_label)\n # concatenate two augmentations of unlabeled data\n joined_unlabeled = torch.cat((unlabeled_images_aug1, unlabeled_images_aug2), dim=0)\n joined_pseudolabels = torch.cat((pseudo_label1, pseudo_label2), dim=0)\n joined_maxprobs = torch.cat((max_probs1, max_probs2), dim=0)\n\n pred_joined_unlabeled, features_joined_unlabeled = model(normalize(joined_unlabeled, dataset),\n return_features=True)\n pred_joined_unlabeled = interp(pred_joined_unlabeled)\n\n\n # apply clas balance for cityspcaes dataset\n if dataset == 'cityscapes':\n class_weights = torch.from_numpy(\n class_weights_curr.get_weights(num_iterations, only_labeled=False)).cuda()\n else:\n class_weights = torch.from_numpy(np.ones((num_classes))).cuda()\n\n loss = 0\n\n # SELF-SUPERVISED SEGMENTATION\n unlabeled_loss = CrossEntropyLoss2dPixelWiseWeighted(ignore_index=ignore_label,\n weight=class_weights.float()).cuda() #\n\n # Pseudo-label weighting\n pixelWiseWeight = sigmoid_ramp_up(i_iter, RAMP_UP_ITERS) * torch.ones(joined_maxprobs.shape).cuda()\n pixelWiseWeight = pixelWiseWeight * torch.pow(joined_maxprobs.detach(), 6)\n\n # Pseudo-label loss\n loss_ce_unlabeled = unlabeled_loss(pred_joined_unlabeled, joined_pseudolabels, pixelWiseWeight)\n\n loss = loss + loss_ce_unlabeled\n\n # entropy loss\n valid_mask = (joined_pseudolabels != ignore_label).unsqueeze(1)\n loss = loss + entropy_loss(torch.nn.functional.softmax(pred_joined_unlabeled, dim=1), valid_mask) * 0.01\n\n\n if i_iter > RAMP_UP_ITERS:\n\n '''\n CONTRASTIVE LEARNING ON UNLABELED DATA. align unlabeled features to labeled features\n '''\n joined_pseudolabels_down = nn.functional.interpolate(joined_pseudolabels.float().unsqueeze(1),\n size=(features_joined_unlabeled.shape[2],\n features_joined_unlabeled.shape[3]),\n mode='nearest').squeeze(1)\n\n # mask features that do not have ignore label in the labels (zero-padding because of data augmentation like resize/crop)\n mask = (joined_pseudolabels_down != ignore_label)\n\n features_joined_unlabeled = features_joined_unlabeled.permute(0, 2, 3, 1)\n features_joined_unlabeled = features_joined_unlabeled[mask, ...]\n joined_pseudolabels_down = joined_pseudolabels_down[mask]\n\n # get predicted features\n proj_feat_unlabeled = model.projection_head(features_joined_unlabeled)\n pred_feat_unlabeled = model.prediction_head(proj_feat_unlabeled)\n\n # Apply contrastive learning loss\n loss_contr_unlabeled = contrastive_class_to_class_learned_memory(model, pred_feat_unlabeled,\n joined_pseudolabels_down,\n num_classes, feature_memory.memory)\n\n loss = loss + loss_contr_unlabeled * 0.1\n\n\n # common code\n\n loss_l_value += loss.item()\n\n # optimize\n loss.backward()\n optimizer.step()\n\n m = 1 - (1 - 0.995) * (math.cos(math.pi * i_iter / num_iterations) + 1) / 2\n ema_model = update_ema_variables(ema_model=ema_model, model=model, alpha_teacher=m, iteration=i_iter)\n\n\n if i_iter % save_checkpoint_every == 0 and i_iter != 0:\n _save_checkpoint(i_iter, model, optimizer, config)\n\n if i_iter % val_per_iter == 0 and i_iter != 0:\n print('iter = {0:6d}/{1:6d}'.format(i_iter, num_iterations))\n\n model.eval()\n mIoU, eval_loss = evaluate(model, dataset, deeplabv2=deeplabv2, ignore_label=ignore_label,\n save_dir=checkpoint_dir, pretraining=pretraining)\n model.train()\n\n if mIoU > best_mIoU:\n best_mIoU = mIoU\n if save_teacher:\n _save_checkpoint(i_iter, ema_model, optimizer, config, save_best=True)\n else:\n _save_checkpoint(i_iter, model, optimizer, config, save_best=True)\n iters_without_improve = 0\n else:\n iters_without_improve += val_per_iter\n\n '''\n if the performance has not improve in N iterations, try to reload best model to optimize again with a lower LR\n Simulating an iterative training'''\n if iters_without_improve > num_iterations/5.:\n print('Re-loading a previous best model')\n checkpoint = torch.load(os.path.join(checkpoint_dir, f'best_model.pth'))\n model.load_state_dict(checkpoint['model'])\n ema_model = create_ema_model(model, Res_Deeplab)\n ema_model.train()\n ema_model = ema_model.cuda()\n model.train()\n model = model.cuda()\n iters_without_improve = 0 # reset timer\n\n _save_checkpoint(num_iterations, model, optimizer, config)\n\n # FINISH TRAINING, evaluate again\n model.eval()\n mIoU, eval_loss = evaluate(model, dataset, deeplabv2=deeplabv2, ignore_label=ignore_label, save_dir=checkpoint_dir,\n pretraining=pretraining)\n model.train()\n\n if mIoU > best_mIoU and save_best_model:\n best_mIoU = mIoU\n _save_checkpoint(i_iter, model, optimizer, config, save_best=True)\n\n # TRY IMPROVING BEST MODEL WITH EMA MODEL OR UPDATING BN STATS\n\n # Load best model\n checkpoint = torch.load(os.path.join(checkpoint_dir, f'best_model.pth'))\n model.load_state_dict(checkpoint['model'])\n model = model.cuda()\n\n model = update_BN_weak_unlabeled_data(model, normalize, batch_size_unlabeled, trainloader_remain)\n model.eval()\n mIoU, eval_loss = evaluate(model, dataset, deeplabv2=deeplabv2, ignore_label=ignore_label, save_dir=checkpoint_dir,\n pretraining=pretraining)\n model.train()\n if mIoU > best_mIoU and save_best_model:\n best_mIoU = mIoU\n _save_checkpoint(i_iter, model, optimizer, config, save_best=True)\n\n print('BEST MIOU')\n print(max(best_mIoU_improved, best_mIoU))\n\n end = timeit.default_timer()\n print('Total time: ' + str(end - start) + ' seconds')\n\n\nif __name__ == '__main__':\n\n print('---------------------------------Starting---------------------------------')\n\n args = get_arguments()\n\n if args.resume:\n config = torch.load(args.resume)['config']\n else:\n config = json.load(open(args.config))\n\n model = config['model']\n dataset = config['dataset']\n\n if dataset == 'cityscapes':\n num_classes = 19\n if config['training']['data']['split_id_list'] == 0:\n split_id = './splits/city/split_0.pkl'\n elif config['training']['data']['split_id_list'] == 1:\n split_id = './splits/city/split_1.pkl'\n elif config['training']['data']['split_id_list'] == 2:\n split_id = './splits/city/split_2.pkl'\n else:\n split_id = None\n\n elif dataset == 'pascal_voc':\n num_classes = 21\n data_dir = './data/voc_dataset/'\n data_list_path = './data/voc_list/train_aug.txt'\n if config['training']['data']['split_id_list'] == 0:\n split_id = './splits/voc/split_0.pkl'\n elif config['training']['data']['split_id_list'] == 1:\n split_id = './splits/voc/split_1.pkl'\n elif config['training']['data']['split_id_list'] == 2:\n split_id = './splits/voc/split_2.pkl'\n else:\n split_id = None\n\n batch_size = config['training']['batch_size']\n num_iterations = config['training']['num_iterations'] * 2\n\n input_size_string = config['training']['data']['input_size']\n h, w = map(int, input_size_string.split(','))\n input_size = (h, w)\n\n ignore_label = config['ignore_label'] # 255 for PASCAL-VOC / 250 for Cityscapes\n\n learning_rate = config['training']['learning_rate']\n\n optimizer_type = config['training']['optimizer']\n lr_power = config['training']['lr_schedule_power']\n weight_decay = config['training']['weight_decay']\n momentum = config['training']['momentum']\n num_workers = config['training']['num_workers']\n random_seed = config['seed']\n pretraining = config['training']['pretraining']\n labeled_samples = config['training']['data']['labeled_samples']\n\n save_checkpoint_every = config['utils']['save_checkpoint_every']\n if args.resume:\n checkpoint_dir = os.path.join(*args.resume.split('/')[:-1]) + '_resume-'\n else:\n checkpoint_dir = os.path.join(config['utils']['checkpoint_dir'])\n log_dir = checkpoint_dir\n\n val_per_iter = config['utils']['val_per_iter']\n\n save_best_model = True\n\n deeplabv2 = \"2\" in config['version']\n use_teacher = True # by default\n if \"use_teacher_train\" in config['training']:\n use_teacher = config['training']['use_teacher_train']\n save_teacher = False # by default\n if 'save_teacher_test' in config['training']:\n save_teacher = config['training']['save_teacher_test']\n\n main()\n","sub_path":"trainSSL_less_memory.py","file_name":"trainSSL_less_memory.py","file_ext":"py","file_size_in_byte":37824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"394694073","text":"import os\nimport sys\nimport random\nimport string\nimport subprocess\nfrom subprocess import Popen, PIPE\n\ndef isIndexed(genome):\n # Check if the Reference Genome is indexed as expected\n extensions = ['.amb','.fai','.ann','.bwt','.pac','.sa']\n for extension in extensions:\n if not os.path.isfile(genome + extension):\n return False\n return True \n\ndef assignName(c,n):\n formatOption = '{0:0%s}' % len(str(n))\n return 'sample' + formatOption.format(c)\n\ndef parseCNVconfig(p):\n d = {\n 'PATH' : '',\n 'N_READS' : 10000,\n 'READ_LENGTH' : 100,\n 'REGION_MINIMUM_LENGTH': 1000,\n 'REGION_MAXIMUM_LENGTH': 100000,\n 'COPY_NUMBER_MINIMUM': 3,\n 'COPY_NUMBER_MAXIMUM': 10\n }\n with open(p,'r') as file:\n for line in file:\n k,v = line.rstrip().split('=')\n d[k.strip()] = v.strip()\n return d\n\ndef CreateDirs(wd, name):\n if not os.path.exists(wd + '/sra/' + name ):\n os.makedirs(wd + '/sra/' + name )\n os.makedirs(wd + '/sra/' + name + '/balanced' )\n os.makedirs(wd + '/sra/' + name + '/amplified' )\n os.makedirs(wd + '/sra/' + name + '/deleted' ) \n\ndef countCHR(dir):\n l = set()\n for fasta in os.listdir(dir):\n if fasta.endswith(\".fa\") or fasta.endswith('.fasta'):\n l.add(fasta)\n return l\n\ndef Seeding():\n seed = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(6))\n return seed\n\ndef Report(wd, dir, name, tmp):\n command = [\n wd + '/sh/report.sh', \n dir + name,\n name,\n dir + name,\n tmp\n ]\n process = subprocess.Popen(' '.join(command), shell=True, stdout=PIPE)\n process.wait()\n\ndef cls():\n os.system('clear')\n\ndef progression(inputList, TempoRunningList):\n RunningList = []\n for x in range(0, len(TempoRunningList)):\n if TempoRunningList[x] == 0:\n RunningList.append('\\033[91mRUNNING\\033[0m')\n elif TempoRunningList[x] == 1:\n RunningList.append('\\033[92mCOMPLETED\\033[0m')\n elif TempoRunningList[x] == 2:\n RunningList.append('\\033[94mWAITING\\033[0m')\n else:\n RunningList.append('\\033[93mNOT REQUESTED\\033[0m')\n \n\n printOutput = '''\n #################################################\n # #\n # CNVbencher #\n # v1.0 #\n # #\n # support: davide.baldazzi8@unibo.it #\n # #\n #################################################\n \n Input\n Number of Sample to generate: %s\n Approach: %s\n Subsampling: %s\n Threads: %s\n Number of Reads (per Chromosome): %s\n Read length: %s\n Number of CNVs (per Chromosome): %s\n\n Monitoring:\n Sample/s Completed: %s/%s\n < Running Sample >\n CNVs Simulation: %s\n Quality Check: %s\n Automatic Quality Adjustment: %s\n Quality Check (2): %s\n Alignment: %s\n Compute Coverage: %s\n Create Subsamples: %s\n Quality Check (SubS.): %s\n Alignment (SubS.): %s\n Compute Coverage (SubS.): %s\n Report Generation: %s\n '''\n cls()\n print(printOutput % (\n inputList[0],\n inputList[1],\n inputList[2],\n inputList[3],\n inputList[4],\n inputList[5],\n inputList[6],\n inputList[7],\n inputList[0],\n RunningList[0],\n RunningList[1],\n RunningList[2],\n RunningList[3],\n RunningList[4],\n RunningList[5],\n RunningList[6],\n RunningList[7],\n RunningList[8],\n RunningList[9],\n RunningList[10]\n ))\n\ndef cleaner(tmp):\n command = [\n 'rm', \n '-r',\n tmp\n ]\n process = subprocess.Popen(' '.join(command), shell=True, stdout=PIPE)\n process.wait()","sub_path":"modules/checker.py","file_name":"checker.py","file_ext":"py","file_size_in_byte":4661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"79603352","text":"import pandas as pd\n\ndata = pd.read_csv('faculty.csv')\n\nemail_list = []\nfor index, row in data.iterrows():\n\ts = row[' email']\n\temail_list.append(s)\ndf_emails = pd.DataFrame(email_list)\ndf_emails.to_csv('emails.csv', header=False, index=False)","sub_path":"python/advanced_python_csv.py","file_name":"advanced_python_csv.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"430451811","text":"import random\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass Environment:\n def __init__(self, height, width, frame_rate):\n if height < 7 or width < 7:\n print('Height and Width must be larger or equal to 7!!!')\n else:\n # Set frame_rate\n self.frame_rate = frame_rate\n\n # Set arena\n self.height = height\n self.width = width\n self.arena = np.zeros(shape=(self.height, self.width), dtype=float)\n\n # Set the starting base, edges and score of each game\n self.base, self.edges, self.score = [None] * 3\n\n # Set snake info of each game\n self.snake, self.snake_loc, self.momentum = [None] * 3\n self.head_y, self.head_x, self.second_x, self.second_y, self.tail_x, self.tail_y = [None] * 6\n self.opposite_action = {'L': 'R', 'R': 'L', 'U': 'D', 'D': 'U'}\n\n # Set food info of each game\n self.food = None\n\n # Set image\n plt.ion()\n plt.figure()\n\n def reset(self):\n # Set the base and define edges\n self.base = self.arena.copy()\n self.base[[0, -1], :] = 1.0\n self.base[:, [0, -1]] = 1.0\n\n self.edges = np.argwhere(self.base == 1.0).tolist()\n\n # Set snake\n self.snake = self.arena.copy()\n self.head_y, self.head_x = self.height // 3, self.width // 2\n self.second_y, self.second_x = self.head_y, self.head_x + 1\n self.tail_y, self.tail_x = self.head_y, self.head_x + 2\n\n self.snake[self.head_y, self.head_x] = 0.7\n self.snake[self.second_y, self.second_x] = 0.4\n self.snake[self.tail_y, self.tail_x] = 0.4\n self.snake_loc = [[self.head_y, self.head_x], [self.second_y, self.second_x], [self.tail_y, self.tail_x]]\n\n self.momentum = 'L'\n\n # Set food\n self.food = self.arena.copy()\n\n if np.argwhere(self.base + self.food + self.snake == 0.3).size == 0:\n food_y, food_x = random.choice(np.argwhere(self.base + self.food + self.snake == 0))\n self.food[food_y, food_x] = 0.3\n\n # Reset score\n self.score = 0\n\n # Show initial stage\n plt.clf()\n plt.imshow(self.base + self.food + self.snake)\n plt.pause(self.frame_rate)\n\n state = np.stack([self.base, self.food, self.snake], axis=-1)\n return state\n\n def step(self, action):\n # determine new head of snake based on action\n if self.opposite_action[action] == self.momentum:\n processed_action = self.momentum\n\n else:\n processed_action = action\n\n # update the momentum\n self.momentum = processed_action\n\n # determine the location of new_head if the action is implemented\n if processed_action == 'L':\n new_head_y = self.head_y\n new_head_x = self.head_x - 1\n\n elif processed_action == 'R':\n new_head_y = self.head_y\n new_head_x = self.head_x + 1\n\n elif processed_action == 'U':\n new_head_y = self.head_y - 1\n new_head_x = self.head_x\n\n elif processed_action == 'D':\n new_head_y = self.head_y + 1\n new_head_x = self.head_x\n\n else:\n print('error: incorrect action input')\n exit()\n\n '''determine result of action'''\n # update the snake_loc and snake board based on new move\n self.snake[new_head_y, new_head_x] = 0.7\n self.snake[self.head_y, self.head_x] = 0.4\n self.snake[self.tail_y, self.tail_x] = 0.0\n self.snake_loc = [[new_head_y, new_head_x]] + self.snake_loc\n\n # lose the game if hitting edges\n if [new_head_y, new_head_x] in self.edges:\n is_dead = True\n reward = -1\n info = 'You lose! You hit a wall! Total score: ' + str(self.score)\n\n # lose the game if eating itself\n elif [new_head_y, new_head_x] in self.snake_loc[1:]:\n is_dead = True\n reward = -1\n info = 'You lose! You ate yourself! Total score: ' + str(self.score)\n\n else:\n is_dead = False\n\n # if the food is at the tail of the snake, transform the food into the new tail of the snake\n if self.food[self.tail_y, self.tail_x] == 0.3:\n self.food[self.tail_y, self.tail_x] = 0.0\n self.snake[self.tail_y, self.tail_x] = 0.4\n else:\n self.snake_loc.pop(-1)\n\n # update current head and current tail\n self.head_y, self.head_x = self.snake_loc[0]\n self.tail_y, self.tail_x = self.snake_loc[-1]\n\n # score if the new_head reaches food\n if self.food[new_head_y, new_head_x] == 0.3:\n reward = 1\n self.score += 1\n info = 'Score!!! +' + str(1) + ' point(s)'\n\n # generate new food\n food_y, food_x = random.choice(np.argwhere(self.base + self.food + self.snake == 0))\n self.food[food_y, food_x] = 0.3\n\n else:\n reward = -0.01\n info = None\n\n plt.clf()\n plt.imshow(self.base + self.food + self.snake)\n plt.pause(self.frame_rate)\n\n next_state = np.stack([self.base, self.food, self.snake], axis=-1)\n return next_state, reward, is_dead, info\n","sub_path":"environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":5411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"433180798","text":"import pandas as pd\nfrom pandas import Series, DataFrame\n\n# 数据表合并\n# 多个 DataFrame 数据表的合并就相当于多个数据库的表合并\n\ndf1 = DataFrame({'name':['ZhangFei', 'GuanYu', 'a', 'b', 'c'], 'data1':range(5)})\ndf2 = DataFrame({'name':['ZhangFei', 'GuanYu', 'A', 'B', 'C'], 'data2':range(5)})\n\n# 1. 基于指定列进行连接\n# 基于 name 进行连接\n\ndf3 = pd.merge(df1, df2, on='name')\nprint(df3)\n\n# 2. inner 内连接\n# inner 内连接是键的交集,在这里 df1, df2 相同的键是 name\n# 所以是基于 name 字段做的连接\n\ndf4 = pd.merge(df1, df2, how='inner')\nprint(df4)\n\n# left 左连接\n# 以第一个 DataFrame 为主进行的连接,第二个 DataFrame 作为补充\n\ndf5 = pd.merge(df1, df2, how='left')\nprint(df5)\n\n# right 右连接\n# 以第二个 DataFrame 为主进行的连接,第一个 DataFrame 作为补充\ndf6 = pd.merge(df1, df2, how='right')\nprint(df6)\n\n# outer 外连接\n# 外连接相当于求两个 DataFrame 的并集\n\ndf7 = pd.merge(df1, df2, how='outer')\nprint(df7)\n","sub_path":"pandas_base/dataframe_merge.py","file_name":"dataframe_merge.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"431698350","text":"\r\nfrom tkinter import * \r\n\r\n\r\n\r\n\r\nfrom test import horairefunct\r\n\r\n\r\nfenetre = Tk()\r\ncadre = Frame(fenetre, borderwidth =10)\r\ncadre.pack(fill = X)\r\n\r\nmessage = Button(cadre, text=\"Horaire\",font = (\"Times\",16), command = horairefunct)\r\nmessage.pack(side = \"top\",fill=X)\r\nmessage2 = Button(cadre, text=\"Budget\",font = (\"Times\",16))\r\nmessage2.pack(side=\"bottom\",fill = X)\r\n\r\nfenetre.mainloop()\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"MenuPrincipal.py","file_name":"MenuPrincipal.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"631585667","text":"# Copyright The IETF Trust 2007, All Rights Reserved\n\n# Portion Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).\n# All rights reserved. Contact: Pasi Eronen \n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n#\n# * Neither the name of the Nokia Corporation and/or its\n# subsidiary(-ies) nor the names of its contributors may be used\n# to endorse or promote products derived from this software\n# without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport os\nimport re\nimport html5lib\nimport sys\nimport urllib2\n\nfrom unittest.util import strclass\nfrom bs4 import BeautifulSoup\n\nimport django.test\nfrom django.conf import settings\nfrom django.utils.text import slugify\n\nimport debug # pyflakes:ignore\n\nreal_database_name = settings.DATABASES[\"default\"][\"NAME\"]\n\ndef split_url(url):\n if \"?\" in url:\n url, args = url.split(\"?\", 1)\n args = dict([ map(urllib2.unquote,arg.split(\"=\", 1)) for arg in args.split(\"&\") if \"=\" in arg ])\n else:\n args = {}\n return url, args\n\ndef login_testing_unauthorized(test_case, username, url, password=None):\n r = test_case.client.get(url)\n test_case.assertIn(r.status_code, (302, 403))\n if r.status_code == 302:\n test_case.assertTrue(\"/accounts/login\" in r['Location'])\n if not password:\n password = username + \"+password\"\n return test_case.client.login(username=username, password=password)\n\ndef unicontent(r):\n \"Return a HttpResponse object's content as unicode\"\n return r.content.decode(r.charset)\n\ndef textcontent(r):\n text = BeautifulSoup(r.content, 'lxml').get_text()\n text = re.sub('(\\n\\s+){2,}', '\\n\\n', text)\n return text\n\ndef reload_db_objects(*objects):\n \"\"\"Rerequest the given arguments from the database so they're refreshed, to be used like\n\n foo, bar = reload_db_objects(foo, bar)\"\"\"\n\n t = tuple(o.__class__.objects.get(pk=o.pk) for o in objects)\n if len(objects) == 1:\n return t[0]\n else:\n return t\n\nclass ReverseLazyTest(django.test.TestCase):\n def test_redirect_with_lazy_reverse(self):\n response = self.client.get('/ipr/update/')\n self.assertRedirects(response, \"/ipr/\", status_code=301)\n\nclass TestCase(django.test.TestCase):\n \"\"\"\n Does basically the same as django.test.TestCase, but adds asserts for html5 validation.\n \"\"\"\n\n parser = html5lib.HTMLParser(strict=True)\n\n def assertValidHTML(self, data):\n try:\n self.parser.parse(data)\n except Exception as e:\n raise self.failureException(str(e))\n\n def assertValidHTMLResponse(self, resp):\n self.assertHttpOK(resp)\n self.assertTrue(resp['Content-Type'].startswith('text/html'))\n self.assertValidHTML(resp.content)\n\n def tempdir(self, label):\n slug = slugify(self.__class__.__name__.replace('.','-'))\n dirname = \"tmp-{label}-{slug}-dir\".format(**locals())\n path = os.path.abspath(dirname)\n if not os.path.exists(path):\n os.mkdir(path)\n return path\n\n def assertNoFormPostErrors(self, response, error_css_selector=\".has-error\"):\n \"\"\"Try to fish out form errors, if none found at least check the\n status code to be a redirect.\n\n Assumptions:\n - a POST is followed by a 302 redirect\n - form errors can be found with a simple CSS selector\n\n \"\"\"\n\n if response.status_code == 200:\n from pyquery import PyQuery\n from lxml import html\n self.maxDiff = None\n\n errors = [html.tostring(n).decode() for n in PyQuery(response.content)(error_css_selector)]\n if errors:\n explanation = u\"{} != {}\\nGot form back with errors:\\n----\\n\".format(response.status_code, 302) + u\"----\\n\".join(errors)\n self.assertEqual(response.status_code, 302, explanation)\n\n self.assertEqual(response.status_code, 302)\n \n def assertMailboxContains(self, mailbox, subject=None, text=None, count=None):\n \"\"\"\n Asserts that the given mailbox contains *count* mails with the given\n *subject* and body *text* (if not None). At least one of subject,\n text, and count must be different from None. If count is None, the\n filtered mailbox must be non-empty.\n \"\"\"\n if subject is None and text is None and count is None:\n raise self.failureException(\"No assertion made, both text and count is None\")\n mlist = mailbox\n if subject:\n mlist = [ m for m in mlist if subject in m[\"Subject\"] ]\n if text:\n mlist = [ m for m in mlist if text in m.get_payload(decode=True) ]\n if count and len(mlist) != count:\n sys.stderr.write(\"Wrong count in assertMailboxContains(). The complete mailbox contains %s emails:\\n\\n\" % len(mailbox))\n for m in mailbox:\n sys.stderr.write(m.as_string())\n sys.stderr.write('\\n\\n')\n if count:\n self.assertEqual(len(mlist), count)\n else:\n self.assertGreater(len(mlist), 0)\n\n def __str__(self):\n return \"%s (%s.%s)\" % (self._testMethodName, strclass(self.__class__),self._testMethodName)\n\n \n","sub_path":"ietf/utils/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":6476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"401839425","text":"# -*- coding: utf-8 -*-\n\"\"\"\nnctfidf.py - Normalized Convolvable tfidf\nコーパス各行の特徴ベクターが長さ1になるよう規格化したtfidf行列を返します。\nまたconvolutionを与えると文脈性を強めるための畳込みを行います。\n\n\"\"\"\nfrom __future__ import unicode_literals\n\nimport sys\nimport codecs\nimport pickle\nfrom collections import Counter\nimport numpy as np\n\nimport cloudstorage\nfrom google.appengine.api import app_identity\n\ncloudstorage.set_default_retry_params(\n cloudstorage.RetryParams(\n initial_delay=0.2, max_delay=5.0, backoff_factor=2, max_retry_period=15\n ))\n\nBUCKET_NAME = app_identity.get_default_gcs_bucket_name()\n\n\nfrom tinysegmenter import TinySegmenter\nSegmenter = TinySegmenter()\n\nSE_STOPCHAR = '-ー一~〜。、'\n\ndef segment(text):\n \"\"\" textを分かち書きして得られた文字列のリストを返す \"\"\"\n l = Segmenter.segment(text)\n l = [x.rstrip(SE_STOPCHAR) for x in l]\n l = [x for x in l if x]\n return l\n\n\nclass NCTfidf:\n def __init__(self,name):\n self.name=name\n\n\n def load_cache(self):\n path = \"/{}/{}\".format(BUCKET_NAME,self.name)\n with cloudstorage.open(path+\".feat.pickle\") as f:\n self.feat = np.load(f)\n\n with cloudstorage.open(path+\".tfidf.npz\") as f:\n self.tfidf = np.load(f)\n\n with cloudstorage.open(path+\".df.npz\") as f:\n self.df = np.load(f)\n\n\n def save_cache(self):\n path = \"/{}/{}\".format(BUCKET_NAME,self.name)\n with cloudstorage.open(path+\".feat.pickle\",\"w\") as f:\n pickle.dump(self.feat,f)\n\n with cloudstorage.open(path+\".tfidf.npz\",\"w\") as f:\n np.save(f,self.tfidf)\n\n with cloudstorage.open(path+\".df.npz\",'w') as f:\n np.save(f,self.df)\n\n\n def update(self,corpus,convolution=None):\n \"\"\"\n テキスト検索をするため、corpusをtfidf行列に変換する。\n 検索にはdfも必要になるため格納しておく。\n corpus : 入力文字列のリスト\n convolution : (optional)\n 一次元のnp.ndarrayを与える。[1.0,0.5,0.2]のように減衰する値にする\n \"\"\"\n\n \"\"\"\n 前処理:\n corpusの発言部分を分かち書きし、単語リストを生成してfeatに格納する。\n corpusを分かち書きしたリストのリストに変換し、corpus_splittedに格納する。\n \"\"\"\n\n words = []\n corpus_splitted = []\n for line in corpus:\n l=segment(line)\n words.extend(l)\n corpus_splitted.append(l)\n\n v = Counter(words)\n\n self.feat = list(v.keys())\n\n\n \"\"\"\n Term Frequency: 各行内での単語の出現頻度\n tf(t,d) = (ある単語tの行d内での出現回数)/(行d内の全ての単語の出現回数の和)\n \"\"\"\n wv = np.zeros((len(corpus),len(self.feat)),dtype=np.float32)\n tf = np.zeros((len(corpus),len(self.feat)),dtype=np.float32)\n\n i=0\n for line in corpus_splitted:\n v = Counter(line)\n for word,count in v.items():\n j = self.feat.index(word)\n wv[i,j] = count\n i+=1\n\n \"\"\"\n wvの畳み込み\n 文脈性を強調するため、n行目にはn-1行目やn-2行目の単語も含まれているとみなす。\n ただし現在の行から離れるほど重み付けは低くなるようにしたい。これをnp.convoluteで\n 実装した。\n \"\"\"\n if convolution:\n wv = np.apply_along_axis(\n np.convolve,0,wv,convolution,str('full'))\n # str('full'): casted to str because of numpy bug.\n # see https://github.com/numpy/numpy/issues/2301\n\n wv = np.delete(wv,[0,convolution.shape[0]-1],axis=0)\n\n tf = wv / np.sum(wv,axis=0)\n\n\n \"\"\"\n Inverse Document Frequency: 各単語が現れる行の数の割合\n df(t) = ある単語tが出現する行の数 / 全行数\n idf(t) = log(1 +1/ df(t) )\n \"\"\"\n self.df = np.apply_along_axis(np.count_nonzero,axis=0,arr=wv) / float(tf.shape[0])\n idf = np.log(1+1/self.df)\n self.tfidf = tf*idf\n\n \"\"\"\n 正規化\n すべてのtfidfベクトルの長さを1にする。これによりretrieveでnormの計算を\n 毎回しないですむ\n \"\"\"\n norm = np.apply_along_axis(np.linalg.norm,axis=1,arr=self.tfidf)\n self.tfidf = self.tfidf / norm[:, np.newaxis]\n\n\n\n\n def retrieve(self,speech):\n \"\"\"\n corpusを検索し、speechに似ている順に並べた行番号のリストを返す\n\n 与えられた文字列speechをcorpusと同じ方法でtfidfベクターに変換する。\n ただしspeechはcorpusに全く現れない単語だけの場合がある。\n この場合tfidfは計算できないため、Noneを返す\n\n そうでない場合、corpusを検索し、speechに似ている順に並べた行番号のリストを返す\n \"\"\"\n\n \"\"\" 分かち書き \"\"\"\n speech = segment(speech)\n\n\n \"\"\" tf \"\"\"\n wv = np.zeros((len(self.feat)))\n tf = np.zeros((len(self.feat)))\n\n v = Counter(speech)\n for word,count in v.items():\n if word in self.feat:\n j = self.feat.index(word)\n \"\"\"\n featに含まれない言葉がユーザ発言に含まれる場合、\n 現状無視しているが、相手に聞き返すなどの対処がほしい\n \"\"\"\n wv[j] = count\n\n nd = np.sum(wv)\n if nd == 0:\n \"\"\"\n corpusと何も一致しない文字列の場合\n Noneを返す\n \"\"\"\n return None\n\n\n \"\"\" tfidf \"\"\"\n tf = wv / nd\n df = self.df/float(tf.shape[0])\n idf = np.log(1+1/df)\n tfidf = tf*idf\n\n \"\"\" 正規化 \"\"\"\n norm = np.linalg.norm(tfidf)\n tfidf /= norm\n\n \"\"\"\n corpusのtfidf(ct)とspeechのtdidf(vt)でcos類似度ベクターを生成し、\n ベクターの成分は類似度で、それを降順に並び替えたindexリストを返す\n\n cos類似度 = ct・vt / |ct||vt|\n だが、tfidf計算の中でベクトルの長さを1に正規化しているため、|ct|=|vt|=1。つまり\n cos類似度 = ct・vt\n で計算する。\n \"\"\"\n\n return np.argsort(np.inner(self.tfidf,tfidf), axis=0)[::-1]\n","sub_path":"reactor/nctfidf.py","file_name":"nctfidf.py","file_ext":"py","file_size_in_byte":6605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"609223364","text":"#!/opt/antelope/5.4/bin/python\n#Program to do th vincenty inverse and forward\n#By Zhengyang\nimport math\n\n# WGS 84\na = 6378137 # meters\nf = 1 / 298.257223563\nb = 6356752.314245 # meters; b = (1 - f)a\n\nMAX_ITERATIONS = 200\nCONVERGENCE_THRESHOLD = 1e-12 # .000,000,000,001\n\ndef vincenty_inverse(point1, point2):\n \"\"\"\n Vincenty's formula (inverse method) to calculate the distance (in\n kilometers or miles) between two points on the surface of a spheroid\n unit is degree\n \"\"\"\n # short-circuit coincident points\n if point1[0] == point2[0] and point1[1] == point2[1]:\n return 0,0,0\n\n U1 = math.atan((1 - f) * math.tan(math.radians(point1[0])))\n U2 = math.atan((1 - f) * math.tan(math.radians(point2[0])))\n L = math.radians(point2[1] - point1[1])\n Lambda = L\n\n sinU1 = math.sin(U1)\n cosU1 = math.cos(U1)\n sinU2 = math.sin(U2)\n cosU2 = math.cos(U2)\n\n for iteration in range(MAX_ITERATIONS):\n sinLambda = math.sin(Lambda)\n cosLambda = math.cos(Lambda)\n sinSigma = math.sqrt((cosU2 * sinLambda) ** 2 +\n (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) ** 2)\n if sinSigma == 0:\n return 0.0 # coincident points\n cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda\n sigma = math.atan2(sinSigma, cosSigma)\n sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma\n cosSqAlpha = 1 - sinAlpha ** 2\n try:\n cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha\n except ZeroDivisionError:\n cos2SigmaM = 0\n C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha))\n LambdaPrev = Lambda\n Lambda = L + (1 - C) * f * sinAlpha * (sigma + C * sinSigma *\n (cos2SigmaM + C * cosSigma *\n (-1 + 2 * cos2SigmaM ** 2)))\n if abs(Lambda - LambdaPrev) < CONVERGENCE_THRESHOLD:\n break # successful convergence\n else:\n return None # failure to converge\n\n uSq = cosSqAlpha * (a ** 2 - b ** 2) / (b ** 2)\n A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)))\n B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)))\n deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma *\n (-1 + 2 * cos2SigmaM ** 2) - B / 6 * cos2SigmaM *\n (-3 + 4 * sinSigma ** 2) * (-3 + 4 * cos2SigmaM ** 2)))\n s = b * A * (sigma - deltaSigma)\n\n s /= 1000 # meters to kilometers\n\n alpha1 = math.atan2(cosU2 * math.sin(Lambda), cosU1 * sinU2 - sinU1 * cosU2 * math.cos(Lambda))\n alpha2 = math.atan2(cosU1 * math.sin(Lambda), -cosU2 * sinU1 + sinU2 * cosU1 * math.cos(Lambda))\n\n return round(s, 6),math.degrees(alpha1),math.degrees(alpha2)\n\ndef vincenty_forward(point1, azimuthd, distancekm):\n \"\"\"\n :param point1: start point \n :param azimuthd: unit in degree\n :param distancekm: unit in km\n :return: point2 lat & lon\n \"\"\"\n distance = distancekm * 1000\n azimuth = math.radians(azimuthd)\n phi1 = math.radians(point1[0])\n U1 = math.atan((1 - f) * math.tan(phi1))\n Sigma1 = math.atan2(math.tan(U1),math.cos(azimuth))\n sinAlaph = math.cos(U1)*math.sin(azimuth)\n cosAlaph = math.sqrt(1 - sinAlaph ** 2)\n uSq = (cosAlaph ** 2) * ( (a * a - b * b) / (b ** 2) )\n A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)))\n B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)))\n\n Sigma = distance / (b * A)\n\n for i in range(MAX_ITERATIONS):\n cos2Sigmam = math.cos(2 * Sigma1 + Sigma)\n sinSigma = math.sin(Sigma)\n cosSigma = math.cos(Sigma)\n deltaSigma = B * sinSigma * (cos2Sigmam + B/4 * (cosSigma * (-1 +\n 2 * cos2Sigmam ** 2) - B/6 * cos2Sigmam * (-3 + 4 * cos2Sigmam ** 2) *\n (-3 + 4 * sinSigma ** 2)))\n Sigmapre = Sigma\n Sigma = distance / (b * A) + deltaSigma\n if abs(Sigma - Sigmapre) < CONVERGENCE_THRESHOLD:\n break\n else:\n return None\n\n tem = math.sin(U1) * math.sin(Sigma) - math.cos(U1) * math.cos(Sigma) * math.cos(azimuth)\n phi2 = math.atan2(math.sin(U1) * math.cos(Sigma) + math.cos(U1) * math.sin(Sigma) * math.cos(azimuth),\n ((1-f) * math.sqrt(sinAlaph ** 2 + tem ** 2)))\n Lamda = math.atan2(math.sin(Sigma) * math.sin(azimuth) ,(math.cos(U1) * math.cos(Sigma) -\n math.sin(U1) * math.sin(Sigma) * math.cos(azimuth)))\n c = f / 16 * cosAlaph ** 2 * (4 + f * (4 - 3 * cosAlaph ** 2))\n L = Lamda - (1 - c) * f * sinAlaph * (Sigma + c * math.sin(Sigma) * (math.cos(Sigma1 * 2 + Sigma) + c * math.cos(Sigma)\n * (-1 + 2 * math.cos(Sigma1 * 2 + Sigma) ** 2)))\n lamda1 = math.radians(point1[1])\n lamda2 = lamda1 + L\n point2 = [round(math.degrees(phi2),6),round(math.degrees(lamda2),6)]\n return point2\n\ndef distance_diff(point1,point2):\n dist = vincenty_inverse(point1, point2)\n dp1 = vincenty_inverse([-90,0], point1)\n dp2 = vincenty_inverse([-90,0], point2)\n np1 = vincenty_forward([0,0],point1[1],dp1[0])\n np2 = vincenty_forward([0,0],point2[1],dp2[0])\n ndist = vincenty_inverse(np1, np2)\n return (ndist[0]-dist[0])\n\ndef changetoequa(point):\n dist = vincenty_inverse([-90,0], point)\n return vincenty_forward([0,0], point[1], dist[0])\n\ndef backtonorm(point):\n dist = vincenty_inverse([0,0], point)\n return vincenty_forward([-90,0],dist[1],dist[0])\n","sub_path":"GDAproject/vincenty.py","file_name":"vincenty.py","file_ext":"py","file_size_in_byte":5574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"47529424","text":"# -*- coding: utf-8 *-*\nfrom django.conf.urls.defaults import *\n#from django.views.generic.simple import direct_to_template\n\nfrom projects import views as views\n\nurlpatterns = patterns(\"\",\n url(r'^modules/$', views.show_modules, name='module_home'),\n url(r'^modules/(?P\\d+)$', views.show_module, name='module_view'),\n url(r'^projects/$', views.show_projects, name='project_home'),\n url(r'^projects/(?P\\d+)$', views.show_project, name='project_view'),\n )\n","sub_path":"projects/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"2032893","text":"from django.core.exceptions import ValidationError\nfrom django.db import DataError\n\nfrom ApiManager.models import ProjectInfo, ModuleInfo, TestCaseInfo, UserInfo\n\n'''用户注册信息落地'''\n\n\ndef add_register_data(**kwargs):\n user_info = UserInfo.objects\n try:\n username = kwargs.pop('account')\n password = kwargs.pop('password')\n email = kwargs.pop('email')\n\n if user_info.filter(username__exact=username).filter(status=1).count() > 0:\n return '该用户名已被注册,请更换用户名'\n if user_info.filter(email__exact=email).filter(status=1).count() > 0:\n return '该邮箱已被其他用户注册,请更换邮箱'\n user_info.create(username=username, password=password, email=email)\n return 'ok'\n except DataError:\n return '字段长度超长,请重新编辑'\n\n\n'''项目数据落地'''\n\n\ndef add_project_data(type, **kwargs):\n project_opt = ProjectInfo.objects\n try:\n if type:\n if project_opt.get_pro_name(kwargs.get('project_name')) < 1:\n project_opt.insert_project(kwargs.pop('project_name'), kwargs.pop('responsible_name'),\n kwargs.pop('test_user'), kwargs.pop('dev_user'), kwargs.pop('publish_app'),\n kwargs.pop('simple_desc'), kwargs.pop('other_desc'))\n else:\n return '该项目已存在,请重新编辑'\n else:\n if kwargs.get('project_name') != project_opt.get_pro_name('', type=False, id=kwargs.get(\n 'index')) and project_opt.get_pro_name(kwargs.get('project_name')) > 0:\n return '该项目已存在, 请重新命名'\n project_opt.update_project(kwargs.pop('index'), kwargs.pop('project_name'), kwargs.pop('responsible_name'),\n kwargs.pop('test_user'), kwargs.pop('dev_user'), kwargs.pop('publish_app'),\n kwargs.pop('simple_desc'), kwargs.pop('other_desc'))\n\n except DataError:\n return '字段长度超长,请重新编辑'\n return 'ok'\n\n\n'''模块数据落地'''\n\n\ndef add_module_data(type, **kwargs):\n module_opt = ModuleInfo.objects\n belong_project = kwargs.pop('belong_project')\n try:\n if type:\n if module_opt.filter(belong_project__pro_name__exact=belong_project) \\\n .filter(module_name__exact=kwargs.get('module_name')).count() < 1:\n belong_project = ProjectInfo.objects.get_pro_name(belong_project, type=False)\n module_opt.insert_module(kwargs.pop('module_name'), belong_project, kwargs.pop('test_user'),\n kwargs.pop('lifting_time'), kwargs.pop('simple_desc'),\n kwargs.pop('other_desc'))\n else:\n return '该模块已在项目中存在,请重新编辑'\n else:\n if kwargs.get('module_name') != module_opt.get_module_name('', type=False, id=kwargs.get('index')) \\\n and module_opt.filter(belong_project__pro_name__exact=belong_project) \\\n .filter(module_name__exact=kwargs.get('module_name')).count() > 0:\n return '该模块已存在,请重新命名'\n module_opt.update_module(kwargs.pop('index'), kwargs.pop('module_name'), kwargs.get('test_user'),\n kwargs.pop('lifting_time'),\n kwargs.pop('simple_desc'), kwargs.pop('other_desc'))\n\n except DataError:\n return '字段长度超长,请重新编辑'\n except ValidationError:\n return '提测时间格式非法'\n return 'ok'\n\n\n'''用例数据落地'''\n\n\ndef add_case_data(type, **kwargs):\n case_info = kwargs.get('test').get('case_info')\n case_opt = TestCaseInfo.objects\n name = kwargs.get('test').get('name')\n module = case_info.get('module')\n project = case_info.get('project')\n try:\n if type:\n if case_opt.get_case_name(name, module, project) < 1:\n belong_module = ModuleInfo.objects.get_module_name(module, type=False, project=project)\n case_opt.insert_case(belong_module, **kwargs)\n else:\n return '用例或配置已存在,请重新编辑'\n else:\n index = int(case_info.get('test_index'))\n if name != case_opt.get_case_by_id(index, type=False) \\\n and case_opt.get_case_name(name, module, project) > 0:\n return '用例或配置已在该模块中存在,请重新命名'\n else:\n case_opt.update_case(**kwargs)\n\n except DataError:\n return '字段长度超长,请重新编辑'\n return 'ok'\n\n\n'''配置数据落地'''\n\n\ndef add_config_data(type, **kwargs):\n case_opt = TestCaseInfo.objects\n config_info = kwargs.get('config').get('config_info')\n name = kwargs.get('config').get('name')\n module = config_info.get('config_module')\n project = config_info.get('project')\n try:\n if type:\n if case_opt.get_case_name(name, module, project) < 1:\n belong_module = ModuleInfo.objects.get_module_name(module, type=False, project=project)\n case_opt.insert_config(belong_module, **kwargs)\n else:\n return '用例或配置已存在,请重新编辑'\n else:\n index = int(config_info.get('test_index'))\n if name != case_opt.get_case_by_id(index, type=False) \\\n and case_opt.get_case_name(name, module, project) > 0:\n return '用例或配置已在该模块中存在,请重新命名'\n else:\n case_opt.update_config(**kwargs)\n except DataError:\n return '字段长度超长,请重新编辑'\n return 'ok'\n\n\n'''改变状态'''\n\n\ndef change_status(Model, **kwargs):\n name = kwargs.pop('name')\n obj = Model.objects.get(id=name)\n obj.status = kwargs.pop('status')\n obj.save()\n return 'ok'\n\n'''批量导入用例数据落地'''\n\n\ndef bulk_import_data(**kwargs):\n\n case_opt = TestCaseInfo.objects\n\n case_request_list = kwargs.get('case_info') # 获取前端导入的文件处理后的数据\n\n if isinstance(case_request_list, list):\n pass\n else:\n case_request_list = list(case_request_list)\n case_list_to_insert = []\n for values in enumerate(case_request_list):\n\n # print(values[1])\n if 'config' in values[1]:\n name = values[1].get('config').get('name') # case 配置文件的名字\n type = 2 #设置类型是config类型\n else:\n type = 1\n name = values[1].get('test').get('name') # case的名字\n belong_project = '未分类' # 系统默认项目分类\n module = '未分类' # 系统默认模块分类\n belong_module = ModuleInfo.objects.get_module_name(module, type=False, project=belong_project)\n author = 'system'\n request = values[1]\n if type == 2:\n case_list_to_insert.append(TestCaseInfo(name=name, type=type, belong_project=belong_project,\n belong_module=belong_module, author=author, request=request))\n else:\n case_list_to_insert.append(TestCaseInfo(name=name, type=type, belong_project=belong_project,\n belong_module=belong_module, author=author, request=request))\n\n # print(case_list_to_insert)\n\n case_opt.bulk_create(case_list_to_insert)\n # return 'ok'","sub_path":"ApiManager/utils/operation.py","file_name":"operation.py","file_ext":"py","file_size_in_byte":7680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"98790016","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n#________________________________________________________________________________________________________________________________#\n\nimport argparse\nimport csv\n\n#________________________________________________________________________________________________________________________________#\n\ndef getArgs():\n parser = argparse.ArgumentParser(description=\"\",version=\"0.1\")\n parser.add_argument('-l',dest=\"liste_id\",type=argparse.FileType('r'),required=True,help='A list of Esi gene to keep')\n parser.add_argument('-c',dest=\"comm\",type=str,required=True,help='\"Gene.csv\" file from Orcae')\n parser.add_argument('-o',dest=\"out\",type=str,required=True,help='Outputfile name')\n \n arg = parser.parse_args()\n \n return arg\n\ndef EsiListe(args):\n esiID=[]\n for line in args.liste_id:\n esiID.append(line.split()[0])\n \n return esiID\n\ndef CommParse(args, esiID):\n \n dicotmp={}\n \n with open(args.comm, 'rb') as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n for line in reader:\n if line[1] in esiID:\n if dicotmp.has_key(line[1]):\n if int(line[0]) > int(dicotmp[line[1]][0]): #select the last modification i.e. the last row number in the db table\n dicotmp[line[1]]=line\n else:\n dicotmp[line[1]]=line\n\n\n with open(args.out, 'wb') as csvfile:\n writer = csv.writer(csvfile, delimiter=';', quotechar='\"', quoting=csv.QUOTE_ALL, lineterminator=\";\\n\")\n for key in sorted(dicotmp.keys()):\n writer.writerow(['']+dicotmp[key][1:7]+['2014-09-23 12:00:00'])\n \n\ndef main(args):\n esiID=EsiListe(args)\n CommParse(args, esiID)\n \n\nif __name__ == '__main__':\n args = getArgs()\n main(args)","sub_path":"orcae/old/orcae_gene.py","file_name":"orcae_gene.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"483914899","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.svm import SVC\r\nfrom sklearn import model_selection\r\nfrom sklearn.preprocessing import StandardScaler\r\nimport numpy as np\r\nimport csv\r\n\r\n# --- Load Data ---\r\ndataset = pd.read_csv('Wisconsin Breast Cancer Dataset (Original).csv')\r\n\r\n# --- Data Visualization ---\r\n\r\ndesired_width = 320\r\npd.set_option('display.width', desired_width)\r\nnp.set_printoptions(linewidth=desired_width)\r\npd.set_option('display.max_columns', 32)\r\nprint(dataset.describe())\r\n'''\r\nplt.figure(figsize=(12, 6))\r\nsns.heatmap(dataset.corr(), annot=True, cmap='cubehelix_r')\r\nax = plt.gcf()\r\nplt.ylim((10, 0))\r\nplt.show()\r\n'''\r\n\r\n# --- Data Processing ---\r\ndataset.drop('id', axis=1, inplace=True)\r\ndataset.dropna(axis=0, inplace=True)\r\n\r\nY = dataset[['class']]\r\nX = dataset[['size_uniformity', 'shape_uniformity', 'marginal_adhesion',\r\n 'epithelial_size', 'bare_nucleoli', 'bland_chromatin',\r\n 'normal_nucleoli']]\r\n\r\n# --- Rescaling Datasets ---\r\nsc = StandardScaler()\r\nX = sc.fit_transform(X)\r\n\r\n# --- CSV rows ---\r\nrows = [[\r\n 'Model',\r\n 'Mean Accuracy',\r\n 'Mean F1 Score',\r\n 'ROC AUC Score',\r\n 'Explained Variance',\r\n 'Mean Absolute Error',\r\n 'Average Accurate Classification',\r\n 'Average Inaccurate Classifications',\r\n 'Total Instances']]\r\n\r\n# --- Training models ---\r\nmodels = [('SVM', SVC(gamma='scale', probability=True)),\r\n ('KNN', KNeighborsClassifier(metric='minkowski')),\r\n ('NB', GaussianNB())]\r\n\r\nresults = []\r\nnames = []\r\nfolds = 10\r\n\r\nfor i in range(folds + 1):\r\n if i >= 2:\r\n rows.append(['K-Fold: ' + str(i)])\r\n for name, model in models:\r\n kfold = model_selection.KFold(n_splits=i, random_state=i)\r\n accuracy = model_selection.cross_val_score(model, X, np.ravel(Y), cv=kfold, scoring='accuracy')\r\n MAE = model_selection.cross_val_score(model, X, np.ravel(Y), cv=kfold, scoring='neg_mean_absolute_error')\r\n explain_variance = model_selection.cross_val_score(model, X, np.ravel(Y), cv=kfold, scoring='explained_variance')\r\n total_instances = len(X)\r\n correct_instances = total_instances * accuracy\r\n incorrect_instances = total_instances - correct_instances\r\n f1 = model_selection.cross_val_score(model, X, np.ravel(Y), cv=kfold, scoring='f1_macro')\r\n roc_auc = model_selection.cross_val_score(model, X, np.ravel(Y), cv=kfold, scoring='roc_auc')\r\n\r\n rows.append([\r\n name,\r\n \"{0:.3f}\".format(accuracy.mean()),\r\n \"{0:.3f}\".format(f1.mean()),\r\n \"{0:.3f}\".format(roc_auc.mean()),\r\n \"{0:.3f}\".format(explain_variance.mean()),\r\n \"{0:.3f}\".format(MAE.mean() * -1),\r\n int(round(correct_instances.mean())),\r\n int(round(incorrect_instances.mean())),\r\n len(X)\r\n ])\r\n\r\nnew_file = open('results (original).csv', 'w', newline='')\r\ncsv_output = csv.writer(new_file)\r\ncsv_output.writerows(rows)\r\n","sub_path":"Original_Test.py","file_name":"Original_Test.py","file_ext":"py","file_size_in_byte":3192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"322403018","text":"# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n def removeNthFromEnd(self, head, n):\n \"\"\"\n :type head: ListNode\n :type n: int\n :rtype: ListNode\n \"\"\"\n array = [head.val]\n while head.next is not None:\n head = head.next\n array.append(head.val)\n\n array.pop(-n)\n return array\n","sub_path":"solutions/remove_nth_node_from_end_of_list.py","file_name":"remove_nth_node_from_end_of_list.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"123364396","text":"import pytest\nimport yaml\nfrom kalc.model.kubernetes import KubernetesCluster\nfrom kalc.model.kinds.Pod import Pod\nfrom kalc.model.kinds.Node import Node\nfrom kalc.model.kinds.Service import Service\nfrom kalc.model.kinds.Deployment import Deployment\nfrom kalc.model.kinds.PriorityClass import PriorityClass\nfrom kalc.model.system.Scheduler import Scheduler\nfrom kalc.misc.const import *\nfrom kalc.model.search import K8ServiceInterruptSearch\nfrom kalc.misc.object_factory import labelFactory\nfrom click.testing import CliRunner\nimport kalc.misc.util as util\n\nTEST_CLUSTER_FOLDER = \"./tests/daemonset_eviction/cluster_dump\"\nTEST_DEPLOYMENT = \"./tests/test-deployment/deployment.yaml\"\nTEST_DEPLOYMENT1 = \"./tests/test-deployment/deployment1.yaml\"\n\nTEST_DEPLOYMENT_DUMP = \"./tests/test-deployment/dump\"\n\nTEST_TARGET_DUMP = \"./tests/daemonset_eviction_with_deployment/cluster_dump\"\nTEST_TARGET_CREATE = \"./tests/daemonset_eviction_with_deployment/daemonset_create.yaml\" #TODO rename file to deployment_create.yaml\n\n@pytest.mark.skip(reason=\"FIXME\")\ndef test_pod_target_attached():\n k = KubernetesCluster()\n k.load_dir(TEST_TARGET_DUMP)\n k.create_resource(open(TEST_TARGET_CREATE).read())\n k._build_state()\n deployments = filter(lambda x: isinstance(x, Deployment), k.state_objects)\n for deployment in deployments:\n if deployment.metadata_name._get_value() == \"redis-master-create\":\n for pod in util.objDeduplicatorByName(deployment.podList._get_value()):\n assert pod.targetService._get_value() != None\n \n\ndef test_load_twise_exeption():\n k = KubernetesCluster()\n k.create_resource(open(TEST_DEPLOYMENT).read())\n k.create_resource(open(TEST_DEPLOYMENT).read())\n try:\n k._build_state()\n except AssertionError as e:\n print(str(e))\n assert str(e) == \"Error from server (AlreadyExists): deployments.apps \\\"redis-master\\\" already exists\"\n objects = filter(lambda x: isinstance(x, Deployment), k.state_objects)\n for p in objects:\n if p.metadata_name == \"redis-master\":\n return\n raise ValueError(\"Could not find service loded\")\n\ndef test_load_load_create_exeption():\n k = KubernetesCluster()\n k.load_dir(TEST_CLUSTER_FOLDER)\n k.create_resource(open(TEST_DEPLOYMENT).read())\n try:\n k._build_state()\n except AssertionError as e:\n print(str(e))\n assert str(e) == \"Error from server (AlreadyExists): deployments.apps \\\"redis-master\\\" already exists\"\n objects = filter(lambda x: isinstance(x, Deployment), k.state_objects)\n for p in objects:\n if p.metadata_name == \"redis-master\":\n return\n raise ValueError(\"Could not find service loded\")\n\ndef test_load_limits():\n k = KubernetesCluster()\n k.load_dir(TEST_CLUSTER_FOLDER)\n k.create_resource(open(TEST_DEPLOYMENT).read())\n k._build_state()\n objects = filter(lambda x: isinstance(x, Deployment), k.state_objects)\n for p in objects:\n if p.metadata_name == \"redis-master\" and \\\n p.cpuRequest > -1 and \\\n p.memRequest > -1 and \\\n p.memLimit > -1:\n return\n raise ValueError(\"Could not find service loded\")\n\ndef test_limits_for_pods_created():\n k = KubernetesCluster()\n k.load_dir(TEST_CLUSTER_FOLDER)\n k.create_resource(open(TEST_DEPLOYMENT).read())\n k._build_state()\n objects = filter(lambda x: isinstance(x, Pod), k.state_objects)\n for p in objects:\n if str(p.metadata_name).startswith(\"redis-master\") and \\\n p.cpuRequest > -1 and \\\n p.memRequest > -1 and \\\n p.memLimit > -1:\n return\n raise ValueError(\"Could not find service loded\")\n\ndef test_load_deployment():\n k = KubernetesCluster()\n k.load_dir(TEST_DEPLOYMENT_DUMP)\n k._build_state()\n\ndef test_load_twise_warning():\n k = KubernetesCluster()\n k.create_resource(open(TEST_DEPLOYMENT).read())\n k.create_resource(open(TEST_DEPLOYMENT1).read())","sub_path":"tests/test_deployment.py","file_name":"test_deployment.py","file_ext":"py","file_size_in_byte":3971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"368241606","text":"# Standard\nimport datetime\n\n# Django\nfrom django.http import JsonResponse\n\n# AR\nfrom rank.models import Post\n\nPARAM_DATE_FORMAT = '%Y%m%d%H%M'\n\ndef post_list(request):\n\n result = Post.objects.all()\n\n media_property = request.GET.get('media_property', None)\n if media_property:\n result = result.filter(domain__media_property__name=media_property)\n\n top_place = int(request.GET.get('top_place', 25))\n if top_place:\n result = result.filter(top_place__lte=top_place)\n\n begin_str = request.GET.get('begin', None)\n if begin_str:\n begin = datetime.datetime.strptime(begin_str, PARAM_DATE_FORMAT)\n result = result.filter(created__gte=begin)\n\n return JsonResponse({'result': [p.api_serialize() for p in result]})\n\n \n\n\n\n\n","sub_path":"alienrank/rank/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"35212333","text":"\"\"\"\n 运算符重载\n 增强运算符 += -= *= /= ...\n + 无论可变还是不可变对象,都创建新对象\n\n += 对于可变对象,在原有基础上进行修改\n 对于不可变对象,创建新对象\n 练习:exercise02\n\n\"\"\"\n\n\nclass Vector2:\n \"\"\"\n 二维向量\n \"\"\"\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n # +=\n def __iadd__(self, other):\n # 因为自定义类是可变对象\n # 所以返回原有对象self,不是创建新对象\n self.x += other.x\n self.y += other.y\n return self\n\npos01 = Vector2(1, 2)\nprint(id(pos01))\npos01 += Vector2(3, 4)\nprint(id(pos01))\n\n\"\"\"\n# += 对于可变对象,在原有基础上进行修改\nlist01 = [1]\nprint(id(list01))# 139887136870152\nlist01 += [2]\nprint(id(list01))# 139887136870152\n\n# += 对于不可变对象,创建新对象\ntuple01 = (1,)\nprint(id(tuple01))# 139887167310872\ntuple01 += (2,)\nprint(id(tuple01))# 139887136858376\n\"\"\"\n","sub_path":"month_01/teacher/day12/demo03.py","file_name":"demo03.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"217470084","text":"import torch\nfrom torch.autograd import Variable\n\nfrom .spline import spline\n\nfrom .edgewise_spline_weighting import edgewise_spline_weighting\n\n\ndef spline_conv(\n adj, # Tensor\n input, # Variable\n weight, # Variable\n kernel_size,\n is_open_spline,\n K,\n degree=1,\n bias=None):\n\n values = adj._values()\n row, col = adj._indices()\n\n # Get features for every end vertex with shape [|E| x M_in].\n output = input[col]\n # Convert to [|E| x M_in] feature matrix and calculate [|E| x M_out].\n amount, index = spline(values, kernel_size, is_open_spline, K, degree)\n output = edgewise_spline_weighting(output, weight[:-1], amount, index)\n\n # Convolution via `scatter_add`. Converts [|E| x M_out] feature matrix to\n # [n x M_out] feature matrix.\n zero = output.data.new(adj.size(1), output.size(1)).fill_(0.0)\n zero = Variable(zero) if not torch.is_tensor(output) else zero\n r = row.view(-1, 1).expand(row.size(0), output.size(1))\n output = zero.scatter_add_(0, Variable(r), output)\n\n # Weighten root node features by multiplying with root weight.\n output += torch.mm(input, weight[-1])\n\n # Normalize output by degree.\n ones = values.new(values.size(0)).fill_(1)\n zero = values.new(output.size(0)).fill_(0)\n degree = zero.scatter_add_(0, row, ones)\n degree = torch.clamp(degree, min=1)\n output = output / Variable(degree.view(-1, 1))\n\n if bias is not None:\n output += bias\n\n return output\n","sub_path":"torch_geometric/nn/functional/spline_conv/spline_conv.py","file_name":"spline_conv.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"244397403","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport matplotlib\nmatplotlib.use('agg')\nimport subprocess\nimport os\nimport glob\nimport numpy as np\nimport numpy.fft\nimport pandas as pd\nimport astropy.units as u\nfrom tqdm import tqdm\nfrom pathlib import Path\nfrom astropy.io import fits\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\nfrom matplotlib.patches import Ellipse\nfrom matplotlib.colors import ListedColormap\nfrom mpl_toolkits.axes_grid1.anchored_artists import AnchoredAuxTransformBox\nimport multiprocessing as mp\n'''\n\nTo use this you need to install \n WSClean: https://sourceforge.net/p/wsclean/wiki/Installation/\n and Casa: https://casa.nrao.edu/casa_obtaining.shtml (Don't forget to set path in bashrc)\n\nPreferably your folder structure should look like this /home/.../Sources//data/*.uvf \n\n--convertion from fits files to .ms files--\nThe measurement sets, which are requierd for WSClean, are created from every .uvf file \nand stored within in the data folder in an extra measurement_sets folder.\n--run WSClean--\nWSClean will be run several times per epoch with your requested parameter combinations. The best\noutcomes will be stored in '...//best_epochs//MRun_Run_Nr_/'.\nYou could open the resulting -image.fits for example with ds9 or every other fitsviewer.\n--plot results--\nFor every epoch, there will be a results_ folder with subfolders for the diffrent MRuns.\nWithin you find a data_.hdf file with all parameters and Dynamic Ranges for each run.\nAlso you will find some plots: a plot of the best image, that is to say the image with the highest Dynamic Range, \na plot of the best three images and their corresponding residuals, \na plot for every paramter distribution.\n\nQuestions: yvonne.kasper@tu-dortmund.de\n'''\n\n'''\nFunctions to get the data to desired format\n'''\ndef uvfits_to_ms(input_data, output_data):\n '''\n INPUT_DATA: path to radio image in fits format\n OUTPUT_DATA: path to save casa measurement set\n \n EXAMPLE: uvfits_to_ms('/home/MAXMUSTERMANN/*path to data*/sources//data/.uvf',\n '/home/MAXMUSTERMANN/*Path to data*/sources//data/measurement_sets/.ms')\n \n Converts .uvf files to .ms measurement sets\n\n '''\n in_file = input_data\n out_file = output_data\n parent_path= Path(out_file).parent\n\n casa = 'casa -c '\n arg = \"importuvfits(fitsfile='\"+str(in_file)+\"'\"+\", vis=\"+\"'\"+str(out_file)+\"')\"\n\n \n command = casa + '\"' + arg + '\"'\n\n if os.path.exists(str(out_file)):\n print('Measurement set already exists!')\n elif os.path.exists(str(parent_path))==False:\n subprocess.call([\"mkdir\", str(parent_path) ])\n subprocess.run(command, shell=True)\n else:\n subprocess.run(command, shell=True)\n\n\ndef all_uvf2ms(input_dir):\n '''\n INPUT_DIR: folder with your .uvf files of the source\n\n EXAMPLE: all_uvf2ms('/home/MAXMUSTERMANN/*path to data*//sources//data')\n \n Converts all .uvf files in the input dictionary to .ms files. Saves .ms files in \n measurement_sets folder with original filename. \n \n '''\n data_path = input_dir\n \n files= glob.glob(str(data_path)+'/*.uvf')\n for f in tqdm(files):\n name= Path(f).stem\n uvfits_to_ms(f,str(data_path)+'/measurement_sets/'+str(name)+'.ms')\n\n\ndef all_data2ms(data_path,data_type):\n '''\n INPUT_DIR: folder with your .data_type files of the source\n DATA_TYPE: data type of your data.\n EXAMPLE: all_data2ms('/home/MAXMUSTERMANN/*path to data*/sources//data', 'uvf')\n \n Converts all .data_type files in the input dictionary to .ms files, Saves .ms files in \n measurement_sets folder with original filename. \n \n '''\n \n files= glob.glob(str(data_path)+'/*.'+str(data_type))\n for f in tqdm(files):\n name= Path(f).stem\n uvfits_to_ms(f,str(data_path)+'/measurement_sets/'+str(name)+'.ms')\n\n'''\nFunctions for actual cleaning\n'''\n\ndef run_wsclean(data_path, model_name, xsize, ysize, scale, niter = 1000000,\n mgain=0.8, auto_thresh=6, gain=0.1, auto_mask=3,\n weight=0, rank_filter=3, multiscale=True,\n scale_bias=0.6, model=False, predict=False,\n ):\n '''\n DATA_PATH: path to radio data in fits format\n MODEL_NAME: name for the cleaned image and models\n XSIZE,YSIZE: desired size of the image in pixle\n SCALE: angular size of a single pixel\n ...\n\n Example: run_wsclean('/home/MAXMUSTERMANN/*path_to_data*/sources//data/measurement_sets/.ms/',\n 'name_of_measurement', 1024, 1024, 0.1)\n\n Runs wsclean with choosen parameters. The cleaning will be stopped after five minutes. The used parameters are saved \n in an textfile for further juse.\n\n '''\n parent_path= Path(data_path).parent\n parent2_path= Path(parent_path).parent\n parent3_path= Path(parent2_path).parent\n measurement=Path(data_path).stem\n\n out_dict = str(parent3_path) +'/epochs/' + measurement \n out_dict2 = str(out_dict) +'/'+ str(model_name) \n\n \n command = 'wsclean '\n if multiscale is True:\n command = command \\\n +'-quiet ' \\\n\t +'-j '+str(3)+' ' \\\n +'-multiscale ' \\\n +' -size ' + str(xsize) + ' ' + str(ysize) \\\n + ' -scale ' + str(scale) + 'masec' \\\n + ' -niter ' + str(niter) \\\n + ' -mgain ' + str(mgain) \\\n + ' -gain ' + str(gain) \\\n + ' -auto-mask ' + str(auto_mask) \\\n + ' -weight briggs ' + str(weight) \\\n + ' -multiscale-scale-bias ' + str(scale_bias) \\\n + ' -auto-threshold ' + str(auto_thresh) \\\n + ' -name ' + str(out_dict2)+'/'+str(model_name) \\\n + ' ' + str(data_path)\n else:\n command = command \\\n +'-quiet ' \\\n +' -size ' + str(xsize) + ' ' + str(ysize) \\\n + ' -scale ' + str(scale) + 'masec' \\\n + ' -niter ' + str(niter) \\\n + ' -mgain ' + str(mgain) \\\n + ' -gain ' + str(gain) \\\n + ' -auto-mask ' + str(auto_mask) \\\n + ' -weight briggs ' + str(weight) \\\n + ' -auto-threshold ' + str(auto_thresh) \\\n + ' -name ' + str(out_dict2)+'/'+str(model_name) \\\n + ' ' + str(data_path) \n #create folder for wsclean output\n \n if os.path.exists(out_dict2)==False:\n subprocess.call([\"mkdir\", str(out_dict2)])\n \n # run command (with timelimit of five minutes) and save textfile with parameters\n print('...WSCleaning...')\n\n try:\n subprocess.run(command, shell=True, timeout = 300)\n f = open(str(out_dict2)+\"/\" + \"parameter_info.txt\", \"w+\")\n f.write(str(xsize) + ' ' + str(ysize)+ ' ' \\\n +str(scale)+ ' ' + str(niter)+ ' ' \\\n +str(mgain) + ' '+ str(gain)+ ' ' \\\n +str(auto_mask)+ ' ' + str(auto_thresh)+ ' ' \\\n +str(scale_bias))\n\n except subprocess.TimeoutExpired: \n f = open(str(out_dict2)+\"/\" + \"parameter_info.txt\", \"w+\")\n f.write(str(xsize) + ' ' + str(ysize)+ ' ' \\\n +str(scale)+ ' ' + str(niter)+ ' ' \\\n +str(mgain) + ' '+ str(gain)+ ' ' \\\n +str(auto_mask)+ ' ' + str(auto_thresh)+ ' ' \\\n +str(scale_bias) +' WSCLEAN DID NOT TERMINATED!')\n print(' WSCLEAN DID NOT TERMINATED!') \n #There are certainly some more suitable data formats, but this works fore the moment.\n \ndef run_grid(data_path, model_name, \n xsize, ysize, scale, \n niter= 5000,\n mgain_min=0.6875, mgain_max=0.7250, mgain_steps=4,\n gain_min=0.04, gain_max = 0.0675, gain_steps =4,\n auto_mask_min=2, auto_mask_max =4, auto_mask_steps = 4,\n auto_thresh_min=0.2, auto_thresh_max=0.7, auto_thresh_steps = 4,\n weight_min=-1, weight_max =1, weight_step = 3, \n rank_filter=3, \n multiscale=True,\n scale_bias_min=0.5,scale_bias_max=0.7,scale_bias_step=4,\n model=False, \n predict=False, run_nr =0):\n ''' \n DATA_PATH: path to .ms file\n MODEL_NAME: name for the cleaned image and models\n XSIZE,YSIZE: desired size of the image in pixle\n SCALE: angular size of a single pixel\n PARAMETER_MAX: highest possible value for the parameter\n PARAMETER_MIN: lowest possible value for the parameter\n PARAMETER_step: amout of steps in the value space\n ...\n RUN_NR: number of MRun, accordingly for the inital grid run_nr = 0\n\n EXAMPLE: run_grid('/home/MAXMUSTERMANN/*path to data*/sources//data/measurement_sets/.ms/',\n 'name of measurement',1024,1024,0.1)\n \n Creates an inital parametergrid out of the given values, calls run_wsclean and saves the output in the epochs\n folder. Creates results folder for each epoch with subfolders for the MRuns.\n The parametersets are saved in the data_.hdf with key:'ParamSets'\n '''\n parent_path= Path(data_path).parent\n parent2_path= Path(parent_path).parent\n parent3_path= Path(parent2_path).parent\n \n #creation of the paramsets\n mgain = np.linspace(mgain_min, mgain_max, num = mgain_steps)\n gain = np.linspace(gain_min, gain_max, num = gain_steps)\n automask =np.linspace(auto_mask_min, auto_mask_max, num = auto_mask_steps) \n autothresh = np.linspace(auto_thresh_min, auto_thresh_max, num = auto_mask_steps)\n weight =np.linspace(weight_min, weight_max, num =weight_step)\n scale_bias = np.linspace(scale_bias_min, scale_bias_max, num =scale_bias_step)\n i = 0\n print(model_name)\n print(mgain)\n print(gain)\n print(automask)\n print(autothresh)\n print(weight)\n print(scale_bias)\n \n #create epochs folder\n if os.path.exists(str(parent3_path)+'/epochs')==False:\n subprocess.call([\"mkdir\", str(parent3_path)+'/epochs/'])\n \n #creates subfolder for every epoch\n if os.path.exists(str(parent3_path)+'/epochs/'+str(model_name))==False:\n subprocess.call([\"mkdir\", str(parent3_path)+'/epochs/'+str(model_name)])\n \n #creates results folder for each epoch\n if os.path.exists(str(parent3_path)+'/results_'+str(model_name))==False:\n subprocess.call([\"mkdir\", str(parent3_path)+'/results_'+str(model_name)+'/'])\n \n #creates subfolder for the MRun\n if os.path.exists(str(parent3_path)+'/results_'+str(model_name)+'/MRun_'+str(run_nr))==False:\n subprocess.call([\"mkdir\", str(parent3_path)+'/results_'+str(model_name)+'/MRun_'+str(run_nr)]) \n \n for m in mgain:\n for am in automask:\n for a in autothresh:\n for w in weight:\n for g in gain:\n for s in scale_bias:\n run_wsclean(str(data_path),\n 'Run_Nr'+str(i)+'_'+str(model_name),\n xsize, ysize, scale,\n niter= niter, mgain=m, gain = g,\n auto_mask = am, auto_thresh= a,\n weight = w, scale_bias = s)\n i=i+1\n \n #creates a dataframe with the parametersets and saves them in the hdf with key:'ParamSets'\n df = pd.DataFrame((mgain, gain, automask, autothresh, weight, scale_bias),\n index=['mgain', 'gain', 'auto_mask', 'auto_thresh', 'weight', 'scale_bias']) \n \n df.to_hdf(str(parent3_path)+'/results_'+str(model_name)+'/MRun_'+str(run_nr)+'/data_'+str(Path(parent3_path).stem)+'.h5', 'ParamSets')\n\ndef run_another_grid(path_to_hdf, path_to_ms, number_paramspace, xsize =1024, ysize = 1024, scale = 0.1,\n niter= 5000, rank_filter=3, multiscale=True, model=False, \n predict=False, run_nr=0):\n ''' \n PATH_TO_HDF: path to .hdf file with data of the initial grid\n PATH_TO_MS: path to the measurement_sets\n NUMBER_PARAMSPACE: amout of values in the new paramspace\n XSIZE,YSIZE: desired size of the image in pixle\n SCALE: angular size of a single pixel\n ...\n RUN_NR: number of MRun, accordingly the number of the grid\n\n EXAMPLE: run_another_grid('/home/MAXMUSTERMANN/*path to data*/TXS/results_0149+710.u.2018_02_02/MRun_1/data.hdf',\n str(Path(path_to_data).parent)+'/measurement_sets/'+str(name)+'.ms',\n number_paramspace=3, xsize =1024, ysize = 1024, scale = 0.1,\n niter= 5000, rank_filter=3, multiscale=True, model=False, \n predict=False, run_nr=2) \n\n Calls get_new_paramspace(...) to create new parameter spaces for each parameter. Calls run_grid(...) to run another grid.\n '''\n #creating new parameter spaces for each parameter\n number = number_paramspace \n mgain_min, mgain_max, mgain_steps = get_new_paramspace(path_to_hdf, 'mgain', number, run_nr=run_nr)\n gain_min, gain_max, gain_steps = get_new_paramspace(path_to_hdf, 'gain', number, run_nr=run_nr)\n auto_mask_min, auto_mask_max, auto_mask_steps = get_new_paramspace(path_to_hdf, 'auto_mask', number, run_nr=run_nr)\n auto_thresh_min, auto_thresh_max, auto_thresh_steps = get_new_paramspace(path_to_hdf, 'auto_thresh', number, run_nr=run_nr)\n weight_min, weight_max, weight_step = get_new_paramspace(path_to_hdf, 'weight', number, run_nr=run_nr)\n scale_bias_min,scale_bias_max,scale_bias_step = get_new_paramspace(path_to_hdf, 'scale_bias', number, run_nr=run_nr)\n\n #run new grid with run_grid\n name=Path(path_to_ms).stem\n run_grid(path_to_ms, name, xsize, ysize, scale, niter,\n mgain_min, mgain_max, mgain_steps,\n gain_min, gain_max, gain_steps,\n auto_mask_min, auto_mask_max, auto_mask_steps,\n auto_thresh_min, auto_thresh_max, auto_thresh_steps,\n weight_min, weight_max, weight_step,\n rank_filter, multiscale,\n scale_bias_min,scale_bias_max,scale_bias_step,\n model, predict,run_nr)\n\n\n'''\nFunction to delete unnecessary data\n'''\n\ndef delete_data(path_to_hdf, value, run_nr):\n '''\n PATH_TO_DATA: Path to data_{}.hdf file\n VALUE: amout of images to preserve\n\n Example: delete_data(/home/MAXMUSTERMANN/*path to Data*/TXS/results_0149+710.u.2018_02_02/MRun_1/data.hdf', 3, 0)\n \n Saves the best WSClean output.The amount is given by VALUE. \n Adds the Number of MRun to the data name, to avoid loosing data in later MRuns.\n Copies the best WSClean output to BestEpochs folder. \n Deletes everything in the epochs folder.\n\n '''\n #get paths to best data\n df = pd.read_hdf(path_to_hdf, key = 'df')\n sorted_df = df.sort_values(by=['DR'], axis = 1, ascending=False).iloc[:,0:value]\n listed = sorted_df.loc['path',:].tolist()\n\n parent_path= Path(listed[0]).parent\n parent2_path= Path(parent_path).parent\n parent3_path= Path(parent2_path).parent #../Source//results<...>\n parent4_path= Path(parent3_path).parent #'../Source/\n \n #create new folder for best epochs\n if os.path.exists(str(parent4_path)+'/BestEpochs')==False:\n subprocess.call([\"mkdir\", str(parent4_path)+'/BestEpochs/'])\n\n #rename and copy best epochs \n for listedpath in listed:\n old = str(Path(listedpath).parent)\n name = old.split('/')[-1]\n command = 'mv ' + str(Path(listedpath).parent)+'/ '+ str(Path(listedpath).parent.parent)+'/MRun'+str(run_nr)+'_'+str(name)+'/'\n subprocess.call(command, shell=True)\n command2='cp -r ' + str(Path(listedpath).parent.parent)+'/MRun'+str(run_nr)+'_'+str(name)+'/ '+ str(parent4_path)+'/BestEpochs/'\n subprocess.call(command2, shell=True)\n \n #delete everything in the epochs folder\n command3 = 'rm -rf ' +str(parent4_path)+'/epochs/*'\n subprocess.call(command3, shell=True)\n'''\nFunctions to get specific quantities\n'''\n\ndef get_rms(image):\n '''\n IMAGE: image data of the image.fits\n\n Example: get_rms(fits.open(str(path_to_data))[0])\n Calculates the rms (root mean square) in all four corners of the image with some distance to the source.\n '''\n x0=int(image.header['CRPIX1'])-75\n x1=int(image.header['CRPIX1'])+75\n y0=int(image.header['CRPIX2'])-75\n y1=int(image.header['CRPIX2'])+75\n \n image_data = image.data[0,0,:,:]\n lower_left = np.sqrt(np.mean(np.square(image_data[0:x0,0:y0])))\n lower_right = np.sqrt(np.mean(np.square(image_data[x1:image.header['NAXIS1'],0:y0])))\n upper_left = np.sqrt(np.mean(np.square(image_data[0:x0,y1:image.header['NAXIS2']])))\n upper_right = np.sqrt(np.mean(np.square(image_data[x1:image.header['NAXIS2'],y1:image.header['NAXIS2']])))\n x = np.array([lower_left,lower_right,upper_left,upper_right])\n return(np.mean(x)) \n \ndef get_dynamic_range(path_to_data):\n '''\n PATH_TO_DATA: path to the *-image.fits file\n\n Example: get_dynamic_range('/home/MAXMUSTERMANN/*path to data*/IC310/epochs/0313+411.u.2014_05_12/\n Run_Nr67_0313+411.u.2014_05_12/Run_Nr67_0313+411.u.2014_05_12-image.fits')\n\n Calculates the Dynamic Range of the image. The Dynamic Range is definded as \n max peak flux/ rms of pic.\n '''\n\n data_file = fits.open(str(path_to_data))\n data =data_file[0]\n rms= get_rms(data)\n im_data = data.data[0,0,:,:]\n peak = im_data.max() \n return peak/rms \n\ndef get_params(path_to_data):\n '''\n PATH_TO_DATA: path to the *-image.fits\n\n Example: get_params(str(path_to_data)+/*-image.fits')\n\n Function gets all important cleaning parameter and returns them as a list\n '''\n parent = Path(path_to_data).parent\n xsize, ysize, scale, niter, mgain, gain, auto_mask, auto_thresh, scale_bias = np.genfromtxt(str(parent)+'/parameter_info.txt', unpack=True)\n data_file = fits.open(str(path_to_data))\n data =data_file[0]\n weight_string = data.header['WSCWEIGH']\n weight = float(weight_string.replace(\"Briggs'(\", \"\").replace(')',''))\n DRange = get_dynamic_range(path_to_data)\n paramslist = (xsize, ysize, scale, niter, mgain, gain, auto_mask, auto_thresh, weight, scale_bias, DRange, str(path_to_data))\n return paramslist\n\ndef get_all_parameters(path_to_data, run_nr=0):\n '''\n PATH_TO_DATA: Path to the folder in the epoch folder : .../epochs/name\n RUN_NR: number of MRun\n\n Example: get_all_parameters('/home/MAXMUSTERMANN/*path to data*/IC310/epochs/0313+411.u.2014_05_12')\n \n Collects all parameter of evey image in given data and stores them\n in an dataframe with image names as columns and parameter as row index:\n\n Output Example:\n Run_Nr3156_0149+710.u.2017_01_28-image\n xsize 1024\n ysize 1024\n scale 0.1\n niter 500000\n mgain 0.952\n gain 0.08\n auto_mask 1.8725\n auto_thresh 3.75\n weight Briggs'(-0.5)\n ... ... \n \n '''\n im = glob.glob(str(path_to_data)+'/**/*-image.fits')\n dicti = {}\n for i in tqdm(im) :\n dicti[str(Path(i).stem)] = (get_params(i))\n\n df = pd.DataFrame(dicti,index=['xsize', 'ysize', 'scale', 'niter', 'mgain','gain', 'auto_mask',\n 'auto_thresh', 'weight', 'scale_bias', 'DR', 'path'])\n df = df.dropna(axis='columns') \n #print(df.sort_values(by=['DR'], axis = 1).iloc[:,0:3]) #first 3\n #print(df.sort_values(by=['DR'], axis = 1).iloc[:,-3:]) #last 3\n name = im[0].split('/')[-5]\n model_name= str(path_to_data).split('/')[-1]\n print(im)\n df.to_hdf(str(Path(path_to_data).parent.parent)+'/results_'+str(model_name)+'/MRun_'+str(run_nr)+'/data_'+str(name)+'.h5', 'df')\n return(df)\n\ndef get_new_paramspace(path_to_hdf, param, number, run_nr):\n '''\n PATH_TO_HDF: Path to the .hdf file with the results of the previous grid\n PARAM: The Parameter to find a new value space for\n NUMBER: Amount of values for the new space\n RUN_NR: Number of the current MRun\n\n Example: get_new_paramspace('/home/MAXMUSTERMANN/*path to data*/IC310/results_0313+411.u.2014_05_12/MRun_1/data_IC310.h5', 'mgain', number=3, run_nr=2)\n\n Creates a new parameter space for the next grid, based on the parameters of the best image in\n the previous run. \n If there is only one value given, this is value is used again as the only one for the next grid.\n Some parameters (weight and scale_bias) can be assuemed to be satisfactorily determined\n after two grid runs. To save computational time, these will be set to the best value after \n two runs. \n '''\n #get old paramsets and get rid of unused data\n ParamSets = pd.read_hdf(path_to_hdf, 'ParamSets')\n df = pd.read_hdf(path_to_hdf, 'df')\n df_new = df.transpose()\n df_short = df_new.drop(['xsize','ysize','scale','niter','path'], axis =1) \n\n #get parameter value of the best image\n df_DR = df_short.sort_values(by=['DR'], axis = 0, ascending=False)\n bestDRvalues = df_DR.iloc[0]\n bestParam = bestDRvalues.loc[param]\n\n #if only one value is given, keep it\n if len(ParamSets.loc[param].dropna())==1:\n return(bestParam, bestParam, 1)\n \n #dont change weight and scalebias values after third MRun\n if run_nr >= 2 and param == 'weight':\n return(bestParam, bestParam, 1)\n if run_nr >= 2 and param == 'scale_bias':\n return(bestParam, bestParam, 1) \n\n #get position of best value\n ParamRange = ParamSets.loc[param].values[:]\n spacing = np.abs(ParamRange[1]-ParamRange[0])\n mask = np.zeros_like(ParamRange)\n mask[ParamRange == bestParam]=1\n\n # weight needs to be between -1 and 1\n if param =='weight':\n if mask[0]==1: \n end = 0\n space = np.abs((end-bestParam)/number)\n stop = end-space\n return (bestParam, stop, number)\n\n elif mask[-1]==1: \n end = 0\n space = np.abs((end-bestParam)/number)\n start = end+space\n return (start, bestParam, number)\n\n else :\n newSpacing = spacing/(number-(number/2))\n start= bestParam - ((number-1)/2)*newSpacing\n if start < -1: \n start = -1\n stop= bestParam + ((number-1)/2)*newSpacing\n if stop >1:\n stop=1\n return (start, stop, number)\n\n #gain and mgain need to be >0\n if param == 'gain' or 'mgain':\n if mask[0]==1: \n start= bestParam-(spacing/(2*run_nr)*number)\n if start <0:\n start =0.000001\n return (start, bestParam, number)\n\n elif mask[-1]==1: \n end= bestParam+(spacing/(2*run_nr)*(number))\n if end <1:\n end =0.99999\n return (bestParam,end, number)\n\n else :\n newSpacing = spacing/(number-(number/2))\n start= bestParam - ((number-1)/2)*newSpacing\n stop= bestParam + ((number-1)/2)*newSpacing\n if start<0 :\n start = 0.000001\n if stop >1 :\n stop = 0.99999 \n return (start, stop, number) \n\n # everything else\n # if best value is on the far left\n if mask[0]==1: \n start= bestParam-(spacing/(2*run_nr)*number)\n return (start, bestParam, number)\n\n #if best value is on the far right\n elif mask[-1]==1: \n end= bestParam+(spacing/(2*run_nr)*(number))\n return (bestParam,end, number)\n\n #if value is not at the edge\n else :\n newSpacing = spacing/(number-(number/2))\n start= bestParam - ((number-1)/2)*newSpacing\n stop= bestParam + ((number-1)/2)*newSpacing\n return (start, stop, number)\n\n'''\nFunctions to plot data\n'''\n \n\ndef get_best_pictures(path_to_hdf, sourcename, run_nr=0):\n '''\n PATH_TO_HDF: Path to .hdf file with results of the grid.\n RUN_NR: Number of MRun. Used for output path.\n SOURCENAME: Name of the Source. Used for the title.\n\n Creates plot with six subplots. Three best clean images with corresponding residuals.\n Coordinates are in pixel and (yet) without a beam.\n '''\n\n df = pd.read_hdf(path_to_hdf, 'df')\n sorted_df = df.sort_values(by=['DR'], axis = 1).iloc[:,-3:]\n listed = sorted_df.loc['path',:].tolist()\n Drange = sorted_df.loc['DR',:].tolist()\n #print(Drange)\n \n im1 = fits.open(listed[0])[0].data[0,0,:,:]\n im2 = fits.open(listed[1])[0].data[0,0,:,:]\n im3 = fits.open(listed[2])[0].data[0,0,:,:]\n\n name1 = Path(listed[0]).stem\n parent1 = Path(listed[0]).parent\n path_to_resi1 = str(parent1) +'/'+ str(name1.split('-')[0])+'-residual.fits' \n name2 = Path(listed[1]).stem\n parent2 = Path(listed[1]).parent\n path_to_resi2 = str(parent2) +'/'+ str(name2.split('-')[0])+'-residual.fits' \n name3 = Path(listed[2]).stem\n parent3 = Path(listed[2]).parent\n path_to_resi3 = str(parent3) +'/'+ str(name3.split('-')[0])+'-residual.fits' \n print(name1)\n print(name2)\n print(name3)\n epoch = name1.split('-')[0].split('.u.')[-1]\n nice_year=str(epoch).split('_')[0]\n nice_month=str(epoch).split('_')[1]\n nice_day=str(epoch).split('_')[2]\n re1 = fits.open(path_to_resi1)[0].data[0,0,:,:]\n re2 = fits.open(path_to_resi2)[0].data[0,0,:,:]\n re3 = fits.open(path_to_resi3)[0].data[0,0,:,:]\n\n fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(nrows=2, ncols=3, figsize=[12, 9])\n fig.suptitle('Best three images of '+str(sourcename) + ', Epoch: '+str(nice_day)+'.'+str(nice_month)+'.'+str(nice_year), fontsize=20)\n\n ax1.set_title('DR='+ str(Drange[0]))\n ax1.set_xlabel('Pixel')\n ax1.set_ylabel('Pixel')\n plt1 = ax1.imshow(im1,origin='lower',\n cmap='hot',\n norm = colors.SymLogNorm(linthresh=0.0001, \n linscale=0.0001, vmin= -0.001345288, vmax=0.09435418) )\n ax1.set_ylim(400,700)\n ax1.set_xlim(400,700) \n fig.colorbar(plt1, ax=ax1, ticks = [(-1e-3, 0, 1e-3, 1e-2)] , fraction=0.046, pad=0.04, label='Flux in Jy/beam')\n \n ax2.set_title('DR='+ str(Drange[1]))\n ax2.set_xlabel('Pixel')\n ax2.set_ylabel('Pixel')\n plt2 = ax2.imshow(im2,origin='lower',\n cmap='hot',\n norm = colors.SymLogNorm(linthresh=0.0001, \n linscale=0.0001, vmin= -0.001345288, vmax=0.09435418) )\n ax2.set_ylim(400,700)\n ax2.set_xlim(400,700) \n fig.colorbar(plt2, ax=ax2, ticks = [(-1e-3, 0, 1e-3, 1e-2)] , fraction=0.046, pad=0.04, label='Flux in Jy/beam')\n\n ax3.set_title('DR='+ str(Drange[2]))\n ax3.set_xlabel('Pixel')\n ax3.set_ylabel('Pixel')\n plt3 = ax3.imshow(im3,origin='lower',\n cmap='hot',\n norm = colors.SymLogNorm(linthresh=0.0001, \n linscale=0.0001, vmin= -0.001345288, vmax=0.09435418) )\n ax3.set_ylim(400,700)\n ax3.set_xlim(400,700) \n fig.colorbar(plt3, ax=ax3, ticks = [(-1e-3, 0, 1e-3, 1e-2)] ,fraction=0.046, pad=0.04, label='Flux in Jy/beam')\n\n ax4.set_title('Corresponding Residual')\n ax4.set_xlabel('Pixel')\n ax4.set_ylabel('Pixel')\n plt4 = ax4.imshow(re1,origin='lower',\n cmap='hot',\n norm = colors.SymLogNorm(linthresh=0.0001, \n linscale=0.0001, vmin= -0.001345288, vmax=0.09435418) )\n ax4.set_ylim(400,700)\n ax4.set_xlim(400,700) \n fig.colorbar(plt4, ax=ax4, ticks = [(-1e-3, 0, 1e-3, 1e-2)] , fraction=0.046, pad=0.04, label='Flux in Jy/beam')\n\n ax5.set_title('Corresponding Residual')\n ax5.set_xlabel('Pixel')\n ax5.set_ylabel('Pixel')\n plt5 = ax5.imshow(re2,origin='lower',\n cmap='hot',\n norm = colors.SymLogNorm(linthresh=0.0001, \n linscale=0.0001, vmin= -0.001345288, vmax=0.09435418) )\n ax5.set_ylim(400,700)\n ax5.set_xlim(400,700) \n fig.colorbar(plt5, ax=ax5, ticks = [(-1e-3, 0, 1e-3, 1e-2)] , fraction=0.046, pad=0.04, label='Flux in Jy/beam')\n\n ax6.set_title('Corresponding Residual')\n ax6.set_xlabel('Pixel')\n ax6.set_ylabel('Pixel')\n plt6 = ax6.imshow(re3,origin='lower',\n cmap='hot',\n norm = colors.SymLogNorm(linthresh=0.0001, \n linscale=0.0001, vmin= -0.001345288, vmax=0.09435418) )\n fig.colorbar(plt6, ax=ax6, ticks = [(-1e-3, 0, 1e-3, 1e-2)] , fraction=0.046, pad=0.04, label='Flux in Jy/beam')\n ax6.set_ylim(400,700)\n ax6.set_xlim(400,700) \n plt.tight_layout()\n \n plt.savefig(str(Path(path_to_hdf).parent)+'/Best3_MRun_'+str(run_nr)+'.png')\n plt.clf()\t\n\ndef get_nicest_picture(path_to_hdf, sourcename, run_nr):\n '''\n PATH_TO_HDF: Path to .hdf file with results of the grid.\n RUN_NR: Number of MRun. Used for the title and output path.\n SOURCENAME: Name of the Source. Used for the title.\n\n Creates a nice plot in relativ R.A. and relativ Declination (both in mas) \n coordinates with five contourlines as logspace between min and max of data.\n '''\n df = pd.read_hdf(path_to_hdf, 'df')\n sorted_df = df.sort_values(by=['DR'], axis = 1).iloc[:,-3:]\n listed = sorted_df.loc['path',:].tolist()\n Drange = sorted_df.loc['DR',:].tolist()\n \n image = fits.open(listed[0])[0]\n\n im1 = image.data[0,0,:,:]\n header = image.header\n name1 = Path(listed[0]).stem\n epoch = name1.split('-')[0].split('.u.')[-1]\n \n \n scale = np.logspace(np.log10(np.absolute(im1.min())), np.log10(im1.max()), 5)\n\n x_n_pixel = header['NAXIS1']\n\n x_inc = (header['CDELT1'] * u.degree).to(u.mas) \n x_ref_value = (header['CRVAL1'] * u.degree).to(u.mas)\n y_n_pixel = header['NAXIS2']\n\n\n y_inc = (header['CDELT2'] * u.degree).to(u.mas)\n y_ref_value = (header['CRVAL2'] * u.degree).to(u.mas)\n\n x_ref_pixel = header['CRPIX1']\n y_ref_pixel = header['CRPIX2']\n\n x = np.linspace(x_ref_pixel * -x_inc, (x_n_pixel - x_ref_pixel) * (x_inc), x_n_pixel)\n y = np.linspace(y_ref_pixel * -y_inc, (y_n_pixel - y_ref_pixel) * y_inc, y_n_pixel)\n\n bmin = (header['BMIN'] * u.degree).to(u.mas)\n bmaj = (header['BMAJ'] * u.degree).to(u.mas)\n fig, ax = plt.subplots(figsize=(8,6))\n\n im = plt.pcolormesh(x,y,im1,\n cmap='hot',\n norm = colors.SymLogNorm(linthresh=0.0001, \n linscale=0.0001, vmin= -0.001345288, vmax=0.09435418) )\n \n cont = plt.contour(x,y, im1,\n scale,\n colors='white',linewidths = 1, linestyles='solid',\n norm = colors.SymLogNorm(linthresh=0.0001, \n linscale=0.0001, vmin= -0.001345288, vmax=0.09435418))\n \n #cbar = plt.colorbar(im, ticks = [-0.001, 0, 0.001, 0.01], label='Flux in Jy/beam')\n cbar = plt.colorbar(im, ticks = [(-1e-3, 0, 1e-3, 1e-2)] , label='Flux in Jy/beam')\n plt.ylim([-15, 20])\n plt.xlim([15, -20])\n nice_year=str(epoch).split('_')[0]\n nice_month=str(epoch).split('_')[1]\n nice_day=str(epoch).split('_')[2]\n\n plt.xlabel('Relativ R.A. in mas')\n plt.ylabel('Relativ Declination in mas')\n plt.title(str(sourcename)+' '+'Epoch: '+str(nice_day)+'.'+str(nice_month)+'.'+str(nice_year)+' MRun '+str(run_nr))\n \n box = AnchoredAuxTransformBox(ax.transData, loc='lower left', frameon = False)\n el = Ellipse((0, 0), width=bmin.value, height=bmaj.value, angle = -header['BPA'],color='white',ec='k',alpha =0.75) \n box.drawing_area.add_artist(el)\n\n ax.add_artist(box)\n #cbar.ax.set_ylabel('Flux in Jy/beam')\n plt.tight_layout()\n plt.savefig(str(Path(path_to_hdf).parent)+'/BestOne_MRun_'+str(run_nr)+'.png')\n plt.clf()\n\ndef plot_parameterplot(path_to_hdf, Parameter):\n '''\n PATH_TO_HDF: Path to the .hdf file with the results of the previous grid\n PARAMETER: The Parameter to find a new value space for\n\n Example: plot_parameterplot('/home/MAXMUSTERMANN/*path to data*/IC310/results_0313+411.u.2014_05_12/MRun_1/data_IC310.h5', 'mgain')\n\n Plots an histogram of the distribution of values in the parameterspace.\n Shows how many images are within a certain range of Dynamic Ranges when beeing cleand with a certain value.\n '''\n #get paramspace and dataframe with results\n ParamSets = pd.read_hdf(path_to_hdf, 'ParamSets')\n df = pd.read_hdf(path_to_hdf, 'df')\n df_new = df.transpose()\n df_short = df_new.drop(['xsize','ysize','scale','niter','path'], axis =1) \n\n #sort by DR\n df_DR = df_short.sort_values(by=['DR'], axis = 0, ascending=False)\n bestDRvalue = df_DR['DR'].values[0]\n \n Drange2= df_DR.loc[:,'DR'].tolist()\n\n # find index where the DR gets less than xy% of best DR\n Drange = np.array(Drange2)\n ind1 = len(Drange[Drange>0.9*bestDRvalue])\n ind2 = len(Drange[Drange>0.5*bestDRvalue])\n ind3 = len(Drange[Drange>0.3*bestDRvalue])\n \n #fill arrays to hist \n a = np.array([df_DR.iloc[0][str(Parameter)]])\n b = df_DR.iloc[1:ind1][str(Parameter)].values[:]\n c = df_DR.iloc[ind1:ind2][str(Parameter)].values[:]\n d = df_DR.iloc[ind2:ind3][str(Parameter)].values[:]\n\n space = ParamSets.loc[str(Parameter)].dropna().values[:]\n\n #calculate bins\n if len(space) == 1:\n bins = np.array([space[0]-space[0]/2, space[0], space[0]+space[0]/2])\n bins = np.sort(bins)\n center = (bins[:-1]+bins[1:])/2\n start = space[0]-space[0]/2 \n stop = space[0]+space[0]/2\n\n else: \n start = space[0]+(space[0]-space[1])\n stop = space[-1]-(space[0]-space[1])\n #print(space)\n bins = np.linspace(start, stop, len(space)+2)\n center = (bins[:-1]+bins[1:])/2\n\n newbins = np.sort(center)\n\n #plot\n plt.figure()\n plt.hist([a,b,c,d],newbins,ec='k', histtype='barstacked', lw=1,stacked=True, color=['#80BA26', '#6B6B6B', '#919191', '#BFBFBF'])\n plt.ylim(0.1, 1000)\n plt.xlim(start,stop)\n plt.xticks(space)\n plt.yscale('log')\n plt.xlabel(str(Parameter))\n plt.ylabel('Number of Pictures')\n plt.tight_layout()\n plt.savefig(str(Path(path_to_hdf).parent)+'/Parameterplot_'+str(Parameter)+'.pdf')\n plt.clf()\n plt.close('all')\n\ndef plot_all_parameterplots(path_to_hdf):\n '''\n PATH_TO_HDF: Path to the .hdf file with the results of the previous grid\n PARAMETER: The Parameter to find a new value space for\n\n Example: plot_all_parameterplots('/home/MAXMUSTERMANN/*path to data*/IC310/results_0313+411.u.2014_05_12/MRun_1/data_IC310.h5')\n\n Calls plot_parameterplot(...) for every varied parameter\n '''\n paramSets = pd.read_hdf(path_to_hdf, 'ParamSets')\n params = paramSets.index.values\n for param in params:\n plot_parameterplot(path_to_hdf, param)\n print(param, 'done')\n\n'''\nDO EVERYTHING\n'''\ndef do_everything(path_to_data):\n '''\n PATH_TO_DATA: path to the .uvf files\n\n Example: do_everything('/home/MAXMUSTERMANN/*path to data*/IC310/data/0313+411.u.2014_05_12.uvf')\n\n There are things you need to change in this function to customize your grid:\n number_MRuns: number of grids that are processed consecutively\n run_grid(...): parameter space for the inital grid\n\n WSClean will be run several times, with the every parameter combination prepared by the grid.\n This will be done as often as you like, with a automaticaly adjusted parameter space for the grid. \n '''\n #choose your desired amout of MRuns\n number_MRuns = 3\n\n name = Path(path_to_data).stem #0313+411.u.2013_05_05\n path_to_ms= str(Path(path_to_data).parent)+'/measurement_sets/'+str(name)+'.ms'\n uvfits_to_ms(path_to_data, path_to_ms)\n source = str(path_to_ms).split('/')[-4]\n sourcename = Path(path_to_data).parent.parent.stem\n run_nr = 0\n\n #choose the initial parameters and the parameter spaces for your grid\n run_grid(path_to_ms, name, \n xsize=1024, ysize=1024, scale=0.1, \n niter= 5000,\n mgain_min=0.5, mgain_max=0.95, mgain_steps=3,\n gain_min=0.05, gain_max = 0.1, gain_steps =3,\n auto_mask_min=2, auto_mask_max =3, auto_mask_steps = 3,\n auto_thresh_min=0.5 ,auto_thresh_max=4, auto_thresh_steps = 3,\n weight_min=-1, weight_max =1, weight_step = 3, \n rank_filter=3, \n multiscale=True,\n scale_bias_min=0.5,scale_bias_max=0.7,scale_bias_step=3,\n model=False, \n predict=False, run_nr =run_nr) \n path_to_epochs= str(Path(path_to_ms).parent.parent.parent)+'/epochs' \n get_all_parameters(str(path_to_epochs)+'/'+str(name), run_nr=run_nr)\n path_to_hdf= str(Path(path_to_ms).parent.parent.parent)+'/results_'+str(name)+'/MRun_'+str(run_nr)+'/data_'+str(source)+'.h5'\n get_best_pictures(path_to_hdf, sourcename, run_nr=run_nr)\n get_nicest_picture(path_to_hdf, sourcename, run_nr=run_nr)\n plot_all_parameterplots(path_to_hdf)\n delete_data(path_to_hdf, 3, 0)\n \n for run_nr in np.linspace(1, number_MRuns-1, num=number_MRuns-1):\n run_nr = int(run_nr)\n run_another_grid(path_to_hdf, path_to_ms, number_paramspace=3, xsize =1024, ysize = 1024, scale = 0.1,\n niter= 5000, rank_filter=3, multiscale=True, model=False, \n predict=False, run_nr=run_nr) \n path_to_epochs= str(Path(path_to_ms).parent.parent.parent)+'/epochs' \n get_all_parameters(str(path_to_epochs)+'/'+str(name), run_nr=run_nr)\n path_to_hdf= str(Path(path_to_ms).parent.parent.parent)+'/results_'+str(name)+'/MRun_'+str(run_nr)+'/data_'+str(source)+'.h5'\n get_best_pictures(path_to_hdf, sourcename, run_nr=run_nr) # maybe get sourcename out of the data.hdf \n get_nicest_picture(path_to_hdf, sourcename, run_nr=run_nr)\n plot_all_parameterplots(path_to_hdf)\n delete_data(path_to_hdf, 3, run_nr)\n \ndef main():\n '''\n You need to change the path to your data.\n The epochs in '.../sources//data/' will be done one by one. WSClean uses three threads per epoch.\n '''\n path_to_data = '/home/yvonne/Dokumente/MA/Sources/TXS/data'\n epochs = glob.glob(str(path_to_data)+'/*.uvf')\n for epoch in epochs:\n do_everything(epoch)\n\nif __name__ == '__main__':\n main()\n","sub_path":"Radio_tools_local.py","file_name":"Radio_tools_local.py","file_ext":"py","file_size_in_byte":39335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"126193535","text":"class Token:\n def __init__(self, type, literal):\n self.type = type\n self.literal = literal\n\n\nILLEGAL = \"ILLEGAL\"\nEOF = \"EOF\"\n\nIDENT = \"IDENT\"\nINT = \"INT\"\n\nASSIGN = \"=\"\nPLUS = \"+\"\nMINUS = \"-\"\nBANG = \"!\"\nASTERISK = \"*\"\nSLASH = \"/\"\n\nLT = \"<\"\nGT = \">\"\n\nEQ = \"==\"\nNOT_EQ = \"!=\"\n\nCOMMA = \",\"\nSEMICOLON = \";\"\n\nLPAREN = \"(\"\nRPAREN = \")\"\nLBRACE = \"{\"\nRBRACE = \"}\"\n\nFUNCTION = \"FUNCTION\"\nLET = \"LET\"\nTRUE = \"TRUE\"\nFALSE = \"FALSE\"\nIF = \"IF\"\nELSE = \"ELSE\"\nRETURN = \"RETURN\"\n\n_keywords = {\n \"fn\": FUNCTION,\n \"let\": LET,\n \"true\": TRUE,\n \"false\": FALSE,\n \"if\": IF,\n \"else\": ELSE,\n \"return\": RETURN,\n}\n\n\ndef lookup_ident(ident):\n return _keywords.get(ident, IDENT)\n","sub_path":"python/intp/token.py","file_name":"token.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"529680213","text":"from bs4 import BeautifulSoup\nimport re\nfrom regcheck import RegCheck\n\nprint(\"XML SORT\\n\")\ninfile = open(\"rules/Rules.xml\",\"r\", encoding='utf-16')\n#rint(infile)\ncontents = infile.read()\nsoup = BeautifulSoup(contents,'xml')\nrules = soup.find_all('commandBlock')\nrule_name_list = []\n\n# print(\"list names :\")\npattern = r'(?<=rule name=\")[^\"]*'\n#data_soup.find_all(attrs={\"data-foo\": \"value\"})\n\nfor match in re.finditer(pattern, contents):\n rule_name_list.append(match.group())\n # print(match.group())\n\n\npattern = \"(?<=')[^']*\"\nmatch_list = []\n#print(rules)\nrule_list = []\n\n\nfor i, rule in enumerate(rules): # Search for starting location for regex search\n #print(i, \" \", rule.text)\n start_pos = rule.text.find('-Mode Audit')\n #print(\"Start position :\", start_pos)\n if start_pos < 0:\n start_pos = rule.text.find('-Mode Enforce')\n\n end_pos = rule.text.find('Except') # Search for ending location for regex search\n if end_pos == 0:\n end_pos = rule.text.find(\"FromScope\")\n if end_pos == 0:\n end_pos = rule.text.find('-SetAudit')\n rule_list.append(rule.text[start_pos:end_pos])\n #print(rule_list[i])\n\nprint(\"######\\n\")\ncomplete_list = []\n\nfor i, rule in enumerate(rule_list):\n print(\"\\nList #{}: {}\".format(i,rule_name_list[i]))\n match_num = 0\n for match in re.finditer(pattern, rule):\n if str(match.group()) != \", \": # Eliminate erroneous non-regexes\n if str(match.group()) != \" -\":\n if str(match.group()) != \" -FromScope NotInOrganization -\":\n match_num +=1\n match_list.append(match.group())\n print(match_num, \" :\", match.group())\n match_info={'list': rule_name_list[i], 'match':match.group(), 'match_num':match_num}\n complete_list.append(match_info)\n\n\nprint(\"\\n######\\n\")\n\nRegCheck(r\"mail/mail.txt\", complete_list)\n","sub_path":"xml_sort.py","file_name":"xml_sort.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"557938354","text":"import numpy as np\r\nimport pandas as pd\r\nimport os\r\nimport torch\r\nimport torch.nn as nn\r\nimport time\r\nimport copy\r\nfrom torch.utils.data import Dataset, DataLoader\r\nimport torch.nn.functional as F\r\nfrom sklearn.metrics import f1_score\r\nfrom sklearn.model_selection import KFold\r\ndevice = torch.device(\"cuda:0\") if torch.cuda.is_available() else torch.device(\"cpu\")\r\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau\r\n\r\n\r\nclass Bi_RNN(nn.Module):\r\n\r\n def __init__(self, input_dim, hidden_dim, batch_size, output_dim=11, num_layers=1, rnn_type='LSTM'):\r\n super(Bi_RNN, self).__init__()\r\n self.input_dim = input_dim\r\n self.hidden_dim = hidden_dim\r\n self.batch_size = batch_size\r\n self.num_layers = num_layers\r\n\r\n # Define the initial linear hidden layer\r\n self.init_linear_text = nn.Linear(self.input_dim[0], self.input_dim[0])\r\n self.init_linear_image = nn.Linear(self.input_dim[1], self.input_dim[1])\r\n self.init_linear_other = nn.Linear(self.input_dim[2], self.input_dim[2])\r\n # Define the LSTM layer\r\n self.lstm_text = eval('nn.' + rnn_type)(self.input_dim[0], self.hidden_dim, self.num_layers, batch_first=True,\r\n bidirectional=True)\r\n self.lstm_image = eval('nn.' + rnn_type)(self.input_dim[1], self.hidden_dim, self.num_layers, batch_first=True,\r\n bidirectional=True)\r\n self.lstm_other = eval('nn.' + rnn_type)(self.input_dim[2], self.hidden_dim, self.num_layers, batch_first=True,\r\n bidirectional=True)\r\n # Define the output layer\r\n self.linear = nn.Linear(self.hidden_dim * 2, output_dim)\r\n\r\n def init_hidden(self):\r\n # initialise our hidden state\r\n return (torch.zeros(self.num_layers, self.batch_size, self.hidden_dim),\r\n torch.zeros(self.num_layers, self.batch_size, self.hidden_dim))\r\n\r\n def forward(self, input):\r\n # Forward pass through initial hidden layer\r\n linear_input_text = self.init_linear_text(input[0])\r\n linear_input_image = self.init_linear_image(input[1])\r\n linear_input_other = self.init_linear_other(input[2])\r\n\r\n lstm_out_text, self.hidden_text = self.lstm_text(linear_input_text)\r\n lstm_out_image, self.hidden_image = self.lstm_image(linear_input_image)\r\n lstm_out_other, self.hidden_other = self.lstm_other(linear_input_other)\r\n\r\n concate = torch.Tensor([lstm_out_text, lstm_out_image, lstm_out_other])\r\n # mean pooling all the states\r\n mean_pooling = torch.mean(concate, 0)\r\n return mean_pooling\r\n\r\n\r\nclass SameType_Agg_Bi_RNN(nn.Module):\r\n\r\n def __init__(self, input_dim, hidden_dim, batch_size, output_dim, num_layers=1, rnn_type='LSTM'):\r\n super(SameType_Agg_Bi_RNN, self).__init__()\r\n self.input_dim = input_dim\r\n self.hidden_dim = hidden_dim\r\n self.batch_size = batch_size\r\n self.num_layers = num_layers\r\n\r\n # Define the initial linear hidden layer\r\n self.init_linear = nn.Linear(self.input_dim, self.input_dim)\r\n\r\n # Define the LSTM layer\r\n self.lstm = eval('nn.' + rnn_type)(self.input_dim, self.hidden_dim, self.num_layers, batch_first=True,\r\n bidirectional=True)\r\n # Define the output layer\r\n self.linear = nn.Linear(self.hidden_dim * 2, output_dim)\r\n\r\n def init_hidden(self):\r\n # initialise our hidden state\r\n return (torch.zeros(self.num_layers, self.batch_size, self.hidden_dim),\r\n torch.zeros(self.num_layers, self.batch_size, self.hidden_dim))\r\n\r\n def forward(self, input):\r\n # Forward pass through initial hidden layer\r\n linear_input = self.init_linear(input)\r\n lstm_out, self.hidden = self.lstm(linear_input)\r\n # mean pooling all the states\r\n mean_pooling = torch.mean(last_state, 0)\r\n return mean_pooling\r\n\r\n\r\ndef node_het_agg(self, node_type): #heterogeneous neighbor aggregation\r\n #attention module\r\n if node_type == \"user\":\r\n c_agg_batch = Bi_RNN(\"user\")\r\n else:\r\n c_agg_batch = Bi_RNN(\"post\")\r\n u_agg_batch = SameType_Agg_Bi_RNN(\"user\")\r\n p_agg_batch = SameType_Agg_Bi_RNN(\"post\")\r\n\r\n c_agg_batch_2 = torch.cat((c_agg_batch, c_agg_batch), 1).view(len(c_agg_batch), self.embed_d * 2)\r\n u_agg_batch_2 = torch.cat((c_agg_batch, u_agg_batch), 1).view(len(c_agg_batch), self.embed_d * 2)\r\n p_agg_batch_2 = torch.cat((c_agg_batch, p_agg_batch), 1).view(len(c_agg_batch), self.embed_d * 2)\r\n\r\n #compute weights\r\n concate_embed = torch.cat((c_agg_batch_2, u_agg_batch_2, p_agg_batch_2), 1).view(len(c_agg_batch), 4, self.embed_d * 2)\r\n if node_type == \"user\":\r\n atten_w = self.act(torch.bmm(concate_embed, self.u_neigh_att.unsqueeze(0).expand(len(c_agg_batch),*self.u_neigh_att.size())))\r\n else:\r\n atten_w = self.act(torch.bmm(concate_embed, self.p_neigh_att.unsqueeze(0).expand(len(c_agg_batch),*self.p_neigh_att.size())))\r\n atten_w = self.softmax(atten_w).view(len(c_agg_batch), 1, 4)\r\n\r\n #weighted combination\r\n concate_embed = torch.cat((c_agg_batch, u_agg_batch, p_agg_batch), 1).view(len(c_agg_batch), 4, self.embed_d)\r\n weight_agg_batch = torch.bmm(atten_w, concate_embed).view(len(c_agg_batch), self.embed_d)\r\n\r\n return weight_agg_batch\r\n\r\n'''def het_agg(self, triple_index, c_id_batch, pos_id_batch, neg_id_batch):\r\n embed_d = self.embed_d\r\n # batch processing\r\n # nine cases for academic data (user, paper)\r\n if triple_index == 0:\r\n c_agg = self.node_het_agg(c_id_batch, \"user\")\r\n p_agg = self.node_het_agg(pos_id_batch, \"user\")\r\n n_agg = self.node_het_agg(neg_id_batch, \"user\")\r\n elif triple_index == 1:\r\n c_agg = self.node_het_agg(c_id_batch, \"user\")\r\n p_agg = self.node_het_agg(pos_id_batch, \"post\")\r\n n_agg = self.node_het_agg(neg_id_batch, \"post\")\r\n elif triple_index == 2:\r\n c_agg = self.node_het_agg(c_id_batch, \"post\")\r\n p_agg = self.node_het_agg(pos_id_batch, \"user\")\r\n n_agg = self.node_het_agg(neg_id_batch, \"user\")\r\n elif triple_index == 4:\r\n c_agg = self.node_het_agg(c_id_batch, \"post\")\r\n p_agg = self.node_het_agg(pos_id_batch, \"post\")\r\n n_agg = self.node_het_agg(neg_id_batch, \"post\")\r\n elif triple_index == 5: # save learned node embedding\r\n embed_file = open(self.args.data_path + \"node_embedding.txt\", \"w\")\r\n save_batch_s = self.args.mini_batch_s\r\n for i in range(2):\r\n if i == 0:\r\n batch_number = int(len(self.u_train_id_list) / save_batch_s)\r\n else:\r\n batch_number = int(len(self.p_train_id_list) / save_batch_s)\r\n for j in range(batch_number):\r\n if i == 0:\r\n id_batch = self.u_train_id_list[j * save_batch_s: (j + 1) * save_batch_s]\r\n out_temp = self.node_het_agg(id_batch, \"user\")\r\n else:\r\n id_batch = self.p_train_id_list[j * save_batch_s: (j + 1) * save_batch_s]\r\n out_temp = self.node_het_agg(id_batch, \"post\")\r\n out_temp = out_temp.data.cpu().numpy()\r\n for k in range(len(id_batch)):\r\n index = id_batch[k]\r\n if i == 0:\r\n embed_file.write('u' + str(index) + \" \")\r\n else:\r\n embed_file.write('p' + str(index) + \" \")\r\n for l in range(embed_d - 1):\r\n embed_file.write(str(out_temp[k][l]) + \" \")\r\n embed_file.write(str(out_temp[k][-1]) + \"\\n\")\r\n\r\n if i == 0:\r\n id_batch = self.u_train_id_list[batch_number * save_batch_s: -1]\r\n out_temp = self.node_het_agg(id_batch, \"user\")\r\n else:\r\n id_batch = self.p_train_id_list[batch_number * save_batch_s: -1]\r\n out_temp = self.node_het_agg(id_batch, \"post\")\r\n out_temp = out_temp.data.cpu().numpy()\r\n for k in range(len(id_batch)):\r\n index = id_batch[k]\r\n if i == 0:\r\n embed_file.write('u' + str(index) + \" \")\r\n else:\r\n embed_file.write('p' + str(index) + \" \")\r\n for l in range(embed_d - 1):\r\n embed_file.write(str(out_temp[k][l]) + \" \")\r\n embed_file.write(str(out_temp[k][-1]) + \"\\n\")\r\n embed_file.close()\r\n return [], [], []\r\n\r\n return c_agg, p_agg, n_agg'''\r\n","sub_path":"het_agg.py","file_name":"het_agg.py","file_ext":"py","file_size_in_byte":9005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"596421000","text":"def find_my_seat_id():\n mid, i = 64, 0\n while True:\n for seat in free_seats:\n if seat[0] == mid + i:\n return str(seat[0] * 8 + seat[1])\n i += 1\n\n\n\nif __name__ == '__main__':\n file = open(\"day-5-data\", \"r\")\n table = {70: 48, 66: 49, 82: 49, 76: 48}\n seats = []\n for line in file.readlines():\n row = int(line[:-4].translate(table), 2)\n column = int(line[-4:].translate(table), 2)\n seats.append((row, column))\n\n print(\"First part answer: \" + str(max([x[0] * 8 + x[1] for x in seats])))\n\n all_seats = []\n for i in range(128):\n for j in range(8):\n all_seats.append((i, j))\n\n free_seats = [x for x in all_seats if x not in seats]\n\n print(\"Second part answer: \" + find_my_seat_id())\n\n","sub_path":"2020/day-5/day-5.py","file_name":"day-5.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"68378429","text":"from sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.feature_extraction.text import TfidfTransformer\r\nimport re\r\nfrom nltk.tokenize import word_tokenize\r\nfrom string import punctuation\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.stem import WordNetLemmatizer\r\n\r\n\r\nclass PreProcessTweets:\r\n def __init__(self):\r\n self._stopwords = set(stopwords.words('english') + list(punctuation) + ['AT_USER', 'URL'])\r\n\r\n def cleanTweetSet(self, rawData):\r\n cleanedSet = []\r\n print(\"cleaning...\")\r\n for tweet in rawData:\r\n tweet = self.cleanTweet(tweet)\r\n cleanedSet.append(tweet)\r\n\r\n print(\"clean complete.\")\r\n return cleanedSet\r\n\r\n def cleanTweet(self, text):\r\n text = re.sub('((www\\.[^\\s]+)|(https?://[^\\s]+))', 'URL', text)\r\n text = re.sub('@[^\\s]+', 'USER', text)\r\n text = text.lower().replace(\"ё\", \"е\")\r\n text = re.sub('[^a-zA-Zа-яА-Я1-9]+', ' ', text)\r\n text = re.sub(' +', ' ', text)\r\n tweet = word_tokenize(text)\r\n\r\n cleanedWords = []\r\n lem = WordNetLemmatizer()\r\n for w in tweet:\r\n w = lem.lemmatize(w)\r\n if w not in self._stopwords:\r\n cleanedWords.append(w)\r\n\r\n joinedWords = ' '.join(cleanedWords)\r\n\r\n return joinedWords\r\n\r\n # def featureExtraction(self, cleanedSet):\r\n # # create bag of words\r\n #\r\n # # convert words to numbers using bag of words approach\r\n # # as the data could contain tens thousands of unique words\r\n # # max_features is set to 1500 to collect most occurring words as features\r\n # # min_df is set to 5 = include words that occur in at least 5 tweets\r\n # # max_df is set to 0.7 = include words that occur in a max of 70% of all tweets\r\n # vectorizer = CountVectorizer(max_df=0.7)\r\n #\r\n # # converts text into corresponding numeric features\r\n # X = vectorizer.fit_transform(cleanedSet)\r\n #\r\n # tfidfconverter = TfidfVectorizer(max_df=0.7)\r\n # X = tfidfconverter.fit_transform(cleanedSet)\r\n","sub_path":"preProcessTweets.py","file_name":"preProcessTweets.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"648853449","text":"# Import the required libraries.\nfrom __future__ import division, print_function\n\nimport os\nimport cv2\nimport warnings\nimport numpy as np\nimport skfuzzy as fuzz\n\nfrom sklearn.cluster import KMeans\nfrom time import time\n\nwarnings.filterwarnings(\"ignore\")\n\n\n# Class creation\nclass FuzzyC(object):\n # Read in the images.\n def readImage(self):\n folder = '../Evaluation Scans/Full/'\n list_images = os.listdir(folder)\n list_img = []\n for i in list_images:\n path = folder+i\n img = cv2.imread(path)\n img = cv2.resize(img, (128, 128))\n img = cv2.medianBlur(img, 5)\n rgb_img = img.reshape((img.shape[0] * img.shape[1], 3))\n list_img.append(rgb_img)\n\n return list_img\n\n # Compute the area of the objects in a binary image.\n def bwarea(self, img):\n row = img.shape[0]\n col = img.shape[1]\n total = 0.0\n for r in range(row-1):\n for c in range(col-1):\n sub_total = img[r:r+2, c:c+2].mean()\n if sub_total == 255:\n total += 1\n elif sub_total == (255.0/3.0):\n total += (7.0/8.0)\n elif sub_total == (255.0/4.0):\n total += 0.25\n elif sub_total == 0:\n total += 0\n else:\n r1c1 = img[r, c]\n r1c2 = img[r, c+1]\n r2c1 = img[r+1, c]\n r2c2 = img[r+1, c+1]\n\n if (((r1c1 == r2c2) & (r1c2 == r2c1)) & (r1c1 != r2c1)):\n total += 0.75\n else:\n total += 0.5\n return total\n\n def centroid_histogram(self, clt):\n numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1)\n (hist, _) = np.histogram(clt.labels_, bins=numLabels)\n\n hist = hist.astype(\"float\")\n hist /= hist.sum()\n\n return hist\n\n def plot_colors(self, hist, centroids):\n bar = np.zeros((50, 300, 3), dtype=\"uint8\")\n startX = 0\n for (percent, color) in zip(hist, centroids):\n endX = startX + (percent * 300)\n cv2.rectangle(\n bar,\n (int(startX), 0),\n (int(endX), 50),\n color.astype(\"uint8\").tolist(),\n -1\n )\n startX = endX\n\n return bar\n\n def change_color_kmeans(self, predict_img, clusters):\n img = []\n for val in predict_img:\n img.append(clusters[val])\n return img\n\n def change_color_fuzzycmeans(self, cluster_membership, clusters):\n img = []\n for pix in cluster_membership.T:\n img.append(clusters[np.argmax(pix)])\n return img\n\n def process(self, list_img, clusters):\n self.seg_array = []\n for rgb_img in list_img[:]:\n img = np.reshape(rgb_img, (128, 128, 3)).astype(np.uint8)\n shape = np.shape(img)\n\n clt = KMeans(n_clusters=clusters, n_jobs=4)\n clt.fit(rgb_img)\n predict_img = clt.predict(rgb_img)\n new_img = self.change_color_kmeans(\n predict_img,\n clt.cluster_centers_\n )\n # kmeans_img = np.reshape(new_img, shape).astype(np.uint8)\n # hist = self.centroid_histogram(clt)\n # bar = self.plot_colors(hist, clt.cluster_centers_)\n new_time = time()\n\n cntr, u, u0, d, jm, p, fpc = fuzz.cluster.cmeans(\n rgb_img.T,\n clusters,\n 2,\n error=0.005,\n maxiter=1000,\n init=None,\n seed=42\n )\n\n new_img = self.change_color_fuzzycmeans(u, cntr)\n fuzzy_img = np.reshape(new_img, shape).astype(np.uint8)\n self.ret, self.seg_img = cv2.threshold(\n fuzzy_img,\n np.max(fuzzy_img) - 1,\n 255,\n cv2.THRESH_BINARY\n )\n print(time() - new_time, 'seconds')\n print(self.bwarea(self.seg_img[:, :, 1]))\n\n self.seg_array.append(self.seg_img)\n\n \"\"\"\n plt.subplot(131)\n plt.gca().set_title(\"Original\"), plt.imshow(img)\n plt.xticks([]), plt.yticks([])\n\n plt.subplot(132)\n plt.gca().set_title(\"Fuzzy\"), plt.imshow(fuzzy_img)\n plt.xticks([]), plt.yticks([])\n\n plt.subplot(133)\n plt.gca().set_title(\"Segmented\"), plt.imshow(self.seg_img)\n plt.xticks([]), plt.yticks([])\n plt.show()\n \"\"\"\n\n def writeFile(self, OUTDIR):\n for i in range(len(self.seg_array)):\n cv2.imwrite(\n OUTDIR +\n \"Result_\" +\n str(i) +\n \".png\",\n self.seg_array[i]\n )\n\n\nif __name__ == \"__main__\":\n OUTDIR = './Fuzzy Results/Full/'\n\n fuzzy = FuzzyC()\n list_img = fuzzy.readImage()\n fuzzy.process(list_img, 6)\n fuzzy.writeFile(OUTDIR)\n","sub_path":"Segmentation_Methods/Fuzzy_C_Means.py","file_name":"Fuzzy_C_Means.py","file_ext":"py","file_size_in_byte":5206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"48954364","text":"###############################################################################\r\n# #\r\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may #\r\n# not use this file except in compliance with the License. You may obtain a #\r\n# copy of the License at http://www.apache.org/licenses/LICENSE-2.0 #\r\n# #\r\n# Unless required by applicable law or agreed to in writing, software #\r\n# distributed under the License is distributed on an \"AS IS\" BASIS, #\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #\r\n# See the License for the specific language governing permissions and #\r\n# limitations under the License. #\r\n# #\r\n###############################################################################\r\n# #\r\n# Software developed based on the work published in the following articles: #\r\n# - F. Couto and A. Lamurias, \"Semantic similarity definition,\" in Reference #\r\n# Module in Life Sciences (Encyclopedia of Bioinformatics and Computational #\r\n# Biology), pp. 1--17, Elsevier, 2018 #\r\n# https://doi.org/10.1016/B978-0-12-809633-8.20401-9, #\r\n# https://www.researchgate.net/publication/323219905 #\r\n# #\r\n# @author Francisco M. Couto #\r\n###############################################################################\r\n\r\nimport sqlite3\r\nimport math\r\n\r\nintrinsic = False\r\nmica = False\r\n\r\ndef semantic_base (sb_file):\r\n\r\n global connection\r\n\r\n connection = sqlite3.connect(sb_file)\r\n \r\ndef get_id (name):\r\n\r\n rows = connection.execute('''\r\n SELECT id\r\n FROM entry\r\n WHERE name = ?\r\n ''', (name,))\r\n\r\n row = rows.fetchone()\r\n if row is None:\r\n iden = -1\r\n else : \r\n iden = row[0]\r\n\r\n return iden\r\n\r\ndef get_name(cid):\r\n\r\n rows = connection.execute('''\r\n SELECT name\r\n FROM entry\r\n WHERE id = ?\r\n ''', (cid,))\r\n\r\n row = rows.fetchone()\r\n if row is None:\r\n iden = -1\r\n else : \r\n iden = row[0]\r\n\r\n return iden\r\n\r\n\r\ndef common_ancestors (entry1, entry2):\r\n\r\n ancestors = []\r\n \r\n rows = connection.execute('''\r\n SELECT DISTINCT t1.entry2\r\n FROM entry e, transitive t1, transitive t2\r\n WHERE t1.entry1=? AND t2.entry1=? AND t1.entry2=t2.entry2\r\n AND e.id=t1.entry2\r\n ORDER BY e.freq\r\n ''', (entry1, entry2, ))\r\n \r\n for row in rows:\r\n ancestors.append(row[0])\r\n return ancestors\r\n\r\n\r\ndef information_content_extrinsic (entry):\r\n #print entry\r\n rows = connection.execute('''\r\n SELECT e.freq\r\n FROM entry e\r\n WHERE e.id = ?\r\n ''', (entry,))\r\n freq = rows.fetchone()[0] + 1.0\r\n #print (freq)\r\n\r\n rows = connection.execute('''\r\n SELECT MAX(e.freq)\r\n FROM entry e\r\n ''')\r\n maxfreq = rows.fetchone()[0] + 1.0 \r\n \r\n return -math.log(freq/maxfreq)\r\n\r\ndef information_content_intrinsic (entry):\r\n\r\n\t#print entry\r\n rows = connection.execute('''\r\n SELECT e.desc\r\n FROM entry e\r\n WHERE e.id = ?\r\n ''', (entry,))\r\n freq = rows.fetchone()[0] + 1.0\r\n #print (freq)\r\n\r\n rows = connection.execute('''\r\n SELECT MAX(e.desc)\r\n FROM entry e\r\n ''')\r\n maxfreq = rows.fetchone()[0] + 1.0 \r\n \r\n return -math.log(freq/maxfreq)\r\n\r\ndef information_content (entry):\r\n if intrinsic:\r\n return information_content_intrinsic (entry)\r\n else: \r\n return information_content_extrinsic (entry)\r\n\r\ndef num_paths (entry1, ancestor):\r\n \r\n rows = connection.execute('''\r\n SELECT COUNT(*)\r\n FROM transitive t\r\n WHERE t.entry1=? AND t.entry2=? \r\n ''', (entry1, ancestor, ))\r\n\r\n npaths = rows.fetchone()[0] + 1.0 \r\n\r\n return npaths\r\n\r\ndef shared_ic_dca (entry1, entry2):\r\n\r\n ancestors = common_ancestors(entry1, entry2)\r\n dca = {}\r\n\r\n for anc in ancestors: \r\n pd = abs(num_paths(entry1, anc) - num_paths(entry2, anc))\r\n ic = information_content(anc)\r\n dca[pd] = max(information_content(anc),dca.get(pd,0));\r\n \r\n values = dca.values()\r\n\r\n if len(values) > 0 :\r\n ret = float(sum(values)) / float(len(values))\r\n else:\r\n ret = 0\r\n\r\n return ret\r\n \r\ndef shared_ic_mica (entry1, entry2):\r\n\r\n ic = 0 \r\n\r\n ancestors = common_ancestors(entry1, entry2)\r\n\r\n for anc in ancestors:\r\n ic = max(information_content(anc),ic)\r\n\r\n return ic\r\n\r\nshared_ic_cache = {}\r\n\r\ndef shared_ic (entry1, entry2):\r\n\r\n\tvalue = 0\r\n\tkey_cache = str(mica)+':'+str(intrinsic)+':'+str(max(entry1,entry2))+':'+str(min(entry1,entry2))\r\n\tvalue = shared_ic_cache.get(key_cache,-1)\r\n\t\r\n\tif value == -1 :\r\n\t\tif mica:\r\n\t\t\tvalue = shared_ic_mica (entry1, entry2)\r\n\t\telse:\r\n\t\t\tvalue = shared_ic_dca (entry1, entry2)\r\n\t\tshared_ic_cache[key_cache]=value\r\n\t\r\n\treturn value \r\n\r\n\r\ndef ssm_resnik (entry1, entry2):\r\n\r\n return abs(shared_ic(entry1, entry2))\r\n\r\ndef ssm_lin (entry1, entry2):\r\n aux = (information_content(entry1) + information_content(entry2))\r\n\r\n if aux > 0 : \r\n return 2*shared_ic(entry1, entry2) / aux\r\n else:\r\n return 1.0\r\n\r\ndef ssm_jiang_conrath (entry1, entry2):\r\n\r\n distance = information_content(entry1) + information_content(entry2) - 2*shared_ic(entry1, entry2)\r\n if distance > 0:\r\n return 1 / distance\r\n else:\r\n return 1.0\r\n\r\ndef ssm_multiple (m, entry1_list, entry2_list):\r\n\r\n results = []\r\n for entry1 in entry1_list : \r\n results_entry1 = []\r\n for entry2 in entry2_list : \r\n result=m(entry1, entry2)\r\n results_entry1.append(result) \r\n # maximum of all values for entry1\r\n results.append(max(results_entry1)) \r\n # average of all values for all entries\r\n avg = sum(results) / float(len(results))\r\n return avg \r\n\r\n \r\n","sub_path":"DiShIn/ssm.py","file_name":"ssm.py","file_ext":"py","file_size_in_byte":6364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"92449289","text":"import random\n\nimport zc.blist\n\ndef checkIndex(ix, b, previous, previous_ix=0):\n computed = 0\n if len(previous) < previous_ix+1:\n previous.append(None)\n assert len(previous) >= previous_ix + 1\n # assert isinstance(ix, zc.blist.Index)\n assert b.data is ix or len(ix) <= b.index_size\n assert b.data is ix or len(ix) >= b.index_size // 2\n assert ix.minKey() == 0\n for k, v in ix.items():\n v = b._mapping[v]\n assert computed == k\n assert v.parent == ix.identifier\n p = previous[previous_ix]\n if p is not None:\n p = p.identifier\n assert v.previous == p\n assert (v.previous is None or\n previous[previous_ix].next == v.identifier)\n assert (v.next is None or\n b._mapping[v.next].previous == v.identifier)\n computed += v.contained_len(b)\n if isinstance(v, zc.blist.Index):\n checkIndex(v, b, previous, previous_ix+1)\n else:\n assert isinstance(v, zc.blist.Bucket)\n assert len(v) <= b.bucket_size\n assert (len(v) >= b.bucket_size // 2)\n previous[previous_ix] = v\n \ndef matches(b, result):\n assert list(b) == result, repr(list(b)) + ' != ' + repr(result)\n assert len(b) == len(result)\n assert list(b[::-1]) == list(reversed(result))\n res = []\n bad = [(i, (b_i, r_i)) for (i, b_i, r_i) in\n ((i, b[i], result[i]) for i in range(len(b)))\n if b_i != r_i]\n assert not bad, 'getitems do not match on these indices: ' + repr(bad)\n # we'll check the buckets internally while we are here\n assert b.data.parent is None\n assert b.data.previous is None and b.data.next is None\n if isinstance(b.data, zc.blist.Index):\n checkIndex(b.data, b, [None])\n return True\n\ndef checkCopies(one, two):\n one_diff = list(\n one.family.IO.difference(one._mapping, two._mapping))\n for k in one_diff:\n data = one._mapping[k]\n assert one in data.collections\n assert two not in data.collections\n two_diff = list(\n one.family.IO.difference(two._mapping, one._mapping))\n for k in two_diff:\n data = two._mapping[k]\n assert two in data.collections\n assert one not in data.collections\n diff = []\n for k, v in one._mapping.items():\n alt = two._mapping.get(k)\n if alt is None:\n assert k in one_diff\n continue\n if alt is v:\n assert one in v.collections and two in v.collections\n else:\n assert (one in v.collections and\n one not in alt.collections and\n two in alt.collections and\n two not in v.collections)\n diff.append((k, v, alt))\n return one_diff, two_diff, diff\n\ndef RandomGenerator():\n while 1:\n yield random.randint(-sys.maxint, sys.maxint)\n\ndef StringGenerator(src='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'):\n \"infinite-ish unique string generator\"\n for el in src:\n yield el\n for pre in StringGenerator(src):\n for el in src:\n yield pre + el\n\ndef NumberGenerator(number=0, interval=1):\n \"infinite-ish unique number generator\"\n while 1:\n yield number\n number += interval","sub_path":"zc.blist/tags/1.0b2/src/zc/blist/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"573127046","text":"# -*- coding: utf-8 -*-\n\nfrom snakemake.shell import shell\n\npaths_calls = \" \".join(snakemake.input.calls)\npaths_models = \" \".join(snakemake.input.calls)\n\nshell(\n r\"\"\"\nset -x\n\nexport TMPDIR=$(mktemp -d)\ntrap \"rm -rf $TMPDIR\" ERR EXIT\n\nexport THEANO_FLAGS=\"base_compiledir=$TMPDIR/theano_compile_dir\"\n\nitv_vcf={snakemake.output.itv_vcf}\nseg_vcf={snakemake.output.seg_vcf}\n\nsample_index=-1\nfor path in $(dirname {snakemake.input.calls[0]})/cnv_calls-calls/SAMPLE_*; do\n if [[ \"$(cat $path/sample_name.txt)\" == \"{snakemake.wildcards.library_name}\" ]]; then\n sample_index=$(basename $path | sed -e 's/SAMPLE_//')\n break\n fi\ndone\n\ngatk PostprocessGermlineCNVCalls \\\n $(for x in {paths_calls}; do echo --calls-shard-path $(dirname $x)/cnv_calls-calls; done) \\\n $(for x in {paths_models}; do echo --model-shard-path $(dirname $x)/cnv_calls-model; done) \\\n --contig-ploidy-calls $(dirname {snakemake.input.ploidy})/ploidy-calls \\\n --sample-index $sample_index \\\n --autosomal-ref-copy-number 2 \\\n --allosomal-contig X \\\n --allosomal-contig Y \\\n --output-genotyped-intervals ${{itv_vcf%.gz}} \\\n --output-genotyped-segments ${{seg_vcf%.gz}} \\\n --output-denoised-copy-ratios {snakemake.output.ratio_tsv}\n\nperl -p -i -e 's/ID=GT,Number=1,Type=Integer/ID=GT,Number=1,Type=String/g' ${{itv_vcf%.gz}}\nperl -p -i -e 's/ID=GT,Number=1,Type=Integer/ID=GT,Number=1,Type=String/g' ${{seg_vcf%.gz}}\n\nbgzip ${{itv_vcf%.gz}}\ntabix -f $itv_vcf\nbgzip ${{seg_vcf%.gz}}\ntabix -f $seg_vcf\n\nfor x in $itv_vcf $itv_vcf.tbi $seg_vcf $seg_vcf.tbi {snakemake.output.ratio_tsv}; do\n pushd $(dirname $x)\n md5sum $(basename $x) >$(basename $x).md5\n popd\ndone\n\"\"\"\n)\n","sub_path":"snappy_wrappers/wrappers/gcnv/post_germline_calls/wrapper.py","file_name":"wrapper.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"383523382","text":"# Copyright (c) 2015, The MITRE Corporation. All rights reserved.\n# See LICENSE.txt for complete terms.\n\nimport unittest\nfrom mixbox.vendor.six import StringIO\n\nimport sdv\nimport sdv.errors as errors\n\nSTIX_1_1_1_XML = \\\n\"\"\"\n\n \n Example watchlist that contains domain information.\n Indicators - Watchlist\n \n \n \n Domain Watchlist\n Sample domain Indicator for this watchlist\n \n \n \n malicious1.example.com##comma##malicious2.example.com##comma##malicious3.example.com\n \n \n \n \n \n\n\"\"\"\n\nSTIX_INVALID = \\\n\"\"\"\n\n \n Unknown version of STIX\n this is an invalid field\n \n\n\"\"\"\n\n\nSTIX_NO_VERSION_XML = \\\n\"\"\"\n\n \n Unknown version of STIX\n \n\n\"\"\"\n\nclass STIXSchemaTests(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n StringIO(STIX_1_1_1_XML)\n\n def test_invalid(self):\n xml = StringIO(STIX_INVALID)\n results = sdv.validate_xml(xml)\n\n # Assert that the document is identified as being invalid\n self.assertFalse(results.is_valid)\n\n # Assert that the badAttr attribute and stix:INVALID element are\n # errors are recorded.\n self.assertEqual(len(results.errors), 2)\n\n def test_valid(self):\n xml = StringIO(STIX_1_1_1_XML)\n results = sdv.validate_xml(xml)\n self.assertTrue(results.is_valid)\n\n def test_invalid_version(self):\n xml = StringIO(STIX_1_1_1_XML)\n func = sdv.validate_xml\n self.assertRaises(\n errors.InvalidSTIXVersionError, func, xml, version=\"INVALID\"\n )\n\n def test_unknown_version(self):\n func = sdv.validate_xml\n xml = StringIO(STIX_NO_VERSION_XML)\n self.assertRaises(\n errors.UnknownSTIXVersionError, func, xml\n )\n\n def test_defined_version(self):\n xml = StringIO(STIX_NO_VERSION_XML)\n results = sdv.validate_xml(xml, version=\"1.1.1\")\n self.assertTrue(results.is_valid)\n\n def test_invalid_doc(self):\n func = sdv.validate_xml\n self.assertRaises(errors.ValidationError, func, \"INVALID XML DOC\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"sdv/test/stix_schema_tests.py","file_name":"stix_schema_tests.py","file_ext":"py","file_size_in_byte":4236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"538728219","text":"# -*- coding: utf-8 -*-\n\n# Base Imports\nimport time\nimport random\nimport config\nimport base64\nimport hashlib\nimport webapp2\n\n# Webapp2 Extras\nfrom webapp2_extras import securecookie\n\n# AppTools Util Imports\nfrom apptools.util import json\nfrom apptools.util import debug\nfrom apptools.util import datastructures\n\n# Google API Imports\nfrom google.appengine.ext import ndb\n\n# Session Models\nfrom yoga.models import session as models\n\n# Tantric Imports\nfrom yoga.platform.tantric.core import CoreAPI\nfrom yoga.platform.tantric.exceptions import session as exceptions\n\n\n## Constants\n_DEFAULT_SECRET = '__SECRET__'\n\n\n## CoreSessionAPI - adds functionality for app-level session management\nclass CoreSessionAPI(CoreAPI):\n\n\t''' Manages establishment and management of user sessions for the Tantric platform. '''\n\n\t# Session State\n\t__session = None\n\n\t# Config State\n\t_versionflag = 'V1'\n\t_config_path = 'yoga.platform.tantric.core.SessionAPI'\n\n\t# Bindings\n\tmodels = datastructures.DictProxy(**{\n\t\t'session': models.Session,\n\t\t'data': models.SessionData\n\t})\n\n\tdef __init__(self, bus, handler):\n\n\t\t''' Initialize the Core Session API. '''\n\n\t\tself.context = ndb.get_context()\n\t\tself.bus, self.handler = bus, handler\n\t\tself.serializer = securecookie.SecureCookieSerializer(self._session_config.get('secret_key'))\n\n\t## ==== Cached Shortcuts ==== ##\n\t@webapp2.cached_property\n\tdef _session_config(self):\n\n\t\t''' Named config pipe. '''\n\n\t\treturn config.config.get('webapp2_extras.sessions', {'secret_key': _DEFAULT_SECRET})\n\n\t@webapp2.cached_property\n\tdef _cookie_config(self):\n\n\t\t''' Cookie config. '''\n\n\t\treturn self._session_config.get('cookie_args', {'name': 'session', 'max_age': 86400, 'path': '/', 'domain': '*', 'secure': False, 'httponly': False})\n\n\t@webapp2.cached_property\n\tdef logging(self):\n\n\t\t''' Named logging pipe. '''\n\n\t\treturn debug.AppToolsLogger(path='yoga.platform.tantric.core.session', name='CoreSessionAPI')._setcondition(self.config.get('debug', True))\n\n\t@property\n\tdef ticket(self):\n\n\t\t''' Cached shortcut to the current session. '''\n\n\t\tif isinstance(self.__session, ndb.Future):\n\t\t\t# oops, we have to block :(\n\t\t\tself.__session = self.__session.get_result()\n\t\treturn self.__session\n\n\t@property\n\tdef data(self):\n\n\t\t''' Cached shortcut to the current session data blob. '''\n\n\t\tif not self.__session:\n\t\t\treturn None\n\t\tif isinstance(self.ticket.data, ndb.Future):\n\t\t\t# oops, we have to block :(\n\t\t\tdata = self.__session.data.get_result()\n\t\t\tself.__session._set_data(data)\n\t\treturn self.__session.data\n\n\t@webapp2.cached_property\n\tdef _salt(self):\n\n\t\t''' Retrieve the current hash salt. '''\n\n\t\tsecret = self._session_config.get('secret_key')\n\t\tif secret == _DEFAULT_SECRET:\n\t\t\tif not config.debug:\n\t\t\t\tself.logging.warning('Sessions could not find a unique session key, using default.')\n\t\t\t\tself.logging.critical('Core Sessions API encountered a default secret_key. Please change ASAP.')\n\t\t\telse:\n\t\t\t\traise exceptions.EmptySecret(\"It's very important that you set a secret_key in config for secure sessions.\")\n\t\treturn secret\n\n\t## ==== Internal Methods ==== ##\n\t@staticmethod\n\tdef _generate_session_id():\n\n\t\t''' Generate a new, pseudo-random session ID. '''\n\n\t\t# Generate and hash a new session ID\n\t\treturn hashlib.sha256('::'.join([str(int(time.time())), str(reduce(lambda x, y: x * y, (random.randint(10000, 99999) for x in xrange(1, 5))))])).hexdigest()\n\n\tdef _build_session_key(self, id=None, user=None):\n\n\t\t''' Build a session key from a random session ID. '''\n\n\t\t# Package into an NDB key, optionally with a User as parent\n\t\treturn ndb.Key(models.Session, id or self._generate_session_id(), parent=user)\n\n\tdef _encode_session(self):\n\n\t\t''' Encode a session key into an obfuscated string, suitable for transmission to the client. '''\n\n\t\tif not self.ticket:\n\t\t\traise exceptions.MissingSession('Must have a session to call _encode_session.')\n\n\t\t# Generate payload and timestamp, encode + return\n\t\tpayload, timestamp = json.dumps({'v': self._versionflag, 'k': self.ticket.key.urlsafe(), 't': str(int(time.mktime(self.ticket.established.timetuple())))}), str(int(time.time()))\n\t\treturn base64.b64encode('::'.join([payload, hashlib.md5('::'.join([payload, timestamp, self._salt])).hexdigest(), timestamp]))\n\n\tdef _validate_session(self, payload, signature, timestamp):\n\n\t\t''' Validate a session blob via the provided signature and timestamp. '''\n\n\t\t# Re-generate signature\n\t\thashspec = '::'.join([payload, timestamp, self._salt])\n\t\thashcheck = hashlib.md5(hashspec).hexdigest()\n\n\t\t# Perform tests\n\t\ttry:\n\t\t\tassert hashcheck == signature\n\t\t\tassert int(time.time()) > int(timestamp)\n\t\t\tassert all((payload, signature, timestamp))\n\n\t\texcept AssertionError as e:\n\n\t\t\t# Log debug messages\n\t\t\tself.logging.debug('Session Salt: \"%s\".' % self._salt)\n\t\t\tself.logging.debug('Session Payload: \"%s\".' % payload)\n\t\t\tself.logging.debug('Session Signature: \"%s\".' % signature)\n\t\t\tself.logging.debug('Session Timestamp: \"%s\".' % timestamp)\n\n\t\t\t# Session didn't validate\n\t\t\tif self._session_config.get('require_valid', True):\n\t\t\t\tself.logging.warning('Could not validate session from decoded session blob.')\n\t\t\t\tif config.debug:\n\t\t\t\t\traise exceptions.InvalidSession('Could not validate session from decoded session blob.')\n\t\t\t\telse:\n\t\t\t\t\treturn False\n\n\t\telse:\n\n\t\t\t# Session validated! Yay :)\n\t\t\tself.logging.info('Session with signature \"%s\" is VALID. Loading.' % payload)\n\t\t\treturn True\n\n\tdef _decode_session(self, blob):\n\n\t\t''' Decode a session key into a session ID. '''\n\n\t\t# Decode and split payload\n\t\tpayload = base64.b64decode(blob).split('::')\n\t\tif len(payload) < 3:\n\n\t\t\t# Must have payload, signature + timestamp\n\t\t\traise exceptions.InvalidSessionBlob('The specified session blob contains an incorrent number of parameters. Blob in question: \"%s\".' % payload)\n\n\t\telse:\n\t\t\t# Validate and return\n\t\t\tif self._validate_session(*payload):\n\t\t\t\treturn json.loads(payload[0])\n\t\t\telse:\n\t\t\t\traise exceptions.InvalidSessionBlob('The specified session blob could not be validated.')\n\n\tdef _get_session(self):\n\n\t\t''' Get the current SessionData object. '''\n\n\t\treturn self.__session\n\n\tdef _set_session(self, obj=None, user=None):\n\n\t\t''' Set the current session object, or provision a new one. '''\n\n\t\tif not obj:\n\t\t\t# Provision a new session\n\t\t\tobj = self.models.session.provision(self._generate_session_id(), user)\n\n\t\tself.__session = obj\n\t\treturn self.__session\n\n\t## ==== Mid-level Methods ==== ##\n\t@ndb.tasklet\n\tdef _get_ndb_session(self, skey):\n\n\t\t''' Load an NDB-based session by it's SID. '''\n\n\t\tticket = yield skey.get_async()\n\t\traise ndb.Return(ticket)\n\n\t@ndb.tasklet\n\tdef _put_ndb_session(self):\n\n\t\t''' Save the current session to the datastore. '''\n\n\t\tticket = yield self.ticket.save_ticket_async()\n\t\tdata = yield self.ticket.save_data_async()\n\t\traise ndb.Return([ticket, data])\n\n\t@ndb.tasklet\n\tdef _put_mem_session(self):\n\n\t\t''' Save the current session to memcache. '''\n\n\t\tticket = yield self.context.memcache_set(self.ticket._encode_cachekey(self.ticket.key), self.ticket)\n\t\tdata = yield self.context.memcache_set(self.ticket.data._encode_cachekey(), self.ticket.data)\n\t\traise ndb.Return([ticket, data])\n\n\t@ndb.tasklet\n\tdef _get_mem_session(self, skey):\n\n\t\t''' Attempt to load a session from memcache, by SID. '''\n\n\t\tticket = yield self.context.memcache_get(self.models.session()._encode_cachekey(skey))\n\t\traise ndb.Return(ticket)\n\n\t@ndb.tasklet\n\tdef _save_session(self):\n\n\t\t''' Save the current session to the datastore. '''\n\n\t\tkeys = yield self._put_ndb_session(), self._put_mem_session()\n\t\traise ndb.Return(keys)\n\n\tdef _make_session_cookie(self):\n\n\t\t''' Make a stringified session cookie, from the active session. '''\n\n\t\tname, value = self._cookie_config.get('name'), self._encode_session()\n\t\tserialized_value = self.serializer.serialize(name, value)\n\t\tself.handler.response.set_cookie(self._cookie_config.get('name'), serialized_value, *tuple([self._cookie_config.get(x) for x in ('max_age', 'path', 'domain', 'secure', 'http_only')]))\n\t\treturn self\n\n\t## ==== Public Methods ==== ##\n\tdef load_session(self, handler=None):\n\n\t\t''' Load a session ticket, by the user's session ID. '''\n\n\t\tsession = None\n\t\tif handler is not None:\n\t\t\tself.handler = handler\n\n\t\t# Look for cookie\n\t\tblob = self.handler.request.cookies.get(self._cookie_config.get('name'))\n\n\t\t# Look for header\n\t\tif not blob:\n\t\t\tself.logging.debug('Did not find session cookie.')\n\t\t\tblob = self.handler.request.headers.get('X-Tantric-Session')\n\n\t\t\t# Look for param\n\t\t\tif not blob:\n\t\t\t\tself.logging.debug('Did not find session header.')\n\t\t\t\tblob = self.handler.request.params.get(self._cookie_config.get('name'))\n\t\t\t\tif not blob:\n\t\t\t\t\tself.logging.debug('Did not find session GET/POST param. No session.')\n\n\t\t# Found Cookie\n\t\telse:\n\t\t\tself.logging.info('Session cookie found. Deserializing.')\n\t\t\tblob = self.serializer.deserialize(self._cookie_config.get('name'), blob, None)\n\n\t\tif blob is not None:\n\n\t\t\tself.logging.info('Found session on request.')\n\n\t\t\ttry:\n\t\t\t\tdecoded = self._decode_session(blob)\n\n\t\t\texcept exceptions.InvalidSessionBlob as e:\n\t\t\t\t\n\t\t\t\tself.logging.warning('Detected session blob as invalid. Discarding.')\n\t\t\t\treturn\n\n\t\t\texcept exceptions.InvalidSession as e:\n\n\t\t\t\tself.logging.error('Detected session as invalid. Discarding. Exception: \"%s\".' % e)\n\n\t\t\telse:\n\t\t\t\tself.logging.info('Detected session as valid.')\n\t\t\t\tself.logging.debug('Decoded Session: \"%s\".' % decoded)\n\n\t\t\t\t# Build session key and retrieve\n\t\t\t\tsession_key = ndb.Key(urlsafe=decoded.get('k'))\n\n\t\t\t\t# Check memcache first\n\t\t\t\tsession = self._get_mem_session(session_key).get_result()\n\t\t\t\tif not session:\n\n\t\t\t\t\t# Fallback to NDB\n\t\t\t\t\tsession = self._get_ndb_session(session_key).get_result()\n\n\t\t\t\tif session:\n\t\t\t\t\t\t# If found, set a future for the data blob\n\t\t\t\t\t\tsession._set_data(ndb.Key(self.models.data, 'data', parent=session_key).get_async())\n\t\telse:\n\t\t\tself.logging.info('No session found on request.')\n\n\t\t# Set the current session\n\t\tself._set_session(session)\n\n\t\treturn self\n\n\tdef establish(self, handler):\n\n\t\t''' Resolve or establish a user's session. '''\n\n\t\t# Copy over handler + attempt to load session\n\t\treturn self.load_session(handler)\n\n\tdef commit(self):\n\n\t\t''' Save the current session and write a response cookie. '''\n\n\t\tself._make_session_cookie()._save_session().get_result()\n\t\tndb.Return(self.handler)\n","sub_path":"app/yoga/platform/tantric/core/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":10262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"540148643","text":"import numpy as np\n\n\"\"\"\n Minimalistic implementation of the Learning Vector Quantization (LVQ)\n based on Python Data Science Cookbook\n\"\"\"\n\n# class of prototype vectors\nclass prototype(object):\n \"\"\"\n Define prototype, prototype is a vector with weights(p_vector) and label(class_id)\n \"\"\"\n def __init__(self, class_id, p_vector, epsilon):\n self.class_id = class_id\n self.p_vector = p_vector\n self.epsilon = epsilon\n def update(self, u_vector, increment = True):\n \"\"\"\n The function to update the prototype vector of the closest point\n\n If the class label of the prototype vector is the same as the input data point, we will\n increment the prototype vector with the difference between the prototype vector and data\n point.\n If the class label is different, we will decrement the prototype vector with the difference\n between the prototype vector and data point.\n \"\"\"\n if increment:\n # Move the prototype closer to input vector\n self.p_vector = self.p_vector + self.epsilon * (u_vector - self.p_vector)\n else:\n # Move the prototype away from input vector\n self.p_vector = self.p_vector - self.epsilon * (u_vector - self.p_vector)\n\nclass LVQ(object):\n def __init__(self, x, y, n_classes, n_neurons, p_vectors, epsilon=0.9, epsilon_dec_factor=0.001):\n \"\"\"\n Initialize a LVQ network.\n\n Parameters\n -------\n x, y : the data and label\n n_classes: the # of distinctive classes\n n_neurons: the # of prototype vectors for each class\n epsilon: learning rate\n epsilon_dec_factor: decrease factor for learning rate\n\n p_vectors: the set of prototype vectors\n \"\"\"\n self.n_classes = n_classes\n self.n_neurons = n_neurons\n self.epsilon = epsilon\n self.epsilon_dec_factor = epsilon_dec_factor\n self.p_vectors = p_vectors\n if(len(self.p_vectors) == 0):\n p_vectors = []\n for i in range(n_classes):\n # select class i\n y_subset = np.where(y == i)\n # select tuple for chosen class\n x_subset = x[y_subset]\n # get R random indices between 0 and len(x_subset)\n samples = np.random.randint(0, len(x_subset), n_neurons)\n # select p_vectors, they are chosen randomly from the samples x\n for sample in samples:\n s = x_subset[sample]\n p = prototype(i, s, epsilon)\n p_vectors.append(p)\n self.p_vectors = p_vectors\n def find_closest(self, in_vector, proto_vectors):\n \"\"\"\n Find the closest prototype vector for a given vector\n\n Parameters\n -------\n in_vector: the given vector\n proto_vectors: the set of prototype vectors\n \"\"\"\n closest = None\n position = None\n closest_distance = 99999\n for i in range(len(proto_vectors)):\n distance = np.linalg.norm(in_vector - proto_vectors[i].p_vector)\n if distance < closest_distance:\n closest_distance = distance\n closest = proto_vectors[i]\n position = i\n return [position, closest]\n \n def find_runnerup(self, in_vector, proto_vectors):\n \"\"\"\n Find the second closest prototype vector for a given vector\n\n Parameters\n -------\n in_vector: the given vector\n proto_vectors: the set of prototype vectors\n \"\"\"\n closest_p_vector = self.find_closest(in_vector, proto_vectors)\n runnerup = closest_p_vector\n closest_distance = 99999\n for p_v in proto_vectors:\n distance = np.linalg.norm(in_vector - p_v.p_vector)\n if (distance < closest_distance) and (p_v != closest_p_vector):\n closest_distance = distance\n runnerup = p_v\n return runnerup\n def predict(self, test_vector):\n \"\"\"\n Predict label for a given input\n\n Parameters\n -------\n test_vector: input vector\n \"\"\"\n return self.find_closest(test_vector, self.p_vectors)[1].class_id\n def fit(self, x, y):\n \"\"\"\n Perform iteration to adjust the prototype vector \n in order to classify any new incoming points using existing data points\n\n Parameters\n -------\n x: input\n y: label\n \"\"\"\n while self.epsilon >= 0.01:\n rnd_i = np.random.randint(0, len(x))\n rnd_s = x[rnd_i]\n target_y = y[rnd_i]\n \n self.epsilon = self.epsilon - self.epsilon_dec_factor\n \n closest_pvector = self.find_closest(rnd_s, self.p_vectors)[1]\n \n if target_y == closest_pvector.class_id:\n closest_pvector.update(rnd_s)\n else:\n closest_pvector.update(rnd_s, False)\n closest_pvector.epsilon = self.epsilon\n return self.p_vectors\n\n def train_LVQ2(self, x, y):\n \"\"\"\n First improvement for LVQ, update both the winner and the runner up vector\n\n Parameters\n -------\n x: input\n y: label\n \"\"\"\n while self.epsilon >= 0.01:\n rnd_i = np.random.randint(0, len(x))\n rnd_s = x[rnd_i]\n target_y = y[rnd_i]\n \n self.epsilon = self.epsilon - self.epsilon_dec_factor\n \n closest_pvector = self.find_closest(rnd_s, self.p_vectors)[1]\n second_closest_pvector = self.find_runnerup(rnd_s, self.p_vectors)\n compare_distance = np.linalg.norm(closest_pvector.p_vector - rnd_s)/np.linalg.norm(second_closest_pvector.p_vector - rnd_s)\n \n if target_y == second_closest_pvector.class_id and target_y != closest_pvector.class_id and compare_distance > 0.8 and compare_distance < 1.2:\n closest_pvector.update(rnd_s, False)\n second_closest_pvector.update(rnd_s)\n elif target_y == closest_pvector.class_id:\n closest_pvector.update(rnd_s)\n elif target_y != closest_pvector.class_id:\n closest_pvector.update(rnd_s, False)\n closest_pvector.epsilon = self.epsilon\n return self.p_vectors","sub_path":"20180822/LVQ.py","file_name":"LVQ.py","file_ext":"py","file_size_in_byte":6388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"339736467","text":"import math\n\nclass Solution:\n def isPowerOfTwo(self, n: int) -> bool:\n try:\n b=math.log(n, 2)\n temp=2**int(b)\n if n==temp:\n return True\n else:\n return False\n except:\n return False\n\nA=Solution()\nprint(A.isPowerOfTwo(0))","sub_path":"231. Power of Two.py","file_name":"231. Power of Two.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"297053473","text":"import sys\nimport pudb as db\nfrom typing import Callable\n# from Leetcode.utils import perf\n\nimport threading\nimport functools\n\n\nclass Printer:\n\n def __init__(self):\n self.words = []\n\n def __call__(self, item):\n self.words.append(str(item))\n\n def serialize(self):\n return ', '.join(self.words)\n\n\nclass FizzBuzz_Condition:\n\n def __init__(self, n: int):\n self.n = n\n self.cond = threading.Condition()\n self.curr = 1\n\n def sequence(self):\n for num in range(1, self.n + 1):\n yield num\n\n # printFizz() outputs \"fizz\"\n def fizz(self, printFizz: 'Callable[[], None]') -> None:\n for num in self.sequence():\n if num % 3 == 0 and num % 5 != 0:\n with self.cond:\n self.cond.wait_for(lambda: self.curr == num)\n printFizz()\n self.curr += 1\n self.cond.notify_all()\n\n # printBuzz() outputs \"buzz\"\n def buzz(self, printBuzz: 'Callable[[], None]') -> None:\n for num in self.sequence():\n if num % 5 == 0 and num % 3 != 0:\n with self.cond:\n self.cond.wait_for(lambda: self.curr == num)\n printBuzz()\n self.curr += 1\n self.cond.notify_all()\n\n # printFizzBuzz() outputs \"fizzbuzz\"\n def fizzbuzz(self, printFizzBuzz: 'Callable[[], None]') -> None:\n for num in self.sequence():\n if num % 3 == 0 and num % 5 == 0:\n with self.cond:\n self.cond.wait_for(lambda: self.curr == num)\n printFizzBuzz()\n self.curr += 1\n self.cond.notify_all()\n\n # printNumber(x) outputs \"x\", where x is an integer.\n def number(self, printNumber: 'Callable[[int], None]') -> None:\n for num in self.sequence():\n if num % 3 != 0 and num % 5 != 0:\n with self.cond:\n self.cond.wait_for(lambda: self.curr == num)\n printNumber(num)\n self.curr += 1\n self.cond.notify_all()\n\n\nclass FizzBuzz_Lock:\n\n def __init__(self, n: int):\n self.n = n\n self.lock = threading.Lock()\n self.curr = 1\n\n def sequence(self):\n for num in range(1, self.n + 1):\n yield num\n\n # printFizz() outputs \"fizz\"\n def fizz(self, printFizz: 'Callable[[], None]') -> None:\n for num in self.sequence():\n if num % 3 == 0 and num % 5 != 0:\n while self.curr <= num:\n with self.lock:\n if self.curr == num:\n printFizz()\n self.curr += 1\n\n # printBuzz() outputs \"buzz\"\n def buzz(self, printBuzz: 'Callable[[], None]') -> None:\n for num in self.sequence():\n if num % 5 == 0 and num % 3 != 0:\n while self.curr <= num:\n with self.lock:\n if self.curr == num:\n printBuzz()\n self.curr += 1\n\n # printFizzBuzz() outputs \"fizzbuzz\"\n def fizzbuzz(self, printFizzBuzz: 'Callable[[], None]') -> None:\n for num in self.sequence():\n if num % 3 == 0 and num % 5 == 0:\n while self.curr <= num:\n with self.lock:\n if self.curr == num:\n printFizzBuzz()\n self.curr += 1\n\n # printNumber(x) outputs \"x\", where x is an integer.\n def number(self, printNumber: 'Callable[[int], None]') -> None:\n for num in self.sequence():\n if num % 3 != 0 and num % 5 != 0:\n while self.curr <= num:\n with self.lock:\n if self.curr == num:\n printNumber(num)\n self.curr += 1\n\n\nif __name__ == '__main__':\n\n def execute_thread(inst, method_name, printer):\n th_name = threading.current_thread().name\n method = getattr(inst, method_name)\n method(printer)\n\n tests = [\n [\n 15,\n \"1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizzbuzz\"\n ],\n ]\n\n test_results = []\n for i, t in enumerate(tests):\n n, exp = t\n\n if sys.argv[1:2] and int(sys.argv[1]) == i + 1:\n db.set_trace()\n\n # fizz_buzz = FizzBuzz_Condition(n)\n fizz_buzz = FizzBuzz_Lock(n)\n printer = Printer()\n threads = []\n thread_tasks = [\n ['fizz', functools.partial(printer, 'fizz')],\n ['buzz', functools.partial(printer, 'buzz')],\n ['fizzbuzz', functools.partial(printer, 'fizzbuzz')],\n ['number', printer],\n ]\n\n for method_name, local_printer in thread_tasks:\n th = threading.Thread(\n target=execute_thread,\n args=(fizz_buzz, method_name, local_printer),\n name=method_name\n )\n threads.append(th)\n\n for th in threads:\n th.start()\n\n for th in threads:\n th.join()\n\n ans = printer.serialize()\n test_results.append(ans == exp)\n print(f'{i + 1})', 'ans:')\n print(ans)\n print('exp:')\n print(exp)\n print('same:', test_results[-1])\n\n print('\\nAll tests passed:', all(test_results), f'({sum(test_results)} of {len(test_results)})')\n\n\n\"\"\"\n1195. Fizz Buzz Multithreaded\nMedium\n\nWrite a program that outputs the string representation of numbers from 1 to n, however:\n\n * If the number is divisible by 3, output \"fizz\".\n * If the number is divisible by 5, output \"buzz\".\n * If the number is divisible by both 3 and 5, output \"fizzbuzz\".\n\nFor example, for n = 15, we output: 1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizzbuzz.\n\nSuppose you are given the following code:\n\nclass FizzBuzz {\n public FizzBuzz(int n) { ... } // constructor\n public void fizz(printFizz) { ... } // only output \"fizz\"\n public void buzz(printBuzz) { ... } // only output \"buzz\"\n public void fizzbuzz(printFizzBuzz) { ... } // only output \"fizzbuzz\"\n public void number(printNumber) { ... } // only output the numbers\n}\n\nImplement a multithreaded version of FizzBuzz with four threads. The same instance of FizzBuzz will be passed to four different threads:\n\n 1. Thread A will call fizz() to check for divisibility of 3 and outputs fizz.\n 2. Thread B will call buzz() to check for divisibility of 5 and outputs buzz.\n 3. Thread C will call fizzbuzz() to check for divisibility of 3 and 5 and outputs fizzbuzz.\n 4. Thread D will call number() which should only output the numbers.\n\"\"\"\n","sub_path":"Leetcode/concurrency/fizz_buzz_multithreaded.py","file_name":"fizz_buzz_multithreaded.py","file_ext":"py","file_size_in_byte":6804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"5615073","text":"try:\n from cStringIO import StringIO\n import xmlrpclib\nexcept ImportError:\n from io import StringIO\n import xmlrpc.client as xmlrpclib\n\nimport werckercli\nfrom werckercli.cli import puts, get_term\n\nimport semantic_version as semver\n\n\ndef find_current_version(package, cur_version, index_urls=None):\n\n if index_urls is None:\n index_urls = ['http://pypi.python.org/pypi']\n\n for index_url in index_urls:\n pypi = xmlrpclib.ServerProxy(index_url, xmlrpclib.Transport())\n pypi_hits = pypi.package_releases(package)\n if len(pypi_hits) > 0:\n if semver.Version(pypi_hits[0]) > cur_version:\n return semver.Version(pypi_hits[0])\n\n return False\n\n\ndef update(current_version=None):\n\n term = get_term()\n\n if current_version is None:\n current_version = werckercli.__version__\n\n current_version = semver.Version(current_version)\n\n newer_version = find_current_version(\n \"wercker\",\n current_version\n )\n\n if newer_version:\n puts(\"\"\"A newer version of the wercker-cli was found ({newer_version}).\nPlease upgrade:\n\"\"\".format(newer_version=newer_version) +\n term.bold_white('pip install wercker --upgrade')\n )\n return True\n\n else:\n puts(\"Current version is up-to-date ({version})\".format(\n version=current_version))\n\n return False\n","sub_path":"werckercli/commands/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"471198565","text":"def mod(u, m):\n return (u % m + m) % m\n\n\ndef power_mod(a, e, m):\n result = 1\n while e > 0:\n if e % 2 == 0:\n e = e // 2\n a = (a * a) % m\n else:\n e = e - 1\n result = (result * a) % m\n e = e // 2\n a = (a * a) % m\n return result\n\n\ndef update_egcd(r0, r1, q):\n tmp = r0 - q * r1\n r0 = r1\n r1 = tmp\n return r0, r1\n\n\ndef egcd(r0, r1):\n x1 = y0 = 0\n y1 = x0 = 1\n while r1:\n q = r0 // r1\n r0, r1 = update_egcd(r0, r1, q)\n x0, x1 = update_egcd(x0, x1, q)\n y0, y1 = update_egcd(y0, y1, q)\n return r0, x0, y0\n\n\ndef inverse_mod(a, m):\n g, x, _ = egcd(a, m)\n if g != 1:\n return -1\n else:\n return (x % m + m) % m\n\n\ndef solve_lde(a, b, c):\n g, x, y = egcd(a, b)\n m = c // g\n x *= m\n y *= m\n success = (c - m * g) == 0\n return g, x, y, success\n\n\ndef crt(rs, ms):\n R = rs[0]\n M = ms[0]\n for i in range(1, len(rs)):\n g, v, u, success = solve_lde(M, -ms[i], rs[i] - R)\n if not success:\n return -1, -1\n g = abs(g)\n v = mod(v, ms[i] / g)\n R = M * v + R\n M = M // g * ms[i]\n R %= M\n return R, M\n\n\nif __name__ == \"__main__\":\n n = 26\n for i in range(1, n):\n inv = inverse_mod(i, n)\n print(f\"{i} x {inv} = {(i * inv) % n}\")","sub_path":"modulo.py","file_name":"modulo.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"353117749","text":"from twitchbot import Command\n\n\n@Command('commands', aliases=['command'])\nasync def cmd_function(msg, *args):\n await msg.reply(' lisare1Heart feel free to try !robbery, !soulmate, !wisdom, !seduce, !karma, !vampire, !zoo lisare1Heart ')\n\n\n@Command('schedule')\nasync def cmd_function(msg, *args):\n await msg.reply(\n 'lisare1Heart weekdays: 9-ish till evening I study and have lectures, then python and/or eve online in the evenings till cca 10pm. weekends: surprise but basically a more chill study/python/eve time lisare1Heart ')\n\n\n@Command('emotes', aliases=['emo','emoji'])\nasync def cmd_function(msg, *args):\n await msg.reply(' lisare1Hiss lisare1Skull lisare1Heart lisare1Robot lisare1Arson ')\n\n\n@Command('subscribe', aliases=['sub'])\nasync def cmd_function(msg, *args):\n await msg.reply(' u get to use more than just these and also u will make me happy... lisare1Hiss lisare1Skull lisare1Heart lisare1Robot lisare1Arson ')\n\n@Command('theend')\nasync def cmd_function(msg, *args):\n allowed_users = {'lisarei'}\n if msg.author in allowed_users:\n await msg.reply(\n 'lisare1Heart thank u all for watching!!! pls follow me!!! also come to my discord and see u tomorrow!!! <3 https://discord.com/invite/YuXqUR6 lisare1Heart ')\n\n\n","sub_path":"commands/housekeeping_commands.py","file_name":"housekeeping_commands.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"558925561","text":"import numpy as np\nimport random\nimport copy\nfrom collections import namedtuple, deque\n\nfrom p2_model import Actor, Critic\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nBUFFER_SIZE = int(1e6) # replay buffer size\nBATCH_SIZE = 128 # batch size\nGAMMA = 0.99 # discount factor\nTAU = 1e-3 # for soft update of target parameters\nLR_ACTOR = 1e-3 # learning rate for actor\nLR_CRITIC = 1e-3 # learning rate for critic\nWEIGHT_DECAY = 0 # L2 weight decay\nUPDATE_EVERY = 20 # update every n steps\nNUM_LEARNING = 10 # number of times to use experiences from Replay Buffer to learn\nEPSILON = 1.0 # explore->exploit noise process added to act step\nEPSILON_DECAY = 1e-6 # decay rate for noise process\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nclass Agent():\n \"\"\"Interacts with and learns from the environment.\"\"\"\n\n def __init__(self, state_size, action_size, seed, fc1_uni=400, fc2_uni=300, leak=0.001):\n \"\"\"Initialize an Agent object.\n\n Params\n ======\n state_size (int): dimension of each state\n action_size (int): dimension of each action\n seed (int): random seed\n \"\"\"\n self.state_size = state_size\n self.action_size = action_size\n self.seed = random.seed(seed)\n self.epsilon = EPSILON\n\n # Actor Network (local / target)\n self.actor_local = Actor(state_size, action_size, seed, fc1_units=fc1_uni, fc2_units=fc2_uni, leak=leak).to(device)\n self.actor_target = Actor(state_size, action_size, seed, fc1_units=fc1_uni, fc2_units=fc2_uni, leak=leak).to(device)\n self.actor_optimizer = optim.Adam(self.actor_local.parameters(), lr=LR_ACTOR)\n\n self.critic_local = Critic(state_size, action_size, seed, fcs1_units=fc1_uni, fc2_units=fc2_uni, leak=leak).to(device)\n self.critic_target = Critic(state_size, action_size, seed, fcs1_units=fc1_uni, fc2_units=fc2_uni, leak=leak).to(device)\n self.critic_optimizer = optim.Adam(self.critic_local.parameters(), lr=LR_CRITIC)\n\n # Noise process \n self.noise = OUNoise(action_size, seed)\n\n # Replay memory\n self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, seed)\n\n # Initialize time step (for updating every UPDATE_EVERY steps)\n self.t_step = 0\n\n def step(self, state, action, reward, next_state, done):\n \"\"\"Save experience in replay memory, and use random sample from buffer to learn.\"\"\"\n # Save experience / reward\n self.memory.add(state, action, reward, next_state, done)\n\n # Learn, if enough samples are available in memory\n # Learn every UPDATE_EVERY time steps\n self.t_step = (self.t_step + 1) % UPDATE_EVERY\n if self.t_step == 0:\n if len(self.memory) > BATCH_SIZE:\n for ii in range(NUM_LEARNING): # repetitively randomly learn\n experiences = self.memory.sample()\n self.learn(experiences, GAMMA)\n\n def act(self, state, add_noise=True):\n \"\"\"Returns actions for given state as per current policy.\"\"\"\n state = torch.from_numpy(state).float().to(device)\n self.actor_local.eval()\n with torch.no_grad():\n action = self.actor_local(state).cpu().data.numpy()\n self.actor_local.train()\n\n if add_noise:\n action += self.epsilon * self.noise.sample()\n return np.clip(action, -1., 1.)\n\n def reset(self):\n self.noise.reset()\n\n def learn(self, experiences, gamma):\n \"\"\"Update policy and value parameters using given batch of experience tuples.\n Q_targets = r + γ * critic_target(next_state, actor_target(next_state))\n where:\n actor_target(state) -> action\n critic_target(state, action) -> Q-value\n\n Params\n ======\n experiences (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples \n gamma (float): discount factor\n \"\"\"\n states, actions, rewards, next_states, dones = experiences\n\n # ---------------------------- update critic ---------------------------- #\n # Get predicted next-state actions and Q values from target models\n action_target_next = self.actor_target(next_states)\n Q_target_next = self.critic_target(next_states, action_target_next)\n # Compute Q targets for current states (y_i)\n y_i = rewards + (gamma * Q_target_next * (1 - dones))\n # Compute critic loss\n Q_local_current = self.critic_local(states, actions)\n critic_loss = F.mse_loss(Q_local_current, y_i)\n # Minimize the loss\n self.critic_optimizer.zero_grad()\n critic_loss.backward()\n torch.nn.utils.clip_grad_norm(self.critic_local.parameters(), 1)\n self.critic_optimizer.step()\n\n # ---------------------------- update actor ---------------------------- #\n # Use policy gradient to update actor\n # Compute sampled expected Q value of current state\n action_local_current = self.actor_local(states)\n negative_expected_Q_current = -self.critic_local(states, action_local_current).mean()\n # Maximize expected Q value from samples = using gradient descent to minimize -(expected Q)\n self.actor_optimizer.zero_grad() # clear gradients\n negative_expected_Q_current.backward()\n self.actor_optimizer.step()\n\n # ----------------------- update target networks ----------------------- # \n self.soft_update(self.actor_local, self.actor_target, TAU)\n self.soft_update(self.critic_local, self.critic_target, TAU)\n\n # ---------------------------- update noise ---------------------------- #\n self.epsilon -= EPSILON_DECAY\n self.noise.reset()\n\n def soft_update(self, local_model, target_model, tau):\n \"\"\"Soft update model parameters.\n θ_target = τ*θ_local + (1 - τ)*θ_target\n\n Params\n ======\n local_model: PyTorch model (weights will be copied from)\n target_model: PyTorch model (weights will be copied to)\n tau (float): interpolation parameter \n \"\"\"\n for local_params, target_params in zip(local_model.parameters(), target_model.parameters()):\n target_params.data.copy_(tau * local_params.data + (1 - tau) * target_params.data)\n\nclass OUNoise():\n \"\"\"Ornstein-Uhlenbeck process.\"\"\"\n\n def __init__(self, size, seed, mu=0., theta=0.15, sigma=0.2):\n \"\"\"Initialize parameters and noise process.\"\"\"\n self.mu = mu * np.ones(size)\n self.theta = theta\n self.sigma = sigma\n self.seed = random.seed(seed)\n self.reset()\n\n def reset(self):\n \"\"\"Reset the internal state (= noise) to mean (mu).\"\"\"\n self.state = copy.copy(self.mu)\n\n def sample(self):\n x = self.state\n dx = self.theta * (self.mu - x) + self.sigma * np.array([random.random() for i in range(len(x))])\n self.state = x + dx \n return self.state\n\nclass ReplayBuffer():\n \"\"\"Fixed-size buffer to store experience tuples.\"\"\"\n\n def __init__(self, action_size, buffer_size, batch_size, seed):\n \"\"\"Initialize a ReplayBuffer object.\n Params\n ======\n buffer_size (int): maximum size of buffer\n batch_size (int): size of each training batch\n \"\"\"\n self.action_size = action_size\n self.memory = deque(maxlen=buffer_size)\n self.batch_size = batch_size\n self.experience = namedtuple(\"Experiences\", field_names=[\"state\", \"action\", \"reward\", \"next_state\", \"done\"])\n self.seed = random.seed(seed)\n\n def add(self, state, action, reward, next_state, done):\n \"\"\"Add a new experience to memory.\"\"\"\n exp_ = self.experience(state, action, reward, next_state, done)\n self.memory.append(exp_)\n\n def sample(self):\n \"\"\"Randomly sample a batch of experiences from memory.\"\"\"\n samples = random.sample(self.memory, k=self.batch_size)\n\n states = torch.from_numpy(np.vstack([s_.state for s_ in samples if s_ is not None])).float().to(device)\n actions = torch.from_numpy(np.vstack([s_.action for s_ in samples if s_ is not None])).float().to(device)\n rewards = torch.from_numpy(np.vstack([s_.reward for s_ in samples if s_ is not None])).float().to(device)\n next_states = torch.from_numpy(np.vstack([s_.next_state for s_ in samples if s_ is not None])).float().to(device)\n dones = torch.from_numpy(np.vstack([s_.done for s_ in samples if s_ is not None]).astype(np.uint8)).float().to(device)\n return (states, actions, rewards, next_states, dones)\n\n def __len__(self):\n \"\"\"Return the current size of internal memory.\"\"\"\n return len(self.memory)\n\n","sub_path":"p2_ddpg_agent.py","file_name":"p2_ddpg_agent.py","file_ext":"py","file_size_in_byte":8805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"16382295","text":"import pandas as pd\nimport numpy as np\nimport os, glob, re\nimport matplotlib.pyplot as plt\nimport toolkits as tk\nfrom sklearn.neighbors import KernelDensity\nimport seaborn as sns\nfrom datetime import date\nimport datetime\n\n\n\n\ndef check_zero_values(crypto_names, crypto_df):\n\n zero_value = False\n # crypto is str here\n for crypto in crypto_names:\n price = crypto_df[crypto].values\n if 0 in price:\n zero_value = True\n zero_index = np.where(price == 0)[0]\n print(crypto, zero_index)\n\n for zero_row in zero_index:\n previous_value = crypto_df.loc[[zero_row-1],crypto].values\n i = 1\n next_value = 0\n while True:\n # next value\n if crypto_df.loc[[zero_row+i],crypto].values != 0:\n next_value = crypto_df.loc[[zero_row+i],crypto].values\n break\n i += 1\n crypto_df.at[zero_row, crypto] = (previous_value + next_value)/2\n if zero_value:\n crypto_df.to_csv('csv_folder/qualified_all_cryptos_price_156weeks.csv', index = False)\n\n return crypto_df\n\n\n\n\ndef calculate_sd_expected_return(crypto_names, crypto_df, df, extreme_value = True):\n '''\n This function will merge sd and E to a df\n df: merged dataframe\n '''\n\n # standard deviation for each crypto return\n sd_crypto = []\n # expected return E(r_i)\n expected_return = []\n \n for crypto in crypto_names:\n # remember: weekly data requires lag = 6\n daily_return = tk.compute_n_lag_return(crypto_df[crypto], 6, change_rate = True)\n if not extreme_value:\n sd_crypto.append(np.std(daily_return))\n expected_return.append(np.average(daily_return))\n else:\n # take log if there are very large number\n ## log risk vs log return\n sd_crypto.append(np.log(np.std(daily_return)))\n expected_return.append(np.log(np.average(daily_return)))\n \n \n df['sd_price'] = sd_crypto\n df['expected_return_7D'] = expected_return\n\n return sd_crypto, expected_return, df\n\n\n\n\ndef main():\n\n price_df = pd.read_csv('csv_folder/qualified_all_cryptos_price_156weeks.csv')\n \n crypto_names = list(price_df.columns.values)\n del crypto_names[0]\n del crypto_names[-1]\n \n df = pd.DataFrame(crypto_names, columns = ['crypto'])\n \n \n \n \n # 1\n # check if there are zeros in df\n price_df = check_zero_values(crypto_names, price_df)\n\n # 2\n # merge SD and expected return\n sd_crypto, expected_return, df = calculate_sd_expected_return(crypto_names, price_df, df, False)\n \n \n\n\n\n\n\n\n\n\n # 3\n # plot SD-E() graph\n # note: if sd and expected value is too small, the log of them would be < 0\n '''\n log(SD) and log(E) are positive correlated. It is almost linear!\n '''\n plt.scatter(sd_crypto, expected_return)\n plt.xlabel('log of std. deviation (risk)')\n plt.ylabel('log of expected return')\n #plt.savefig('figures/weekly_crypto_log-risk_log-return.png')\n #plt.savefig('crypto_log-risk_log-return.png')\n plt.clf()\n \n \n '''\n Because the SD and E() of crypto: digixdao is extremely large, outlier. \n Let's see would the risk-return figure look like if we remove digixdao\n '''\n #==============\n #\n #\n #max_index = sd_crypto.index(max(sd_crypto))\n #print(max_index)\n #print(df.loc[[max_index]])\n #\n #price_digixdao = price_df['digixdao'].values\n #plt.plot([i for i in range(len(price_digixdao))], price_digixdao)\n #plt.savefig('a.png')\n #plt.clf()\n \n \n\n ## Remove outlier\n large_index = []\n # contains all outlier names\n outlier = []\n for i in sd_crypto:\n if i > 50:\n large_index.append(sd_crypto.index(i))\n print(large_index)\n\n\n for outlier_crypto in large_index:\n outlier.append(df.loc[[outlier_crypto]]['crypto'].values[0])\n print(outlier)\n price_df = price_df.drop(outlier, axis = 1)\n\n\n\n\n crypto_names = list(price_df.columns.values)\n del crypto_names[0]\n del crypto_names[-1]\n\n df = pd.DataFrame(crypto_names, columns = ['crypto'])\n sd_crypto, expected_return, df = calculate_sd_expected_return(crypto_names, price_df, df, False)\n\n plt.scatter(sd_crypto, expected_return)\n plt.xlabel('std. deviation (risk)')\n plt.ylabel('expected return')\n plt.savefig('figures/weekly_crypto_no_outlier_risk_return.png')\n plt.clf()\n \n\n #==============\n \n \n \n \n\n\n\n\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n\n\n\n\n","sub_path":"web_scrapping/all_crypto_data/analysis_weekly_data.py","file_name":"analysis_weekly_data.py","file_ext":"py","file_size_in_byte":4624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"491633214","text":"# Import modules\nimport numpy as np\nimport numpy.ma as ma\nimport math\nimport pyswarms.backend as P\nfrom pyswarms.backend.topology import AdaptiveRing\nfrom pyswarms.utils.functions.constrained import Sphere\ncop = Sphere()\nN = 100\ndim = 2\nl_lim = cop.l_lim\nu_lim = cop.u_lim\nif l_lim == None or u_lim == None:\n bounds = None\nelse:\n l_lims = np.asarray([l_lim] * dim)\n u_lims = np.asarray([u_lim] * dim)\n bounds = (l_lims, u_lims)\nmy_topology = AdaptiveRing()\nmy_options = {'c1': 0.6, 'c2': 0.3, 'w': 0.4,\n 'feasibility': np.zeros(N, dtype = bool),\n 'best_position': None}\nmy_swarm = P.create_swarm(n_particles = N, dimensions=dim, options=my_options, bounds = bounds)\nmy_swarm.pbest_pos = np.asarray([None] * N)\nmy_swarm.pbest_cost = np.asarray([None] * N)\niterations = 100\nk_delta = math.ceil( N / iterations)\nk = k_delta\nmy_swarm.options['feasibility'] = cop.constraints(my_swarm.position)\nmy_swarm.current_cost = cop.objective(my_swarm.position)\nfor particle_id in range(N):\n if my_swarm.options['feasibility'][particle_id] == True:\n my_swarm.pbest_pos[particle_id] = my_swarm.position[particle_id]\n my_swarm.pbest_cost[particle_id] = my_swarm.current_cost[particle_id]\n\nfor i in range(iterations):\n if np.all(my_swarm.pbest_cost == None) == False:\n my_swarm.best_cost = min(x for x in my_swarm.pbest_cost if x is not None)\n min_pos_id = np.where(my_swarm.pbest_cost == my_swarm.best_cost)[0][0]\n my_swarm.options['best_position'] = my_swarm.pbest_pos[min_pos_id]\n if k < N:\n my_swarm.best_pos = my_topology.compute_gbest(my_swarm, p = 2, k = k)\n else:\n my_swarm.best_pos = my_topology.compute_gbest(my_swarm, p = 2, k = N)\n k += k_delta\n if i%50==0:\n print('Iteration: {} | my_swarm.best_cost: {:.4f}'.format(i+1, my_swarm.best_cost))\n my_swarm.velocity = my_topology.compute_constrained_velocity(my_swarm)\n my_swarm.position = my_topology.compute_position(my_swarm)\n my_swarm.options['feasibility'] = cop.constraints(my_swarm.position)\n my_swarm.current_cost = cop.objective(my_swarm.position)\n my_swarm.pbest_pos, my_swarm.pbest_cost = P.compute_constrained_pbest(my_swarm)\n\nprint('The best cost found by our swarm is: {:.4f}'.format(my_swarm.best_cost))\nprint('The best position found by our swarm is: {}'.format(my_swarm.options['best_position']))\n","sub_path":"docs/examples/tutorials/topology/test_ring.py","file_name":"test_ring.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"502959939","text":"import numpy as np \nimport matplotlib.pyplot as plt \n\n\ndef multiple_data(n_samples, n_features):\n X=list()\n E=list()\n\n alpha = np.abs(np.random.uniform(0.1,1, size=n_features))\n constant = np.random.uniform(0.1,1, size=n_features)\n for i in range(n_features):\n E.append(np.random.normal(0,np.abs(np.random.normal()), size=n_samples)) #noise generator\n X.append(np.random.normal(0,5,size=n_samples)) #single n_features random variable generation\n \n X = np.array(X).T\n E = np.array(E).T\n Y = np.sum(X*alpha + constant, axis=1)\n X = X+E\n return(X,Y)\n\n\n\ndef logistic_data(n_samples, n_features):\n\n\tmean1, mean2 = np.zeros(n_features) - 1, np.zeros(n_features) + 1\n\tcov_mat = np.identity(n_features)\n##\tcov_mat = np.array([[0.2,0.9],[0.4,0.7]])\n\tsize1 = n_samples//2\n\tsize2 = n_samples - size1\n\tx1 = np.random.multivariate_normal(mean1, cov_mat, size1)\n\tx2 = np.random.multivariate_normal(mean2, cov_mat, size2)\n\n\ty1 = np.zeros(size1)\n\ty2 = np.zeros(size2)+1\n\n\ty=np.hstack((y1,y2))\n\tx=np.vstack((x1,x2))\n\t\n\treturn(x,y)\n\n\ndef kmeans_data(n_samples, n_features, n_clusters):\n\tcov_mat = np.identity(n_features)\n\tsize = n_samples//n_clusters\n\tmean=np.random.multivariate_normal(np.zeros(n_features), cov_mat*n_clusters)\n\tx=np.random.multivariate_normal(mean, cov_mat, (n_samples-(size*(n_clusters-1))))\n\ty=np.zeros(n_samples-(size*(n_clusters-1)))\n\tsize = n_samples//n_clusters\n\n\tfor i in range(n_clusters-1):\n\t\tmean=np.random.multivariate_normal(np.zeros(n_features), cov_mat*n_clusters)\n\t\tx = np.vstack((x,np.random.multivariate_normal(mean, cov_mat, size)))\n\t\ty = np.hstack((y,(np.zeros(size)+i+1)))\n\n\n\treturn(x,y)\n\n\n\n\n# x,y = multiple_data(10,1)\n# print(x.shape)\n# print(y.shape)\n# plt.scatter(x,y)\n\n# x,y = kmeans_data(1000,2,4)\n# print(x.shape)\n# print(y.shape)\n# plt.scatter(x[:,0],x[:,1],c=y)\n# plt.show()\n\n\n# x,y = logistic_data(100,2)\n# print(x.shape)\n# print(y.shape)\n# plt.scatter(x[:,0], x[:,1], c=y)\n# plt.show()\n","sub_path":"Assignment/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"319895146","text":"__author__ = 'kic'\nimport flask\nfrom forum_app.api_packs.make_response.make_response import make_response\nfrom forum_app.api_packs.db_queries.queries import exec_sql, open_sql, build_sql_select_all_query, \\\n build_sql_update_query\n\n\ndef close_thread(data):\n code = 0\n thread_id = data['thread']\n\n sql_scheme = {\n 'columns_names': ['id'],\n 'columns_values': [thread_id],\n 'table': 'Thread'\n }\n\n sql_check = build_sql_select_all_query(sql_scheme)\n res = open_sql(sql_check)\n\n if res:\n sql_scheme = {\n 'columns_names': ['isClosed'],\n 'columns_values': [1],\n 'condition': {'id': thread_id},\n 'table': 'Thread'\n }\n exec_message = exec_sql(build_sql_update_query(sql_scheme))\n if exec_message != 0:\n code = 4\n\n else:\n code = 1\n\n keys = ['thread']\n values = [thread_id]\n\n resp_dict = make_response(keys, values, code)\n return flask.jsonify(resp_dict)","sub_path":"forum_app/api_packs/thread_api/thread_close.py","file_name":"thread_close.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"321425560","text":"import numpy as np\nfrom flask import Flask, request, jsonify, render_template\nimport pickle\n\napp = Flask(__name__)\nmodel = pickle.load(open('model.pkl', 'rb'))\n\n@app.route('/') #index or landing page of website\ndef home():\n return render_template('index.html')\n# 127.0.0.1:8080/predict\n@app.route('/predict',methods=['POST']) #post method is used to send parameters in http request\ndef predict():\n '''\n For rendering results on HTML GUI'''\n int_features = [int(x) for x in request.form.values()]\n final_features = [np.array(int_features)]\n print(\"Features are \", final_features, \" No of features =\", len(final_features))\n prediction = model.predict(final_features)\n output = round(prediction[0], 2)\n # output =10\n return render_template('index.html', \n \tprediction_text='Inflow for Tomorrow is (Cusecs) {}'.format(output))\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\",port=8080) # EC2\n # app.run(host=\"127.0.0.1\",port=8080) # local machine","sub_path":"sklearn_version/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"652725062","text":"# init_app.py\n\n\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sug_config import DB_NAME, RANDOM_STRING, APP_NAME\n\ndb = SQLAlchemy()\n\n\ndef create_app():\n app = Flask(APP_NAME)\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(DB_NAME)\n app.config['SECRET_KEY'] = RANDOM_STRING\n db.init_app(app)\n\n with app.app_context():\n import routes\n\n # creates only tables that do not exist\n db.create_all()\n db.session.commit()\n\n return app","sub_path":"init_app.py","file_name":"init_app.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"483064141","text":"'''\n7 2\n1 1 2 2 2 2 3\n>> 4\n\n7 4\n1 1 2 2 2 2 3\n>> -1\n'''\nfrom bisect import bisect_left, bisect_right\n\ndef count_by_range(l, a, b):\n \"\"\"\n 만약 원소가 없다면 0을 반환한다.\n 왜냐하면 리스트 최솟값 보다 작다면 둘다 0을 반환하고,\n 최대값보다 크다면 length값을 반환하기 때문이다.\n \"\"\"\n left_idx = bisect_left(l, a)\n right_idx = bisect_right(l, b)\n result = right_idx - left_idx\n if result <= 0:\n return -1\n else:\n return result\n \n\nn, x = map(int, input().split())\ndata = list(map(int, input().split()))\n\nprint(count_by_range(data, x, x))\n\n'''\n\n동일하다.\n'''","sub_path":"books/dongbin-na/part3_binary_search/binary_search_1_1.py","file_name":"binary_search_1_1.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"168336576","text":"from aqt.qt import *\r\nfrom aqt import mw\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\nimport requests\r\nfrom os.path import dirname, join, realpath\r\nfrom aqt.utils import tooltip\r\nfrom datetime import date, datetime\r\nfrom .Stats import Stats\r\nfrom .Leaderboard import start_main\r\n\r\nclass Ui_Dialog(object):\r\n\tdef setupUi(self, Dialog):\r\n\t\tDialog.setObjectName(\"Dialog\")\r\n\t\tDialog.resize(569, 240)\r\n\t\tDialog.setWindowFlags(QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowMinimizeButtonHint)\r\n\t\tDialog.setWindowIcon(QtGui.QIcon(join(dirname(realpath(__file__)), 'person.png')))\r\n\t\tDialog.setFixedSize(Dialog.size())\r\n\t\tself.Accout = QtWidgets.QGroupBox(Dialog)\r\n\t\tself.Accout.setGeometry(QtCore.QRect(10, 0, 261, 231))\r\n\t\tself.Accout.setObjectName(\"Accout\")\r\n\t\tself.layoutWidget = QtWidgets.QWidget(self.Accout)\r\n\t\tself.layoutWidget.setGeometry(QtCore.QRect(11, 21, 241, 201))\r\n\t\tself.layoutWidget.setObjectName(\"layoutWidget\")\r\n\t\tself.gridLayout = QtWidgets.QGridLayout(self.layoutWidget)\r\n\t\tself.gridLayout.setContentsMargins(0, 0, 0, 0)\r\n\t\tself.gridLayout.setObjectName(\"gridLayout\")\r\n\t\tself.create_info = QtWidgets.QLabel(self.layoutWidget)\r\n\t\tself.create_info.setObjectName(\"create_info\")\r\n\t\tself.gridLayout.addWidget(self.create_info, 0, 0, 1, 1)\r\n\t\tself.create_username = QtWidgets.QLineEdit(self.layoutWidget)\r\n\t\tself.create_username.setText(\"\")\r\n\t\tself.create_username.setMaxLength(15)\r\n\t\tself.create_username.setObjectName(\"create_username\")\r\n\t\tself.gridLayout.addWidget(self.create_username, 1, 0, 1, 1)\r\n\t\tself.create_button = QtWidgets.QPushButton(self.layoutWidget)\r\n\t\tself.create_button.setObjectName(\"create_button\")\r\n\t\tself.gridLayout.addWidget(self.create_button, 1, 1, 1, 1)\r\n\t\tself.login_info = QtWidgets.QLabel(self.layoutWidget)\r\n\t\tself.login_info.setObjectName(\"login_info\")\r\n\t\tself.gridLayout.addWidget(self.login_info, 2, 0, 1, 1)\r\n\t\tself.login_username = QtWidgets.QLineEdit(self.layoutWidget)\r\n\t\tself.login_username.setText(\"\")\r\n\t\tself.login_username.setObjectName(\"login_username\")\r\n\t\tself.gridLayout.addWidget(self.login_username, 3, 0, 1, 1)\r\n\t\tself.login_button = QtWidgets.QPushButton(self.layoutWidget)\r\n\t\tself.login_button.setObjectName(\"login_button\")\r\n\t\tself.gridLayout.addWidget(self.login_button, 3, 1, 1, 1)\r\n\t\tself.delete_info = QtWidgets.QLabel(self.layoutWidget)\r\n\t\tself.delete_info.setObjectName(\"delete_info\")\r\n\t\tself.gridLayout.addWidget(self.delete_info, 4, 0, 1, 1)\r\n\t\tself.delete_username = QtWidgets.QLineEdit(self.layoutWidget)\r\n\t\tself.delete_username.setText(\"\")\r\n\t\tself.delete_username.setObjectName(\"delete_username\")\r\n\t\tself.gridLayout.addWidget(self.delete_username, 5, 0, 1, 1)\r\n\t\tself.delete_button = QtWidgets.QPushButton(self.layoutWidget)\r\n\t\tself.delete_button.setObjectName(\"delete_button\")\r\n\t\tself.gridLayout.addWidget(self.delete_button, 5, 1, 1, 1)\r\n\t\tself.Friends = QtWidgets.QGroupBox(Dialog)\r\n\t\tself.Friends.setGeometry(QtCore.QRect(280, 0, 279, 141))\r\n\t\tself.Friends.setObjectName(\"Friends\")\r\n\t\tself.layoutWidget1 = QtWidgets.QWidget(self.Friends)\r\n\t\tself.layoutWidget1.setGeometry(QtCore.QRect(10, 20, 261, 111))\r\n\t\tself.layoutWidget1.setObjectName(\"layoutWidget1\")\r\n\t\tself.gridLayout_2 = QtWidgets.QGridLayout(self.layoutWidget1)\r\n\t\tself.gridLayout_2.setContentsMargins(0, 0, 0, 0)\r\n\t\tself.gridLayout_2.setObjectName(\"gridLayout_2\")\r\n\t\tself.add_friends_info = QtWidgets.QLabel(self.layoutWidget1)\r\n\t\tself.add_friends_info.setObjectName(\"add_friends_info\")\r\n\t\tself.gridLayout_2.addWidget(self.add_friends_info, 0, 0, 1, 1)\r\n\t\tself.friend_username = QtWidgets.QLineEdit(self.layoutWidget1)\r\n\t\tself.friend_username.setText(\"\")\r\n\t\tself.friend_username.setObjectName(\"friend_username\")\r\n\t\tself.gridLayout_2.addWidget(self.friend_username, 1, 0, 1, 1)\r\n\t\tself.add_friends_button = QtWidgets.QPushButton(self.layoutWidget1)\r\n\t\tself.add_friends_button.setObjectName(\"add_friends_button\")\r\n\t\tself.gridLayout_2.addWidget(self.add_friends_button, 1, 1, 1, 1)\r\n\t\tself.remove_friend_info = QtWidgets.QLabel(self.layoutWidget1)\r\n\t\tself.remove_friend_info.setObjectName(\"remove_friend_info\")\r\n\t\tself.gridLayout_2.addWidget(self.remove_friend_info, 2, 0, 1, 1)\r\n\t\tself.remove_friend_username = QtWidgets.QLineEdit(self.layoutWidget1)\r\n\t\tself.remove_friend_username.setText(\"\")\r\n\t\tself.remove_friend_username.setObjectName(\"remove_friend_username\")\r\n\t\tself.gridLayout_2.addWidget(self.remove_friend_username, 3, 0, 1, 1)\r\n\t\tself.remove_friend_button = QtWidgets.QPushButton(self.layoutWidget1)\r\n\t\tself.remove_friend_button.setObjectName(\"remove_friend_button\")\r\n\t\tself.gridLayout_2.addWidget(self.remove_friend_button, 3, 1, 1, 1)\r\n\t\tself.widget = QtWidgets.QWidget(Dialog)\r\n\t\tself.widget.setGeometry(QtCore.QRect(280, 150, 281, 86))\r\n\t\tself.widget.setObjectName(\"widget\")\r\n\t\tself.gridLayout_4 = QtWidgets.QGridLayout(self.widget)\r\n\t\tself.gridLayout_4.setContentsMargins(0, 0, 0, 0)\r\n\t\tself.gridLayout_4.setObjectName(\"gridLayout_4\")\r\n\t\tself.subject = QtWidgets.QComboBox(self.widget)\r\n\t\tself.subject.setObjectName(\"subject\")\r\n\t\tself.subject.addItem(\"\")\r\n\t\tself.subject.addItem(\"\")\r\n\t\tself.subject.addItem(\"\")\r\n\t\tself.subject.addItem(\"\")\r\n\t\tself.gridLayout_4.addWidget(self.subject, 0, 0, 1, 3)\r\n\t\tself.country = QtWidgets.QLineEdit(self.widget)\r\n\t\tself.country.setObjectName(\"country\")\r\n\t\tself.gridLayout_4.addWidget(self.country, 1, 0, 1, 3)\r\n\t\tself.next_day_info1 = QtWidgets.QLabel(self.widget)\r\n\t\tself.next_day_info1.setObjectName(\"next_day_info1\")\r\n\t\tself.gridLayout_4.addWidget(self.next_day_info1, 2, 0, 1, 1)\r\n\t\tself.newday = QtWidgets.QSpinBox(self.widget)\r\n\t\tself.newday.setMaximum(23)\r\n\t\tself.newday.setObjectName(\"newday\")\r\n\t\tself.gridLayout_4.addWidget(self.newday, 2, 1, 1, 1)\r\n\t\tself.next_day_info2 = QtWidgets.QLabel(self.widget)\r\n\t\tself.next_day_info2.setObjectName(\"next_day_info2\")\r\n\t\tself.gridLayout_4.addWidget(self.next_day_info2, 2, 2, 1, 1)\r\n\r\n\t\tself.create_button.clicked.connect(self.create_account)\r\n\t\tself.login_button.clicked.connect(self.login)\r\n\t\tself.delete_button.clicked.connect(self.delete)\r\n\t\tself.add_friends_button.clicked.connect(self.add_friend)\r\n\t\tself.remove_friend_button.clicked.connect(self.remove_friend)\r\n\t\tself.newday.valueChanged.connect(self.set_time)\r\n\t\tself.subject.currentTextChanged.connect(self.set_subject)\r\n\t\tself.country.textEdited.connect(self.set_country)\r\n\r\n\t\tself.retranslateUi(Dialog)\r\n\t\tQtCore.QMetaObject.connectSlotsByName(Dialog)\r\n\r\n\tdef retranslateUi(self, Dialog):\r\n\t\t_translate = QtCore.QCoreApplication.translate\r\n\r\n\t\tconfig = mw.addonManager.getConfig(__name__)\r\n\t\tconfig4 = int(config['newday'])\r\n\t\tconfig5 = config[\"subject\"]\r\n\t\tconfig6 = config[\"country\"]\r\n\t\tself.newday.setValue(config4)\r\n\t\tself.country.setText(config6)\r\n\r\n\t\tDialog.setWindowTitle(_translate(\"Dialog\", \"Config\"))\r\n\t\tself.Accout.setTitle(_translate(\"Dialog\", \"Account\"))\r\n\t\tself.create_info.setText(_translate(\"Dialog\", \"Create Account:\"))\r\n\t\tself.create_username.setPlaceholderText(_translate(\"Dialog\", \"Username\"))\r\n\t\tself.create_button.setText(_translate(\"Dialog\", \"Create Account\"))\r\n\t\tself.login_info.setText(_translate(\"Dialog\", \"Login:\"))\r\n\t\tself.login_username.setPlaceholderText(_translate(\"Dialog\", \"Username\"))\r\n\t\tself.login_button.setText(_translate(\"Dialog\", \"Login\"))\r\n\t\tself.delete_info.setText(_translate(\"Dialog\", \"Delete Account:\"))\r\n\t\tself.delete_username.setPlaceholderText(_translate(\"Dialog\", \"Username\"))\r\n\t\tself.delete_button.setText(_translate(\"Dialog\", \"Delete Account\"))\r\n\t\tself.Friends.setTitle(_translate(\"Dialog\", \"Friends\"))\r\n\t\tself.add_friends_info.setText(_translate(\"Dialog\", \"Add Friend:\"))\r\n\t\tself.friend_username.setPlaceholderText(_translate(\"Dialog\", \"Friend\"))\r\n\t\tself.add_friends_button.setText(_translate(\"Dialog\", \"Add Friend\"))\r\n\t\tself.remove_friend_info.setText(_translate(\"Dialog\", \"Remove Friend:\"))\r\n\t\tself.remove_friend_username.setPlaceholderText(_translate(\"Dialog\", \"Friend\"))\r\n\t\tself.remove_friend_button.setText(_translate(\"Dialog\", \"Remove Friend\"))\r\n\t\t\r\n\t\tself.subject.setItemText(0, _translate(\"Dialog\", \"What are you studying?\"))\r\n\t\tself.subject.setItemText(1, _translate(\"Dialog\", \"Languages\"))\r\n\t\tself.subject.setItemText(2, _translate(\"Dialog\", \"Medicine\"))\r\n\t\tself.subject.setItemText(3, _translate(\"Dialog\", \"Law\"))\r\n\t\tself.subject.setCurrentText(config5)\r\n\t\t\r\n\t\tself.country.setPlaceholderText(_translate(\"Dialog\", \"What country are you from (in English)\"))\r\n\t\tself.next_day_info1.setText(_translate(\"Dialog\", \"Next day starts\"))\r\n\t\tself.next_day_info2.setText(_translate(\"Dialog\", \"hours past midnight\"))\r\n\t\t\r\n\r\n\tdef create_account(self):\r\n\t\ttry:\r\n\t\t\tusername = self.create_username.text()\r\n\t\t\tconfig = mw.addonManager.getConfig(__name__)\r\n\t\t\tconfig3 = config['friends']\r\n\t\t\tconfig4 = config['newday']\r\n\t\t\tconfig5 = config['subject']\r\n\t\t\tconfig6 = config['country']\r\n\t\t\turl = 'https://ankileaderboard.pythonanywhere.com/users/'\r\n\t\t\tx = requests.post(url)\r\n\t\t\tif username in eval(x.text):\r\n\t\t\t\ttooltip(\"Username already taken\")\r\n\t\t\telse:\r\n\t\t\t\turl = 'https://ankileaderboard.pythonanywhere.com/sync/'\r\n\t\t\t\tstreak, cards, time, cards_past_30_days = Stats()\r\n\t\t\t\tdata = {'Username': username , \"Streak\": streak, \"Cards\": cards , \"Time\": time , \"Sync_Date\": datetime.now(), \"Month\": cards_past_30_days, \"Subject\": config5, \"Country\": config6}\r\n\t\t\t\tx = requests.post(url, data = data)\r\n\t\t\t\tconfig = {\"new_user\": \"False\",\"username\": username, \"friends\": config3, \"newday\": config4, \"country\": config6, \"subject\": config5}\r\n\t\t\t\tmw.addonManager.writeConfig(__name__, config)\r\n\t\t\t\ttooltip(\"Successfully created account.\")\r\n\t\t\t\tself.create_username.setText(\"\")\r\n\t\texcept:\r\n\t\t\tpass\r\n\r\n\tdef login(self):\r\n\t\ttry:\r\n\t\t\tusername = self.login_username.text()\r\n\t\t\tconfig = mw.addonManager.getConfig(__name__)\r\n\t\t\tconfig3 = config['friends']\r\n\t\t\tconfig4 = config['newday']\r\n\t\t\tconfig5 = config['subject']\r\n\t\t\tconfig6 = config['country']\r\n\t\t\turl = 'https://ankileaderboard.pythonanywhere.com/users/'\r\n\t\t\tx = requests.post(url)\r\n\t\t\tif username in eval(x.text):\r\n\t\t\t\tconfig = {\"new_user\": \"False\",\"username\": username, \"friends\": config3, \"newday\": config4, \"country\": config6, \"subject\": config5}\r\n\t\t\t\tmw.addonManager.writeConfig(__name__, config)\r\n\t\t\t\ttooltip(\"Successfully logged in.\")\r\n\t\t\t\tself.login_username.setText(\"\")\r\n\t\t\telse:\r\n\t\t\t\ttooltip(\"Account doesn't exist.\")\r\n\t\texcept:\r\n\t\t\tpass\r\n\r\n\tdef delete(self):\r\n\t\ttry:\r\n\t\t\tusername = self.delete_username.text()\r\n\t\t\tconfig = mw.addonManager.getConfig(__name__)\r\n\t\t\tconfig3 = config['friends']\r\n\t\t\tconfig4 = config['newday']\r\n\t\t\tconfig5 = config['subject']\r\n\t\t\tconfig6 = config['country']\r\n\t\t\turl = 'https://ankileaderboard.pythonanywhere.com/delete/'\r\n\t\t\tdata = {'Username': username}\r\n\t\t\tx = requests.post(url, data = data)\r\n\t\t\tif x.text == \"Deleted\":\r\n\t\t\t\tconfig = {\"new_user\": \"True\",\"username\": \"\", \"friends\": config3, \"newday\": config4, \"country\": config6, \"subject\": config5}\r\n\t\t\t\tmw.addonManager.writeConfig(__name__, config)\r\n\t\t\t\ttooltip(\"Successfully deleted account.\")\r\n\t\t\t\tself.delete_username.setText(\"\")\r\n\t\t\telse:\r\n\t\t\t\ttooltip(\"Error\")\r\n\t\texcept:\r\n\t\t\tpass\r\n\r\n\tdef add_friend(self):\r\n\t\tusername = self.friend_username.text()\r\n\t\tconfig = mw.addonManager.getConfig(__name__)\r\n\t\tconfig1 = config['new_user']\r\n\t\tconfig2 = config['username']\r\n\t\tconfig3 = config['friends']\r\n\t\tconfig4 = config['newday']\r\n\t\tconfig5 = config['subject']\r\n\t\tconfig6 = config['country']\r\n\t\turl = 'https://ankileaderboard.pythonanywhere.com/users/'\r\n\t\tx = requests.post(url)\r\n\t\tif config2 not in config3:\r\n\t\t\tconfig3.append(config2)\r\n\t\tif username in eval(x.text):\r\n\t\t\tconfig3.append(username)\r\n\t\t\tconfig = {\"new_user\": config1,\"username\": config2, \"friends\": config3, \"newday\": config4, \"country\": config6, \"subject\": config5}\r\n\t\t\tmw.addonManager.writeConfig(__name__, config)\r\n\t\t\ttooltip(username + \" is now your friend.\")\r\n\t\t\tself.friend_username.setText(\"\")\r\n\t\telse:\r\n\t\t\ttooltip(\"Couldn't find friend\")\r\n\r\n\tdef remove_friend(self):\r\n\t\tusername = self.remove_friend_username.text()\r\n\t\tconfig = mw.addonManager.getConfig(__name__)\r\n\t\tconfig1 = config['new_user']\r\n\t\tconfig2 = config['username']\r\n\t\tconfig3 = config['friends']\r\n\t\tconfig4 = config['newday']\r\n\t\tconfig5 = config['subject']\r\n\t\tconfig6 = config['country']\r\n\t\turl = 'https://ankileaderboard.pythonanywhere.com/users/'\r\n\t\tx = requests.post(url)\r\n\t\tif username in config3:\r\n\t\t\tconfig3.remove(username)\r\n\t\t\tconfig = {\"new_user\": config1,\"username\": config2, \"friends\": config3, \"newday\": config4, \"country\": config6, \"subject\": config5}\r\n\t\t\tmw.addonManager.writeConfig(__name__, config)\r\n\t\t\ttooltip(username + \" was removed from your friendlist\")\r\n\t\t\tself.remove_friend_username.setText(\"\")\r\n\t\telse:\r\n\t\t\ttooltip(\"Couldn't find friend\")\r\n\r\n\tdef set_time(self):\r\n\t\tbeginning_of_new_day = self.newday.value()\r\n\t\tconfig = mw.addonManager.getConfig(__name__)\r\n\t\tconfig1 = config['new_user']\r\n\t\tconfig2 = config['username']\r\n\t\tconfig3 = config['friends']\r\n\t\tconfig5 = config['subject']\r\n\t\tconfig6 = config['country']\r\n\t\tconfig = {\"new_user\": config1,\"username\": config2, \"friends\": config3, \"newday\": str(beginning_of_new_day), \"country\": config6, \"subject\": config5}\r\n\t\tmw.addonManager.writeConfig(__name__, config)\r\n\r\n\tdef set_subject(self):\r\n\t\tsubject = self.subject.currentText()\r\n\t\tconfig = mw.addonManager.getConfig(__name__)\r\n\t\tconfig1 = config['new_user']\r\n\t\tconfig2 = config['username']\r\n\t\tconfig3 = config['friends']\r\n\t\tconfig4 = config['newday']\r\n\t\tconfig6 = config['country']\r\n\t\tif subject == \"What are you studying?\":\r\n\t\t\tsubject = \"Custom\"\r\n\t\tconfig = {\"new_user\": config1,\"username\": config2, \"friends\": config3, \"newday\": config4, \"subject\": subject, \"country\": config6}\r\n\t\tmw.addonManager.writeConfig(__name__, config)\r\n\r\n\tdef set_country(self):\r\n\t\tcountry = self.country.text()\r\n\t\tcountry = country.capitalize()\r\n\t\tconfig = mw.addonManager.getConfig(__name__)\r\n\t\tconfig1 = config['new_user']\r\n\t\tconfig2 = config['username']\r\n\t\tconfig3 = config['friends']\r\n\t\tconfig4 = config['newday']\r\n\t\tconfig5 = config['subject']\r\n\t\tconfig = {\"new_user\": config1,\"username\": config2, \"friends\": config3, \"newday\": config4, \"subject\": config5 , \"country\": country}\r\n\t\tmw.addonManager.writeConfig(__name__, config)\r\n\r\n\r\nclass start_setup(QDialog):\r\n\tdef __init__(self, parent=None):\r\n\t\tself.parent = parent\r\n\t\tQDialog.__init__(self, parent, Qt.Window)\r\n\t\tself.dialog = Ui_Dialog()\r\n\t\tself.dialog.setupUi(self)\r\n","sub_path":"Setup.py","file_name":"Setup.py","file_ext":"py","file_size_in_byte":14244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"560880255","text":"# =============================================================================\n# periscope-ps (unis)\n#\n# Copyright (c) 2012-2016, Trustees of Indiana University,\n# All rights reserved.\n#\n# This software may be modified and distributed under the terms of the BSD\n# license. See the COPYING file for details.\n#\n# This software was created at the Indiana University Center for Research in\n# Extreme Scale Technologies (CREST).\n# =============================================================================\n\"\"\"\nGeneral Periscope Settings.\n\"\"\"\nimport ssl\nimport logging\nimport os\nimport sys\nfrom netlogger import nllog\nfrom tornado.log import LogFormatter, enable_pretty_logging\n\nLIST_OPTIONS = [\"unis.root_urls\"]\n\n######################################################################\n# Setting up path names.\n######################################################################\nPERISCOPE_ROOT = os.path.dirname(os.path.abspath(__file__)) + os.sep\nsys.path.append(os.path.dirname(os.path.dirname(PERISCOPE_ROOT)))\nSCHEMA_CACHE_DIR = \"/var/lib/periscope/.cache\"\n\nGCF_PATH = \"/opt/gcf/src/\"\nsys.path.append(os.path.dirname(GCF_PATH))\n\nAUTH_STORE_DIR = os.path.join(os.path.dirname(__file__), \"abac\")\n\nJSON_SCHEMAS_ROOT = PERISCOPE_ROOT + \"/schemas\"\nUNIS_SCHEMAS_USE_LOCAL = False\n\n######################################################################\n# Configuration options\n######################################################################\nDEFAULT_CONFIG = {\n \"unis_ssl\": {\n \"enable\": False,\n },\n \"unis\": {\n \"url\": \"http://localhost:8888\",\n \"summary_collection_period\": 60 * 60,\n \"root_urls\": [],\n \"summary_size\": 10,\n \"use_ms\": True,\n \"ms_url\": \"http://localhost:8888\",\n \"db_host\": \"127.0.0.1\",\n \"db_port\": 27017,\n \"db_name\": \"unis_db\"\n },\n \"auth\": {\n \"enabled\": False\n }\n}\n\n\n\n\n######################################################################\n# Tornado settings.\n######################################################################\n\n#ENABLE_SSL = False\nSSL_OPTIONS = {\n 'certfile': os.path.join(PERISCOPE_ROOT, \"ssl/server.pem\"),\n 'keyfile': os.path.join(PERISCOPE_ROOT, \"ssl/server.key\"),\n 'cert_reqs': ssl.CERT_REQUIRED,\n 'ca_certs': os.path.join(PERISCOPE_ROOT, \"ssl/genica.bundle\")\n}\n\nCLIENT_SSL_OPTIONS = {\n 'certfile': \"/usr/local/etc/certs/ms_cert.pem\",\n 'keyfile': \"/usr/local/etc/certs/ms_key.pem\"\n}\n\n######################################################################\n# Measurement Store settings.\n######################################################################\nMS_CLIENT_CERT = \"/usr/local/etc/certs/ms_cert.pem\"\nMS_CLIENT_KEY = \"/usr/local/etc/certs/ms_key.pem\"\nGEMINI_NODE_INFO = None\n\n\n######################################################################\n# Periscope Application settings.\n######################################################################\n# Enable application wide debugging options\nDEBUG = False\n\n# Time to wait before reconnecting in seconds\nREGISTER_RETRY_PERIOD = 10\n\nAPP_SETTINGS = {\n 'cookie_secret': \"43oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=\",\n 'template_path': os.path.join(os.path.dirname(__file__), \"templates/\"),\n 'static_path': os.path.join(os.path.dirname(__file__), \"static/\"),\n 'xsrf_cookies': False,\n 'autoescape': \"xhtml_escape\",\n 'debug': DEBUG,\n}\n\n######################################################################\n# Mongo Database settings\n######################################################################\nDB_AUTH = {\n 'auth_field' : \"secToken\",\n 'auth_default' : None,\n 'attrib_list' : (\"landsat\",\"unauth\"),\n}\n\n######################################################################\n# Netlogger settings\n######################################################################\nNETLOGGER_NAMESPACE = \"periscope\"\n\n_log = None\ndef config_logger(namespace=NETLOGGER_NAMESPACE, level = None, filename = None):\n tmpLog = nllog.get_logger(namespace)\n tmpLog.propagate = False\n nllog.PROJECT_NAMESPACE = namespace\n\n if filename:\n add_filehandler(tmpLog, filename)\n else:\n handler = logging.StreamHandler()\n handler.setFormatter(LogFormatter(\"%(message)s\"))\n tmpLog.addHandler(handler)\n\n if level == \"WARN\":\n tmpLog.setLevel(logging.WARN)\n elif level == \"TRACE\":\n tmpLog.setLevel(nllog.TRACE)\n elif level == \"DEBUG\":\n tmpLog.setLevel(logging.DEBUG)\n if not filename:\n enable_pretty_logging()\n elif level == \"CONSOLE\":\n tmpLog.setLevel(25)\n else:\n tmpLog.setLevel(logging.INFO)\n \n return tmpLog\n\ndef add_filehandler(log, logfile):\n log.handlers = []\n \n try:\n fileHandler = logging.handlers.RotatingFileHandler(logfile, maxBytes = 500000, backupCount = 5)\n fileHandler.setFormatter(logging.Formatter(\"%(message)s\"))\n log.addHandler(fileHandler)\n except AttributeError as exp:\n log.error(\"Could not attach File Logger: {exp}\".format(exp = exp))\n\ndef get_logger(namespace=NETLOGGER_NAMESPACE, level = None, filename = None):\n \"\"\"Return logger object\"\"\"\n # Test if netlloger is initialized\n global _log\n if nllog.PROJECT_NAMESPACE != namespace or not _log:\n _log = config_logger(namespace, level, filename)\n return _log\n\n######################################################################\n# NetworkResource Handlers settings\n######################################################################\nMIME = {\n 'HTML': 'text/html',\n 'JSON': 'application/json',\n 'PLAIN': 'text/plain',\n 'SSE': 'text/event-stream',\n 'PSJSON': 'application/perfsonar+json',\n 'PSBSON': 'application/perfsonar+bson',\n 'PSXML': 'application/perfsonar+xml',\n}\n\n#SCHEMA_HOST = 'localhost'\nSCHEMA_HOST = 'unis.crest.iu.edu'\n\n_schema = \"http://{host}/schema/{directory}/{name}\"\nSCHEMAS = {\n 'manifest': _schema.format(host = SCHEMA_HOST, directory = \"20160630\", name = \"manifest#\"),\n 'networkresource': _schema.format(host = SCHEMA_HOST, directory = \"20160630\", name = \"networkresource#\"),\n 'node': _schema.format(host = SCHEMA_HOST, directory = \"20160630\", name = \"node#\"),\n 'domain': _schema.format(host = SCHEMA_HOST, directory = \"20160630\", name = \"domain#\"),\n 'port': _schema.format(host = SCHEMA_HOST, directory = \"20160630\", name = \"port#\"),\n 'link': _schema.format(host = SCHEMA_HOST, directory = \"20160630\", name = \"link#\"),\n 'path': _schema.format(host = SCHEMA_HOST, directory = \"20160630\", name = \"path#\"),\n 'network': _schema.format(host = SCHEMA_HOST, directory = \"20160630\", name = \"network#\"),\n 'topology': _schema.format(host = SCHEMA_HOST, directory = \"20160630\", name = \"topology#\"),\n 'service': _schema.format(host = SCHEMA_HOST, directory = \"20160630\", name = \"service#\"),\n 'metadata': _schema.format(host = SCHEMA_HOST, directory = \"20160630\", name = \"metadata#\"),\n 'data': _schema.format(host = SCHEMA_HOST, directory = \"20160630\", name = \"data#\"),\n 'datum': _schema.format(host = SCHEMA_HOST, directory = \"20160630\", name = \"datum#\"),\n 'measurement': _schema.format(host = SCHEMA_HOST, directory = \"20160630\", name = \"measurement#\"),\n 'exnode': _schema.format(host = SCHEMA_HOST, directory = \"exnode/6\", name = \"exnode#\"),\n 'extent': _schema.format(host = SCHEMA_HOST, directory = \"exnode/6\", name = \"extent#\"),\n}\n\n# Default settings that apply to almost all network resources\n# This is used to make writing `Resources` easier.\ndefault_resource_settings= {\n \"base_url\": \"\", # For additional URL extension, e.g. /mynetwork/unis will make /ports like /mynetwork/unis/ports\n \"handler_class\": \"periscope.handlers.NetworkResourceHandler\", # The HTTP Request Handler class\n \"is_capped_collection\": False,\n \"capped_collection_size\": 0,\n \"id_field_name\": \"id\",\n \"timestamp_field_name\": \"ts\",\n \"allow_get\": True,\n \"allow_post\": True,\n \"allow_put\": True,\n \"allow_delete\": True,\n \"accepted_mime\": [MIME['SSE'], MIME['PSJSON'], MIME['PSBSON']],\n \"content_types_mime\": [MIME['SSE'], MIME['PSJSON']]\n}\n\nlinks = dict(default_resource_settings.items() + \\\n {\n \"name\": \"links\",\n \"pattern\": \"/links$\", # The regex used to match the handler in URI\n \"model_class\": \"periscope.models.Link\", # The name of the database collection\n \"collection_name\": \"links\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"link\"], MIME['PSBSON']: SCHEMAS[\"link\"]}, # JSON Schema fot this resource\n }.items()\n)\nlink = dict(default_resource_settings.items() + \\\n {\n \"name\": \"link\",\n \"pattern\": \"/links/(?P[^\\/]*)$\",\n \"model_class\": \"periscope.models.Link\",\n \"collection_name\": \"links\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"link\"], MIME['PSBSON']: SCHEMAS[\"link\"]},\n }.items()\n)\n\nlogin = dict(default_resource_settings.items() + \\\n {\n \"name\": \"login\",\n \"pattern\": \"/login$\",\n # \"model_class\": \"periscope.models.Port\",\n # \"collection_name\": \"ports\",\n # \"schema\": {MIME['PSJSON']: SCHEMAS[\"port\"]},\n }.items()\n)\n\nports = dict(default_resource_settings.items() + \\\n {\n \"name\": \"ports\",\n \"pattern\": \"/ports$\",\n \"model_class\": \"periscope.models.Port\",\n \"collection_name\": \"ports\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"port\"], MIME['PSBSON']: SCHEMAS[\"port\"]},\n }.items()\n)\nport = dict(default_resource_settings.items() + \\\n {\n \"name\": \"port\",\n \"pattern\": \"/ports/(?P[^\\/]*)$\",\n \"model_class\": \"periscope.models.Port\",\n \"collection_name\": \"ports\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"port\"], MIME['PSBSON']: SCHEMAS[\"port\"]},\n }.items()\n)\nnodes = dict(default_resource_settings.items() + \\\n {\n \"name\": \"nodes\",\n \"pattern\": \"/nodes$\",\n \"model_class\": \"periscope.models.Node\",\n \"collection_name\": \"nodes\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"node\"], MIME['PSBSON']: SCHEMAS[\"node\"]},\n }.items()\n)\nnode = dict(default_resource_settings.items() + \\\n {\n \"name\": \"node\",\n \"pattern\": \"/nodes/(?P[^\\/]*)$\",\n \"model_class\": \"periscope.models.Node\",\n \"collection_name\": \"nodes\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"node\"], MIME['PSBSON']: SCHEMAS[\"node\"]},\n }.items()\n)\nservices = dict(default_resource_settings.items() + \\\n {\n \"name\": \"services\",\n \"pattern\": \"/services$\",\n \"model_class\": \"periscope.models.Service\",\n \"collection_name\": \"services\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"service\"], MIME['PSBSON']: SCHEMAS[\"service\"]},\n }.items()\n)\nservice = dict(default_resource_settings.items() + \\\n {\n \"name\": \"service\",\n \"pattern\": \"/services/(?P[^\\/]*)$\",\n \"model_class\": \"periscope.models.Service\",\n \"collection_name\": \"services\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"service\"], MIME['PSBSON']: SCHEMAS[\"service\"]},\n }.items()\n)\ngetSchema = dict( \\\n {\n \"name\": \"getSchema\",\n \"pattern\": \"/getSchema$\",\n \"base_url\":\"\",\n \"handler_class\": \"periscope.handlers.SchemaHandler\",\n }.items()\n)\ngetParent = dict( \\\n {\n \"name\": \"getFolder\",\n \"pattern\": \"/getFolder$\",\n \"base_url\":\"\",\n \"handler_class\": \"periscope.handlers.FolderHandler\",\n }.items()\n)\npaths = dict(default_resource_settings.items() + \\\n {\n \"name\": \"paths\",\n \"pattern\": \"/paths$\",\n \"model_class\": \"periscope.models.Path\",\n \"collection_name\": \"paths\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"path\"], MIME['PSBSON']: SCHEMAS[\"path\"]},\n }.items()\n)\npath = dict(default_resource_settings.items() + \\\n {\n \"name\": \"path\",\n \"pattern\": \"/paths/(?P[^\\/]*)$\",\n \"model_class\": \"periscope.models.Path\",\n \"collection_name\": \"paths\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"path\"], MIME['PSBSON']: SCHEMAS[\"path\"]},\n }.items()\n)\nnetworks = dict(default_resource_settings.items() + \\\n {\n \"name\": \"networks\",\n \"pattern\": \"/networks$\",\n \"handler_class\": \"periscope.handlers.CollectionHandler\",\n \"model_class\": \"periscope.models.Network\",\n \"collection_name\": \"networks\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"network\"], MIME['PSBSON']: SCHEMAS[\"network\"]},\n \"collections\": {},\n }.items()\n)\nnetwork = dict(default_resource_settings.items() + \\\n {\n \"name\": \"network\",\n \"pattern\": \"/networks/(?P[^\\/]*)$\",\n \"handler_class\": \"periscope.handlers.CollectionHandler\",\n \"model_class\": \"periscope.models.Network\",\n \"collection_name\": \"networks\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"network\"], MIME['PSBSON']: SCHEMAS[\"network\"]},\n \"collections\": {},\n }.items()\n)\ndomains = dict(default_resource_settings.items() + \\\n {\n \"name\": \"domains\",\n \"pattern\": \"/domains$\",\n \"handler_class\": \"periscope.handlers.CollectionHandler\",\n \"model_class\": \"periscope.models.Domain\",\n \"collection_name\": \"domains\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"domain\"], MIME['PSBSON']: SCHEMAS[\"domain\"]},\n \"collections\": {},\n }.items()\n)\ndomain = dict(default_resource_settings.items() + \\\n {\n \"name\": \"domain\",\n \"pattern\": \"/domains/(?P[^\\/]*)$\",\n \"handler_class\": \"periscope.handlers.CollectionHandler\",\n \"model_class\": \"periscope.models.Domain\",\n \"collection_name\": \"domains\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"domain\"], MIME['PSBSON']: SCHEMAS[\"domain\"]},\n \"collections\": {},\n }.items()\n)\ntopologies = dict(default_resource_settings.items() + \\\n {\n \"name\": \"topologies\",\n \"pattern\": \"/topologies$\",\n \"handler_class\": \"periscope.handlers.CollectionHandler\",\n \"model_class\": \"periscope.models.Topology\",\n \"collection_name\": \"topologies\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"topology\"], MIME['PSBSON']: SCHEMAS[\"topology\"]},\n \"collections\": {},\n }.items()\n)\ntopology = dict(default_resource_settings.items() + \\\n {\n \"name\": \"topology\",\n \"pattern\": \"/topologies/(?P[^\\/]*)$\",\n \"handler_class\": \"periscope.handlers.CollectionHandler\",\n \"model_class\": \"periscope.models.Topology\",\n \"collection_name\": \"topologies\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"topology\"], MIME['PSBSON']: SCHEMAS[\"topology\"]},\n \"collections\": {},\n }.items()\n)\n\nmetadatas = dict(default_resource_settings.items() + \\\n {\n \"name\": \"metadatas\",\n \"pattern\": \"/metadata$\", \n \"model_class\": \"periscope.models.Metadata\",\n \"collection_name\": \"metadata\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"metadata\"], MIME['PSBSON']: SCHEMAS[\"metadata\"]},\n }.items()\n)\nmetadata = dict(default_resource_settings.items() + \\\n {\n \"name\": \"metadata\",\n \"pattern\": \"/metadata/(?P[^\\/]*)$\",\n \"model_class\": \"periscope.models.Metadata\",\n \"collection_name\": \"metadata\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"metadata\"], MIME['PSBSON']: SCHEMAS[\"metadata\"]},\n }.items()\n)\n\nevents = dict(default_resource_settings.items() + \\\n {\n \"name\": \"events\",\n \"pattern\": \"/events$\", \n \"handler_class\" : \"periscope.handlers.EventsHandler\",\n \"model_class\": \"periscope.models.Event\",\n \"collection_name\": \"events_cache\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"datum\"], MIME['PSBSON']: SCHEMAS[\"datum\"]},\n }.items()\n)\n\nevent = dict(default_resource_settings.items() + \\\n {\n \"name\": \"event\",\n \"pattern\": \"/events/(?P[^\\/]*)$\",\n \"handler_class\" : \"periscope.handlers.EventsHandler\",\n \"model_class\": \"periscope.models.Event\",\n \"collection_name\": None,\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"datum\"], MIME['PSBSON']: SCHEMAS[\"datum\"]},\n }.items()\n)\n\ndatas = dict(default_resource_settings.items() + \\\n {\n \"name\": \"datas\",\n \"pattern\": \"/data$\", \n \"handler_class\" : \"periscope.handlers.DataHandler\",\n \"model_class\": \"periscope.models.Data\",\n \"collection_name\": \"data\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"data\"], MIME['PSBSON']: SCHEMAS[\"data\"]},\n }.items()\n)\n\ndata = dict(default_resource_settings.items() + \\\n {\n \"name\": \"data\",\n \"pattern\": \"/data/(?P[^\\/]*)$\",\n \"handler_class\" : \"periscope.handlers.DataHandler\",\n \"model_class\": \"periscope.models.Data\",\n \"collection_name\": \"data\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"data\"], MIME['PSBSON']: SCHEMAS[\"data\"]},\n }.items()\n)\n\nmeasurements = dict(default_resource_settings.items() + \\\n {\n \"name\": \"measurements\",\n \"pattern\": \"/measurements$\",\n \"model_class\": \"periscope.models.Measurement\",\n \"collection_name\": \"measurements\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"measurement\"], MIME['PSBSON']: SCHEMAS[\"measurement\"]},\n }.items()\n)\nmeasurement = dict(default_resource_settings.items() + \\\n {\n \"name\": \"measurement\",\n \"pattern\": \"/measurements/(?P[^\\/]*)$\",\n \"model_class\": \"periscope.models.Measurement\",\n \"collection_name\": \"measurements\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"measurement\"], MIME['PSBSON']: SCHEMAS[\"measurement\"]},\n }.items()\n)\n\nextents = dict(default_resource_settings.items() + \\\n {\n \"name\" : \"extents\",\n \"pattern\" : \"/extents$\",\n \"model_class\" : \"periscope.models.Extent\",\n \"collection_name\" : \"extents\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"extent\"], MIME['PSBSON']: SCHEMAS[\"extent\"]}\n }.items()\n)\nextent = dict(default_resource_settings.items() + \\\n {\n \"name\" : \"extent\",\n \"pattern\" : \"/extents/(?P[^\\/]*)$\",\n \"model_class\" : \"periscope.models.Extent\",\n \"collection_name\" : \"extents\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"extent\"], MIME['PSBSON']: SCHEMAS[\"extent\"]}\n }.items()\n)\n\nexnodes = dict(default_resource_settings.items() + \\\n {\n \"name\" : \"exnodes\",\n \"pattern\" : \"/exnodes$\",\n \"handler_class\" : \"periscope.handlers.ExnodeHandler\",\n \"model_class\" : \"periscope.models.Exnode\",\n \"collection_name\" : \"exnodes\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"exnode\"], MIME['PSBSON']: SCHEMAS[\"exnode\"]},\n \"collections\": { \"extents\": extent }\n }.items()\n)\nexnode = dict(default_resource_settings.items() + \\\n {\n \"name\" : \"exnode\",\n \"pattern\" : \"/exnodes/(?P[^\\/]*)$\",\n \"handler_class\" : \"periscope.handlers.ExnodeHandler\",\n \"model_class\" : \"periscope.models.Exnode\",\n \"collection_name\" : \"exnodes\",\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"exnode\"], MIME['PSBSON']: SCHEMAS[\"exnode\"]},\n \"collections\": { \"extents\": extent }\n }.items()\n)\n\nreg_settings = dict(default_resource_settings.items() + \\\n {\n \"name\": \"register\",\n \"pattern\": \"/register$\",\n \"model_class\": \"periscope.models.Service\",\n \"handler_class\": \"periscope.handlers.RegisterHandler\",\n \"collection_name\": \"register\",\n \"allow_get\": False, \"allow_delete\": False, \"allow_put\": False,\n \"schema\": {MIME['PSJSON']: SCHEMAS[\"service\"], MIME['PSBSON']: SCHEMAS[\"service\"]},\n }.items()\n)\n\n\nitemSubscription = {\n \"base_url\" : \"\",\n \"name\" : \"itemSubscription\",\n \"pattern\" : \"/subscribe/(?P[^\\/]*)/(?P[^\\/]*)$\",\n \"handler_class\" : \"periscope.handlers.SubscriptionHandler\"\n}\n\ncatSubscription = {\n \"base_url\" : \"\",\n \"name\" : \"categorySubscription\",\n \"pattern\" : \"/subscribe/(?P[^\\/]*)$\",\n \"handler_class\" : \"periscope.handlers.SubscriptionHandler\"\n}\n\nquerySubscription = {\n \"base_url\" : \"\",\n \"name\" : \"querySubscription\",\n \"pattern\" : \"/subscribe\",\n \"handler_class\" : \"periscope.handlers.SubscriptionHandler\"\n}\n\ncollections = {\n \"links\": link,\n \"ports\": port,\n \"nodes\": node,\n \"services\": service,\n \"paths\": path,\n \"networks\": network,\n \"domains\": domain,\n \"topologies\": topology,\n \"measurements\": measurement,\n}\n\ntopologies[\"collections\"] = collections\ntopology[\"collections\"] = collections\ndomains[\"collections\"] = collections\ndomain[\"collections\"] = collections\nnetworks[\"collections\"] = collections\nnetwork[\"collections\"] = collections\n\nResources = {\n \"links\": links,\n \"link\": link,\n \"ports\": ports,\n \"port\": port,\n \"nodes\": nodes,\n \"node\": node,\n \"services\": services,\n \"service\": service,\n \"paths\": paths,\n \"path\": path,\n \"networks\": networks,\n \"network\": network,\n \"domains\": domains,\n \"domain\": domain,\n \"topologies\": topologies,\n \"topology\": topology,\n \"metadatas\": metadatas,\n \"metadata\": metadata,\n \"events\" : events,\n \"event\" : event,\n \"data\" : data,\n \"datas\" : datas,\n \"measurements\": measurements,\n \"measurement\" : measurement,\n \"exnodes\" : exnodes,\n \"exnode\" : exnode,\n \"extents\" : extents,\n \"extent\" : extent,\n}\n\nSubscriptions = {\n \"itemSubscription\" : itemSubscription,\n \"catSubscription\" : catSubscription,\n \"querySubscription\" : querySubscription,\n}\n\n\nmain_handler_settings = {\n \"resources\": [\"links\", \"ports\", \"nodes\", \"services\", \"paths\",\n \"networks\", \"domains\", \"topologies\", \"events\", \"datas\", \"metadatas\", \"measurements\", \"exnodes\", \"extents\"],\n \"name\": \"main\",\n \"base_url\": \"\",\n \"pattern\": \"/$\",\n \"handler_class\": \"periscope.handlers.MainHandler\",\n}\nabout_handler_settings = {\n \"resources\": [],\n \"name\": \"about\",\n \"base_url\": \"\",\n \"pattern\": \"/about$\",\n \"handler_class\": \"periscope.handlers.AboutHandler\"\n}\n\n######################################################################\n# PRE/POST content processing module definitions.\n######################################################################\nPP_MODULES=[]\n#if (ENABLE_AUTH): \n# PP_MODULES.append(('periscope.filters.dataAuth','DataAuth')) #[('periscope.#gemini', 'Gemini')]\n\n# Settings for the GEMINI-specific authentication handlers\nauth_user_settings= {\n \"base_url\": \"\",\n \"handler_class\": \"periscope.gemini.AuthUserCredHandler\",\n \"name\": \"cred_geniuser\",\n \"pattern\": \"/credentials/geniuser\",\n \"schema\": [MIME['PLAIN']]\n}\n\nauth_slice_settings= {\n \"base_url\": \"\",\n \"handler_class\": \"periscope.gemini.AuthSliceCredHandler\",\n \"name\": \"cred_genislice\",\n \"pattern\": \"/credentials/genislice\",\n \"schema\": [MIME['PLAIN']]\n}\nauth_login_settings= {\n \"base_url\": \"\",\n \"handler_class\": \"periscope.filters.dataAuth.UserCredHandler\",\n \"name\": \"authenticate_user\",\n \"pattern\": \"/login\",\n \"schema\": [MIME['PLAIN']]\n}\nAuthResources = {\n \"cred_login\" : auth_login_settings,\n \"cred_geniuser\": auth_user_settings,\n \"cred_genislice\": auth_slice_settings\n}\n \n\nif GEMINI_NODE_INFO is not None:\n logger = get_logger()\n nconf = {}\n with open(GEMINI_NODE_INFO, 'r') as cfile:\n for line in cfile:\n name, var = line.partition(\"=\")[::2]\n nconf[name.strip()] = str(var).rstrip()\n\n try:\n AUTH_UUID = nconf['auth_uuid']\n except Exception as e:\n AUTH_UUID = None\n logger.warn(\"read_settings\", msg=\"Could not find auth_uuid in node configuration\")\nelse:\n AUTH_UUID = None\n\ntry:\n from M2Crypto import X509\n SERVER_CERT_FINGERPRINT = X509.load_cert(SSL_OPTIONS['certfile'], X509.FORMAT_PEM).get_fingerprint('sha1')\nexcept Exception as e:\n SERVER_CERT_FINGERPRINT = ''\n logger = get_logger()\n logger.warn(\"read_settings\", msg=\"Could not open SSL CERTFILE: %s\" % e)\n","sub_path":"periscope/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":25104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"325520381","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 31 08:12:08 2020\n\n@author: Shivadhar SIngh\n\"\"\"\n\ndef any_one_is_sum1(a,b,c):\n ''' to check whether each of the number os some of the other two'''\n sum_c=a+b\n sum_b=a+c\n sum_a=b+c\n if sum_c == a+b:\n if sum_b == c+a:\n if sum_a == b+c:\n return True\n else:\n return False\n \ndef any_one_is_sum2(a,b,c):\n ''' to check whether the sum of last two numbers is equivalent to \n the first number'''\n if b + c == a:\n print(True)\n return True\n# if c + b == a:\n# print(True)\n else:\n print(False)\n return False\n\ndef any_one_is_sum(a, b, c):\n if a+b==c and a+c==b:\n return True\n else:\n return False","sub_path":"any_one_is_sum.py","file_name":"any_one_is_sum.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"271822627","text":"'''\n* @Author: Mohammad Fatha.\n* @Date: 2021-09-17 19:40 \n* @Last Modified by: Mohammad Fatha\n* @Last Modified time: 2021-09-17 19:43\n* @Title: Generating distinct coupon number\n'''\nimport random\n\ndef distinct_coupons():\n \"\"\"\n Description:\n This function is used to generate random and unique coupon numbers.\n User input is given for number and range of coupon numbers.\n Random fuction is used to generate random coupon numbers.\n \n \"\"\" \ncoupon = [] #empty list\nrandom_numbers=0 #no.of random numbers needed to generate distinct coupons\ntry:\n number=int(input(\"Enter The Number Of Coupons You Want To Generate: \")) \n print(\"Distinct Coupon Numbers Generated\")\n for element in range(number):\n coupon_number = random.randint(10,100) \n if coupon_number not in coupon: #Checking the number is present in list or not\n coupon.append(coupon_number) #adding the distinct random number gnerated to list \n print(coupon_number)\n random_numbers+=1\n else:\n pass \n print(\"Total Random Numbers Needed To Get All Distinct Numbers:\",end = \" \")\n print(random_numbers,end = \" \")\nexcept Exception as err:\n print(\"Not A Valid Number\",err)\n\nif __name__ == '__main__':\n distinct_coupons()","sub_path":"Logical Programs/CouponNumber.py","file_name":"CouponNumber.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"156706953","text":"from odoo import api, fields, models, _\n\nclass MrpWorkorder(models.Model):\n _inherit = 'mrp.workorder'\n\n# Created By | Created Date |Info.\n# Pradip |09-05-19 | if user has manager group the qty_producing field editable else non-editable\n\n id_check=fields.Boolean(string='id_check',compute='_id_check_user_group')\n\n @api.depends('id_check')\n def _id_check_user_group(self):\n # print(\"==============96===========>>res_user_group\",res_user_group)\n for i in self:\n print(\"===================>>>>\",i.workcenter_id.res_grp.name)\n if i.workcenter_id.res_grp.name=='User':\n print(i.workcenter_id.res_grp.name)\n i.id_check=True\n else:\n i.id_check=False\n \n \n","sub_path":"manufacturing_module/models/mrp_workorder.py","file_name":"mrp_workorder.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"400409969","text":"import numpy\nimport vtk\nfrom line_line_intersector import LineLineIntersector\n\n\nclass PolysegmentIter:\n\n def __init__(self, grid, locator, p0, p1):\n \"\"\"\n Constructor\n @param grid instance of vtkUnstructuredGrid\n @param locator vtkCellLocator instance attached to the above grid\n @param p0 start point\n @param p1 end point\n \"\"\"\n\n # small tolerances \n self.eps = 1.73654365e-14\n self.eps100 = 100. * self.eps\n self.tol = 1.e-3 # to determine if a point is inside a cell\n\n\n self.grid = grid\n self.locator = locator\n\n self.cellIds = []\n self.xis = []\n self.ts = []\n self.__collectLineGridSegments(p0, p1)\n\n c2Inds = {}\n for i in range(len(self.cellIds)):\n cId = self.cellIds[i]\n c2Inds[cId] = c2Inds.get(cId, []) + [i]\n\n self.segCellIds = []\n self.segTas = []\n self.segTbs = []\n self.segXias = []\n self.segXibs = []\n self.segCoeffs = []\n\n for cId, inds in c2Inds.items():\n # sort by ts values\n indSorted = sorted(inds, key=lambda i: self.ts[i])\n n = len(indSorted)\n for i in range(n - 1):\n i0 = indSorted[i]\n i1 = indSorted[i + 1]\n ta, xia = self.ts[i0], self.xis[i0]\n tb, xib = self.ts[i1], self.xis[i1]\n self.segCellIds.append(cId)\n self.segTas.append(ta)\n self.segTbs.append(tb)\n self.segXias.append(xia)\n self.segXibs.append(xib)\n self.segCoeffs.append(1.0)\n\n n = len(self.segCellIds)\n inds = [i for i in range(n)]\n # sort by ta values\n indSorted = sorted(inds, key=lambda i: self.segTas[i])\n self.segCellIds = [self.segCellIds[i] for i in indSorted]\n self.segTas = [self.segTas[i] for i in indSorted]\n self.segTbs = [self.segTbs[i] for i in indSorted]\n self.segXias = [self.segXias[i] for i in indSorted]\n self.segXibs = [self.segXibs[i] for i in indSorted]\n\n # assign coefficients that account for duplicity, ie segments \n # that are shared between two cells\n self.__assignCoefficientsToSegments()\n\n self.numSegs = len(self.segCellIds)\n\n self.totalT = 0\n for i in range(self.numSegs):\n ta, tb = self.segTas[i], self.segTbs[i]\n coeff = self.segCoeffs[i]\n self.totalT += (tb - ta) * coeff\n\n # reset the iterator\n self.reset()\n\n\n def getIntegratedParamCoord(self):\n \"\"\"\n Get the integrated linear parametric coordinates\n @return value\n \"\"\"\n return self.totalT\n\n\n def reset(self):\n \"\"\"\n Reset the counter\n \"\"\"\n self.index = -1\n\n\n def __iter__(self):\n return self\n\n\n def __next__(self):\n \"\"\"\n Update iterator\n \"\"\"\n if self.index < self.numSegs - 1:\n self.index += 1\n return self\n else:\n raise StopIteration()\n\n # Python2\n def next(self):\n return self.__next__()\n\n\n def getCellId(self):\n \"\"\"\n Get the current cell Id\n @return index\n \"\"\"\n return self.segCellIds[self.index]\n\n\n def getBegCellParamCoord(self):\n \"\"\"\n Get the current cell parametric coordinates at the beginning of segment\n @return 2d array\n \"\"\"\n return self.segXias[self.index]\n \n\n def getEndCellParamCoord(self):\n \"\"\"\n Get the current cell parametric coordinates at the end of segment\n @return 2d array\n \"\"\"\n return self.segXibs[self.index]\n \n\n def getBegLineParamCoord(self):\n \"\"\"\n Get the current line parametric coordinates at the beginning of segment\n @return 2d array\n \"\"\"\n return self.segTas[self.index]\n \n\n def getEndLineParamCoord(self):\n \"\"\"\n Get the current line parametric coordinates at the end of segment\n @return 2d array\n \"\"\"\n return self.segTbs[self.index]\n\n\n def getCoefficient(self):\n \"\"\"\n Get the coefficient accounting for duplicates\n @return coefficient\n \"\"\"\n return self.segCoeffs[self.index]\n \n\n def getIndex(self):\n \"\"\"\n Get the current index\n @return index\n \"\"\"\n return self.index\n\n\n def __assignCoefficientsToSegments(self):\n\n n = len(self.segCellIds)\n # copy\n sCellIds = self.segCellIds[:]\n sTas = self.segTas[:]\n sTbs = self.segTbs[:]\n sXias = self.segXias[:]\n sXibs = self.segXibs[:]\n sCoeffs = self.segCoeffs[:]\n # remove zero length segments\n self.segCellIds = []\n self.segTas = []\n self.segTbs = []\n self.segXias = []\n self.segXibs = []\n self.segCoeffs = []\n for i in range(n):\n ta, tb = sTas[i], sTbs[i]\n if abs(tb - ta) > self.eps100:\n self.segCellIds.append(sCellIds[i])\n self.segTas.append(sTas[i])\n self.segTbs.append(sTbs[i])\n self.segXias.append(sXias[i])\n self.segXibs.append(sXibs[i])\n self.segCoeffs.append(sCoeffs[i])\n\n # reduce contribution for overlapping segments. If two \n # segments overlap then the coefficient of first segment\n # is set to 1.0 - overlap/(tb - ta). Assumes overlap \n # can only happen for pairs of segment\n n = len(self.segCellIds)\n for i0 in range(n - 1):\n i1 = i0 + 1\n ta0, tb0 = self.segTas[i0], self.segTbs[i0]\n ta1, tb1 = self.segTas[i1], self.segTbs[i1]\n overlap = max(0., min(tb0, tb1) - max(ta1, ta0))\n self.segCoeffs[i0] = 1.0 - overlap/(tb0 - ta0)\n\n\n def __collectIntersectionPoints(self, pBeg, pEnd):\n \"\"\"\n Collect all the intersection points\n @param pBeg starting point\n @param pEnd end point\n @return [(cellId, lambda, point), ...]\n @note lambda is the linear parametric coordinate along the line\n \"\"\"\n\n res = []\n\n intersector = LineLineIntersector()\n cellIds = vtk.vtkIdList()\n ptIds = vtk.vtkIdList()\n\n dp = pEnd - pBeg\n\n # find all the cells intersected by the line\n self.locator.FindCellsAlongLine(pBeg, pEnd, self.tol, cellIds)\n\n # collect the intersection points in between\n for i in range(cellIds.GetNumberOfIds()):\n\n cId = cellIds.GetId(i)\n\n self.grid.GetCellPoints(cId, ptIds)\n\n # iterate over the quads' edges\n for j0 in range(4):\n\n j1 = (j0 + 1) % 4\n v0 = numpy.array(self.grid.GetPoint(ptIds.GetId(j0)))\n v1 = numpy.array(self.grid.GetPoint(ptIds.GetId(j1)))\n\n # look for an intersection\n intersector.setPoints(pBeg[:2], pEnd[:2], v0[:2], v1[:2])\n if not intersector.hasSolution(self.eps):\n continue\n\n if abs(intersector.getDet()) > self.eps:\n # normal intersection, 1 solution\n lambRay, lambEdg = intersector.getSolution()\n\n # is it valid? Intersection must be within (p0, p1) and (q0, q1)\n if lambRay >= 0. - self.eps100 and lambRay <= 1. + self.eps100 and \\\n lambEdg >= 0. - self.eps100 and lambEdg <= 1. + self.eps100:\n\n point = pBeg + lambRay*dp\n res.append( (cId, lambRay, point) )\n\n else:\n # det is almost zero\n # looks like the two lines (p0, p1) and (q0, q1) are overlapping\n # add the starting/ending points \n lama, lamb = intersector.getBegEndParamCoords()\n pa = pBeg + lama*dp\n pb = pBeg + lamb*dp\n res.append( (cId, lama, pa) )\n res.append( (cId, lamb, pb) )\n\n return res\n\n\n def __collectLineGridSegments(self, p0, p1):\n \"\"\"\n Collect all the line-grid intersection points\n @param p0 starting point of the line\n @param p1 end point of the line \n \"\"\"\n\n # things we need to define\n ptIds = vtk.vtkIdList()\n cell = vtk.vtkGenericCell()\n cellIds = vtk.vtkIdList()\n subId = vtk.mutable(-1)\n dist = vtk.mutable(0.)\n xi = numpy.zeros((3,), numpy.float64)\n pBeg = numpy.zeros((3,), numpy.float64)\n pEnd = numpy.zeros((3,), numpy.float64)\n point = numpy.zeros((3,), numpy.float64)\n closestPoint = numpy.zeros((3,), numpy.float64)\n weights = numpy.array((4,), numpy.float64)\n\n # VTK wants 3d positions\n pBeg[:] = p0[0], p0[1], 0.0\n pEnd[:] = p1[0], p1[1], 0.0\n\n # add starting point\n cId = self.locator.FindCell(pBeg, self.eps, cell, xi, weights)\n if cId >= 0:\n self.cellIds.append(cId)\n self.xis.append(xi[:2].copy())\n self.ts.append(0.)\n else:\n pass\n #print('Warning: starting point {} not found!'.format(p0))\n\n #\n # find all intersection points in between\n #\n\n intersections = self.__collectIntersectionPoints(pBeg, pEnd)\n\n # find the cell id of the neighbouring cells\n for cId, lambRay, point in intersections:\n\n found = self.grid.GetCell(cId).EvaluatePosition(point, closestPoint, subId, xi, dist, weights)\n if found:\n self.cellIds.append(cId)\n self.xis.append(xi[:2].copy())\n self.ts.append(lambRay)\n else:\n print('Warning: param coord search failed point {} in cell {}'.format(point, cId))\n\n \n # add last point \n cId = self.locator.FindCell(pEnd, self.eps, cell, xi, weights)\n if cId >= 0:\n self.cellIds.append(cId)\n self.xis.append(xi[:2].copy())\n self.ts.append(1.)\n else:\n pass\n #print('Warning: end point {} not found!'.format(p1))\n\n#################################################################################################\n\ndef main():\n import argparse\n from math import pi\n from ugrid_reader import UgridReader\n from polyline_iter import PolylineIter\n\n parser = argparse.ArgumentParser(description='Break line into segments')\n parser.add_argument('-i', dest='input', default='mesh_C4.nc', help='Specify input file')\n parser.add_argument('-p', dest='points', default='(0., 0.),(2*pi,0.)', help='Points describing broken line as \"(x0, y0),(x1, y1)...\"')\n args = parser.parse_args()\n\n ur = UgridReader(filename=args.input)\n points = eval(args.points)\n pli = PolylineIter(points)\n \n countLine = 0\n tTotal = 0.\n for line in pli:\n t0 = line.getBegParamCoord()\n t1 = line.getEndParamCoord()\n p0 = line.getBegPoint()\n p1 = line.getEndPoint()\n print('line {} t = {} -> {}'.format(countLine, t0, t1))\n\n psi = PolysegmentIter(ur.getUnstructuredGrid(), \n ur.getUnstructuredGridCellLocator(), \n p0, p1)\n\n countSeg = 0\n for seg in psi:\n cellId = seg.getCellId()\n xia = seg.getBegCellParamCoord()\n xib = seg.getEndCellParamCoord()\n ta = seg.getBegLineParamCoord()\n tb = seg.getEndLineParamCoord()\n print('\\tseg {} in cell {} t = {} -> {} xi = {} -> {}'.format(countSeg, cellId, ta, tb, xia, xib))\n\n countSeg += 1\n\n tTotal += psi.getIntegratedParamCoord()\n countLine += 1\n\n\n print('Integrated t = {}'.format(tTotal))\n\n \n\nif __name__ == '__main__':\n main()\n","sub_path":"tools/polysegment_iter.py","file_name":"polysegment_iter.py","file_ext":"py","file_size_in_byte":11950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"409202669","text":"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nimport pickle\nimport pdb\n\n\nimage = mpimg.imread('bridge_shadow.jpg')\ngray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # cv2.COLOR_BGR2GRAY\n\n\ndef show_two_images(image1, image2, title=\"Two Images\"):\n f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))\n f.suptitle(title, fontsize=16)\n f.tight_layout()\n ax1.imshow(image1)\n ax1.set_title('First Image', fontsize=50)\n\n ax2.imshow(image2)\n\n # gray = cv2.cvtColor(image2, cv2.COLOR_RGB2GRAY)\n # ax2.imshow(gray, cmap='gray')\n\n\n ax2.set_title('Second Image', fontsize=50)\n plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)\n plt.show()\n\n\ndef abs_sobel_thresh(img, orient='x', ksize=3, thresh=(0, 255)):\n thresh_min = thresh[0]\n thresh_max = thresh[1]\n # Convert to grayscale\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n # Apply x or y gradient with the OpenCV Sobel() function\n # and take the absolute value\n if orient == 'x':\n abs_sobel = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=ksize))\n if orient == 'y':\n abs_sobel = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=ksize))\n # Rescale back to 8 bit integer\n scaled_sobel = np.uint8(255*abs_sobel/np.max(abs_sobel))\n # Create a copy and apply the threshold\n binary_output = np.zeros_like(scaled_sobel)\n # Here I'm using inclusive (>=, <=) thresholds, but exclusive is ok too\n binary_output[(scaled_sobel >= thresh_min) & (scaled_sobel <= thresh_max)] = 1\n\n # Return the result\n return binary_output\n\n\ndef mag_thresh(img, sobel_kernel=3, mag_thresh=(0, 255)):\n # Convert to grayscale\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n # Take both Sobel x and y gradients\n sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\n sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\n # Calculate the gradient magnitude\n gradmag = np.sqrt(sobelx**2 + sobely**2)\n # Rescale to 8 bit\n scale_factor = np.max(gradmag)/255\n gradmag = (gradmag/scale_factor).astype(np.uint8)\n # Create a binary image of ones where threshold is met, zeros otherwise\n binary_output = np.zeros_like(gradmag)\n binary_output[(gradmag >= mag_thresh[0]) & (gradmag <= mag_thresh[1])] = 1\n\n # Return the binary image\n return binary_output\n\n\ndef dir_threshold(img, sobel_kernel=3, thresh=(0, np.pi/2)):\n # Grayscale\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n # Calculate the x and y gradients\n sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\n sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\n # Take the absolute value of the gradient direction,\n # apply a threshold, and create a binary image result\n absgraddir = np.arctan2(np.absolute(sobely), np.absolute(sobelx))\n binary_output = np.zeros_like(absgraddir)\n binary_output[(absgraddir >= thresh[0]) & (absgraddir <= thresh[1])] = 1\n\n # Return the binary image\n return binary_output\n\n\n# Define a function that thresholds the S-channel of HLS\n# Use exclusive lower bound (>) and inclusive upper (<=)\ndef hls_select(img, thresh=(0, 255)):\n # 1) Convert to HLS color space\n hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\n s_channel = hls[:,:,2]\n\n # 2) Apply a threshold to the S channel\n binary_output = np.zeros_like(s_channel)\n binary_output[(s_channel > thresh[0]) & (s_channel <= thresh[1])] = 1\n\n # 3) Return a binary image of threshold result\n return binary_output\n\n\ndef gray_select(img, thresh=(0, 255)):\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n\n binary_output = np.zeros_like(gray)\n binary_output[(gray > thresh[0]) & (gray <= thresh[1])] = 1\n\n # 3) Return a binary image of threshold result\n return binary_output\n\n\ndef rgb_select(img, channel=0, thresh=(0, 255)):\n channel = img[:,:,channel]\n binary_output = np.zeros_like(channel)\n binary_output[(channel > thresh[0]) & (channel <= thresh[1])] = 1\n\n # 3) Return a binary image of threshold result\n return binary_output\n\n\n# Edit this function to create your own pipeline.\ndef pipeline(img, s_thresh=(170, 255), sx_thresh=(20, 100)):\n img = np.copy(img)\n # Convert to HLS color space and separate the V channel\n hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\n l_channel = hls[:,:,1]\n s_channel = hls[:,:,2]\n\n # Sobel x\n sobelx = cv2.Sobel(l_channel, cv2.CV_64F, 1, 0) # Take the derivative in x\n abs_sobelx = np.absolute(sobelx) # Absolute x derivative to accentuate lines away from horizontal\n scaled_sobel = np.uint8(255*abs_sobelx/np.max(abs_sobelx))\n\n # Threshold x gradient\n sxbinary = np.zeros_like(scaled_sobel)\n sxbinary[(scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])] = 1\n\n # Threshold color channel\n s_binary = np.zeros_like(s_channel)\n s_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 1\n\n # Stack each channel\n color_binary = np.dstack(( np.zeros_like(sxbinary), sxbinary, s_binary)) * 255\n return color_binary\n\n\nresult = pipeline(image)\n\nshow_two_images(image, result, title=\"fff\")\n\n\n\n\nprint('--------------------')\n# pdb.set_trace()\nprint('done')\n\nprint('--------------------')\n","sub_path":"project02 advanced lane lines/lecture/camera calibration.py","file_name":"camera calibration.py","file_ext":"py","file_size_in_byte":5243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"556574598","text":"# -*- coding: utf-8 -*-\n#\n# Copyright 2017-2021 - Swiss Data Science Center (SDSC)\n# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and\n# Eidgenössische Technische Hochschule Zürich (ETHZ).\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Click utilities.\"\"\"\n\nimport click\n\n\nclass CaseInsensitiveChoice(click.Choice):\n \"\"\"Case-insensitive click choice.\n\n Based on https://github.com/pallets/click/issues/569.\n \"\"\"\n\n def convert(self, value, param, ctx):\n \"\"\"Convert value to its choice value.\"\"\"\n if value is None:\n return None\n return super(CaseInsensitiveChoice, self).convert(value.lower(), param, ctx)\n\n\nclass MutuallyExclusiveOption(click.Option):\n \"\"\"Custom option class to allow specifying mutually exclusive options in click commands.\"\"\"\n\n def __init__(self, *args, **kwargs):\n mutually_exclusive = sorted(kwargs.pop(\"mutually_exclusive\", []))\n self.mutually_exclusive = set()\n self.mutually_exclusive_names = []\n\n for mutex in mutually_exclusive:\n if type(mutex) == tuple:\n self.mutually_exclusive.add(mutex[0])\n self.mutually_exclusive_names.append(mutex[1])\n else:\n\n self.mutually_exclusive.add(mutex)\n self.mutually_exclusive_names.append(mutex)\n\n _help = kwargs.get(\"help\", \"\")\n if self.mutually_exclusive:\n ex_str = \", \".join(self.mutually_exclusive_names)\n kwargs[\"help\"] = f\"{_help} NOTE: This argument is mutually exclusive with arguments: [{ex_str}].\"\n super(MutuallyExclusiveOption, self).__init__(*args, **kwargs)\n\n def handle_parse_result(self, ctx, opts, args):\n \"\"\"Handles the parse result for the option.\"\"\"\n if self.mutually_exclusive.intersection(opts) and self.name in opts:\n raise click.UsageError(\n \"Illegal usage: `{}` is mutually exclusive with \"\n \"arguments `{}`.\".format(self.name, \", \".join(sorted(self.mutually_exclusive_names)))\n )\n\n return super(MutuallyExclusiveOption, self).handle_parse_result(ctx, opts, args)\n","sub_path":"renku/cli/utils/click.py","file_name":"click.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"389126040","text":"class UnionFind:\n def __init__(self, n):\n self.arr = [i for i in range(n)]\n self.size = [1 for _ in range(n)]\n self.biggest = self.arr.copy()\n self.components = n\n \n def find(self, n):\n \"\"\"\n finds biggest element in connected components\n \"\"\"\n return self.biggest[self.root(n)]\n\n def root(self, a):\n origin = a\n while self.arr[a] != a:\n a = self.arr[a]\n while self.arr[origin] != a:\n tmp = self.arr[origin]\n self.arr[origin] = a\n origin = tmp\n return a\n\n def union(self, a, b):\n aRoot = self.root(a)\n bRoot = self.root(b)\n if aRoot == bRoot:\n return\n self.components -= 1\n if self.size[aRoot] <= self.size[bRoot]:\n self.arr[aRoot] = bRoot\n self.size[bRoot] += self.size[aRoot]\n self.biggest[bRoot] = max(self.biggest[aRoot], self.biggest[bRoot])\n else:\n self.arr[bRoot] = aRoot\n self.size[aRoot] += self.size[bRoot]\n self.biggest[aRoot] = max(self.biggest[aRoot], self.biggest[bRoot])\n\n def connected(self, a, b):\n return self.root(a) == self.root(b)\n \n\ndef test():\n a = UnionFind(10)\n assert a.components == 10\n assert not a.connected(0,9)\n assert a.find(1) == 1\n a.union(1,2)\n assert a.find(1) == 2\n a.union(2,3)\n assert a.find(1) == 3\n assert a.components == 8\n assert a.connected(1,2)\n assert a.connected(1,3)\n assert not a.connected(0,9)\n a.union(3,9)\n assert a.find(4) == 4\n assert a.find(9) == 9\n assert a.components == 7\n assert a.connected(1,9)\n a.union(0,4)\n assert a.find(0) == 4\n assert a.components == 6\n a.union(1,9)\n assert a.find(1) == 9\n assert a.components == 6\n a.union(5,4)\n a.union(0,1)\n assert a.connected(0,9)\n assert a.components == 4\n print(\"Correct\")\n\ntest()","sub_path":"canonical.py","file_name":"canonical.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"372161434","text":"from django.shortcuts import render, get_object_or_404\nfrom django.shortcuts import redirect\nfrom .models import Nota\nfrom django.utils import timezone\nfrom .forms import NotaForm\nfrom django.contrib.auth.decorators import login_required\n\n# Create your views here.\ndef muro(request):\n notas = Nota.objects.all()\n return render(request,'notas/muro.html',{'notas': notas})\n\n@login_required\ndef nueva_nota(request):\n if request.method == \"POST\":\n formulario = NotaForm(request.POST)\n if formulario.is_valid():\n publicacion = formulario.save(commit=False)\n publicacion.autor = request.user\n publicacion.save()\n return redirect('muro')\n else:\n formulario = NotaForm()\n return render(request, 'notas/editar_nota.html', {'formulario': formulario})\n\n\n@login_required\ndef editar_nota(request, pk):\n publicacion = get_object_or_404(Nota, pk=pk)\n if request.method == \"POST\":\n formulario = NotaForm(request.POST, instance=publicacion)\n if formulario.is_valid():\n publicacion = formulario.save(commit=False)\n publicacion.autor = request.user\n publicacion.published_date = timezone.now()\n publicacion.save()\n return redirect('muro')\n else:\n formulario = NotaForm(instance=publicacion)\n return render(request, 'notas/editar_nota.html', {'formulario': formulario})","sub_path":"notas/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"340918345","text":"from rest_framework.test import APIClient\nfrom testing.testcases import TestCase\nfrom tweets.models import Tweet\n\n# 注意要加 '/' 结尾,要不然会产生 301 redirect\nTWEET_LIST_API = '/api/tweets/'\nTWEET_CREATE_API = '/api/tweets/'\n\nclass TweetApiTest(TestCase):\n\n def setUp(self):\n self.anonymous_client = APIClient()\n\n self.user1 = self.create_user('user1', 'user1@twitter.com')\n self.tweets1 = [\n self.create_tweet(self.user1)\n for i in range(3)\n ]\n self.user1_client = APIClient()\n self.user1_client.force_authenticate(self.user1)\n\n self.user2 = self.create_user('user2', 'user2@twitter.com')\n self.tweets2 = [\n self.create_tweet(self.user2)\n for i in range(2)\n ]\n def test_list_api(self):\n # 必须带 user_id\n response = self.anonymous_client.get(TWEET_LIST_API)\n self.assertEqual(response.status_code, 400)\n\n # regular request\n response = self.anonymous_client.get(TWEET_LIST_API, {'user_id': self.user1.id})\n self.assertEqual(response.status_code, 200)\n self.assertEqual(len(response.data['tweets']), 3)\n response = self.anonymous_client.get(TWEET_LIST_API, {'user_id': self.user2.id})\n self.assertEqual(len(response.data['tweets']), 2)\n\n self.assertEqual(response.data['tweets'][0]['id'], self.tweets2[1].id)\n self.assertEqual(response.data['tweets'][1]['id'], self.tweets2[0].id)\n\n def test_create_api(self):\n # must login\n response = self.anonymous_client.post(TWEET_CREATE_API)\n self.assertEqual(response.status_code, 403)\n\n # must include content\n response = self.user1_client.post(TWEET_CREATE_API)\n self.assertEqual(response.status_code, 400)\n\n response = self.user1_client.post(TWEET_CREATE_API,{'content':'1'})\n self.assertEqual(response.status_code, 400)\n\n #content can't be too long\n response = self.user1_client.post(TWEET_CREATE_API, {\n 'content': '0'*141\n })\n self.assertEqual(response.status_code, 400)\n\n #regular post\n tweets_count = Tweet.objects.count()\n response = self.user1_client.post(TWEET_CREATE_API,{\n 'content':'Hello Word, this is my first tweet!'\n })\n self.assertEqual(response.status_code, 201)\n self.assertEqual(response.data['user']['id'], self.user1.id)\n self.assertEqual(Tweet.objects.count(), tweets_count+1)\n","sub_path":"tweets/api/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"159370516","text":"import DebugUtility\r\n\r\n# bubble sort a number list in ascending order\r\ndef sort(numList, reverse=False):\r\n d = DebugUtility.debugUtil()\r\n d.debugPrompt(\"[Bubble sort] original list: {}\".format(numList))\r\n _numOfComparisons = 0\r\n _numOfSwaps = 0\r\n swapMade = True\r\n n = len(numList)\r\n while swapMade:\r\n swapMade = False\r\n # length of list = N\r\n # Indices: 0, 1, 2, 3, 4 ... N-2, N-1\r\n n -= 1\r\n # for position in range( len(numList) - 1):\r\n for position in range(n):\r\n d.debugPrompt(\"[Bubble sort] Comparing {}(pos={}) and {}(pos={})\".format(numList[position], position, numList[position+1], position+1))\r\n _numOfComparisons += 1\r\n if (not reverse and numList[position] > numList[position+1]) or \\\r\n (reverse and numList[position] < numList[position+1]):\r\n d.debugPrompt(\" ==> we should swap\")\r\n _numOfSwaps += 1\r\n tmp = numList[position+1]\r\n numList[position+1] = numList[position]\r\n numList[position] = tmp\r\n swapMade = True\r\n d.debugPrompt(\" list after comparison: {}\".format(numList))\r\n d.debugPrompt(\"[Bubble sort] sorted list: {}\".format(numList))\r\n print(\"[Bubble sort] Number of comparisons = {}, number of swaps = {}\".format(_numOfComparisons, _numOfSwaps))\r\n","sub_path":"algorithms/sorts/bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"628650187","text":"from nose.tools import *\nfrom yourFinance import user, year, month, stash\n\nanswer ='''\n2017\n\njan\nTotal: 0.0\n\nfeb\nTotal: 0.0\n\n2018\n\nfeb\nTotal: 0.0\n\n'''\n\ndef create_user_obj():\n yearObj = year.Year(2017)\n monthObj = month.Month('jan')\n month2Obj = month.Month('feb')\n yearObj.add_month(monthObj)\n yearObj.add_month(month2Obj)\n obj = user.User('Lucas', 'randomPassword')\n obj.add_year(yearObj)\n year2Obj = year.Year(2018)\n year2Obj.add_month(month2Obj)\n obj.add_year(year2Obj)\n return obj\n\ndef test_init():\n obj = user.User('Lucas', 12345)\n assert_equal(obj.name, 'Lucas')\n assert_equal(obj.password, '12345')\n\ndef test_add_remove_year():\n obj = create_user_obj()\n assert_equal(len(obj.yearDict), 2)\n assert_equal(obj.yearDict[2017].number, 2017)\n assert_equal(len(obj.yearDict[2017].monthDict), 2)\n yearObj = year.Year(2018)\n obj.remove_year(yearObj)\n assert_equal(len(obj.yearDict), 1)\n assert_raises(Exception, obj.remove_year, 2017)\n \ndef test_show_funds():\n obj = create_user_obj()\n assert_equal(obj.show_funds(), answer)\n\n \n","sub_path":"tests/user_tests.py","file_name":"user_tests.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"596806447","text":"\"\"\"\r\nTests that hosts can connect to multiple routers.\r\n\r\nCreates a topology like the following:\r\n\r\n s1 -- c1\r\n / \\ \r\nh1 -- c3 -- s3 -- h2\r\n \\ /\r\n s2 -- c2\r\n\r\nAll links have cost 1.\r\nWhen h1 pings h2, it should send the ping packet to all routers, and the same packet should arrive at h2 3 times.\r\nIn the other direction, h2 to h1, s3 should forward the packet directly to h1 (shortest path).\r\n\r\n\"\"\"\r\n\r\nimport sim\r\nimport sim.api as api\r\nimport sim.basics as basics\r\nimport sys\r\n\r\nfrom tests.test_simple import GetPacketHost, NoPacketHost\r\nfrom tests.test_link_weights import CountingHub\r\n\r\n\r\ndef launch():\r\n h1 = GetPacketHost.create('h1')\r\n h2 = GetPacketHost.create('h2')\r\n\r\n s1 = sim.config.default_switch_type.create('s1')\r\n s2 = sim.config.default_switch_type.create('s2')\r\n s3 = sim.config.default_switch_type.create('s3')\r\n\r\n c1 = CountingHub.create('c1')\r\n c2 = CountingHub.create('c2')\r\n c3 = CountingHub.create('c3')\r\n\r\n h1.linkTo(s1)\r\n s1.linkTo(c1)\r\n c1.linkTo(s3)\r\n h1.linkTo(s2)\r\n s2.linkTo(c2)\r\n c2.linkTo(s3)\r\n h1.linkTo(c3)\r\n c3.linkTo(s3)\r\n s3.linkTo(h2)\r\n\r\n def test_tasklet():\r\n yield 15\r\n\r\n api.userlog.debug('Sending ping from h1 to h2 - it should hit 3 routers')\r\n h1.ping(h2)\r\n\r\n yield 5\r\n\r\n if h1.pings != 0 or h2.pings != 3 or c1.pings != 1 or c2.pings != 1 or c3.pings != 1:\r\n api.userlog.error(\"The ping did not propagate through all routers\")\r\n sys.exit(1)\r\n\r\n api.userlog.debug('Sending ping from h2 to h1 - it should hit 1 router')\r\n h2.ping(h1)\r\n\r\n yield 5\r\n\r\n if h1.pings != 1 or h2.pings != 3 or c1.pings != 1 or c2.pings != 1 or c3.pings != 2:\r\n api.userlog.error(\"The ping hit more than 1 router\")\r\n sys.exit(1)\r\n\r\n api.userlog.debug(\"Pings sent correctly\")\r\n sys.exit(0)\r\n\r\n api.run_tasklet(test_tasklet)","sub_path":"proj2_routing/tests/test_multiple_routers.py","file_name":"test_multiple_routers.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"441427531","text":"from collections import OrderedDict\n\nfrom django import forms\n\nfrom mayan.apps.common.classes import ModelAttribute\nfrom mayan.apps.common.widgets import NamedMultiWidget\n\nfrom .literals import EMPTY_LABEL\n\n\nclass TemplateWidget(NamedMultiWidget):\n class Media:\n js = ('templating/js/template_widget.js',)\n\n def __init__(self, attrs=None, **kwargs):\n widgets = OrderedDict()\n\n widgets['model_attribute'] = forms.widgets.Select(\n attrs={'data-template-fields': 'model_attribute'}\n )\n widgets['template'] = forms.widgets.Textarea(\n attrs={'rows': 5, 'data-template-fields': 'template'}\n )\n super(TemplateWidget, self).__init__(\n widgets=widgets, attrs=attrs, **kwargs\n )\n\n def get_context(self, name, value, attrs):\n result = super(TemplateWidget, self).get_context(name, value, attrs)\n result['widget']['subwidgets'][0]['attrs']['required'] = False\n return result\n\n def decompress(self, value):\n attribute_choices = ModelAttribute.get_all_choices_for(\n model=self.attrs['model']\n )\n choices = []\n\n choices = attribute_choices\n choices.insert(\n 0, ('', EMPTY_LABEL)\n )\n\n self.widgets['model_attribute'].choices = choices\n return {\n 'model_attribute': None, 'template': value\n }\n\n def value_from_datadict(self, querydict, files, name):\n template = querydict.get('{}_template'.format(name))\n\n return template\n","sub_path":"mayan/apps/templating/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"518829707","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nAUTHOR = u'Anthony Nelzin-Santos'\nAUTHORURL = 'https://anthony.nelzin.fr/'\nSITENAME = u'métro[mémo]dodo'\nSITEDESCRIPTION = u'Notes de lecture, par Anthony Nelzin-Santos.'\nSITESHORTNAME = u'[mémo]'\nSITESHORTDESCRIPTION = u'Notes de lecture.'\nSITECOLOR = '#612273'\nSITEURL = 'http://localhost:8000'\n\nLOCALE = ('fr_FR', 'fr_FR.utf8')\nDEFAULT_LANG = u'fr'\nDEFAULT_DATE_FORMAT = '%d %B %Y'\nTIMEZONE = 'Europe/Paris'\n\nPATH = 'content'\nDELETE_OUTPUT_DIRECTORY = True\nTHEME = 'themes/metrozendodo'\nTEMPLATE_PAGES = {'recents.json': 'api/recents.json',\n\t\t\t\t 'feed.json': 'api/feed.json',}\nSTATIC_PATHS = [\"static\"]\n\nHEADER_LINKS = [('Archives','/archives'),\n\t\t\t\t('Thèmes','/themes'),\n\t\t\t\t('À propos', 'https://metrozendodo.fr/a-propos/'),]\n\nFOOTER_LINKS_TITLE = \"métro[…]dodo\"\nFOOTER_LINKS = [('boulot','https://boulot.metrozendodo.fr'),\n\t\t\t\t('clio','https://clio.metrozendodo.fr'),\n\t\t\t\t('labo', 'https://labo.metrozendodo.fr'),\n\t\t\t\t('photo', 'https://photo.metrozendodo.fr'),\n\t\t\t\t('techno', 'https://techno.metrozendodo.fr'),\n\t\t\t\t('stylo', 'https://stylo.metrozendodo.fr'),]\nFOOTER_TAGS = True\nFOOTER_COPY = \"Publié depuis 2010 par Anthony Nelzin-Santos. Tous droits réservés.\"\n\nPLUGIN_PATHS = ['plugins']\nPLUGINS = ['autopages', 'related_posts', 'sitemap']\nSITEMAP = {\n 'format': 'xml',\n 'priorities': {\n 'articles': 0.7,\n 'indexes': 1,\n 'pages': 0.5\n },\n 'changefreqs': {\n 'articles': 'yearly',\n 'indexes': 'weekly',\n 'pages': 'yearly'\n },\n 'exclude': ['categories.html']\n}\n\nRELATIVE_URLS = True\nARTICLE_URL = '{slug}/'\nARTICLE_SAVE_AS = '{slug}/index.html'\nPAGE_URL = '{slug}/'\nPAGE_SAVE_AS = '{slug}/index.html'\nCATEGORY_URL = '{slug}/'\nCATEGORY_SAVE_AS = '{slug}/index.html'\nCATEGORIES_SAVE_AS = ''\nTAG_URL = 'theme/{slug}/'\nTAG_SAVE_AS = 'theme/{slug}/index.html'\nTAGS_SAVE_AS = 'themes/index.html'\nARCHIVES_SAVE_AS = 'archives/index.html'\nAUTHOR_URL = 'auteur/{slug}/'\nAUTHOR_SAVE_AS = 'auteur/{slug}/index.html'\n\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nAUTHOR_FEED_ATOM = None\nAUTHOR_FEED_RSS = None\n","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"204841577","text":"# Copyright (C) 2020 Cancer Care Associates\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport pathlib\nimport time\n\nfrom pymedphys._imports import streamlit as st\n\nfrom pymedphys._streamlit.apps import metersetmap as _metersetmap\nfrom pymedphys._streamlit.apps import pseudonymise as _pseudonymise\nfrom pymedphys._streamlit.utilities import session\n\nfrom pymedphys._experimental.streamlit.apps import anonymise_monaco as _anonymise_monaco\nfrom pymedphys._experimental.streamlit.apps import dashboard as _dashboard\nfrom pymedphys._experimental.streamlit.apps import electrons as _electrons\nfrom pymedphys._experimental.streamlit.apps import iviewdb as _iviewdb\nfrom pymedphys._experimental.streamlit.apps import wlutz as _wlutz\n\nHERE = pathlib.Path(__file__).parent.resolve()\nFAVICON = str(HERE.joinpath(\"pymedphys.png\"))\nTITLE_LOGO = str(HERE.joinpath(\"pymedphys-title.png\"))\n\nAPPLICATION_CATEGORIES = {\n \"mature\": {\n \"title\": \"Mature\",\n \"description\": \"\"\"\n These are mature applications. They are in wide use, and\n they have a high level of automated test coverage.\n \"\"\",\n },\n \"maturing\": {\n \"title\": \"Maturing\",\n \"description\": \"\"\"\n These are relatively new applications. They potentially\n only have limited use within the community, but the still\n adhere to high quality standards with a level of automated\n test coverage that can be expected for a mature application.\n \"\"\",\n },\n \"raw\": {\n \"title\": \"Raw\",\n \"description\": \"\"\"\n These are relatively new applications. They possibly only\n have minimal use within the community, and they have at\n least some automated test coverage. It is likely that these\n applications and their respective configurations will still\n be changing as time goes on.\n \"\"\",\n },\n \"beta\": {\n \"title\": \"Beta\",\n \"description\": \"\"\"\n These applications may not be in use at all within the\n community. They potentially may only have minimal automated\n test coverage.\n \"\"\",\n },\n \"experimental\": {\n \"title\": \"Experimental\",\n \"description\": \"\"\"\n These applications may not be in use at all within the\n community and they may not have any automated test coverage.\n **They may not even work**.\n \"\"\",\n },\n}\n\n\nAPPLICATION_OPTIONS = {\n \"metersetmap\": {\n \"category\": \"raw\",\n \"label\": \"MetersetMap Comparison\",\n \"callable\": _metersetmap.main,\n },\n \"pseudonymise\": {\n \"category\": \"raw\",\n \"label\": \"DICOM Pseudonymisation\",\n \"callable\": _pseudonymise.main,\n },\n \"dashboard\": {\n \"category\": \"experimental\",\n \"label\": \"Clinical Dashboard\",\n \"callable\": _dashboard.main,\n },\n \"electrons\": {\n \"category\": \"experimental\",\n \"label\": \"Electron Insert Factor Modelling\",\n \"callable\": _electrons.main,\n },\n \"anonymise-monaco\": {\n \"category\": \"experimental\",\n \"label\": \"Anonymising Monaco Backend Files\",\n \"callable\": _anonymise_monaco.main,\n },\n \"wlutz\": {\n \"category\": \"experimental\",\n \"label\": \"Winston-Lutz\",\n \"callable\": _wlutz.main,\n },\n \"iviewdb\": {\n \"category\": \"experimental\",\n \"label\": \"iView Database Explorer\",\n \"callable\": _iviewdb.main,\n },\n}\n\n\ndef get_url_app():\n try:\n return st.experimental_get_query_params()[\"app\"][0]\n except KeyError:\n return \"index\"\n\n\ndef swap_app(app):\n st.experimental_set_query_params(app=app)\n\n session_state = session.session_state()\n session_state.app = app\n\n # Not sure why this is needed. The `set_query_params` doesn't\n # appear to work if a rerun is undergone immediately afterwards.\n time.sleep(0.01)\n st.experimental_rerun()\n\n\ndef index():\n st.write(\n \"\"\"\n # Index of applications available\n\n The following applications are organised by category where each\n category is representative of the maturity of the tool.\n \"\"\"\n )\n\n for category_key, category in APPLICATION_CATEGORIES.items():\n st.write(\n f\"\"\"\n ## {category[\"title\"]}\n {category[\"description\"]}\n \"\"\"\n )\n\n st.write(\"---\")\n\n applications_in_this_category = [\n item\n for item in APPLICATION_OPTIONS.items()\n if item[1][\"category\"] == category_key\n ]\n\n if not applications_in_this_category:\n st.write(\"> *No applications are currently in this category.*\")\n\n for app_key, application in applications_in_this_category:\n if st.button(application[\"label\"]):\n swap_app(app_key)\n\n st.write(\"---\")\n\n\ndef main():\n st.set_page_config(page_title=\"PyMedPhys\", page_icon=FAVICON)\n session_state = session.session_state(app=get_url_app())\n\n if (\n session_state.app != \"index\"\n and not session_state.app in APPLICATION_OPTIONS.keys()\n ):\n swap_app(\"index\")\n\n if session_state.app != \"index\":\n if st.sidebar.button(\"Return to Index\"):\n swap_app(\"index\")\n\n st.sidebar.write(\"---\")\n\n if session_state.app == \"index\":\n application_function = index\n else:\n application_function = APPLICATION_OPTIONS[session_state.app][\"callable\"]\n\n application_function()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"lib/pymedphys/_streamlit/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":6040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"553152172","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# zona de funciones\ndef range_cuadrados(a, b):\n\t\"\"\" Crea la lista de números al cuadrado en el rango de a a b-1 \"\"\"\n\tnumeros = range(a, b) # usamos un generador\n\tfor i in numeros:\n\t\tyield i ** 2 # regresando un sólo valor\n\n# zona principal\nfor n in range_cuadrados(10, 2100_000_000): # usando generador -> 0, 1, 2, ...\n\tprint(n)\n","sub_path":"Parte-4/cuadrados-gen.py","file_name":"cuadrados-gen.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"505959631","text":"import scipy.io as sio\n\ncharset = set()\n\ndata = sio.loadmat('traindata.mat')['traindata'][0]\nimgs, labs = zip(*[(x[0][0], x[1][0]) for x in data])\nwith open('anno.txt','wb') as anno:\n for img,lab in zip(imgs,labs):\n img,lab = str(img), str(lab)\n anno.write(img + ' ' + lab + '\\n')\n charset.update(lab)\ncharset = list(charset)\nwith open('charset.txt','wb') as char:\n for w in charset:\n char.write(w + '\\n')\n\n\n","sub_path":"atten_ctc/data/IIIT5K_train/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"537893481","text":"import re\nfrom collections import Counter\n\nfrom compute_graph import ComputeGraph\nfrom compute_graph.operation import Map, Reduce, Sort\n\n\ndef tokenizer_mapper(r):\n \"\"\"\n splits rows with 'text' field into set of rows with 'token' field\n (one for every occurence of every word in text)\n \"\"\"\n text = re.sub('[^A-Za-z]+', ' ', r['text'])\n tokens = text.split()\n for token in tokens:\n yield {\n 'doc_id': r['doc_id'],\n 'word': token.lower(),\n }\n\n\ndef term_frequency_reducer(records):\n \"\"\"\n calculates term frequency for every word in doc_id\n \"\"\"\n word_count = Counter()\n for r in records:\n word_count[r['word']] += 1\n for w, count in word_count.items():\n yield {\n 'word': w,\n 'count': count\n }\n\n\nif __name__ == '__main__':\n graph = ComputeGraph(inputs='../data/text_corpus.txt',\n outputs='../data/output/word_count.txt')\n graph.add(Map(mapper=tokenizer_mapper))\n graph.add(Sort(by='word'))\n graph.add(Reduce(reducer=term_frequency_reducer, key='word'))\n graph.compile()\n graph.summary()\n\n graph.run()\n","sub_path":"1st-term/Python/computation-graph/examples/word_count.py","file_name":"word_count.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"187990735","text":"import os\n\nfrom flask import render_template, request, redirect, url_for, jsonify, Blueprint, flash\nfrom flask.ext.login import current_user\nfrom sqlalchemy import and_\n\nfrom MORTWebsite import db\nfrom MORTWebsite.sql.ORM import Page, RevisionHistory\nfrom MORTWebsite.utilities.permissions import cms_access_required, cms_admin_required\nfrom MORTWebsite import forms\nfrom MORTWebsite.utilities.renderer import new_page_to_file, updated_page_to_file\nfrom MORTWebsite.utilities.helpers import flash_errors, create_new_revision, get_revision_history\nfrom MORTWebsite.utilities.server_logger import log_event\n\npages = Blueprint('pages', __name__)\n\n\n@pages.route('/cms/pages')\n@cms_access_required\ndef pages_overview():\n pages_list = db.session.query(Page)\n if request.method == 'GET':\n return render_template('cms/pages/admin/index.html', pages=pages_list)\n\n\n@pages.route('/cms/pages/new', methods=['GET', 'POST'])\n@cms_access_required\ndef new_page():\n form = forms.Page()\n\n if form.validate_on_submit():\n try:\n page_title = form.page_title.data.decode('unicode_escape').encode('ascii', 'ignore')\n page_url = form.page_url.data.lower().decode('unicode_escape').encode('ascii', 'ignore')\n page_content = form.page_content.data.decode('unicode_escape').encode('ascii', 'ignore')\n page_scripts = form.page_scripts.data\n page_styles = form.page_styles.data\n page_mode = form.page_mode.data\n\n revision_description = form.revision_description.data.decode('unicode_escape').encode('ascii', 'ignore')\n\n # Render page content to html file\n new_page_query = Page(page_title, page_url, page_content, page_scripts, page_styles, page_mode)\n\n db.session.add(new_page_query)\n db.session.commit()\n create_new_revision(new_page_query.id, page_content, revision_description, styles=page_styles,\n scripts=page_scripts)\n\n new_page_to_file(new_page_query.id, page_url, page_title, page_content, page_scripts, page_styles,\n page_mode)\n\n return redirect('/' + page_url)\n except:\n flash(\"Error! Page already exists!\")\n else:\n flash_errors(form)\n return render_template('cms/pages/admin/new-page.html', form=form)\n\n\n@pages.route('/cms/pages/edit/', methods=['GET', 'POST'])\n@cms_access_required\ndef edit_page(page_id):\n form = forms.Page()\n prev_page = db.session.query(Page).filter(Page.id == page_id).first()\n\n revision_history = get_revision_history(prev_page.id)\n\n if form.validate_on_submit():\n try:\n page_title = form.page_title.data.decode('unicode_escape').encode('ascii', 'ignore')\n new_page_url = form.page_url.data.lower().decode('unicode_escape').encode('ascii', 'ignore')\n page_content = request.form['page_content'].decode('unicode_escape').encode('ascii', 'ignore')\n page_scripts = request.form['page_scripts']\n page_styles = request.form['page_styles']\n\n page_mode = request.form['page_mode']\n\n revision_description = form.revision_description.data\n prev_page.page_title = page_title\n prev_page.page_url = new_page_url\n prev_page.page_mode = page_mode\n prev_page.page_content = page_content\n prev_page.page_scripts = page_scripts\n prev_page.page_styles = page_styles\n db.session.commit()\n create_new_revision(prev_page.id, page_content, revision_description, styles=page_styles,\n scripts=page_scripts)\n updated_page_to_file(prev_page.id, prev_page.page_url, new_page_url, page_title, page_content, page_scripts,\n page_styles, page_mode)\n\n return redirect('/' + new_page_url)\n except:\n db.session.rollback()\n flash(\"Unknown database error!\")\n\n else:\n flash_errors(form)\n return render_template('cms/pages/admin/edit-page.html', page=prev_page, form=form,\n revision_history=revision_history)\n\n\n@pages.route('/cms/pages/delete/')\n@cms_access_required\ndef delete_page(page_id):\n page_to_del = db.session.query(Page).filter(Page.id == page_id).first()\n try:\n os.remove('{0}/MORTWebsite/templates/render-files/page/{1}.html'.format(\n os.environ.get('APPLICATION_ROOT'), page_to_del.page_url))\n\n db.session.delete(page_to_del)\n db.session.commit()\n except:\n db.session.rollback()\n flash(\"Error deleting page!\")\n log_event('ERROR', \"Encountered error deleting {0} page\".format(page_to_del.page_title))\n\n return redirect(url_for('pages.pages_overview'))\n\n\n@pages.route('/cms/pages/revert', methods=['POST'])\n@cms_access_required\ndef revert_page():\n page_id = request.values['page_id']\n revision_version = request.values['revision_version']\n\n page = db.session.query(Page).filter(Page.id == page_id).first()\n revision = db.session.query(RevisionHistory).filter(and_(RevisionHistory.page_id == page_id,\n RevisionHistory.revision_version == revision_version)).first()\n\n content = str(revision.content)\n styles = str(revision.styles)\n scripts = str(revision.scripts)\n\n page.page_content = content\n page.page_styles = styles\n page.page_scripts = scripts\n\n try:\n db.session.commit()\n updated_page_to_file(page_id, page.page_url, page.page_url, page.page_title, content, scripts,\n styles, page.page_mode)\n log_event('INFO', '{0} reverted page id {1} to revision version {2}'.format(current_user.username, page_id,\n revision_version))\n return jsonify(success=\"Successful revert!\")\n except:\n log_event('ERROR',\n '{0} attempted to revert a page id {1} to revision version {2}, but db encountered error'.format(\n current_user.username, page_id, revision_version))\n return jsonify(error=\"Error while reverting!\")\n\n\n@pages.route('/cms/pages/edit-index', methods=['GET', 'POST'])\n@cms_admin_required\ndef edit_index():\n if request.method == 'GET':\n page = open('MORTWebsite/templates/bases/index-filler.html', 'r')\n data = page.read().decode('utf-8')\n return render_template('cms/editor.html', data=data)\n else:\n page = open('MORTWebsite/templates/bases/index-filler.html', 'w+')\n content = request.form['content']\n page.write(content)\n return redirect(url_for('cms'))\n\n\n@pages.route('/cms/pages/edit-navbar', methods=['GET', 'POST'])\n@cms_admin_required\ndef edit_navbar():\n if request.method == 'GET':\n page = open('MORTWebsite/templates/bases/navbar.html', 'r')\n data = page.read().decode('utf-8')\n return render_template('cms/editor.html', data=data)\n else:\n page = open('MORTWebsite/templates/bases/navbar.html', 'w+')\n content = request.form['content']\n page.write(content)\n return redirect(url_for('cms'))\n\n\n@pages.route('/cms/pages/edit-cdown', methods=['GET', 'POST'])\n@cms_admin_required\ndef edit_countdown_script():\n if request.method == 'GET':\n page = open('MORTWebsite/static/js/mort/countdown.js', 'r')\n data = page.read().decode('utf-8')\n return render_template('cms/editor.html', data=data)\n else:\n page = open('MORTWebsite/static/js/mort/countdown.js', 'w+')\n content = request.form['content'].decode('utf-8')\n page.write(content)\n return redirect(url_for('cms'))\n\n\n@pages.route('/cms/pages/edit-rbkg', methods=['GET', 'POST'])\n@cms_admin_required\ndef edit_rbkg_script():\n if request.method == 'GET':\n page = open('MORTWebsite/static/js/mort/randomLoginBkg.js', 'r')\n data = page.read().decode('utf-8')\n return render_template('cms/editor.html', data=data)\n else:\n page = open('MORTWebsite/static/js/mort/randomLoginBkg.js', 'w+')\n content = request.form['content'].decode('utf-8')\n page.write(content)\n return redirect(url_for('cms'))\n\n\n@pages.route('/cms/pages/edit-footer', methods=['GET', 'POST'])\n@cms_admin_required\ndef edit_footer():\n if request.method == 'GET':\n page = open('MORTWebsite/templates/bases/footer.html', 'r')\n data = page.read()\n return render_template('cms/editor.html', data=data)\n else:\n page = open('MORTWebsite/templates/bases/footer.html', 'w+')\n content = request.form['content']\n page.write(content)\n return redirect(url_for('cms'))\n\n\n@pages.route('/cms/pages/edit-styles', methods=['GET', 'POST'])\n@cms_admin_required\ndef edit_styles():\n if request.method == 'GET':\n page = open('MORTWebsite/static/css/styles.css', 'r')\n data = page.read()\n return render_template('cms/editor.html', data=data)\n else:\n page = open('MORTWebsite/static/css/styles.css', 'w+')\n content = request.form['content']\n page.write(content)\n return redirect(url_for('cms'))\n","sub_path":"MORTWebsite/routing/cms/pages/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"460724320","text":"import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time\nsys.setrecursionlimit(10**7)\ninf = 10**20\n\ndef eratosthenes(upperBound):\n \"\"\"エラトステネスの篩アルゴリズムによって、upperBound以下の素数すべてからなるリストを計算する。\n\n Args:\n upperBound(int): 計算したい素数リストに含まれる素数の上限値。\n Returns:\n list[int]: 計算された素数リスト。\n \n Examples:\n >>> eratosthenes(10)\n [2, 3, 5, 7]\n >>> eratosthenes(11)\n [2, 3, 5, 7, 11]\n \"\"\"\n primeNumbers = []\n isPrime = [True for _ in range(upperBound + 1)]\n isPrime[0] = isPrime[1] = False\n divider = 0\n while divider <= math.sqrt(upperBound):\n if isPrime[divider]:\n # primeNumbers.append(divider)\n multiple = 2* divider\n while multiple <= upperBound:\n isPrime[multiple] = False\n multiple += divider\n divider += 1\n return [i for i in range(upperBound + 1) if isPrime[i]]\n\nprimeNumberList = eratosthenes(1000010)\n\ndef factorize(number):\n \"\"\"与えられた整数を素因数分解する。素因数とその指数を辞書として返却する。\n\n Args:\n number(int) \n Returns:\n dict[int,int] 素因数->指数の辞書。\n >>> factorize(6)\n {2: 1, 3: 1}\n >>> factorize(20)\n {2: 2, 5: 1}\n \"\"\"\n exponents = {}\n for primeNumber in primeNumberList:\n while number%primeNumber == 0:\n number /= primeNumber\n if primeNumber in exponents:\n exponents[primeNumber] += 1\n else:\n exponents[primeNumber] = 1\n if number != 1:\n exponents[number] = 1\n return exponents\n\nA,B = map(int,input().split())\ngcd = fractions.gcd(A,B)\nfactorizedGcd = factorize(gcd)\nprint(len(factorizedGcd.keys()) + 1)","sub_path":"ABC/142/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"538190159","text":"\"\"\"\n\n문제유형 :\n브루트포스 알고리즘\n백트래킹\n\nn개의 퀸 배치\n무조건 한 행, 한 열에는 퀸이 있어야 한다.\n\n\n\n\"\"\"\nimport sys\n\ninput = sys.stdin.readline\n\nn = int(input())\n\nrow = [0] * n\nanswer = 0\n\ndef adjacent(x) :\n for i in range(x) :\n if row[x] == row[i] or abs(row[x] - row[i]) == x - i :\n return False\n return True\n\ndef dfs(x) :\n global answer\n\n if x == n :\n answer += 1\n else :\n for i in range(n) :\n row[x] = i\n if adjacent(x) :\n dfs(x+1)\n\ndfs(0)\nprint(answer)\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"AlgorithmStudy/백준/무지성 랜덤풀이/9월/9.16/9636 N-Queen.py","file_name":"9636 N-Queen.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"3404810","text":"import h5py #external\r\nimport pandas as pd #external\r\nfrom glob import glob #external\r\nimport numpy as np #external\r\nimport spotipy #external\r\nfrom spotipy.oauth2 import SpotifyOAuth\r\nfrom collections import OrderedDict\r\nfrom random import random, randint\r\nimport sys\r\n\r\nprint(\"Running python script...\")\r\n\r\ndef get_dataset(files): #turns an array of HDF files into a one hot encoded song dataframe\r\n df = pd.DataFrame(np.asarray([h5py.File(file, \"r\").get(\"analysis/songs\")[0] for file in files]))[\"track_id\"]\r\n df = pd.DataFrame(df.str.decode(\"utf-8\"))\r\n title_df = pd.DataFrame(np.asarray([h5py.File(file, \"r\").get(\"metadata/songs\")[0] for file in files]))[\"title\"]\r\n title_df = pd.DataFrame(title_df.str.decode(\"utf-8\"))\r\n df = df.merge(title_df, on=df.index)\r\n df = df.iloc[:,1:]\r\n genres = []\r\n with open(\"genres.txt\", \"r\") as f:\r\n lines = f.read().split(\"\\n\")\r\n for line in lines:\r\n split_line = line.split(\"\\t\")\r\n genres.append(split_line)\r\n genre_df = pd.DataFrame(genres)\r\n genre_df.columns = [\"track_id\", \"genre\"]\r\n df = df.merge(genre_df, on=\"track_id\") #filters out the songs for which we can't find the genre\r\n one_hot = pd.get_dummies(df[\"genre\"]) #one hot encodes the genres\r\n df = df.merge(one_hot, on=df.index)\r\n df = df.iloc[:,1:]\r\n df.columns = df.columns.str.lower()\r\n return df\r\n\r\ndef get_genre_scores(sp): #computes the number of songs for each genre on the user's library\r\n tracks = sp.current_user_saved_tracks()\r\n artists = [tracks[\"items\"][i][\"track\"][\"album\"][\"artists\"][0][\"external_urls\"][\"spotify\"] for i in range(len(tracks[\"items\"]))]\r\n genre_list = [sp.artist(artists[i])[\"genres\"] for i in range(len(artists))]\r\n genres = set()\r\n for genre in genre_list:\r\n genres = genres.union(set(genre))\r\n genres = list(genres)\r\n genre_dict = dict()\r\n for genre in genres:\r\n genre_dict[genre] = sum(genre_list[i].count(genre) for i in range(len(genre_list)))\r\n return {k: v for k, v in sorted(genre_dict.items(), key=lambda item: item[1], reverse=True)} #orders it by decreasing occurences\r\n\r\ndef get_genre_probs(d, dataset_genres): #replaces occurences by probabilities\r\n keys = list(d.keys())\r\n for key in keys: #makes it impossible to get a song whose genre isn't in our dataset\r\n if key not in dataset_genres:\r\n d[key] = 0.0\r\n total = sum(d.values())\r\n for k, v in d.items():\r\n d[k] = v / total\r\n for genre in dataset_genres: #adds the dataset's genres that aren't present in the user's library\r\n if genre not in keys:\r\n d[genre] = 0.0\r\n return d\r\n\r\ndef get_songs_from_duration(sp, d, duration): #content-based recommandation system: returns a playlist based on genre probabilities\r\n song_uris = []\r\n total_duration = 0\r\n index = 0\r\n n_errors = 0\r\n while total_duration < duration: #we keep adding songs until we reach the given playlist duration\r\n index = randint(0, 200)\r\n r = random()\r\n total = 0\r\n current_genre = \"\"\r\n for k, v in d.items(): #computes a genre to choose based on the probability dictionary\r\n total += v\r\n if r <= total:\r\n current_genre = k\r\n try:\r\n response = sp.search(\"genre:\" + current_genre, type=\"track\", limit=1, offset=index) #searches for a song for this genre\r\n song_uris.append(response[\"tracks\"][\"items\"][0][\"uri\"])\r\n total_duration += int(response[\"tracks\"][\"items\"][0][\"duration_ms\"]) / 60000\r\n except:\r\n n_errors += 1\r\n print(f\"Couldn't search for song {n_errors}, retrying with a different one\")\r\n return song_uris\r\n \r\ndef main():\r\n print(\"Running Python script...\")\r\n pkey = \"3687892771ef476f8b497d740c6c2408\" #default values\r\n skey = \"99026e5bffae4711b3f209123ab1df56\"\r\n playlistID = \"https://open.spotify.com/playlist/0Mtvm4D0laomvp7pgfMTHa?si=73c75935991641c4\"\r\n duration = 100\r\n try:\r\n pkey, skey, playlistID, duration = sys.argv[1:] #the python code should be run with the arguments in this order\r\n duration = int(duration)\r\n except:\r\n print(\"Error while reading arguments: using default values instead\")\r\n files = glob(\"C:/Backups/MillionSongSubset/A/A/*/*.h5\") #fetches a large sample of songs from our full dataset (fetching any more would take too much RAM)\r\n files.extend(glob(\"C:/Backups/MillionSongSubset/A/B/*/*.h5\"))\r\n files.extend(glob(\"C:/Backups/MillionSongSubset/A/C/*/*.h5\"))\r\n df = get_dataset(files)\r\n sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=pkey, client_secret=skey, redirect_uri=\"http://localhost:1234/\", scope=\"user-library-read\"))\r\n genre_scores = get_genre_scores(sp)\r\n genre_probs = get_genre_probs(genre_scores, list(df.columns)[3:])\r\n songs = get_songs_from_duration(sp, genre_probs, duration)\r\n sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=pkey, client_secret=skey, redirect_uri=\"http://localhost:1234/\", scope=\"playlist-modify-private\"))\r\n sp.user_playlist_add_tracks(pkey, playlistID, songs) #finally, the tracks are added to the playlist\r\n print(\"Finished!\")\r\n\r\nif __name__==\"__main__\":\r\n main()\r\n","sub_path":"recom.py","file_name":"recom.py","file_ext":"py","file_size_in_byte":5246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"491803154","text":"import collections\nfrom copy import deepcopy\n\ndef getSCC(graph):\n \"\"\"\n rtype: [set(nodes)]\n \"\"\"\n stack, visited, reverseGraph = [], set(), collections.defaultdict(set())\n for node in graph:\n dfs(node, graph, visited, stack)\n for n in graph[node]:\n reverseGraph[n].add(node)\n visited, res = set(), []\n while stack:\n v = stack.pop()\n dfsutil(v, set(), reverseGraph, visited, res)\n return res\n\ndef dfsutil(node, cur, graph, visited, res):\n visited.add(node)\n cur.add(node)\n newNode = False\n for n in graph[node]:\n if n not in visited:\n newNode = True\n dfsutil(node, cur, graph, visited, res)\n if not newNode:\n res.append(cur)\n\ndef dfs(node, graph, visited, stack):\n visited.add(node)\n for n in graph[node]:\n if n not in visited:\n dfs(node, graph, visited, stack)\n stack.append(node)\n\ndef goThrough(graph):\n \"\"\"\n graph: {'a':set(['b'])}\n \"\"\"\n scc, reducedGraph, nodeTable, pairs = getSCC(graph), {}, {}, []\n for c in scc:\n for n in c:\n nodeTable[n] = c[0]\n for start in graph:\n reducedGraph[nodeTable[start]] = map(lambda x: nodeTable[x], graph[start])\n for start in reducedGraph:\n pairs.append(map(lambda x: (start, x), reducedGraph[start]))\n allnodes = reduce(lambda acc, val: acc + val, pairs)\n free = allnodes - set(zip(*pairs)[1])\n if not free:\n return [allnodes[0]] # if the whole graph is scc, return any one\n return list(free) # return the free nodes, the can access the rest of the graph\n\n\n \n","sub_path":"Airbnb/go_through_graph.py","file_name":"go_through_graph.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"336229025","text":"import matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport numpy as np\nimport h5py \nplt.rcParams['mathtext.fontset'] = 'stix'\nplt.rcParams['font.family'] = 'STIXGeneral'\nplt.rcParams.update({'font.size': 9})\n\nt0=1\ntf=120\n\n\n\nfor t in range(t0,tf):\n tstr = \"%03d\" % t\n mybase = \"/home/u21/davidrball/david/tristan_KSI/ple_runs/sig2_bangle0_nograv2/flds.tot.\"+tstr\n\n #mybase = \"/rigel/home/ls3326/home_david/tristan_KSI/smooth_offset_current_test/output/flds.tot.\"+tstr\n\n print(t)\n myf = h5py.File(mybase,'r')\n \n dens = myf['dens'][0,:,:]\n\n ey = myf['ey'][0,:,:]\n #ez = myf['ez'][0,:,:]\n\n jy = myf['jy'][0,:,:]\n\n my0, mx0 = np.shape(jy)\n xscan=250\n x0 = int(mx0/4.)\n xlow=x0-xscan\n xup=x0+xscan\n \n\n\n #now just make cuts of only the quantities we actually want to plot\n jy = jy[:,xlow:xup]\n if t==1:\n jy0 = jy\n\n\n dens = dens[:,xlow:xup]\n\n ey = ey[:,xlow:xup]\n\n\n fig, (ax1, ax2, ax3) = plt.subplots(1,3,sharey=True)\n \n im1=ax1.imshow(-jy*10000,origin='lower',cmap='RdBu',vmin=-8,vmax=8)\n im2=ax2.imshow(ey,origin='lower',cmap='RdBu',vmin=-.0075,vmax=.0075)\n im3=ax3.imshow(dens,origin='lower',cmap='viridis',vmin=4,vmax=24)\n\n plt.rcParams.update({'font.size': 4})\n\n cbar_ax1 = fig.add_axes([.125,.97,.22,.02])\n cb1 = fig.colorbar(im1,cax=cbar_ax1,orientation='horizontal')\n\n cbar_ax2 = fig.add_axes([.4,.97,.22,.02])\n cb2 = fig.colorbar(im2,cax=cbar_ax2,orientation='horizontal')\n \n cbar_ax3 = fig.add_axes([.675,.97,.22,.02])\n cb3 = fig.colorbar(im3,cax=cbar_ax3, orientation='horizontal')\n\n plt.rcParams.update({'font.size': 9})\n\n\n ax1.set_title('$10000j_y$')\n ax2.set_title('$E_y$')\n ax3.set_title('Density')\n\n plt.savefig(\"ple_bangle0_sig2_nograv/moreflds\"+tstr+\".png\",dpi=300,bbox_inches='tight')\n plt.close()\n","sub_path":"current_analysis.py","file_name":"current_analysis.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"12673102","text":"class Solution:\n def twoSum(self, nums, target):\n result = int()\n for i in range(len(nums)):\n finding = target - nums[i]\n numscpy = nums.copy()\n numscpy[i] = None\n if finding in numscpy:\n result = numscpy.index(finding)\n break\n return sorted([i, result])\n\n\ns = Solution()\nprint(s.twoSum([3, 3], 6))\n","sub_path":"leetcode/two-sum.py","file_name":"two-sum.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"491238196","text":"import hashlib\nimport hmac\nimport base64\nimport datetime\nimport pyqrcode\n\ndate = datetime.datetime.now()\nstrdate=date.strftime(\"%Y%m%d\")\n\nnum= 1\n\nsecret_key=b'MGR'\n\ns=b\"MGR\"+strdate.encode()+(num).to_bytes(2, byteorder='big')+secret_key\nprint(s)\n\nmessage = bytes('the message to hash here', 'utf-8')\n\nmessage = s\nsecret = bytes('MGR', 'utf-8')\n\nhash = hmac.new(secret, message, hashlib.md5)\n\n# to lowercase hexits\nm=hash.hexdigest()\n\n# to base64\nbase64.b64encode(hash.digest())\n\nbig_code = pyqrcode.create(m)\nbig_code.png('code.png', scale=5)\n#big_code.show()\nprint(m)\n\nm=hashlib.md5(\"MGR\".encode())\nprint(\"hash md5\",m.hexdigest())\n","sub_path":"QR_CODE/hmac-examples.py","file_name":"hmac-examples.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"515381217","text":"# coding=utf-8\n# Copyright 2018 XXX. All Right Reserved\n# Author: test@XXX.com{test}\n# Web静态服务器-3-使用类.py 18-4-12 下午4:27\n# SITE: https:www.jetbrains.com/pycharm\nfrom socket import *\nfrom multiprocessing import Process\nimport re\n\nHTML_ROOT_DIR = \"./html\"\nHTML_ROOT_JPG =\"./img\"\n\n\nclass HttpServer(object):\n def __init__(self):\n # 创建客户端\n self.tcp = socket(AF_INET, SOCK_STREAM)\n self.tcp.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\n\n # 绑定端口\n def bind(self, port):\n self.tcp.bind((\"\", port))\n\n def start(self):\n # 设置监听\n self.tcp.listen(5)\n while True:\n new_socket, new_address = self.tcp.accept()\n print(\"客户已经链接\")\n Process(target=self.handle_tcp, args=(new_socket,)).start()\n new_socket.close()\n\n # 客户\n def handle_tcp(self, new_socket):\n try:\n # 处理客户请求\n while True:\n recv_data = new_socket.recv(1024)\n response_line = recv_data.splitlines()\n for line in response_line:\n print(line)\n\n response_start_line = response_line[0].decode(\"utf-8\")\n # 获得html名字\n html_name = re.match(\"\\w+ +(/[^ ]*)\", response_start_line).group(1)\n # 判断html\n if html_name == '/':\n html_name = \"3.html\"\n try:\n f = open(HTML_ROOT_DIR+html_name, \"r\")\n except:\n response_start_line = \"HTTP/1.1 404 Found File\\r\\n\"\n response_heard = \"Content-Type: \" \\\n \"text/html;charset=utf-8\\r\\nMyServer: server\\r\\n\"\n response_body = \"文件未找到\"\n else:\n html_read = f.read()\n f.close()\n response_start_line = \"HTTP/1.1 200 OK\\r\\n\"\n response_heard = \"Content-Type: \" \\\n \"text/html;charset=utf-8\\r\\nMyServer: server\\r\\n\"\n response_body = html_read\n response_blank = \"\\r\\n\"\n response = response_start_line + response_heard + response_blank + response_body\n new_socket.send(response.encode(\"utf-8\"))\n new_socket.close()\n except Exception as result:\n print(\"文件未找到\",result)\n\n\ndef main():\n http = HttpServer()\n http.bind(9999)\n http.start()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"萌新/study_0412/Web静态服务器-3-使用类.py","file_name":"Web静态服务器-3-使用类.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"432770574","text":"from random import *\n \ndef begin(palabra):\n size = len(palabra)\n index = randint(0,size-1)\n underscores = []\n for i in range(size):\n underscores.append('_')\n\n for i in range (size):\n if i == index:\n underscores[i] = palabra[index]\n\n for i in range(size):\n print(underscores[i], end = \" \") \n \n acabado = False\n while(acabado == False): \n \n print(\"\")\n print(\"Dema una letra para completar la palabra\", end = \" \")\n letra = input()\n\n for i in range(size):\n if(palabra[i] == letra):\n underscores[i] = palabra [i]\n \n if letra not in underscores:\n print(\"Esa letra no forma parte de la palabra\")\n \n if '_' in underscores:\n acabado = False\n else:\n acabado = True\n\n for i in range(size):\n print(underscores[i], end = \" \")\n\nprint(\"Palabra a adivinar: \")\npalabra = input()\n \nbegin(palabra)\n\n\n\n","sub_path":"AdivinaPalabra.py","file_name":"AdivinaPalabra.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"516739853","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /usr/local/lib/python2.7/site-packages/axon_conabio/trainer/tf_trainer_config.py\n# Compiled at: 2018-12-10 18:39:29\nimport os, tensorflow as tf\nfrom ..utils import memoized, parse_configs\nDEFAULT_CONFIG_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'default_config.yaml')\nOPTIMIZERS = {'GradientDescent': {'factory': tf.train.GradientDescentOptimizer, \n 'arguments': {'learning_rate': 0.001}}, \n 'Adadelta': {'factory': tf.train.AdadeltaOptimizer, \n 'arguments': {'learning_rate': 0.001, \n 'rho': 0.95, \n 'epsilon': 1e-08}}, \n 'Adagrad': {'factory': tf.train.AdagradOptimizer, \n 'arguments': {'learning_rate': 0.001, \n 'initial_accumulator_value': 0.1}}, \n 'AdagradDA': {'factory': tf.train.AdagradDAOptimizer, \n 'arguments': {'learning_rate': 0.001, \n 'global_step': None, \n 'initial_gradient_squared_accumulator_value': 0.1, \n 'l1_regularization_strength': 0.0, \n 'l2_regularization_strength': 0.0}}, \n 'Momentum': {'factory': tf.train.MomentumOptimizer, \n 'arguments': {'learning_rate': 0.001, \n 'momentum': 0.999, \n 'use_nesterov': False}}, \n 'Adam': {'factory': tf.train.AdamOptimizer, \n 'arguments': {'learning_rate': 0.001, \n 'beta1': 0.9, \n 'beta2': 0.999, \n 'epsilon': 1e-08}}, \n 'Ftrl': {'factory': tf.train.FtrlOptimizer, \n 'arguments': {'learning_rate': 0.001, \n 'learning_rate_power': -0.5, \n 'initial_accumulator_value': 0.1, \n 'l1_regularization_strength': 0.0, \n 'l2_regularization_strength': 0.0, \n 'l2_shrinkage_regularization_strength': 0.0}}, \n 'ProximalGradientDescent': {'factory': tf.train.ProximalGradientDescentOptimizer, \n 'arguments': {'learning_rate': 0.001, \n 'l1_regularization_strength': 0.0, \n 'l2_regularization_strength': 0.0}}, \n 'ProximalAdagrad': {'factory': tf.train.ProximalAdagradOptimizer, \n 'arguments': {'learning_rate': 0.001, \n 'initial_accumulator_value': 0.1, \n 'l1_regularization_strength': 0.0, \n 'l2_regularization_strength': 0.0}}, \n 'RMSProp': {'factory': tf.train.RMSPropOptimizer, \n 'arguments': {'learning_rate': 0.001, \n 'decay': 0.9, \n 'momentum': 0.0, \n 'epsilon': 1e-10, \n 'centered': True}}}\n\nclass TrainConfig(object):\n\n def __init__(self, config):\n self.config = config\n self.optimizer = get_optimizer(config)\n\n\ndef get_optimizer(config):\n optimizer = config['optimizer']['name']\n factory = OPTIMIZERS[optimizer]['factory']\n arguments = OPTIMIZERS[optimizer]['arguments'].copy()\n for key in arguments:\n if key in config['optimizer']:\n dtype = type(arguments[key])\n arguments[key] = dtype(config['optimizer'][key])\n\n return (\n factory, arguments)\n\n\n@memoized\ndef get_config(paths=None, config=None):\n if paths is None:\n paths = []\n paths = [\n DEFAULT_CONFIG_PATH] + paths\n configuration = parse_configs(paths)\n if config is not None:\n configuration.update(config)\n return TrainConfig(configuration)","sub_path":"pycfiles/axon-conabio-0.5.1.macosx-10.13-x86_64.tar/tf_trainer_config.py","file_name":"tf_trainer_config.py","file_ext":"py","file_size_in_byte":3994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"14598370","text":"import sqlite3\nfrom util import to_text,get_text,json_loads,json_dumps\n\n__CREATE_TABLE_SQL__ = \"\"\"\nCREATE TABLE IF NOT EXISTS USER_INFO\n(id TEXT PRIMARY KEY NOT NULL ,\nvalue TEXT NOT NULL );\n\"\"\"\n\n\nclass SQLiteHelper():\n\n def __init__(self, filename='.\\data\\session.sqlite3'):\n self.db = sqlite3.connect(filename, check_same_thread=False)\n self.db.text_factory = str\n self.db.execute(__CREATE_TABLE_SQL__)\n\n def get(self, id):\n \"\"\"\n 根据 id 获取数据。\n :param id: 要获取的数据的 id\n :return: 返回取到的数据,如果是空则返��一个空的 ``dict`` 对象\n \"\"\"\n session_json = self.db.execute(\n \"SELECT value FROM USER_INFO WHERE id=? LIMIT 1;\", (id, )\n ).fetchone()\n if session_json is None:\n return {}\n return json_loads(session_json[0])\n\n def set(self, id, value):\n \"\"\"\n 根据 id 写入数据。\n :param id: 要写入的 id\n :param value: 要写入的数据,可以是一个 ``dict`` 对象\n \"\"\"\n self.db.execute(\n \"INSERT OR REPLACE INTO USER_INFO (id, value) VALUES (?,?);\",\n (id, json_dumps(value))\n )\n self.db.commit()\n\n def delete(self, id):\n \"\"\"\n 根据 id 删除数据。\n :param id: 要删除的数据的 id\n \"\"\"\n self.db.execute(\"DELETE FROM USER_INFO WHERE id=?;\", (id, ))\n self.db.commit()\n\n\n","sub_path":"sqlite_helper.py","file_name":"sqlite_helper.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"515154181","text":"from django.shortcuts import get_object_or_404, render\nfrom django.http import HttpResponseRedirect\nfrom ..models import Task, TaskUser\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom ..forms import TaskForm, TaskUserForm\nfrom django.views.generic.list import ListView\n\n\n@login_required\ndef task_edit(request, pk=None):\n instance = Task.objects.filter(pk=pk).first()\n if request.method == \"POST\":\n form = TaskForm(request.POST, user=request.user.userprofile, instance=instance)\n if form.is_valid():\n return HttpResponseRedirect(reverse('task', args=[form.save().pk]))\n else:\n form = TaskForm(user=request.user.userprofile, instance=instance)\n return render(request, 'main/task/edit.html', {'form': form})\n\n\ndef task(request, pk):\n _task = get_object_or_404(Task, pk=pk)\n form = None\n if _task.status and hasattr(request.user, 'userprofile'):\n offer = TaskUser.objects.filter(user=request.user.userprofile, task=_task).all()\n offer = offer[0] if offer.count() > 0 else None\n if request.method == \"POST\":\n if offer and 'delete' in request.POST:\n offer.delete()\n return HttpResponseRedirect(reverse('task', args=[pk]))\n form = TaskUserForm(request.POST, user=request.user.userprofile, task=_task, instance=offer)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse('task', args=[pk]))\n else:\n form = TaskUserForm(user=request.user.userprofile, task=_task, instance=offer)\n return render(request, 'main/task/detail.html', {\n 'task': _task,\n 'form': form,\n })\n\n\nclass TaskListView(ListView):\n model = Task\n paginate_by = 10\n template_name = 'main/task/all.html'\n ordering = ['-status', '-timestamp_create']\n","sub_path":"main/views/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"295826909","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport time\n\nfrom Spider.SAVE_MONGO import save_mongo\n\n\ndef maoyan_year(year_list, HOST, PORT, DB_NAME):\n \"\"\"进入猫眼页面,并获取日期选择中选取年票房\"\"\"\n browser = webdriver.Chrome()\n waite = WebDriverWait(browser, 10)\n need_year_list = []\n\n browser.get('http://piaofang.maoyan.com/?ver=normal')\n\n more_date = waite.until(\n EC.element_to_be_clickable(\n (By.XPATH, '/html/body/ul/li[4]'))\n )\n more_date.click()\n\n month_date = waite.until(\n EC.element_to_be_clickable((By.XPATH, '/html/body/div[7]/ul/li[4]')) # 点击年票房按钮\n )\n month_date.click()\n\n years = browser.find_elements_by_xpath('//div[@class = \"year-content calendar-content\"]/ul/li')\n get_year_list = [get_year.text.split('年')[0] for get_year in years]\n print(get_year_list)\n print(year_list)\n for year in year_list:\n try:\n index_year = get_year_list.index(str(year))\n need_year_list.append(years[index_year])\n except Exception as e:\n print('Error: without year, %s' % str(year))\n return None\n\n need_years(need_year_list, HOST, PORT, DB_NAME, browser)\n\n\ndef need_years(need_year_list, HOST, PORT, DB_NAME, browser):\n \"\"\"进入某个年份页面遍历所有年\"\"\"\n for year in need_year_list:\n try:\n year.click()\n time.sleep(5)\n result = get_data(browser, HOST, PORT, DB_NAME)\n\n if result:\n browser.find_element_by_xpath('/html/body/ul/li[4]').click()\n\n\n except Exception as e:\n print('年份li无效')\n print(e)\n\n\ndef get_data(browser, HOST, PORT, DB_NAME):\n '''获取年中所有的电影相关信息'''\n\n logs_date = browser.find_element_by_xpath('//*[@id=\"desc-wrap\"]/div[1]/span[1]').text\n logs_big = browser.find_element_by_xpath('//*[@id=\"desc-wrap\"]/div[1]/span[2]').text\n logs_numbers = browser.find_element_by_xpath('//*[@id=\"desc-wrap\"]/div[1]/span[3]').text\n logs = logs_date + \":\" + logs_big + logs_numbers\n rows = browser.find_elements_by_xpath('//*[@id=\"ticket_tbody\"]/ul')\n for row in rows:\n data_dict = {}\n columns = row.find_elements_by_xpath('.//li')\n movie_name = columns[0].find_element_by_xpath('.//b').text\n movie_date = columns[0].find_element_by_xpath('.//em').text\n year, month, day = split_movie_date(movie_date)\n release_time = year + '-' + month + '-' + day\n year_office_W = columns[1].find_element_by_xpath('.//b').text\n office_rate = columns[2].text\n one_number_peo = columns[3].text\n average_price = columns[4].find_element_by_xpath('./span').text\n\n data_dict['movie_name'] = movie_name\n data_dict['logs'] = logs\n data_dict['release_time'] = release_time\n data_dict['year_office_W'] = year_office_W\n data_dict['office_rate'] = office_rate\n data_dict['one_number_peo'] = one_number_peo\n data_dict['average_price'] = average_price\n\n # save_mongo(HOST, PORT, DB_NAME, str(year), data_dict) # 保存到mongo\n\n return True\n\n\ndef split_movie_date(movie_date):\n '''重新定义电影上映时间'''\n year, month, day = movie_date.split('-')\n day = day[:2]\n return year, month, day\n\n# if __name__ == \"__main__\":\n# maoyan_year([2018,2017,205])\n","sub_path":"number_photo/Spider/Spider_for_piaofang_year.py","file_name":"Spider_for_piaofang_year.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"482698312","text":"#Inc14prog.py\nimport turtle\n\n#setup the turtle object in global space\nthe_turtle = turtle.getturtle()\n\n'''\nforward: used to bind keyboard up arrow key to control turtle\n'''\ndef forward():\n the_turtle.forward(1)\n print(\"forward key pressed \")\n\n'''\nbackward: used to bind keyboard down arrow key to control turtle\n''' \ndef backward():\n the_turtle.backward(1)\n print(\"backward key pressed \")\n\n'''\nleft: used to bind keyboard left arrow key to control turtle\n'''\ndef left ():\n print(\"left key pressed \")\n\n'''\nright: used to bind keyboard right arrow key to control turtle\n'''\ndef right():\n print(\"right key pressed \")\n\n\n'''\nmain: main function of program\n'''\ndef main():\n window_title = \"My first Turtle Graphics Program\"\n window_width = 400\n window_height = 400\n startx = 0\n starty = 0\n \n #set window size\n turtle.setup(window_width,window_height)\n \n #get reference to turtle window \n window = turtle.Screen()\n \n #set window title bar\n window.title(window_title)\n \n #change the default turtle shape\n the_turtle.shape(\"turtle\")\n \n #set the turtle's posistion\n the_turtle.setpos(0,0)\n\n #bind up keyboard arrow to forward function\n window.onkey( forward , \"Up\")\n\n #bind up keyboard arrow to backward function\n window.onkey( backward , \" Down \")\n\n #bind up keyboard arrow to right function\n window.onkey(right , \" Right \")\n\n #bind up keyboard arrow to left function\n window.onkey(left , \" Left \")\n\n #setup event handler\n window.listen()\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"CSC-119/docs/In-Class Programs 13 - 14/Inc14prog.py","file_name":"Inc14prog.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"43547440","text":"from django.conf.urls import url, include\nfrom rest_framework import routers\nfrom rest_framework.authtoken import views as authviews\nfrom . import views\n\nrouter = routers.DefaultRouter()\n\nurlpatterns = [\n url(r'^register/$', view=views.UserV.as_view()),\n url(r'^request/$', view=views.RequestFriendsViewSet.as_view()),\n url(r'^edit_profile/$', view=views.EditProfileViewSet.as_view()),\n url(r'^post/$', view=views.PostViewSet.as_view()),\n url(r'^like/$', view=views.LikeViewSet.as_view()),\n url(r'^comment/$', view=views.CommentViewSet.as_view()),\n url(r'^login/$', view=views.CustomAuthToken.as_view()),\n url(r'^', include(router.urls)),\n]\n\n\n\n\n\n","sub_path":"BackZeftEnd/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"33000839","text":"\nimport random\n\nimport pandas as pd\nimport numpy as np\n\nimport os\n\nfrom agentViewer import AgentLearnModel, AgentLearnViewer\nfrom logger import log\n\n### FORMATTING\nfloat_formatter = lambda x: \"%.2f\" % x\npd.options.display.float_format = '{:,.2f}'.format\nnp.set_printoptions(formatter={'float_kind':float_formatter})\n\n# STATE TABLE\nFALL_REWARD = -100\nSTEP_REWARD = -1\nGOAL_REWARD = 100\n\nSTATE_ROWS_AMOUNT = 9\nSTATE_COLS_AMOUNT = 16\n\ndef create_reward_table():\n state_table = np.full([STATE_ROWS_AMOUNT,STATE_COLS_AMOUNT], STEP_REWARD)\n state_table[:4,6],state_table[8,2:14], state_table[2:8,13] = FALL_REWARD, FALL_REWARD, FALL_REWARD\n state_table[8,15] = GOAL_REWARD\n return state_table\n\n\ndef get_reward(state_position, state_table):\n row,col = state_position\n return state_table[row,col]\n\ndef is_epoch_end(reward):\n return True if reward == FALL_REWARD or reward == GOAL_REWARD else False\n\n# ACTIONS\nACTION_STEP = 1\n\nACTION_TOP = 'top'\nACTION_LEFT = 'left'\nACTION_RIGHT = 'right'\nACTION_BOTTOM = 'bottom'\nACTION_SKIP = 'skip'\n\nclass AgentAction: \n def __init__(self, name, execute):\n self.name = name\n self.execute = execute\n\nACTIONS=[\n AgentAction(ACTION_TOP, lambda row, col, step : (row - step, col)),\n AgentAction(ACTION_LEFT, lambda row, col, step : (row, col - step)),\n AgentAction(ACTION_RIGHT, lambda row, col, step: (row, col + step)),\n AgentAction(ACTION_BOTTOM, lambda row, col, step: (row + step, col)),\n AgentAction(ACTION_SKIP, lambda row, col, step: (row, col))\n]\n\nACTIONS_AMOUNT = len(ACTIONS)\n\ndef get_action_index(action):\n return ACTIONS.index(action)\n\ndef is_action_acceptable(state_position, state_table):\n rows_amount, cols_amount = state_table.shape\n row,col = state_position\n return True if 0 <= col < cols_amount and 0 <= row < rows_amount else False\n\ndef get_acceptable_actions(state_position, state_table, step):\n actions = []\n row,col = state_position\n for a in ACTIONS:\n if is_action_acceptable(a.execute(row, col, step), state_table):\n actions.append(a)\n return actions\n\n# Q-TABLE\n\ndef create_Q_table():\n q_table = np.empty((STATE_ROWS_AMOUNT, STATE_COLS_AMOUNT), dtype=np.object)\n for r in range(STATE_ROWS_AMOUNT):\n for c in range(STATE_COLS_AMOUNT):\n q_table[r,c] = np.zeros(ACTIONS_AMOUNT)\n\n return q_table\n\ndef get_Q(state_position, q_table, action=None):\n row, col = state_position\n\n if action == None:\n return q_table[row,col]\n\n return q_table[row,col][get_action_index(action)]\n\ndef get_Q_max(state_position, q_table, acceptable_actions):\n row, col = state_position\n\n acceptable_actions_index = [get_action_index(action) for action in acceptable_actions]\n \n return np.max(q_table[row,col][acceptable_actions_index])\n\ndef update_Q_table(state_position, q_table, action, value):\n row, col = state_position\n\n q_table[row,col][get_action_index(action)] = value\n return q_table\n# \n\ndef choose_action(state_position, q_table, acceptable_actions, explorationRate=None):\n row, col = state_position\n\n if explorationRate != None and random.uniform(0, 1) < explorationRate:\n return random.choice(acceptable_actions) \n else:\n acceptable_actions_index = [get_action_index(action) for action in acceptable_actions]\n return acceptable_actions[np.argmax(q_table[row,col][acceptable_actions_index])]\n\n\ndef act(state_position, state_table, action, step):\n row, col = state_position\n\n next_state_position = action.execute(row, col, step)\n reward = get_reward(next_state_position, state_table)\n\n return (next_state_position, reward)\n\ndef reduceExplorationRate(explorationRate, minExplorationRate, reduce=0.1):\n nextExplorationRate = explorationRate - reduce\n return minExplorationRate if minExplorationRate > nextExplorationRate else nextExplorationRate\n\n# LEARNING\n\ndef learn(initial_position, reward_table, epochs, \n learning_rate, discount_rate, \n exploration_rate):\n\n q_table = create_Q_table()\n q_table_storage = QTableStorage()\n\n for epoch in range(0, epochs): \n position, reward = initial_position , 0\n\n total_reward = 0\n steps_amount = 0\n\n while is_epoch_end(reward) == False:\n\n acceptable_actions = get_acceptable_actions(position, reward_table, ACTION_STEP)\n action = choose_action(position, q_table, acceptable_actions, exploration_rate)\n\n next_position, reward = act(position, reward_table, action, ACTION_STEP)\n\n Q = get_Q(position, q_table, action)\n Q = Q + learning_rate * (reward + discount_rate * get_Q_max(next_position, q_table,get_acceptable_actions(next_position, reward_table, ACTION_STEP) ) - Q)\n q_table = update_Q_table(position, q_table, action, Q)\n\n position = next_position\n\n total_reward += reward\n steps_amount+=1\n\n if(epoch % 100 == 0):\n exploration_rate = reduceExplorationRate(exploration_rate, minExplorationRate=0.01)\n \n q_table_storage.save(q_table, total_reward)\n\n log('Epoch: %s, Steps: %s, Total reward: %s,' %(epoch + 1, steps_amount, total_reward))\n \n learnViewer = AgentLearnViewer()\n learnViewer.add(AgentLearnModel(epoch, total_reward)) \n learnViewer.view()\n return q_table_storage.get()\n\ndef emulate(initial_position, reward_table, q_table, max_steps_amount):\n position = initial_position\n\n path = [position]\n\n reward = 0\n\n total_reward = 0\n steps_amount = 0\n\n while steps_amount < max_steps_amount:\n acceptable_actions = get_acceptable_actions(position, reward_table, ACTION_STEP)\n action = choose_action(position, q_table, acceptable_actions)\n\n position, reward = act(position, reward_table, action, ACTION_STEP)\n\n path.append(position)\n\n total_reward += reward\n steps_amount += 1\n\n log('Position: %s, Reward: %s' %(position, reward))\n\n if reward == GOAL_REWARD:\n break\n log('Overal steps: %s, Total reward: %s' %(steps_amount, total_reward))\n return path\n\nclass QTableStorage:\n q_table = []\n reward = 0\n\n def get(self):\n return self.q_table\n \n def save(self, q_table, reward):\n if(self.reward <= reward):\n self.q_table = q_table\n\n\ndef generate_Q_table_view(q_table):\n q_table_view = []\n row_amount, col_amount = q_table.shape\n for row in range(row_amount):\n for col in range(col_amount):\n q_table_view.append(np.append([row, col], q_table[row,col]))\n return q_table_view\n\ndef export_Q_table_weights(q_table, path):\n q_table = generate_Q_table_view(q_table)\n ACTIONS_NAME = [a.name for a in ACTIONS]\n df = pd.DataFrame(q_table, columns=np.append(['row', 'col'], ACTIONS_NAME))\n df.to_csv(path, ',')\n\ndef to_Q_table(q_table_view):\n q_table = np.empty((STATE_ROWS_AMOUNT, STATE_COLS_AMOUNT), dtype=np.object)\n for r in range(STATE_ROWS_AMOUNT):\n for c in range(STATE_COLS_AMOUNT):\n q_table[r,c] = q_table_view[r * STATE_COLS_AMOUNT + c][3:]\n print(q_table[0])\n\n return q_table\n\ndef load_Q_table_weights(path):\n df = pd.read_csv(path)\n return to_Q_table(df.values)\n\ndef plot_agent_path(path):\n y = [pos[0] for pos in path]\n x = [pos[1] for pos in path]\n import matplotlib.pyplot as plt\n plt.scatter(x,y)\n plt.axis([-1 , STATE_COLS_AMOUNT,STATE_ROWS_AMOUNT, 0])\n plt.show()\n\n\n### Main ###\nEPOCHS = 1000\n\nLEARNING_RATE = 0.1 # alpha\nDISCOUNT_RATE = 0.8 # gamma \nEXPLORATION_RATE = 0.8 # epsilon\n\nINITIAL_POSITION = (8,0)\nPATH = 'q_table.csv'\n\nreward_table = create_reward_table()\n\nif(os.path.isfile(PATH)):\n q_table = load_Q_table_weights(PATH)\n path = emulate(INITIAL_POSITION, reward_table, q_table, 100)\n plot_agent_path(path)\nelse:\n q_table = learn(INITIAL_POSITION, reward_table, EPOCHS, \n LEARNING_RATE, DISCOUNT_RATE, EXPLORATION_RATE)\n export_Q_table_weights(q_table, PATH)\n\n","sub_path":"Semester_1/MC/Lab_1/singleAgent.py","file_name":"singleAgent.py","file_ext":"py","file_size_in_byte":8031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"535646951","text":"from django.contrib import admin\nfrom app_sacele.models import Periods,Levels,Groups,GroupStudent,Parciales\nfrom django.contrib.auth.models import User,Group\nfrom app_teachers.models import Grades\n\nclass GroupsAdmin ( admin.ModelAdmin ):\n\n\tdef get_form(self, request, obj=None, **kwargs):\n\n\t\tform = super(GroupsAdmin,self).get_form(request, obj,**kwargs)\n\n\t\tform.base_fields['Teacher'].queryset \t=\tUser.objects.filter( groups = Group.objects.get( name = 'Teachers' ).pk )\n\n\t\treturn form\n\nclass GroupStudentAdmin ( admin.ModelAdmin ):\n\n\t#exclude = ( 'Student', )\n\tfilter_horizontal = ('Student',)\n\n\n\tdef get_form(self, request, obj=None, **kwargs):\n\n\t\tform = super(GroupStudentAdmin,self).get_form(request, obj,**kwargs)\n\t\t\n\t\ttry:\n\t\t\tform.base_fields['Groups'].queryset = Groups.objects.exclude( group_id = obj.Groups )\n\t\texcept:\n\t\t\tform.base_fields['Groups'].queryset = Groups.objects.exclude( group_id__in = GroupStudent.objects.all() )\n\n\t\ttry:\n\t\t\tactive_list = User.objects.filter(groups = Group.objects.get(name = 'Students' ).pk).exclude( pk__in = GroupStudent.objects.all().exclude( Student = GroupStudent.objects.get( Groups = obj.Groups ).Student.values('pk',) ).values('Student') )\n\t\texcept:\n\t\t\tactive_list = User.objects.filter(groups = Group.objects.get( name = 'Students' ).pk).exclude( pk__in = GroupStudent.objects.all().values('Student'))\n\t\t\n\t\tform.base_fields['Student'].queryset \t=\tactive_list\n\n\t\treturn form\n\n\tdef save_model(self, request, obj, form, change):\n\n\t\tif change:\n\n\t\t\tobj.save()\n\n\t\telse:\n\t\t\t\n\t\t\tobj.save()\n\t\t\tfor student in form.cleaned_data['Student']:\n\t\t\t\titem = Grades()\n\t\t\t\titem.Student = User.objects.get( username = student )\n\t\t\t\titem.group \t= Groups.objects.get( Name_Group = form.cleaned_data['Groups'] )\n\t\t\t\titem.save()\n\n\n\nadmin.site.register( Periods )\nadmin.site.register( Levels )\nadmin.site.register( Groups,GroupsAdmin )\nadmin.site.register( GroupStudent, GroupStudentAdmin )\nadmin.site.register( Parciales )\n","sub_path":"app_sacele/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"362074838","text":"# Copyright 2019 Google LLC. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Tests for taxi_utils_bqml.py.\"\"\"\n\nimport os\nimport types\n\nimport apache_beam as beam\nimport tensorflow as tf\nfrom tensorflow import estimator as tf_estimator\nimport tensorflow_model_analysis as tfma\nimport tensorflow_transform as tft\nfrom tensorflow_transform import beam as tft_beam\nfrom tensorflow_transform.tf_metadata import dataset_metadata\nfrom tensorflow_transform.tf_metadata import schema_utils\nfrom tfx.components.trainer import executor as trainer_executor\nfrom tfx.components.trainer.fn_args_utils import DataAccessor\nfrom tfx.components.util import tfxio_utils\nfrom tfx.dsl.io import fileio\nfrom tfx.examples.bigquery_ml import taxi_utils_bqml\nfrom tfx.types import standard_artifacts\nfrom tfx.utils import io_utils\nfrom tfx.utils import path_utils\n\nfrom tfx_bsl.tfxio import tf_example_record\nfrom tensorflow_metadata.proto.v0 import schema_pb2\n\n\nclass TaxiUtilsTest(tf.test.TestCase):\n\n def setUp(self):\n super().setUp()\n self._testdata_path = os.path.join(\n os.path.dirname(os.path.dirname(os.path.dirname(__file__))),\n 'components/testdata')\n\n def testUtils(self):\n key = 'fare'\n xfm_key = taxi_utils_bqml._transformed_name(key)\n self.assertEqual(xfm_key, 'fare_xf')\n\n def testPreprocessingFn(self):\n schema_file = os.path.join(self._testdata_path, 'schema_gen/schema.pbtxt')\n schema = io_utils.parse_pbtxt_file(schema_file, schema_pb2.Schema())\n feature_spec = taxi_utils_bqml._get_raw_feature_spec(schema)\n working_dir = self.get_temp_dir()\n transform_graph_path = os.path.join(working_dir, 'transform_graph')\n transformed_examples_path = os.path.join(\n working_dir, 'transformed_examples')\n\n # Run very simplified version of executor logic.\n # TODO(kestert): Replace with tft_unit.assertAnalyzeAndTransformResults.\n # Generate legacy `DatasetMetadata` object. Future version of Transform\n # will accept the `Schema` proto directly.\n legacy_metadata = dataset_metadata.DatasetMetadata(\n schema_utils.schema_from_feature_spec(feature_spec))\n tfxio = tf_example_record.TFExampleRecord(\n file_pattern=os.path.join(self._testdata_path,\n 'csv_example_gen/Split-train/*'),\n telemetry_descriptors=['Tests'],\n schema=legacy_metadata.schema)\n with beam.Pipeline() as p:\n with tft_beam.Context(temp_dir=os.path.join(working_dir, 'tmp')):\n examples = p | 'ReadTrainData' >> tfxio.BeamSource()\n (transformed_examples, transformed_metadata), transform_fn = (\n (examples, tfxio.TensorAdapterConfig())\n | 'AnalyzeAndTransform' >> tft_beam.AnalyzeAndTransformDataset(\n taxi_utils_bqml.preprocessing_fn))\n\n # WriteTransformFn writes transform_fn and metadata to subdirectories\n # tensorflow_transform.SAVED_MODEL_DIR and\n # tensorflow_transform.TRANSFORMED_METADATA_DIR respectively.\n # pylint: disable=expression-not-assigned\n (transform_fn\n | 'WriteTransformFn' >> tft_beam.WriteTransformFn(\n transform_graph_path))\n\n encoder = tft.coders.ExampleProtoCoder(transformed_metadata.schema)\n (transformed_examples\n | 'EncodeTrainData' >> beam.Map(encoder.encode)\n | 'WriteTrainData' >> beam.io.WriteToTFRecord(\n os.path.join(transformed_examples_path,\n 'Split-train/transformed_examples.gz'),\n coder=beam.coders.BytesCoder()))\n # pylint: enable=expression-not-assigned\n\n # Verify the output matches golden output.\n # NOTE: we don't verify that transformed examples match golden output.\n expected_transformed_schema = io_utils.parse_pbtxt_file(\n os.path.join(\n self._testdata_path,\n 'transform/transform_graph/transformed_metadata/schema.pbtxt'),\n schema_pb2.Schema())\n transformed_schema = io_utils.parse_pbtxt_file(\n os.path.join(transform_graph_path,\n 'transformed_metadata/schema.pbtxt'),\n schema_pb2.Schema())\n # Clear annotations so we only have to test main schema.\n for feature in transformed_schema.feature:\n feature.ClearField('annotation')\n transformed_schema.ClearField('annotation')\n self.assertEqual(transformed_schema, expected_transformed_schema)\n\n def testTrainerFn(self):\n temp_dir = os.path.join(\n os.environ.get('TEST_UNDECLARED_OUTPUTS_DIR', self.get_temp_dir()),\n self._testMethodName)\n\n schema_file = os.path.join(self._testdata_path, 'schema_gen/schema.pbtxt')\n trainer_fn_args = trainer_executor.TrainerFnArgs(\n train_files=os.path.join(\n self._testdata_path,\n 'transform/transformed_examples/Split-train/*.gz'),\n transform_output=os.path.join(self._testdata_path,\n 'transform/transform_graph/'),\n serving_model_dir=os.path.join(temp_dir, 'serving_model_dir'),\n eval_files=os.path.join(\n self._testdata_path,\n 'transform/transformed_examples/Split-eval/*.gz'),\n schema_file=schema_file,\n train_steps=1,\n eval_steps=1,\n base_model=os.path.join(self._testdata_path,\n 'trainer/previous/Format-Serving'),\n data_accessor=DataAccessor(\n tf_dataset_factory=tfxio_utils.get_tf_dataset_factory_from_artifact(\n [standard_artifacts.Examples()], []),\n record_batch_factory=None,\n data_view_decode_fn=None))\n schema = io_utils.parse_pbtxt_file(schema_file, schema_pb2.Schema())\n training_spec = taxi_utils_bqml.trainer_fn(trainer_fn_args, schema)\n\n estimator = training_spec['estimator']\n train_spec = training_spec['train_spec']\n eval_spec = training_spec['eval_spec']\n eval_input_receiver_fn = training_spec['eval_input_receiver_fn']\n\n self.assertIsInstance(estimator, tf_estimator.Estimator)\n self.assertIsInstance(train_spec, tf_estimator.TrainSpec)\n self.assertIsInstance(eval_spec, tf_estimator.EvalSpec)\n self.assertIsInstance(eval_input_receiver_fn, types.FunctionType)\n\n # Train for one step, then eval for one step.\n eval_result, exports = tf_estimator.train_and_evaluate(\n estimator, train_spec, eval_spec)\n print(eval_result, exports)\n self.assertGreater(eval_result['loss'], 0.0)\n self.assertEqual(len(exports), 1)\n self.assertGreaterEqual(len(fileio.listdir(exports[0])), 1)\n\n # Export the eval saved model.\n eval_savedmodel_path = tfma.export.export_eval_savedmodel(\n estimator=estimator,\n export_dir_base=path_utils.eval_model_dir(temp_dir),\n eval_input_receiver_fn=eval_input_receiver_fn)\n self.assertGreaterEqual(len(fileio.listdir(eval_savedmodel_path)), 1)\n\n # Test exported serving graph.\n with tf.compat.v1.Session() as sess:\n metagraph_def = tf.compat.v1.saved_model.loader.load(\n sess, [tf.saved_model.SERVING], exports[0])\n self.assertIsInstance(metagraph_def, tf.compat.v1.MetaGraphDef)\n\n\nif __name__ == '__main__':\n tf.test.main()\n","sub_path":"tfx/examples/bigquery_ml/taxi_utils_bqml_test.py","file_name":"taxi_utils_bqml_test.py","file_ext":"py","file_size_in_byte":7662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"}