diff --git "a/6332.jsonl" "b/6332.jsonl" new file mode 100644--- /dev/null +++ "b/6332.jsonl" @@ -0,0 +1,596 @@ +{"seq_id":"119010991","text":"# Copyright 2014 - Savoir-Faire Linux inc.\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 surveil.api.datamodel.config import realm\nfrom surveil.api.handlers import handler\n\n\nclass RealmHandler(handler.Handler):\n \"\"\"Fulfills a request on the realm resource.\"\"\"\n\n def get(self, realm_name):\n \"\"\"Return a realm.\"\"\"\n\n r = self.request.mongo_connection.shinken.realms.find_one(\n {\"realm_name\": realm_name}, {'_id': 0}\n )\n return realm.Realm(**r)\n\n def update(self, realm_name, realm):\n \"\"\"Modify an existing realm.\"\"\"\n realm_dict = realm.as_dict()\n if \"realm_name\" not in realm_dict.keys():\n realm_dict['realm_name'] = realm_name\n\n self.request.mongo_connection.shinken.realms.update(\n {\"realm_name\": realm_name},\n realm_dict\n )\n\n def delete(self, realm_name):\n \"\"\"Delete existing realm.\"\"\"\n self.request.mongo_connection.shinken.realms.remove(\n {\"realm_name\": realm_name}\n )\n\n def create(self, realm):\n \"\"\"Create a new realm.\"\"\"\n self.request.mongo_connection.shinken.realms.insert(\n realm.as_dict()\n )\n\n def get_all(self):\n \"\"\"Return all realms.\"\"\"\n realms = [c for c\n in self.request.mongo_connection.\n shinken.realms.find(\n {\"register\": {\"$ne\": \"0\"}}, # Don't return templates\n {'_id': 0}\n )]\n realms = [realm.Realm(**r) for r in realms]\n return realms\n","sub_path":"surveil/api/handlers/config/realm_handler.py","file_name":"realm_handler.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"493737419","text":"import unittest\n\nfrom reuse_func import GetData\n\n\nclass Semester(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n self.cal = GetData()\n self.semester = self.cal.get_s3_files(\"semester\")\n\n def test_semester_district_file(self):\n flag = False\n for x in self.semester:\n if x[len(x) - 1].__contains__(\"district\"):\n print(\"semester district file generated successfully\")\n flag = True\n if flag == False:\n raise self.failureException(\"semester district level json file is not generated\")\n\n def test_semester_block_file(self):\n flag = False\n for x in self.semester:\n if x[len(x) - 1].__contains__(\"block\"):\n print(\"semester block file generated successfully\")\n flag = True\n if flag == False:\n raise self.failureException(\"semester block level json file is not generated\")\n\n def test_semester_cluster_file(self):\n flag = False\n for x in self.semester:\n if x[len(x) - 1].__contains__(\"cluster\"):\n print(\"semester cluster file generated successfully\")\n flag = True\n if flag == False:\n raise self.failureException(\"semester cluster level json file is not generated\")\n\n def test_semester_school_file(self):\n flag = False\n for x in self.semester:\n if x[len(x) - 1].__contains__(\"school\"):\n print(\"semester school file generated successfully\")\n flag = True\n if flag == False:\n raise self.failureException(\"semester school level json file is not generated\")\n\n @classmethod\n def tearDownClass(self):\n print(\"\")\n","sub_path":"tests/src/s3/semester.py","file_name":"semester.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"613429463","text":"import requests\nimport datetime\nimport random\nimport sys\nimport os\nimport smtplib\nimport webbrowser\nimport urllib\nimport pyttsx3\nimport speech_recognition as sr\nimport pyaudio\nfrom PyDictionary import PyDictionary\nfrom pygame import mixer\n\nimport ety\nfrom nltk.corpus import wordnet\n\nengine = pyttsx3.init()\n\nvoices = engine.getProperty('voices')\nengine.setProperty('voice', voices[len(voices) - 1].id)\n\nrate = engine.getProperty('rate')\nengine.setProperty('rate', rate-62) # Slows down the speaking speed of the engine voice.\n\ndef speak(audio):\n print(\" \"+audio)\n engine.say(audio)\n engine.runAndWait()\n\ndef command():\n cmd = sr.Recognizer()\n with sr.Microphone() as source:\n cmd.adjust_for_ambient_noise(source) # Adjusts the level to recieve voice even in case of noise in surroundings\n print('Listening..')\n audio = cmd.listen(source)\n try:\n query = cmd.recognize_google(audio,language='en-in')\n print('User: '+query+'\\n')\n except sr.UnknownValueError:\n speak('Sorry ! I did not get that. Could you please type it out ?')\n query = str(input('Command: '))\n return query\n\n\ndef greeting():\n currentH = int(datetime.datetime.now().hour)\n if currentH >= 0 and currentH < 12 :\n speak('Good Morning')\n if currentH >= 12 and currentH < 17 :\n speak('Good Afternoon')\n if currentH >= 17 and currentH != 0 :\n speak('Good Evening')\n \n \ndef find(name, path):\n for root, files in os.walk(path):\n if name in files:\n return os.path.join(root, name)\n\n\ndef playOnYoutube(query_string):\n query_string = urllib.parse.urlencode({\"search_query\" : query})\n search_string = str(\"http://www.youtube.com/results?\" + query_string)\n speak(\"Here's what you asked for. Enjoy!\")\n webbrowser.open_new_tab(search_string)\n\n\ndef tellAJoke():\n res = requests.get(\n 'https://icanhazdadjoke.com/',\n headers={\"Accept\":\"application/json\"}\n )\n if res.status_code == 200:\n speak(\"Okay. Here's one\")\n speak(str(res.json()['joke']))\n else:\n speak('Oops!I ran out of jokes')\n\n\ngreeting()\nspeak('jarvis here.')\nspeak('What would you like me to do for you ?')\n\n\nif __name__ == '__main__':\n while True:\n\n query = command()\n query = query.lower()\n\n\n if 'play music' in query or 'play a song' in query :\n speak(\"Here's your music. Enjoy !\")\n os.system('spotify')\n\n if 'find file' in query:\n speak('What is the name of the file that I should find ?')\n query = command()\n filename = query\n print(filename)\n speak('What would be the extension of the file ?')\n query = command()\n query = query.lower()\n extension = query\n print(extension)\n fullname = str(filename) + '.' + str(extension)\n print(fullname)\n path = r'D:\\\\'\n location = find(fullname,path)\n speak('File is found at the below location')\n print(location)\n\n if 'search' in query:\n speak('What should I search for ?')\n query = command()\n lib = query\n url = \"https://www.google.co.in/search?q=\" +(str(lib))+ \"&oq=\"+(str(lib))+\"&gs_l=serp.12..0i71l8.0.0.0.6391.0.0.0.0.0.0.0.0..0.0....0...1c..64.serp..0.0.0.UiQhpfaBsuU\"\n webbrowser.open_new(url)\n\n if 'play on youtube' in query:\n speak('What should I look up for ?')\n query = command()\n playOnYoutube(query) \n \n if 'joke' in query:\n tellAJoke()\n \n if 'open word' in query:\n os.system('libreoffice word')\n\n if 'send an email' in query:\n speak('whom would you like to send')\n query = command()\n sender = query\n speak('what would you like to send')\n query = command()\n\n # creates SMTP session \n s = smtplib.SMTP('smtp.gmail.com', 587) \n\n # start TLS for security \n s.starttls() \n\n # Authentication \n s.login(\"jarvisassistant.chetz@gmail.com\", \"jarvis@123\") \n\n # message to be sent \n message = query\n\n # sending the mail \n s.sendmail(\"jarvisassistant.chetz@gmail.com\", sender, message) \n\n # terminating the session \n s.quit() \n\n\n\n if 'that would be all' in query or 'that is it' in query or 'go to sleep jarvis' in query:\n speak('Alright. Have a nice day')\n sys.exit()\n if 'tell me about yourself' in query or 'who are you' in query:\n speak('i am jarvis, i was created by chethan and joljas. i am built to make your work simple and easier, i can do many task like sending an email or make u laugh and many more why dont you give a try on me?')\n if 'calculate for me' in query or 'open calculator' in query:\n os.system('gnome-calculator')\n ","sub_path":"jarvis-assistant/jarvis_voiceassistant.py","file_name":"jarvis_voiceassistant.py","file_ext":"py","file_size_in_byte":5073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"183647360","text":"\"\"\"\nA neural network classifier for cat-dog classification\nproject. Dataset is at \nhttps://www.kaggle.com/c/dogs-vs-cats/data\n\nCreated by Huy Dang as self-employed project\nThis file contains the hyperparameters for the model\n\"\"\"\n\n#parameter for processing the dataset\nDATA_PATH = '/home/huy/Desktop/Project/Cat-Dog'\nCPT_PATH = 'checkpoints'\n\nTRAIN_SIZE_CAT = 12000\nTRAIN_SIZE_DOG = 12000\nTEST_SIZE = 4000\nVALID_SIZE = 2000\nIMG_SIZE = 96\nNUM_CHANNEL = 3\n\n#parameter for training CNN\nLEARNING_RATE = 0.005\nBATCH_SIZE = 256\nSKIP_STEP = 10\nDROPOUT = 0.8\nN_EPOCHS = 7\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"344944652","text":"'''\n# -*- coding:utf-8 -*-\n@author: TulLing\n'''\nimport requests\nfrom json import JSONDecoder\n\ngesture_englist = [ 'ok', 'hand_open',\n 'thumb_up', 'thumb_down', 'fist']\ngesture_chinese = [\n \"好的呢,OK\",\n \"手张开\",\n \"点赞\",\n \"差评\",\n \"握拳\",\n ]\n\n\n# 将字典排序\ndef sort_dict(adict):\n return sorted(adict.items(), key=lambda item: item[1])\n\n\nclass Gesture(object):\n def __init__(self):\n self.http_url = 'https://api-cn.faceplusplus.com/humanbodypp/v1/gesture'\n self.key = 'SASuuvcBxQmaweSsUH06xeV3ouCdjrLU'\n self.secret = 'JP6XgFiqH7zMZSh0nUh0LngyYg8Fe0UQ'\n self.data = {\"api_key\": self.key, \"api_secret\": self.secret}\n\n # 获取手势信息\n def get_info(self, files):\n response = requests.post(self.http_url, data=self.data, files=files)\n req_con = response.content.decode('utf-8')\n req_dict = JSONDecoder().decode(req_con)\n #print(req_dict)\n if ('error_message' not in req_dict.keys()) and (len(req_dict['hands'])):\n # 获取\n hands_dict = req_dict['hands']\n # print(type(hands_dict))\n # 获取到手的矩形的字典\n gesture_rectangle_dict = hands_dict[0]['hand_rectangle']\n # 获取到手势的字典\n gesture_dict = hands_dict[0]['gesture']\n\n return gesture_dict, gesture_rectangle_dict\n else:\n return [], [];\n\n # 获取到手势文本信息\n def get_text(self, index):\n return gesture_chinese[index]\n\n # 获取到手势对应的概率\n def get_pro(self, gesture_dict, index):\n # print(gesture_dict)\n if (gesture_dict is None or gesture_dict == []):\n return 0\n return gesture_dict[gesture_englist[index]]\n\n # 获取到手势的位置\n def get_rectangle(self, gesture_rectangle_dict):\n if (gesture_rectangle_dict is None or gesture_rectangle_dict == []):\n return (0, 0, 0, 0)\n x = gesture_rectangle_dict['top']\n y = gesture_rectangle_dict['left']\n width = gesture_rectangle_dict['width']\n height = gesture_rectangle_dict['height']\n return (x, y, width, height)\n","sub_path":"LearnGesture.py","file_name":"LearnGesture.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"168581381","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue May 4 21:05:17 2021\r\n\r\n@author: 1ho79\r\n\"\"\"\r\n\r\nimport pyupbit\r\nimport sys\r\nimport pandas as pd\r\nimport time\r\nimport logging\r\nimport datetime as dt\r\n\r\n\r\ntm = time.localtime()\r\nc_time = time.strftime('%Y-%m/%d %I:%M', tm)\r\nc_time_log = time.strftime('%Y_%m_%d_%I_%M', tm)\r\n\r\n# 로그 생성\r\nlogger = logging.getLogger()\r\n\r\n# 로그의 출력 기준 설정\r\nlogger.setLevel(logging.INFO)\r\n\r\n# log 출력 형식\r\nformatter = logging.Formatter('%(asctime)s - %(message)s')\r\n\r\n# log 출력\r\nstream_handler = logging.StreamHandler()\r\nstream_handler.setFormatter(formatter)\r\nlogger.addHandler(stream_handler)\r\n\r\n# log를 파일에 출력\r\n#file_handler = logging.FileHandler(f\"aggresive_{c_time_log}_log.txt\")\r\ntmp = sys.argv[0]\r\ntmp2 = tmp.split('.')\r\ntmp6 = ['./log/', tmp2[0], '.txt']\r\npath = \"\".join(tmp6)\r\nfile_handler = logging.FileHandler(filename=f\"{path}\")\r\nfile_handler.setFormatter(formatter)\r\nlogger.addHandler(file_handler)\r\n\r\n\r\n#logger.info(\"aaa : %0.2f\", bbb)\r\n\r\naccess = \"ZRRx2FMNNmn8KjefANNB3lQNxHDIzCvvxVpxjwKC\" # 본인 값으로 변경\r\nsecret = \"9FeUPbYFdfrFHRaE0QJ9nMQ3CGy3u5plVxhdVO6x\" # 본인 값으로 변경\r\nserver_url = \"https://upbit.com\"\r\nupbit = pyupbit.Upbit(access, secret)\r\n\r\n\r\n\r\ninit_balance = upbit.get_balance(ticker=\"KRW\")\r\n\r\nlogger.info(\"START!! init balance : %d\", init_balance)\r\n\r\nticker_type = \"KRW\"\r\n\r\ntickers = ['KRW-ETH', 'KRW-NEO', 'KRW-MTL', 'KRW-LTC', 'KRW-XRP', 'KRW-ETC', 'KRW-OMG', 'KRW-SNT', 'KRW-WAVES', 'KRW-XEM', 'KRW-QTUM', 'KRW-LSK', 'KRW-STEEM', 'KRW-XLM', 'KRW-ARDR', 'KRW-KMD', 'KRW-ARK', 'KRW-STORJ', 'KRW-GRS', 'KRW-REP', 'KRW-EMC2', 'KRW-ADA', 'KRW-SBD', 'KRW-POWR', 'KRW-BTG', 'KRW-ICX', 'KRW-EOS', 'KRW-TRX', 'KRW-SC', 'KRW-IGNIS', 'KRW-ONT', 'KRW-ZIL', 'KRW-POLY', 'KRW-ZRX', 'KRW-LOOM', 'KRW-BCH', 'KRW-ADX', 'KRW-BAT', 'KRW-IOST', 'KRW-DMT', 'KRW-RFR', 'KRW-CVC', 'KRW-IQ', 'KRW-IOTA', 'KRW-MFT', 'KRW-ONG', 'KRW-GAS', 'KRW-UPP', 'KRW-ELF', 'KRW-KNC', 'KRW-BSV', 'KRW-THETA', 'KRW-EDR', 'KRW-QKC', 'KRW-BTT', 'KRW-MOC', 'KRW-ENJ', 'KRW-TFUEL', 'KRW-MANA', 'KRW-ANKR', 'KRW-AERGO', 'KRW-ATOM', 'KRW-TT']\r\n#tickers = ['KRW-CRE', 'KRW-SOLVE', 'KRW-MBL', 'KRW-TSHP', 'KRW-WAXP', 'KRW-HBAR', 'KRW-MED', 'KRW-MLK', 'KRW-STPT', 'KRW-ORBS', 'KRW-VET', 'KRW-CHZ', 'KRW-PXL', 'KRW-STMX', 'KRW-DKA', 'KRW-HIVE', 'KRW-KAVA', 'KRW-AHT', 'KRW-LINK', 'KRW-XTZ', 'KRW-BORA', 'KRW-JST', 'KRW-CRO', 'KRW-TON', 'KRW-SXP', 'KRW-LAMB', 'KRW-HUNT', 'KRW-MARO', 'KRW-PLA', 'KRW-DOT', 'KRW-SRM', 'KRW-MVL', 'KRW-PCI', 'KRW-STRAX', 'KRW-AQT', 'KRW-BCHA', 'KRW-GLM', 'KRW-QTCON', 'KRW-SSX', 'KRW-META', 'KRW-OBSR', 'KRW-FCT2', 'KRW-LBC', 'KRW-CBK', 'KRW-SAND', 'KRW-HUM', 'KRW-DOGE', 'KRW-STRK', 'KRW-PUNDIX', 'KRW-FLOW', 'KRW-DAWN', 'KRW-AXS', 'KRW-STX']\r\n\r\n\r\n\r\nold_time = dt.datetime.now()\r\ntime.sleep(10)\r\ncurrent_time = dt.datetime.now()\r\n\r\ndelta_time = current_time - old_time\r\nprint(old_time)\r\nprint(current_time)\r\nprint(delta_time)\r\n\r\ndiff = str(delta_time)\r\nprint(diff)\r\nprint(diff[2:4])\r\ndiff_int = int(diff[2:4])\r\n\r\nprint(diff_int)\r\n\r\n\r\nif (ticker_type == \"BTC\"):\r\n tickers = pyupbit.get_tickers(fiat=\"BTC\")\r\n\r\nglobal bought_list\r\nglobal bought_time_list\r\nglobal check_list\r\nglobal sell_list\r\nbought_list = {}\r\nbought_time_list = {}\r\ncheck_list = {}\r\nsell_order_list = []\r\nsell_list = {}\r\n\r\ndef check_rate_validity(ticker, avg_list):\r\n cnt = 0\r\n total_value = 0\r\n global avg_value\r\n global new_value_1\r\n global new_value_2\r\n avg_value = 0\r\n new_value_1 = 0\r\n new_value_2 = 0\r\n for value in avg_list:\r\n if (cnt < 8):\r\n total_value = total_value + value\r\n if (cnt == 7):\r\n avg_value = total_value / 8\r\n elif (cnt == 8):\r\n new_value_1 = value\r\n elif (cnt == 9):\r\n new_value_2 = value\r\n else:\r\n abc = 0\r\n cnt = cnt + 1\r\n if (new_value_1/avg_value >= 1.01) and (new_value_2/avg_value >= 1.015) and (new_value_1/avg_value < 1.1) and (new_value_2/avg_value < 1.1):\r\n #logger.info(\"avg_value : %0.6f new_value_1/avg_value : %0.6f new_value_2/avg_value : %0.6f\", avg_value, new_value_1/avg_value, new_value_2/avg_value)\r\n return \"valid\"\r\n elif (new_value_2/avg_value >= 1.02) and (new_value_2/avg_value < 1.1) and (ticker_type == \"KRW\"):\r\n #logger.info(\"avg_value : %0.6f new_value_1/avg_value : %0.6f new_value_2/avg_value : %0.6f\", avg_value, new_value_1/avg_value, new_value_2/avg_value)\r\n return \"valid\"\r\n else:\r\n return \"invalid\"\r\n\r\n\r\n\r\n\r\ndef check_rate15_validity(ticker):\r\n cnt = 0\r\n up_ok = 1\r\n down_ok = 1\r\n df = pyupbit.get_ohlcv(f\"{ticker}\", interval=\"minute15\", count=11)\r\n old_list = df['close'][0:10]\r\n new_list = df['close'][1:11]\r\n total_rate = 0\r\n list_from_old = old_list.values.tolist()\r\n list_from_new = new_list.values.tolist()\r\n for old_value, new_value in zip(list_from_old, list_from_new):\r\n rate = new_value / old_value - 1\r\n total_rate = total_rate + rate\r\n logger.info(\"rate : %0.4f total_rate : %0.4f\", rate, total_rate)\r\n if (total_rate >= 0.15):\r\n return \"valid\"\r\n else:\r\n return \"valid\"\r\n\r\n\r\n\r\n\r\n\r\ndef check_volume_validity(ticker, volume_list):\r\n cnt = 0\r\n total_volume = 0\r\n global avg_volume\r\n global new_volume_1\r\n global new_volume_2\r\n avg_volume = 0\r\n new_volume_1 = 0\r\n new_volume_2 = 0\r\n for volume in volume_list:\r\n if (cnt < 8):\r\n total_volume = total_volume + volume\r\n if (cnt == 7):\r\n avg_volume = total_volume / 8\r\n elif (cnt == 8):\r\n new_volume_1 = volume\r\n elif (cnt == 9):\r\n new_volume_2 = volume\r\n else:\r\n abc = 0\r\n cnt = cnt + 1\r\n if (new_volume_1/avg_volume >= 2) and (new_volume_2/avg_volume >= 2.2):\r\n #logger.info(\"avg_volume : %d new_volume_1/avg_volume : %0.3f new_volume_2/avg_volume : %0.3f\", avg_volume, new_volume_1/avg_volume, new_volume_2/avg_volume)\r\n return \"valid\"\r\n elif (new_volume_2/avg_volume >= 5) and (ticker_type == \"KRW\"):\r\n #logger.info(\"avg_volume : %d new_volume_1/avg_volume : %0.3f new_volume_2/avg_volume : %0.3f\", avg_volume, new_volume_1/avg_volume, new_volume_2/avg_volume)\r\n return \"valid\"\r\n else:\r\n return \"invalid\"\r\n \r\n\r\n\r\ndef check_deadcoin(ticker, open_list, close_list, high_list):\r\n cnt = 0\r\n for open_value, close_value, high_value in zip(open_list, close_list, high_list):\r\n if (open_value == close_value) and (open_value == high_value):\r\n cnt = cnt + 1\r\n if (cnt >= 4):\r\n return \"dead\"\r\n else:\r\n return \"alive\"\r\n\r\n\r\n\r\n\r\ndef check_unit(ticker):\r\n str = ticker\r\n if (str.startswith('BTC-')):\r\n unit = pyupbit.get_current_price(f\"{ticker}\")\r\n if (unit < 0.00000100):\r\n return \"small\"\r\n else:\r\n return \"big\"\r\n\r\n\r\n\r\n\r\n\r\ndef cal_unit(price):\r\n if (price < 100):\r\n unit = 0.1\r\n elif (price >= 100) and (price < 1000):\r\n unit = 1\r\n elif (price >= 1000) and (price < 10000):\r\n unit = 5\r\n elif (price >= 10000) and (price < 100000):\r\n unit = 10\r\n elif (price >= 100000) and (price < 1000000):\r\n unit = 50\r\n elif (price >= 1000000) and (price < 10000000):\r\n unit = 500\r\n new_price = price//unit * unit\r\n return new_price\r\n\r\n\r\ndef stop_loss_monitor(ticker, buy_price, loss, delay, cycle, cancle_order):\r\n global bought_list\r\n global sell_list\r\n while_abort_cnt = 0\r\n ticker_balance = upbit.get_balance(ticker=f\"{ticker}\")\r\n while True:\r\n check_price = pyupbit.get_current_price(f\"{ticker}\")\r\n loss_price = buy_price * (1 + loss)\r\n if (loss_price > check_price):\r\n logger.info(\"STOP_LOSS %s - loss_price %0.1f(%0.1f) > check_price %0.8f\",ticker, loss_price, buy_price, check_price)\r\n if (buy_enable == 1):\r\n if (cancle_order == 1):\r\n for order in sell_list[ticker]:\r\n try:\r\n logger.info(\"cancel_order\")\r\n if (buy_enable == 1):\r\n upbit.cancel_order(order)\r\n except:\r\n logger.info(\"already_cancled\")\r\n time.sleep(1)\r\n time.sleep(1)\r\n upbit.sell_market_order(f\"{ticker}\", ticker_balance * 0.995)\r\n logger.info(\"sell_market_order %s ticker_balance : %d\", ticker, ticker_balance)\r\n time.sleep(10)\r\n try:\r\n del sell_list[ticker]\r\n except:\r\n abc = 0\r\n try:\r\n del bought_list[ticker]\r\n except:\r\n abc = 0\r\n return 1\r\n break\r\n else:\r\n time.sleep(delay)\r\n while_abort_cnt = while_abort_cnt + 1\r\n if (while_abort_cnt == cycle):\r\n #logger.info(\"It's safe in %d delay and %d cycles.\", delay, cycle)\r\n return 0\r\n break\r\n\r\ndef buy(ticker):\r\n global buy_price\r\n global buy_balance\r\n buy_price = pyupbit.get_current_price(f\"{ticker}\")\r\n buy_balance = upbit.get_balance(ticker=\"KRW\")\r\n if (buy_enable == 1):\r\n upbit.buy_market_order(f\"{ticker}\", buy_balance * 0.5)\r\n #time.sleep(1800)\r\n logger.info(\"BUY - %s buy_price : %d, buy_balance : %d\", ticker, buy_price, buy_balance)\r\n\r\n\r\ndef sell(ticker):\r\n logger.info(\"SELL - %s\", ticker)\r\n sell_order_list = []\r\n sell_balance_tmp = upbit.get_balance(ticker=f\"{ticker}\")\r\n sell_balance = sell_balance_tmp * 0.333\r\n sell_price_tmp = pyupbit.get_current_price(f\"{ticker}\")\r\n sell_price = buy_price * (1 + target_margin*1/3)\r\n str = ticker\r\n if (str.startswith('KRW-')):\r\n new_price = cal_unit(sell_price)\r\n else:\r\n new_price = sell_price//1\r\n tmp = upbit.sell_limit_order(f\"{ticker}\", new_price, sell_balance)\r\n if 'uuid' in tmp:\r\n sell_order_list.append(tmp['uuid'])\r\n logger.info(\"ticker : %s sell_limit_order : %d\", ticker, new_price)\r\n time.sleep(1)\r\n sell_price = buy_price * (1 + target_margin*2/3)\r\n if (str.startswith('KRW-')):\r\n new_price = cal_unit(sell_price)\r\n else:\r\n new_price = sell_price//1\r\n tmp = upbit.sell_limit_order(f\"{ticker}\", new_price, sell_balance)\r\n if 'uuid' in tmp:\r\n sell_order_list.append(tmp['uuid'])\r\n logger.info(\"ticker : %s sell_limit_order : %d\", ticker, new_price)\r\n time.sleep(1)\r\n sell_price = buy_price * (1 + target_margin)\r\n if (str.startswith('KRW-')):\r\n new_price = cal_unit(sell_price)\r\n else:\r\n new_price = sell_price//1\r\n tmp = upbit.sell_limit_order(f\"{ticker}\", new_price, sell_balance)\r\n if 'uuid' in tmp:\r\n sell_order_list.append(tmp['uuid'])\r\n logger.info(\"ticker : %s sell_limit_order : %d\", ticker, new_price)\r\n time.sleep(1)\r\n return sell_order_list\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nstatus = \"standby\"\r\n\r\ntotal_profit = 0\r\n\r\nlow_price_renewal_past = 0\r\n\r\nsell_aggresive_enable = 0\r\nwhile_cnt = 0\r\n\r\n\r\n\r\n\r\nglobal buy_enable\r\nbuy_enable = 0\r\n\r\nsim_cycle_cnt = 0\r\ntest_cycle_cnt = 0\r\ntest_cycle = 200\r\n\r\n#PARAMETER\r\nsim_cycle = 30\r\nglobal target_margin\r\ntarget_margin = 15\r\n\r\n\r\n\r\n\r\nold_time = dt.datetime.now()\r\ntime.sleep(10)\r\ncurrent_time = dt.datetime.now()\r\n\r\ndelta_time = current_time - old_time\r\nprint(old_time)\r\nprint(current_time)\r\nprint(delta_time)\r\n\r\ndiff = str(delta_time)\r\nprint(diff)\r\nprint(diff[2:4])\r\ndiff_int = int(diff[2:4])\r\n\r\nprint(diff_int)\r\n\r\ndef sim_profit():\r\n sim_total_profit = 0\r\n sim_avg_profit = 0\r\n sim_total_ticker_cnt = 0\r\n sim_plus_cnt = 0\r\n global bought_time_list\r\n global buy_enable\r\n buy_enable = 0\r\n for ticker in tickers:\r\n if ticker in check_list:\r\n sim_total_ticker_cnt = sim_total_ticker_cnt + 1\r\n ref_price = check_list[ticker]\r\n bought_time = bought_time_list[ticker]\r\n current_time = dt.datetime.now()\r\n delta_time = current_time - bought_time\r\n diff = str(delta_time)\r\n valid_candle_cnt = int(diff[2:4])\r\n #count=31 will be changed.\r\n df_t = pyupbit.get_ohlcv(f\"{ticker}\", interval=\"minute1\", count=31)\r\n if (valid_candle_cnt > 30):\r\n high_list = df_t['high']\r\n low_list = df_t['low']\r\n else:\r\n start_idx = 30 - valid_candle_cnt\r\n high_list = df_t['high'][start_idx:30]\r\n low_list = df_t['low'][start_idx:30]\r\n avg_list = (high_list + low_list) / 2\r\n sim_avg = sum(avg_list)/len(avg_list)\r\n current_profit = sim_avg/ref_price - 1\r\n sim_total_profit = sim_total_profit + current_profit\r\n sim_avg_profit = sim_total_profit / sim_total_ticker_cnt\r\n if (current_profit > 0):\r\n sim_plus_cnt = sim_plus_cnt + 1\r\n logger.info(\"sim result - %s bought_time : %s buy_price : %0.1f avg_price : %0.1f current_profit : %0.6f sim_avg_profit : %0.6f valid_candle_cnt : %d\", ticker, bought_time, ref_price, sim_avg, current_profit, sim_avg_profit, valid_candle_cnt)\r\n if (sim_avg_profit > 1.03):\r\n buy_enable = 1\r\n logger.info(\"buy_enable = 1\")\r\n target_margin = sim_avg_profit\r\n else:\r\n buy_enable = 0\r\n logger.info(\"buy_enable = 0\")\r\n logger.info(\"sim_avg_profit : %0.6f sim_plus_cnt/sim_total_ticker_cnt : %d/%d\", sim_avg_profit, sim_plus_cnt, sim_total_ticker_cnt)\r\n\r\n\r\n\r\n\r\nwhile True:\r\n #logger.info(\"while\")\r\n if (status == \"bought\"):\r\n logger.info(\"status : %s\", status)\r\n if (buy_enable == 1):\r\n #upbit.sell_market_order(f\"{ticker}\", ticker_balance)\r\n sell_list[ticker] = sell(ticker)\r\n logger.info(\"sell_list[ticker] : %s\", sell_list[ticker])\r\n if (str.startswith('KRW-')):\r\n sell_balance = upbit.get_balance(ticker=\"KRW\")\r\n elif (str.startswith('BTC-')):\r\n sell_balance = upbit.get_balance(ticker=\"KRW-BTC\")\r\n else:\r\n abc = 0\r\n profit = sell_balance / buy_balance - 1\r\n total_profit = total_profit + profit\r\n status=\"standby\"\r\n #logger.info(\"sell_3 : %d profit : %0.4f total_profit : %0.4f\", sell_balance, profit, total_profit)\r\n continue\r\n elif (status == \"standby\"):\r\n #logger.info(\"status : %s\", status)\r\n ticker_found = 0\r\n for ticker in tickers:\r\n if ticker in bought_list:\r\n #logger.info(\"bought_list has %s\", ticker)\r\n buy_price = bought_list[ticker]\r\n stop_loss_monitor(ticker, buy_price, -0.02, 10, 2, 1)\r\n else:\r\n df = pyupbit.get_ohlcv(f\"{ticker}\", interval=\"minute1\", count=11)\r\n high_list = df['high'][0:10]\r\n low_list = df['low'][0:10]\r\n open_list = df['open'][0:10]\r\n close_list = df['close'][0:10]\r\n volume_list = df['volume'][0:10]\r\n avg_list = (high_list + low_list) / 2\r\n dead_validity = check_deadcoin(ticker, open_list, close_list, high_list)\r\n unit_validity = check_unit(ticker)\r\n if (dead_validity == \"dead\"):\r\n #logger.info(\"%s is dead\", ticker)\r\n continue\r\n else:\r\n if (unit_validity == \"small\"):\r\n #logger.info(\"%s is small\", ticker)\r\n continue\r\n rate_validity = check_rate_validity(ticker, avg_list) \r\n volume_validity = check_volume_validity(ticker, volume_list)\r\n time.sleep(0.1)\r\n #logger.info(\"ticker : %s rate_validity : %s volume_validity : %s\", ticker, rate_validity, volume_validity)\r\n if (rate_validity == \"valid\") and (volume_validity == \"valid\"):\r\n ticker_found = ticker\r\n break\r\n if (ticker_found != 0):\r\n ticker = ticker_found\r\n ticker_price = pyupbit.get_current_price(f\"{ticker}\")\r\n logger.info(\"ticker %s (%0.1f) is found.\", ticker, ticker_price)\r\n logger.info(\"avg_value : %0.6f new_value_1/avg_value : %0.6f new_value_2/avg_value : %0.6f\", avg_value, new_value_1/avg_value, new_value_2/avg_value)\r\n logger.info(\"avg_volume : %d new_volume_1/avg_volume : %0.3f new_volume_2/avg_volume : %0.3f\", avg_volume, new_volume_1/avg_volume, new_volume_2/avg_volume)\r\n rate15_validity = check_rate15_validity(ticker)\r\n if (rate15_validity == \"valid\"):\r\n #logger.info(\"rate15_validity is valid\")\r\n buy(ticker)\r\n current_time = dt.datetime.now()\r\n bought_time_list[ticker] = current_time\r\n bought_list[ticker] = buy_price\r\n check_list[ticker] = buy_price\r\n stop_loss = stop_loss_monitor(ticker, buy_price, -0.02, 10, 60, 0)\r\n if (stop_loss == 1):\r\n status = \"standby\"\r\n else:\r\n status = \"bought\"\r\n else:\r\n logger.info(\"rate15_validity is invalid\")\r\n else:\r\n logger.info(\"Error1\")\r\n if (sim_cycle_cnt == sim_cycle):\r\n sim_profit()\r\n sim_cycle_cnt = 0\r\n check_list = {}\r\n bought_time_list = {}\r\n sell_order_list = []\r\n sell_list = {}\r\n else:\r\n sim_cycle_cnt = sim_cycle_cnt + 1\r\n if (test_cycle_cnt == test_cycle):\r\n upbit.buy_market_order(\"KRW-BTC\", 6000)\r\n test_cycle_cnt = 0\r\n else:\r\n test_cycle_cnt = test_cycle_cnt + 1\r\n","sub_path":"v12_KRW1.py","file_name":"v12_KRW1.py","file_ext":"py","file_size_in_byte":17899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"389180841","text":"from ctypes import *\nfrom ctypes.wintypes import *\nfrom sys import exit\n\ndef customresize(array, new_size):\n return (array._type_*new_size).from_address(addressof(array))\n\nwlanapi = windll.LoadLibrary('wlanapi.dll')\n\nclass GUID(Structure):\n _fields_ = [('Data1', c_ulong),('Data2', c_ushort),('Data3', c_ushort),('Data4', c_ubyte*8),]\n\nWLAN_INTERFACE_STATE = c_uint\n(wlan_interface_state_not_ready,\n wlan_interface_state_connected,\n wlan_interface_state_ad_hoc_network_formed,\n wlan_interface_state_disconnecting,\n wlan_interface_state_disconnected,\n wlan_interface_state_associating,\n wlan_interface_state_discovering,\n wlan_interface_state_authenticating) = map(WLAN_INTERFACE_STATE, range(0, 8))\n\nclass WLAN_INTERFACE_INFO(Structure):\n _fields_ = [\n (\"InterfaceGuid\", GUID),\n (\"strInterfaceDescription\", c_wchar * 256),\n (\"isState\", WLAN_INTERFACE_STATE)\n ]\n\nclass WLAN_INTERFACE_INFO_LIST(Structure):\n _fields_ = [\n (\"NumberOfItems\", DWORD),\n (\"Index\", DWORD),\n (\"InterfaceInfo\", WLAN_INTERFACE_INFO * 1)\n ]\n\nWLAN_MAX_PHY_TYPE_NUMBER = 0x8\nDOT11_RATE_SET_MAX_LENGTH = 126\nDOT11_SSID_MAX_LENGTH = 32\nWLAN_REASON_CODE = DWORD\n\nDOT11_BSS_TYPE = c_uint\n(dot11_BSS_type_infrastructure,\n dot11_BSS_type_independent,\n dot11_BSS_type_any) = map(DOT11_BSS_TYPE, range(1, 4))\n\nDOT11_PHY_TYPE = c_uint\ndot11_phy_type_unknown = 0\ndot11_phy_type_any = 0\ndot11_phy_type_fhss = 1\ndot11_phy_type_dsss = 2\ndot11_phy_type_irbaseband = 3\ndot11_phy_type_ofdm = 4\ndot11_phy_type_hrdsss = 5\ndot11_phy_type_erp = 6\ndot11_phy_type_ht = 7\ndot11_phy_type_IHV_start = 0x80000000\ndot11_phy_type_IHV_end = 0xffffffff\n\nDOT11_AUTH_ALGORITHM = c_uint\nDOT11_AUTH_ALGO_80211_OPEN = 1\nDOT11_AUTH_ALGO_80211_SHARED_KEY = 2\nDOT11_AUTH_ALGO_WPA = 3\nDOT11_AUTH_ALGO_WPA_PSK = 4\nDOT11_AUTH_ALGO_WPA_NONE = 5\nDOT11_AUTH_ALGO_RSNA = 6\nDOT11_AUTH_ALGO_RSNA_PSK = 7\nDOT11_AUTH_ALGO_IHV_START = 0x80000000\nDOT11_AUTH_ALGO_IHV_END = 0xffffffff\n\nDOT11_CIPHER_ALGORITHM = c_uint\nDOT11_CIPHER_ALGO_NONE = 0x00\nDOT11_CIPHER_ALGO_WEP40 = 0x01\nDOT11_CIPHER_ALGO_TKIP = 0x02\nDOT11_CIPHER_ALGO_CCMP = 0x04\nDOT11_CIPHER_ALGO_WEP104 = 0x05\nDOT11_CIPHER_ALGO_WPA_USE_GROUP = 0x100\nDOT11_CIPHER_ALGO_RSN_USE_GROUP = 0x100\nDOT11_CIPHER_ALGO_WEP = 0x101\nDOT11_CIPHER_ALGO_IHV_START = 0x80000000\nDOT11_CIPHER_ALGO_IHV_END = 0xffffffff\n\nWLAN_AVAILABLE_NETWORK_CONNECTED = 1\nWLAN_AVAILABLE_NETWORK_HAS_PROFILE = 2\n\nWLAN_AVAILABLE_NETWORK_INCLUDE_ALL_ADHOC_PROFILES = 0x00000001\nWLAN_AVAILABLE_NETWORK_INCLUDE_ALL_MANUAL_HIDDEN_PROFILES = 0x00000002\n\nclass DOT11_SSID(Structure):\n _fields_ = [(\"SSIDLength\", c_ulong),(\"SSID\", c_char * DOT11_SSID_MAX_LENGTH)]\n\n\nclass WLAN_AVAILABLE_NETWORK(Structure):\n _fields_ = [\n (\"ProfileName\", c_wchar * 256),\n (\"dot11Ssid\", DOT11_SSID),\n (\"dot11BssType\", DOT11_BSS_TYPE),\n (\"NumberOfBssids\", c_ulong),\n (\"NetworkConnectable\", c_bool),\n (\"wlanNotConnectableReason\", WLAN_REASON_CODE),\n (\"NumberOfPhyTypes\", c_ulong),\n (\"dot11PhyTypes\", DOT11_PHY_TYPE * WLAN_MAX_PHY_TYPE_NUMBER),\n (\"MorePhyTypes\", c_bool),\n (\"wlanSignalQuality\", c_ulong),\n (\"SecurityEnabled\", c_bool),\n (\"dot11DefaultAuthAlgorithm\", DOT11_AUTH_ALGORITHM),\n (\"dot11DefaultCipherAlgorithm\", DOT11_CIPHER_ALGORITHM),\n (\"Flags\", DWORD),\n (\"Reserved\", DWORD)\n ]\n\n\nDOT11_MAC_ADDRESS = c_ubyte * 6\n\nDOT11_PHY_TYPE = c_uint\nDOT11_PHY_TYPE_UNKNOWN = 0\nDOT11_PHY_TYPE_ANY = 0\nDOT11_PHY_TYPE_FHSS = 1\nDOT11_PHY_TYPE_DSSS = 2\nDOT11_PHY_TYPE_IRBASEBAND = 3\nDOT11_PHY_TYPE_OFDM = 4\nDOT11_PHY_TYPE_HRDSSS = 5\nDOT11_PHY_TYPE_ERP = 6\nDOT11_PHY_TYPE_HT = 7\nDOT11_PHY_TYPE_VHT = 8\nDOT11_PHY_TYPE_IHV_START = 0X80000000\nDOT11_PHY_TYPE_IHV_END = 0XFFFFFFFF\n\nclass WLAN_RATE_SET(Structure):\n _fields_ = [\n (\"uRateSetLength\", c_ulong),\n (\"usRateSet\", c_ushort * 126)\n ]\n\nclass WLAN_BSS_ENTRY(Structure):\n _fields_ = [\n (\"dot11Ssid\",DOT11_SSID),\n (\"uPhyId\",c_ulong),\n (\"dot11Bssid\", DOT11_MAC_ADDRESS),\n (\"dot11BssType\", DOT11_BSS_TYPE),\n (\"dot11BssPhyType\", DOT11_PHY_TYPE),\n (\"lRssi\", c_long),\n (\"uLinkQuality\", c_ulong),\n (\"bInRegDomain\", c_bool),\n (\"usBeaconPeriod\",c_ushort),\n (\"ullTimestamp\", c_ulonglong),\n (\"ullHostTimestamp\",c_ulonglong),\n (\"usCapabilityInformation\",c_ushort),\n (\"ulChCenterFrequency\", c_ulong),\n (\"wlanRateSet\",WLAN_RATE_SET),\n (\"ulIeOffset\", c_ulong),\n (\"ulIeSize\", c_ulong)]\n\nclass WLAN_BSS_LIST(Structure):\n _fields_ = [\n (\"TotalSize\", DWORD),\n (\"NumberOfItems\", DWORD),\n (\"NetworkBSS\", WLAN_BSS_ENTRY * 1)\n ]\n\nWlanOpenHandle = wlanapi.WlanOpenHandle\nWlanOpenHandle.argtypes = (DWORD, c_void_p, POINTER(DWORD), POINTER(HANDLE))\nWlanOpenHandle.restype = DWORD\n\nWlanCloseHandle = wlanapi.WlanCloseHandle\nWlanCloseHandle.argtypes = (HANDLE, c_void_p)\nWlanCloseHandle.restype = DWORD\n\nWlanEnumInterfaces = wlanapi.WlanEnumInterfaces\nWlanEnumInterfaces.argtypes = (HANDLE, c_void_p,POINTER(POINTER(WLAN_INTERFACE_INFO_LIST)))\nWlanEnumInterfaces.restype = DWORD\n\nWlanGetNetworkBssList = wlanapi.WlanGetNetworkBssList\nWlanGetNetworkBssList.argtypes = (HANDLE, POINTER(GUID),POINTER(GUID),POINTER(GUID), c_bool, c_void_p,POINTER(POINTER(WLAN_BSS_LIST)))\nWlanGetNetworkBssList.restype = DWORD\n\nWlanFreeMemory = wlanapi.WlanFreeMemory\nWlanFreeMemory.argtypes = [c_void_p]\n\nWlanScan = wlanapi.WlanScan\nWlanScan.argtypes = (HANDLE, POINTER(GUID),c_void_p,c_void_p, c_void_p)\nWlanScan.restype = DWORD\n\ndef wifi_scan():\n NegotiatedVersion = DWORD()\n ClientHandle = HANDLE()\n ret = WlanOpenHandle(1, None, byref(NegotiatedVersion), byref(ClientHandle))\n if ret != 0:\n exit(FormatError(ret))\n # find all wireless network interfaces\n pInterfaceList = pointer(WLAN_INTERFACE_INFO_LIST())\n ret = WlanEnumInterfaces(ClientHandle, None, byref(pInterfaceList))\n if ret != 0:\n exit(FormatError(ret))\n try:\n ifaces = customresize(pInterfaceList.contents.InterfaceInfo, pInterfaceList.contents.NumberOfItems)\n BSSI_Values = []\n # find each available network for each interface\n for iface in ifaces:\n\n pAvailableNetworkList2 = pointer(WLAN_BSS_LIST())\n ret = WlanGetNetworkBssList(ClientHandle, byref(iface.InterfaceGuid),\n None, None,True,None,byref(pAvailableNetworkList2))\n \n if ret != 0:\n exit(FormatError(ret)) \n try:\n retScan = WlanScan(ClientHandle,byref(iface.InterfaceGuid),None,None,None)\n if retScan != 0:\n exit(FormatError(retScan))\n \n avail_net_list = pAvailableNetworkList2.contents\n networks = customresize(avail_net_list.NetworkBSS,avail_net_list.NumberOfItems)\n \n for net in networks:\n q = (str(net.uLinkQuality))\n SSID = (net.dot11Ssid.SSID[:net.dot11Ssid.SSIDLength]).decode('utf-8')\n BSSID = ':'.join('%02x' % b for b in net.dot11Bssid).upper()\n signal_strength = str(net.lRssi)\n CenterFreq = net.ulChCenterFrequency/1000000 \n typ = net.dot11BssPhyType\n\n if typ == 7 : typ = \"802.11n\"\n elif typ == 8 : typ =\"802.11ac\"\n \n BSSI_Values.append([SSID, BSSID, typ, CenterFreq, signal_strength, q])\n\n finally:\n WlanFreeMemory(pAvailableNetworkList2)\n WlanCloseHandle(ClientHandle,None)\n finally:\n WlanFreeMemory(pInterfaceList)\n return BSSI_Values\n\n\nwifi_scan()\n#for i in wifi_scan():\n# print(i)","sub_path":"winwifi_api.py","file_name":"winwifi_api.py","file_ext":"py","file_size_in_byte":8175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"281054775","text":"from mininet.topo import Topo\n\nclass Custom1(Topo):\n\tdef __init__(self):\n\t\tTopo.__init__(self)\n\t\th1 = self.addHost('h1')\n\t\th2 = self.addHost('h2')\n\t\ts1 = self.addSwitch('s1')\n\t\ts2 = self.addSwitch('s2')\n\n\t\tself.addLink(h1, s1)\n\t\tself.addLink(h2, s2)\n\t\tself.addLink(s1, s2)\n\ntopos = {\n\t'custom1': (lambda: Custom1())\n}","sub_path":"custom/custom1.py","file_name":"custom1.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"597907308","text":"subj = {}\nwith open(\"text_6.txt\", \"r\", encoding=\"utf-8\") as load_file:\n for line in load_file:\n subject, lecture, practice, lab = line.split()\n if lecture == '-':\n lecture = 0\n elif len(lecture)>2:\n lecture = lecture.replace('(л)', '')\n if practice == '-':\n practice = 0\n elif len(practice)>2:\n practice = practice.replace('(пр)', '')\n if lab == '-':\n lab = 0\n elif len(lab)>2:\n lab = lab.replace('(лаб)', '')\n\n subj[subject] = int(lecture)+int(practice)+int(lab)\n print(subj)","sub_path":"hw6.py","file_name":"hw6.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"281232673","text":"from flask import Flask, render_template, request, redirect\n\nimport webbrowser\nimport pandas as pd\nimport numpy as np\n\nimport tensorflow \nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import load_model\nimport os\n\napp = Flask(__name__)\n\napp.config[\"IMAGE_UPLOADS\"]= \"uploads/unknown_photo\"\n#/Users/gabrieldumbrille/Desktop/COPYFMP/\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\n\ndef upload_img():\n\n if request.method == \"POST\":\n\n if request.files:\n\n image = request.files[\"image\"]\n\n image.save(os.path.join(app.config[\"IMAGE_UPLOADS\"], image.filename))\n\n print(\"Image saved!\")\n\n return redirect(request.url)\n\n return render_template(\"upload_img.html\", methods=[\"GET\", \"POST\"])\n\n@app.route(\"/find_my_photo\")\n\ndef find_my_photo():\n photo = 'uploads'\n #/Users/gabrieldumbrille/Desktop/\n locations = pd.read_csv(r'key.csv')\n #/Users/gabrieldumbrille/Desktop/\n model = load_model(r'MobileNet_Model.h5')\n #/Users/gabrieldumbrille/Desktop/\n\n pred = ImageDataGenerator(rescale=1./255)\n\n pred = pred.flow_from_directory(\n photo,\n target_size=(160, 160),\n batch_size=1,\n shuffle=False\n )\n\n predictions = model.predict(pred, steps=1)\n\n preds = np.argmax(predictions,axis=1)\n\n answer = locations.loc[locations['name'].index == preds[0], 'coord']\n\n street_view = (''.join(list(answer))).replace(' ', '')\n\n webbrowser.open_new_tab(\n 'http://maps.google.com/maps?q=&layer=c&cbll=' + street_view)\n\n return 'Found!'\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"427658149","text":"# -*- coding: utf-8 -*-\n# @Author: Kai Shen\n# @Created Time: 2021/5/14 11:09\n# @Organization: YQN\n\nimport torch\nimport torch.nn as nn\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nos.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'\n\n\nclass PositionEncoding(nn.Module):\n def __init__(self, d_model, dropout_prob=0.1, max_len=5000):\n super(PositionEncoding, self).__init__()\n pe = torch.zeros(max_len, d_model)\n position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) # [max_len,1]\n div_term = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model))\n pe[:,::2]=torch.sin(position*div_term)\n pe[:,1::2]=torch.cos(position*div_term)\n self.dropout=nn.Dropout(dropout_prob)#[max_len,d_model]\n pe=pe.unsqueeze(0)#[batch_size,max_len,d_model]\n self.register_buffer(\"pe\",pe)\n\n def forward(self,x):\n \"\"\"\n :param x: [batch_size,src_len,d_model]\n :return:\n \"\"\"\n x=x+self.pe[:,:x.size(1)]\n return self.dropout(x)\n\n\n\n\nif __name__ == \"__main__\":\n plt.figure(figsize=(15, 5))\n pe = PositionEncoding(20, 0)\n x = torch.zeros(1, 100, 20)\n y=pe(x)\n plt.plot(np.arange(100), y[0, :, 4:8].data.numpy())\n plt.legend([\"dim %d\"%p for p in [4,5,6,7]])\n plt.show()\n","sub_path":"models/backbone/position_encoding.py","file_name":"position_encoding.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"431145354","text":"from lib.db import db_utilities\nfrom lib.ConfigHelper import ConfigHelper\n\nconn = db_utilities.make_connection()\ncur = conn.cursor()\nsel_sql = 'select AddressLine1 from Person.Address where AddressID = ?'\ndata = cur.execute(sel_sql, 1).fetchone()\n\n# print(cur.description)\nprint(data)\n# print(data[0])\n# print(data.AddressLine1)\n\n\n# sql_file = '..//resource//db//sql_script.sql'\n# cur = db_utilities.exec_sql_file(cur, sql_file)\n# data = cur.execute(\"select ProductCategoryID, Name, rowguid from Production.ProductCategory where Name = 'test7'\").fetchone()\n# print(data)\n\n\ncur.close()\n","sub_path":"lib/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"239126923","text":"from airflow.contrib.hooks.aws_hook import AwsHook\nfrom airflow.hooks.postgres_hook import PostgresHook\nfrom airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\n\n\nclass LoadDimFileDataOperator(BaseOperator):\n \"\"\" LoadDimFileDataOperator\n\n Custom Airflow Operator for loading dimension tables from files in an S3 bucket\n \"\"\"\n\n copy_sql = \"\"\"\n COPY {} \n FROM 's3://{}/{}'\n ACCESS_KEY_ID '{}'\n SECRET_ACCESS_KEY '{}'\n {}\n \"\"\"\n\n @apply_defaults\n def __init__(self,\n redshift_conn_id=\"redshift\",\n aws_credentials_id=\"aws_credentials\",\n table=\"\",\n s3_bucket=\"\",\n s3_key=\"\",\n copy_format=\"\",\n *args, **kwargs):\n \"\"\"\n LoadDimFileDataOperator init\n\n :param redshift_conn_id: Name of Redshift connection in Airflow\n :param aws_credentials_id: Name of AWS IAM Credentials connection in Airflow\n :param table: Name of table to load data into\n :param s3_bucket: Name of S3 bucket where data files are stored\n :param s3_key: Name of S3 key of data file to load in\n :param copy_format: SQL string for copy format (CSV or JSON)\n :param args:\n :param kwargs:\n \"\"\"\n super(LoadDimFileDataOperator, self).__init__(*args, **kwargs)\n self.redshift_conn_id = redshift_conn_id\n self.aws_credentials_id = aws_credentials_id\n self.table = table\n self.s3_bucket = s3_bucket\n self.s3_key = s3_key\n self.copy_format = copy_format\n\n def execute(self, context):\n \"\"\"\n LoadDimFileDataOperator execute\n\n Loads a data file in JSON or CSV format from an S3 bucket into a Redshift table. This\n operator will only load data into a table if it is empty.\n\n :param context:\n \"\"\"\n self.log.info(\"Using data file {} from S3 bucket {}\".format(self.s3_key, self.s3_bucket))\n\n aws_hook = AwsHook(self.aws_credentials_id)\n credentials = aws_hook.get_credentials()\n redshift = PostgresHook(postgres_conn_id=self.redshift_conn_id)\n\n # only copy data if dimension table is empty\n records = redshift.get_records(\"SELECT COUNT(*) FROM {}\".format(self.table))\n num_records = records.pop(0)[0]\n\n if num_records == 0:\n self.log.info(\"Inserting into destination Redshift table {}\".format(self.table))\n\n formatted_sql = LoadDimFileDataOperator.copy_sql.format(\n self.table,\n self.s3_bucket,\n self.s3_key,\n credentials.access_key,\n credentials.secret_key,\n self.copy_format\n )\n redshift.run(formatted_sql)\n else:\n self.log.info(\"Found {} records in {}\".format(num_records, self.table))\n self.log.info(\"{} table data is already set\".format(self.table))\n\n self.log.info(\"Data copy complete\")\n\n\n","sub_path":"airflow/plugins/operators/load_dim_file_data.py","file_name":"load_dim_file_data.py","file_ext":"py","file_size_in_byte":3035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"483426081","text":"import airflow\nfrom airflow.models import DAG\nfrom airflow.operators import CDColQueryOperator, CDColFromFileOperator, CDColReduceOperator\nfrom airflow.operators.python_operator import PythonOperator\nfrom cdcol_utils import dag_utils, queue_utils, other_utils\nfrom airflow.utils.trigger_rule import TriggerRule\nfrom cdcol_plugin.operators import common\nfrom datetime import timedelta\nfrom pprint import pprint\n\n_params = {{params}}\n\n_steps = {\n 'generic-step': {\n 'algorithm': _params['algorithm_name'],\n 'version': _params['algorithm_version'],\n 'queue': queue_utils.assign_queue(input_type='multi_temporal_unidad', time_range=_params['time_ranges'][0], unidades=len(_params['products'])),\n 'params': _params,\n },\n 'mosaico': {\n 'algorithm': \"joiner\",\n 'version': '1.0',\n 'queue': queue_utils.assign_queue(input_type='multi_area', lat=_params['lat'], lon=_params['lon']),\n 'params': {},\n 'del_prev_result': _params['elimina_resultados_anteriores'],\n }\n}\n\nargs = {\n 'owner': _params['owner'],\n 'start_date': airflow.utils.dates.days_ago(2),\n 'execID': _params['execID'],\n 'product': \"LS8_OLI_LASRC\"\n}\n\ndag = DAG(\n dag_id=args['execID'], default_args=args,\n schedule_interval=None,\n dagrun_timeout=timedelta(minutes=120))\n\ngeneric_step = dag_utils.queryMapByTile(lat=_params['lat'], lon=_params['lon'],\n time_ranges=_params['time_ranges'][0],\n algorithm=_steps['generic-step']['algorithm'], version=_steps['generic-step']['version'],\n product=_params['products'][0],\n params=_steps['generic-step']['params'],\n queue=_steps['generic-step']['queue'], dag=dag,\n task_id=\"generic-step_\" + _params['products'][0]['name'], to_tiff=not _params['genera_mosaico'], alg_folder=common.COMPLETE_ALGORITHMS_FOLDER)\n\nworkflow = generic_step\nif _params['genera_mosaico']:\n mosaico = dag_utils.OneReduce(workflow, task_id=\"mosaic\",\n algorithm=_steps['mosaico']['algorithm'],\n version=_steps['mosaico']['version'],\n queue=_steps['mosaico']['queue'],\n delete_partial_results=_steps['mosaico']['del_prev_result'],\n trigger_rule=TriggerRule.NONE_FAILED, dag=dag, to_tiff=_params['genera_mosaico'])\n\n workflow = mosaico\n\nworkflow\n","sub_path":"templates/generic_template.py","file_name":"generic_template.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"215814666","text":"import torch.nn as nn\r\n\r\n\r\nclass Net(nn.Module):\r\n def __init__(self, training=False):\r\n super(Net, self).__init__()\r\n self.feature = nn.Sequential(\r\n nn.Conv2d(1, 64, 3, bias=False),\r\n nn.BatchNorm2d(64),\r\n nn.ReLU(),\r\n nn.Conv2d(64, 128, 3, bias=False),\r\n nn.BatchNorm2d(128),\r\n nn.ReLU()\r\n )\r\n self.classifier = nn.Sequential(\r\n nn.AdaptiveAvgPool2d(1),\r\n nn.Flatten(),\r\n nn.Linear(128, 64),\r\n nn.ReLU(),\r\n nn.Linear(64, 10),\r\n nn.Softmax(dim=-1)\r\n )\r\n\r\n def forward(self, x):\r\n y = self.feature(x)\r\n y = self.classifier(y)\r\n return y\r\n\r\n\r\ndef main():\r\n net = Net().cuda()\r\n print(net)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"454045950","text":"#!/sevabot\n\n# -*- coding: utf-8 -*-\n\n\"\"\"\nSimple conference call hosting\n\"\"\"\nfrom __future__ import unicode_literals\n\nimport logging\nimport Skype4Py\n\nfrom sevabot.bot.stateful import StatefulSkypeHandler\nfrom sevabot.utils import ensure_unicode\n\nlogger = logging.getLogger('Call')\n\n# Set to debug only during dev\nlogger.setLevel(logging.INFO)\n\nlogger.debug('Call module level load import')\n\nHELP_TEXT = \"\"\"Simple conference call hosting allows you to have bot host a conference call from the chat.\n\nSevabot can have only one conference call at the same instance.\n\nCommands:\n\n!call help: Show this help text\n\n!call: Start a conference call from the chat\n\n!call start: Same as !call\n\n!call end: Finish the conference call from the chat\n\"\"\"\n\n\nclass CallHandler(StatefulSkypeHandler):\n\n \"\"\"\n Skype message handler class for the conference call hosting.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Use `init` method to initialize a handler.\n \"\"\"\n\n logger.debug('Call handler constructed')\n\n def init(self, sevabot):\n \"\"\"\n Set-up our state. This is called every time module is (re)loaded.\n\n :param skype: Handle to Skype4Py instance\n \"\"\"\n\n logger.debug('Call handler init')\n\n self.skype = sevabot.getSkype()\n self.calls = {}\n\n self.commands = {'help': self.help, 'start': self.start_call, 'end': self.end_call}\n\n def handle_message(self, msg, status):\n \"\"\"\n Override this method to customize a handler.\n \"\"\"\n\n body = ensure_unicode(msg.Body)\n\n logger.debug('Call handler got: {}'.format(body))\n\n # If the separators are not specified, runs of consecutive\n # whitespace are regarded as a single separator\n words = body.split()\n\n if not len(words):\n return False\n\n if words[0] != '!call':\n return False\n\n args = words[1:]\n\n if not len(args):\n # !call simply starts a call\n self.start_call(msg, status, args)\n return True\n\n for name, cmd in self.commands.items():\n if name == args[0]:\n cmd(msg, status, args)\n return True\n\n return False\n\n def shutdown():\n \"\"\"\n Called when the module is reloaded.\n \"\"\"\n logger.debug('Call handler shutdown')\n\n def help(self, msg, status, args):\n \"\"\"\n Show help message to the sender.\n \"\"\"\n msg.Chat.SendMessage(HELP_TEXT)\n\n def is_call_active(self, chat_name=None):\n \"\"\"\n Is a call from the chat active?\n \"\"\"\n\n if not chat_name:\n # Is any call active?\n return len(self.skype.ActiveCalls) > 0\n\n call = self.calls.get(chat_name, False)\n\n if not call:\n # Calls from the chat are not active\n return False\n\n conference_id = call.ConferenceId\n\n if conference_id > 0:\n conference = self.skype.Conference(conference_id)\n return len(conference.ActiveCalls) > 0\n else:\n return call.Status == Skype4Py.clsOnHold or call.Status == Skype4Py.clsLocalHold or call.Status == Skype4Py.clsRemoteHold or call.Status == Skype4Py.clsInProgress\n\n def start_call(self, msg, status, args):\n \"\"\"\n Start a conference call of the chat if any call is not active.\n \"\"\"\n\n chat_name = msg.Chat.Name\n\n if self.is_call_active():\n # Already active\n if not self.is_call_active(chat_name):\n msg.Chat.SendMessage('Sorry, I\\'m talking with someone else...')\n return\n\n def callback(call, status):\n logger.debug('Call status changed (wait): {} - {} - {}'.format(call.Id, call.Status, call.PartnerHandle))\n\n if status in (Skype4Py.clsRinging, Skype4Py.clsInProgress):\n self.calls[chat_name] = call\n self.unregister_callback(self.skype, 'CallStatus', callback)\n\n success = self.register_callback(self.skype, 'CallStatus', callback)\n if not success:\n logger.debug('CALL already issued on {}'.format(chat_name))\n return\n\n # Dirty workaround to start a conference call from a chat\n call_command = self.skype.Command('CALL {}'.format(chat_name))\n self.skype.SendCommand(call_command)\n\n def end_call(self, msg, status, args):\n \"\"\"\n Finish a conference call of the chat.\n \"\"\"\n\n chat_name = msg.Chat.Name\n\n if not self.is_call_active(chat_name):\n # No active calls\n msg.Chat.SendMessage('No calls to finish.')\n return\n\n call = self.calls.get(chat_name, False)\n if not call:\n # Should be never reached\n return\n\n conference_id = call.ConferenceId\n if conference_id > 0:\n self.skype.Conference(conference_id).Finish()\n else:\n call.Finish()\n\n\n# Export the instance to Sevabot\nsevabot_handler = CallHandler()\n\n__all__ = ['sevabot_handler']\n","sub_path":"modules/call.py","file_name":"call.py","file_ext":"py","file_size_in_byte":5051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"632615643","text":"import importlib\nimport os\nimport os.path\nfrom astropy.table import Table\nfrom astropy.utils import data\nimport healpy as hp\nimport numpy as np\n\ntry: # PySM >= 3.2.1\n import pysm3.units as u\n import pysm3 as pysm\nexcept ImportError:\n import pysm.units as u\n import pysm\nimport toml\n\n# pixell is optional and needed when CAR simulations are requested\ntry:\n import pixell\n import pixell.curvedsky\n import pixell.powspec\nexcept:\n pixell = None\n\nfrom so_pysm_models import get_so_models\nfrom .utils import DEFAULT_INSTRUMENT_PARAMETERS, merge_dict\n\nimport socket\non_cori_login = socket.gethostname().startswith(\"cori\")\n\ntry:\n if \"DISABLE_MPI\" in os.environ or on_cori_login:\n raise ImportError\n from mpi4py import MPI\n\n COMM_WORLD = MPI.COMM_WORLD\nexcept ImportError:\n COMM_WORLD = None\n\nimport warnings\n\nfrom .channel_utils import parse_channels\n\nPYSM_COMPONENTS = {\n comp[0]: comp for comp in [\"synchrotron\", \"dust\", \"freefree\", \"cmb\", \"ame\"]\n}\ndefault_output_filename_template = (\n \"simonsobs_{tag}_{telescope}_{band}_nside{nside}_{split}_of_{nsplits}.fits\"\n)\n\n\ndef get_default_so_resolution(ch, field=\"NSIDE\"):\n \"Load the default Simons Observatory resolution\"\n\n default_resolution = Table.read(\n data.get_pkg_data_filename(\"data/so_default_resolution.csv\")\n )\n default_resolution.add_index(\"channel\")\n first_ch = ch if not isinstance(ch, tuple) else ch[0]\n output = default_resolution.loc[first_ch.telescope + \"_\" + str(first_ch.band)][\n field\n ]\n if field == \"CAR_resol\":\n output *= u.arcmin\n return output\n\n\ndef get_map_shape(ch, nside=None, car_resolution=None, car=False):\n \"\"\"Get map shape (and WCS for CAR) for Simons Observatory channels\n\n If N_side or car_resolution is None, get the default value\n from: `mapsims/data/default_resolution.csv`\n\n Parameters\n ----------\n ch : string\n Channel tag, e.g. SA_LF2\n nside : int\n Desired healpix N_side\n car_resolution : astropy.Quantity\n CAR pixels resolution with angle unit\n car : bool\n Set to True for CAR, False for HEALPix\n\n Returns\n -------\n nside : int\n N_side, either return the input or default\n None for CAR\n shape : tuple of int\n (npix,) for HEALPix, (Nx, Ny) for CAR\n wcs : astropy.WCS\n CAR map WCS, None for HEALPix\n \"\"\"\n if car:\n if car_resolution is None:\n car_resolution = get_default_so_resolution(ch, field=\"CAR_resol\")\n shape, wcs = pixell.enmap.fullsky_geometry(\n res=car_resolution.to_value(u.radian)\n )\n nside = None\n else:\n if nside is None:\n nside = get_default_so_resolution(ch)\n shape = (hp.nside2npix(nside),)\n wcs = None\n return nside, shape, wcs\n\n\ndef function_accepts_argument(func, arg):\n \"\"\"Check if a function or class accepts argument arg\n\n Parameters\n ----------\n\n func : Python function or Class\n Input Python function or Class to check\n arg : str\n keyword or positional argument to check\n\n Returns\n -------\n\n accepts_argument : bool\n True if function/class constructor accepts argument\n \"\"\"\n if not hasattr(func, \"__code__\"):\n func = func.__init__\n return arg in func.__code__.co_varnames\n\n\ndef command_line_script(args=None):\n\n import argparse\n\n parser = argparse.ArgumentParser(\n description=\"Execute map based simulations for Simons Observatory\"\n )\n parser.add_argument(\"config\", type=str, help=\"Configuration file\", nargs=\"+\")\n parser.add_argument(\"--nside\", type=int, required=False, help=\"NSIDE\")\n parser.add_argument(\n \"--num\",\n type=int,\n required=False,\n help=\"Simulation number, generally used as seed\",\n )\n parser.add_argument(\n \"--nsplits\", type=int, required=False, help=\"Number of noise splits\"\n )\n parser.add_argument(\n \"--channels\",\n type=str,\n help=\"Channels e.g. all, 'LT1_UHF1,LT0_UHF1', 'tube:LT1', see docstring of MapSim\",\n required=False,\n )\n res = parser.parse_args(args)\n override = {\n key: getattr(res, key)\n for key in [\"nside\", \"channels\", \"num\", \"nsplits\"]\n if getattr(res, key) is not None\n }\n\n simulator = from_config(res.config, override=override)\n simulator.execute(write_outputs=True)\n\n\ndef import_class_from_string(class_string):\n module_name, class_name = class_string.rsplit(\".\", 1)\n return getattr(importlib.import_module(module_name), class_name)\n\n\ndef from_config(config_file, override=None):\n if isinstance(config_file, str):\n config_file = [config_file]\n\n config = toml.load(config_file[0])\n for conf in config_file[1:]:\n merge_dict(config, toml.load(conf))\n\n if override is not None:\n config.update(override)\n\n pysm_components_string = None\n pysm_output_reference_frame = None\n\n nside = config.get(\"nside\", None)\n car = config.get(\"car\", False)\n channels = parse_channels(config[\"channels\"], config[\"instrument_parameters\"])\n car_resolution = config.get(\"car_resolution_arcmin\", None)\n if car_resolution is not None:\n car_resolution = car_resolution * u.arcmin\n nside, shape, wcs = get_map_shape(\n ch=channels[0],\n nside=config.get(\"nside\", None),\n car_resolution=car_resolution,\n car=car,\n )\n\n components = {}\n for component_type in [\"pysm_components\", \"other_components\"]:\n components[component_type] = {}\n if component_type in config:\n component_type_config = config[component_type]\n if component_type == \"pysm_components\":\n pysm_components_string = component_type_config.pop(\n \"pysm_components_string\", None\n )\n pysm_output_reference_frame = component_type_config.pop(\n \"pysm_output_reference_frame\", None\n )\n for comp_name in component_type_config:\n comp_config = component_type_config[comp_name]\n comp_class = import_class_from_string(comp_config.pop(\"class\"))\n if (\n function_accepts_argument(comp_class, \"num\")\n and \"num\" in config\n and \"num\" not in comp_config\n ):\n # If a component has an argument \"num\" and we provide a configuration\n # \"num\" to MapSims, we pass it to all the class.\n # it can be overridden by the actual component config\n # This is used for example by `SOStandalonePrecomputedCMB`\n comp_config[\"num\"] = config[\"num\"]\n if function_accepts_argument(comp_class, \"shape\") and shape is not None:\n comp_config[\"shape\"] = shape\n comp_config[\"wcs\"] = wcs\n components[component_type][comp_name] = comp_class(\n nside=nside, **comp_config\n )\n\n map_sim = MapSim(\n channels=config[\"channels\"],\n nside=nside,\n car=car,\n car_resolution=car_resolution,\n num=config[\"num\"],\n nsplits=config.get(\"nsplits\", 1),\n unit=config[\"unit\"],\n tag=config[\"tag\"],\n output_folder=config.get(\"output_folder\", \"output\"),\n output_filename_template=config.get(\n \"output_filename_template\", default_output_filename_template\n ),\n pysm_components_string=pysm_components_string,\n pysm_custom_components=components[\"pysm_components\"],\n pysm_output_reference_frame=pysm_output_reference_frame,\n other_components=components[\"other_components\"],\n instrument_parameters=config[\"instrument_parameters\"],\n )\n return map_sim\n\n\nclass MapSim:\n def __init__(\n self,\n channels,\n nside=None,\n car=False,\n car_resolution=None,\n num=0,\n nsplits=1,\n unit=\"uK_CMB\",\n output_folder=\"output\",\n tag=\"mapsim\",\n output_filename_template=default_output_filename_template,\n pysm_components_string=None,\n pysm_output_reference_frame=\"C\",\n pysm_custom_components=None,\n other_components=None,\n instrument_parameters=DEFAULT_INSTRUMENT_PARAMETERS,\n ):\n \"\"\"Run map based simulations\n\n MapSim executes PySM for each of the input channels with a sky defined\n by default PySM components in `pysm_components_string` and custom components in\n `pysm_custom_components` and rotates in Alm space to the reference frame `pysm_output_reference_frame`.\n Then for each of the channels specified, smoothes the map with the channel beam\n and finally adds the map generated by `other_components`, for example noise maps, and writes\n the outputs to disk.\n\n Parameters\n ----------\n\n channels : str\n If \"all\", all channels are included.\n Otherwise a list of channel tags:\n LT1_UHF1 and LT0_UHF1 = \"LT1_UHF1,LT0_UHF1\"\n Otherwise, provide a string with:\n * a key, e.g. tube or telescope\n * :\n * comma separated list of desider values\n e.g. all SAT channels = \"telescope:SA\"\n LT1 and LT2 tubes = \"tube:LT1,LT2\"\n nside : int\n output HEALPix Nside, if None, automatically pick the default resolution of the\n first channel,\n see https://github.com/simonsobs/mapsims/tree/master/mapsims/data/so_default_resolution.csv\n car : bool\n True for CAR, False for HEALPix\n car_resolution : astropy.Quantity\n CAR pixels resolution with angle unit\n unit : str\n Unit of output maps\n output_folder : str\n Relative or absolute path to output folder, string template with {nside} and {tag} fields\n num : int\n Realization number, generally used as seed, default is 0, automatically padded to 4 digits\n nsplits : int\n Number of noise splits, see the documentation of :py:class:`SONoiseSimulator`\n tag : str\n String to describe the current simulation, for example its content, which is used into\n string interpolation for `output_folder` and `output_filename_template`\n output_filename_template : str\n String template with {telescope} {channel} {nside} {tag} fields\n pysm_components_string : str\n Comma separated string of PySM components, i.e. \"s1,d4,a2\"\n pysm_output_reference_frame : str\n The output of PySM is in Galactic coordinates, rotate to C for Equatorial or E for Ecliptic,\n set to None to apply no rotation\n pysm_custom_components : dict\n Dictionary of other components executed through PySM\n other_components : dict\n Dictionary of component name, component class pairs, the output of these are **not** rotated,\n they should already be in the same reference frame specified in pysm_output_reference_frame.\n instrument_parameters : ascii file in IPAC table format path or str\n A string specifies an instrument parameters file\n included in the package `data/` folder\n A path or a string containing a path to an externally provided IPAC table file with\n the expected format. By default the latest Simons Observatory parameters\n Instrument parameters in IPAC ascii format, one channel per row, with columns (with units):\n tag, band, center_frequency, fwhm\n It also assumes that in the same folder there are IPAC table files named bandpass_{tag}.tbl\n with columns:\n bandpass_frequency, bandpass_weight\n\n\n \"\"\"\n\n self.channels = parse_channels(\n instrument_parameters=instrument_parameters, filter=channels\n )\n\n self.car = car\n self.nside, self.shape, self.wcs = get_map_shape(\n ch=self.channels[0],\n nside=nside,\n car_resolution=car_resolution,\n car=self.car,\n )\n\n self.unit = unit\n self.num = num\n self.nsplits = nsplits\n self.pysm_components_string = pysm_components_string\n self.pysm_custom_components = pysm_custom_components\n self.run_pysm = not (\n (pysm_components_string is None)\n and (pysm_custom_components is None or len(pysm_custom_components) == 0)\n )\n self.other_components = other_components\n self.tag = tag\n self.output_folder = output_folder.format(\n nside=self.nside, tag=self.tag, num=self.num\n )\n if not os.path.exists(self.output_folder):\n os.makedirs(self.output_folder)\n self.output_filename_template = output_filename_template\n self.rot = None\n self.pysm_output_reference_frame = pysm_output_reference_frame\n\n def execute(self, write_outputs=False):\n \"\"\"Run map simulations\n\n Execute simulations for all channels and write to disk the maps,\n unless `write_outputs` is False, then return them.\n \"\"\"\n\n if self.run_pysm:\n sky_config = []\n preset_strings = []\n if self.pysm_components_string is not None:\n for model in self.pysm_components_string.split(\",\"):\n if model.startswith(\"SO\"):\n sky_config.append(get_so_models(model, self.nside))\n else:\n preset_strings.append(model)\n\n if len(preset_strings) > 0:\n input_reference_frame = \"G\"\n assert (\n len(sky_config) == 0\n ), \"Cannot mix PySM and SO models, they are defined in G and C frames\"\n else:\n input_reference_frame = \"C\"\n\n self.pysm_sky = pysm.Sky(\n nside=self.nside,\n preset_strings=preset_strings,\n component_objects=sky_config,\n output_unit=u.Unit(self.unit),\n )\n\n if self.pysm_custom_components is not None:\n for comp_name, comp in self.pysm_custom_components.items():\n self.pysm_sky.components.append(comp)\n\n if not write_outputs:\n output = {}\n\n # ch can be single channel or tuple of 2 channels (tube dichroic)\n for ch in self.channels:\n if not isinstance(ch, tuple):\n ch = [ch]\n output_map_shape = (len(ch), 3) + self.shape\n output_map = np.zeros(output_map_shape, dtype=np.float64)\n if self.run_pysm:\n for each, channel_map in zip(ch, output_map):\n bandpass_integrated_map = self.pysm_sky.get_emission(\n *each.bandpass\n ).value\n beam_width_arcmin = each.beam\n # smoothing and coordinate rotation with 1 spherical harmonics transform\n smoothed_map = hp.ma(\n pysm.apply_smoothing_and_coord_transform(\n bandpass_integrated_map,\n fwhm=beam_width_arcmin,\n lmax=3 * self.nside - 1,\n rot=None\n if input_reference_frame == self.pysm_output_reference_frame\n else hp.Rotator(\n coord=(\n input_reference_frame,\n self.pysm_output_reference_frame,\n )\n ),\n map_dist=None\n if COMM_WORLD is None\n else pysm.MapDistribution(\n nside=self.nside,\n smoothing_lmax=3 * self.nside - 1,\n mpi_comm=COMM_WORLD,\n ),\n )\n )\n\n if smoothed_map.shape[0] == 1:\n channel_map[0] += smoothed_map\n else:\n channel_map += smoothed_map\n\n output_map = output_map.reshape((len(ch), 1, 3) + self.shape)\n\n if self.other_components is not None:\n for comp in self.other_components.values():\n kwargs = dict(tube=ch[0].tube, output_units=self.unit)\n if function_accepts_argument(comp.simulate, \"ch\"):\n kwargs.pop(\"tube\")\n kwargs[\"ch\"] = ch\n if function_accepts_argument(comp.simulate, \"nsplits\"):\n kwargs[\"nsplits\"] = self.nsplits\n if function_accepts_argument(comp.simulate, \"seed\"):\n kwargs[\"seed\"] = self.num\n component_map = comp.simulate(**kwargs)\n if self.nsplits == 1:\n component_map = component_map.reshape(\n (len(ch), 1, 3) + self.shape\n )\n component_map[hp.mask_bad(component_map)] = np.nan\n output_map = output_map + component_map\n\n for each, channel_map in zip(ch, output_map):\n if write_outputs:\n for split, each_split_channel_map in enumerate(channel_map):\n filename = self.output_filename_template.format(\n telescope=each.telescope\n if each.tube is None\n else each.tube,\n band=each.band,\n nside=self.nside,\n tag=self.tag,\n num=self.num,\n nsplits=self.nsplits,\n split=split + 1,\n )\n warnings.warn(\"Writing output map \" + filename)\n if self.car:\n pixell.enmap.write_map(\n os.path.join(self.output_folder, filename),\n each_split_channel_map,\n extra=dict(units=self.unit),\n )\n else:\n each_split_channel_map[\n np.isnan(each_split_channel_map)\n ] = hp.UNSEEN\n each_split_channel_map = hp.reorder(\n each_split_channel_map, r2n=True\n )\n hp.write_map(\n os.path.join(self.output_folder, filename),\n each_split_channel_map,\n coord=self.pysm_output_reference_frame,\n column_units=self.unit,\n dtype=np.float32,\n overwrite=True,\n nest=True,\n )\n else:\n if self.nsplits == 1:\n channel_map = channel_map[0]\n if not self.car:\n channel_map[np.isnan(channel_map)] = hp.UNSEEN\n output[each.tag] = channel_map\n if not write_outputs:\n return output\n","sub_path":"mapsims/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":19628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"512302519","text":"from django.shortcuts import render, redirect,render_to_response\nfrom piebase.models import Project, Priority, Severity, TicketStatus, Ticket, Requirement, Attachment\nfrom forms import CreateProjectForm, PriorityForm, SeverityForm, TicketStatusForm, RoleForm, CommentForm\nimport json\nimport random\nimport string\nimport os\nimport shutil\nfrom django.utils import timezone\nfrom django.template.defaultfilters import slugify\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse\nfrom django.contrib.auth.tokens import default_token_generator\nfrom django.core.urlresolvers import reverse\nfrom piebase.models import User, Project, Organization, Role, Milestone, Requirement\nfrom forms import CreateProjectForm, CreateMemberForm, PasswordResetForm, MilestoneForm, RequirementForm\nfrom .tasks import send_mail_old_user\nfrom django.core import serializers\nfrom django.core.paginator import Paginator,PageNotAnInteger,EmptyPage\n\n\n\n\n@login_required\ndef create_project(request):\n if(request.method == \"POST\"):\n organization = request.user.organization\n form = CreateProjectForm(request.POST, organization=organization, user = request.user)\n if(form.is_valid()):\n slug = slugify(request.POST['name'])\n project_obj = form.save()\n project_obj.members.add(request.user)\n project_obj.save()\n json_data = {'error': False, 'errors': form.errors, 'slug': slug}\n return HttpResponse(json.dumps(json_data), content_type=\"application/json\")\n else:\n return HttpResponse(json.dumps({'error': True, 'errors': form.errors}), content_type=\"application/json\")\n return render(request, 'project/create_project.html')\n\n\n@login_required\ndef list_of_projects(request):\n template_name = 'project/projects_list.html'\n projects_list = Project.objects.filter(members__email=request.user)\n dict_items = {'projects_list': projects_list}\n return render(request, template_name, dict_items)\n\n\n@login_required\ndef project_detail(request, slug):\n template_name = 'project/project_description.html'\n project_object = Project.objects.get(slug=slug)\n project_members = project_object.members.all()\n dict_items = {'project_object': project_object, 'project_members': project_members}\n return render(request, template_name, dict_items)\n\n\n@login_required\ndef project_details(request, slug):\n project = Project.objects.get(slug=slug)\n dictionary = {'project': project, 'slug': slug}\n template_name = 'project/project_project_details.html'\n\n if(request.method == 'POST'):\n organization = request.user.organization\n form = CreateProjectForm(request.POST, organization=organization)\n\n if(form.is_valid()):\n slug = slugify(request.POST['name'])\n project = Project.objects.get(\n slug=request.POST['oldname'], organization=organization)\n project.name = request.POST['name']\n project.slug = slug\n project.modified_date = timezone.now()\n project.save()\n return HttpResponse(json.dumps({'error': False, 'slug': slug}), content_type=\"application/json\")\n else:\n return HttpResponse(json.dumps({'error': True, 'errors': form.errors}), content_type=\"application/json\")\n\n return render(request, template_name, dictionary)\n\n\n@login_required\ndef delete_project(request, id):\n Project.objects.get(id=id).delete()\n return redirect(\"project:list_of_projects\")\n\n\n@login_required\ndef priorities(request, slug):\n priority_list = Priority.objects.filter(\n project=Project.objects.get(slug=slug))\n return render(request, 'settings/priorities.html', {'slug': slug, 'priority_list': priority_list})\n\n\n@login_required\ndef priority_create(request, slug):\n project = Project.objects.get(slug=slug)\n form = PriorityForm(request.POST, project=project)\n if(form.is_valid()):\n priority = form.save()\n return HttpResponse(json.dumps({'error': False, 'color': priority.color, 'name': priority.name, 'proj_id': priority.id, 'slug': priority.slug}), content_type=\"application/json\")\n else:\n return HttpResponse(json.dumps({'error': True, 'errors': form.errors}), content_type=\"application/json\")\n\n\n@login_required\ndef priority_edit(request, slug, priority_slug):\n project = Project.objects.get(slug=slug)\n instance = Priority.objects.get(slug=priority_slug, project=project)\n form = PriorityForm(request.POST, instance=instance,project=project)\n if(form.is_valid()):\n priority = form.save()\n return HttpResponse(json.dumps({'error': False, 'color': priority.color, 'name': priority.name, 'proj_id': priority.id, 'slug': priority.slug}), content_type=\"application/json\")\n else:\n return HttpResponse(json.dumps({'error': True, 'errors': form.errors}), content_type=\"application/json\")\n\n\n@login_required\ndef priority_delete(request, slug, priority_slug):\n Priority.objects.get(\n slug=priority_slug, project=Project.objects.get(slug=slug)).delete()\n return HttpResponse(json.dumps({'error': False}), content_type=\"application/json\")\n\n\n@login_required\ndef severities(request, slug):\n severity_list = Severity.objects.filter(\n project=Project.objects.get(slug=slug))\n return render(request, 'settings/severities.html', {'slug': slug, 'severity_list': severity_list})\n\n\n@login_required\ndef severity_create(request, slug):\n project = Project.objects.get(slug=slug)\n form = SeverityForm(request.POST, project=project)\n if(form.is_valid()):\n severity = form.save()\n return HttpResponse(json.dumps({'error': False, 'color': severity.color, 'name': severity.name, 'proj_id': severity.id, 'slug': severity.slug}), content_type=\"application/json\")\n else:\n return HttpResponse(json.dumps({'error': True, 'errors': form.errors}), content_type=\"application/json\")\n\n\n@login_required\ndef severity_edit(request, slug, severity_slug):\n project = Project.objects.get(slug=slug)\n instance = Severity.objects.get(slug=severity_slug, project=project)\n form = SeverityForm(request.POST, instance=instance, project=project)\n if(form.is_valid()):\n severity = form.save()\n return HttpResponse(json.dumps({'error': False, 'color': severity.color, 'name': severity.name, 'proj_id': severity.id, 'slug': severity.slug}), content_type=\"application/json\")\n else:\n return HttpResponse(json.dumps({'error': True, 'errors': form.errors}), content_type=\"application/json\")\n\n\n@login_required\ndef severity_delete(request, slug, severity_slug):\n Severity.objects.get(\n slug=severity_slug, project=Project.objects.get(slug=slug)).delete()\n return HttpResponse(json.dumps({'error': False}), content_type=\"application/json\")\n\n\n@login_required\ndef ticket_status(request, slug):\n ticket_status_list = TicketStatus.objects.filter(\n project=Project.objects.get(slug=slug))\n return render(request, 'settings/ticket_status.html', {'slug': slug, 'ticket_status_list': ticket_status_list})\n\n\n@login_required\ndef ticket_status_create(request, slug):\n project = Project.objects.get(slug=slug)\n form = TicketStatusForm(request.POST, project=project)\n if(form.is_valid()):\n ticket_status = form.save()\n return HttpResponse(json.dumps({'error': False, 'color': ticket_status.color, 'name': ticket_status.name, 'proj_id': ticket_status.id, 'slug': ticket_status.slug}), content_type=\"application/json\")\n else:\n return HttpResponse(json.dumps({'error': True, 'errors': form.errors}), content_type=\"application/json\")\n\n\n@login_required\ndef ticket_status_edit(request, slug, ticket_slug):\n project = Project.objects.get(slug=slug)\n instance = TicketStatus.objects.get(slug=ticket_slug, project=project)\n form = TicketStatusForm(request.POST, instance=instance, project=project)\n if(form.is_valid()):\n ticket_status = form.save()\n return HttpResponse(json.dumps({'error': False, 'color': ticket_status.color, 'name': ticket_status.name, 'proj_id': ticket_status.id, 'slug': ticket_status.slug}), content_type=\"application/json\")\n else:\n return HttpResponse(json.dumps({'error': True, 'errors': form.errors}), content_type=\"application/json\")\n\n\n@login_required\ndef ticket_status_delete(request, slug, ticket_slug):\n TicketStatus.objects.get(\n slug=ticket_slug, project=Project.objects.get(slug=slug)).delete()\n return HttpResponse(json.dumps({'error': False}), content_type=\"application/json\")\n\n\ndef password_reset(request, to_email):\n from_email = 'dineshmcmf@gmail.com'\n to_email_dict = {'email': to_email}\n token_generator = default_token_generator\n email_template_name = 'email/reset_email.html'\n subject_template_name = 'email/reset_subject.txt'\n form = PasswordResetForm(to_email_dict)\n if form.is_valid():\n opts = {\n 'use_https': request.is_secure(),\n 'from_email': from_email,\n 'email_template_name': email_template_name,\n 'subject_template_name': subject_template_name,\n 'request': request}\n form.save(**opts)\n\n\n@login_required\ndef project_team(request, slug):\n project = Project.objects.get(slug=slug)\n mem_details = []\n for member in project.members.exclude(email=request.user.email):\n mem_details.append(\n (member, Role.objects.get(users__email=member.email)))\n dictionary = {'project_id': project.id,\n 'mem_details': mem_details, 'slug': slug}\n return render(request, 'settings/team.html', dictionary)\n\n\n@login_required\ndef create_member(request, slug):\n if request.method == 'POST':\n error_count = 0\n json_data = {}\n json_post_index = 0\n email_list = request.POST.getlist('email')\n designation_list = request.POST.getlist('designation')\n description = request.POST.get('description')\n post_dict = {'description': description}\n post_tuple = zip(email_list, designation_list)\n for email_iter, designation_iter in post_tuple:\n post_dict['email'] = email_iter\n post_dict['designation'] = designation_iter\n create_member_form = CreateMemberForm(post_dict)\n if create_member_form.is_valid():\n email = post_dict['email']\n designation = post_dict['designation']\n description = post_dict['description']\n organization_obj = request.user.organization\n if User.objects.filter(email=email).exists():\n send_mail_old_user.delay(email)\n pass\n else:\n random_password = ''.join(\n random.choice(string.digits) for _ in xrange(8))\n new_user_obj = User.objects.create_user(\n email=email, username=email, password=random_password, organization=organization_obj, pietrack_role='user')\n password_reset(request, email_iter)\n project_obj = Project.objects.get(slug=slug)\n user_obj = User.objects.get(email=email)\n project_obj.members.add(user_obj)\n project_obj.organization = organization_obj\n project_obj.save()\n\n random_slug = ''.join(\n random.choice(string.ascii_letters + string.digits) for _ in xrange(10))\n role_obj = Role.objects.create(\n name=designation, slug=random_slug, project=project_obj)\n role_obj.users.add(user_obj)\n role_obj.save()\n else:\n error_count += 1\n json_data[json_post_index] = create_member_form.errors\n json_post_index += 1\n if error_count == 0:\n json_data['error'] = False\n else:\n json_data['error'] = True\n return HttpResponse(json.dumps(json_data), content_type='application/json')\n else:\n return render(request, 'settings/create_member.html')\n\n\n@login_required\ndef member_roles(request, slug):\n project = Project.objects.get(slug=slug)\n list_of_roles = Role.objects.filter(project=project)\n dictionary = {'list_of_roles': list_of_roles, 'slug': slug}\n return render(request, 'settings/member_roles.html', dictionary)\n\n\n@login_required\ndef member_role_create(request, slug):\n project = Project.objects.get(slug=slug)\n form = RoleForm(request.POST, project=project)\n if(form.is_valid()):\n role = form.save()\n return HttpResponse(json.dumps({'error': False, 'role_id': role.id, 'role_name': role.name, 'slug': role.slug}), content_type=\"application/json\")\n else:\n return HttpResponse(json.dumps({'error': True, 'errors': form.errors}), content_type=\"application/json\")\n\n\n@login_required\ndef member_role_edit(request, slug, member_role_slug):\n project=Project.objects.get(slug=slug)\n instance = Role.objects.get(\n slug=member_role_slug, project=project)\n form = RoleForm(request.POST, instance=instance, project=project)\n if(form.is_valid()):\n role = form.save()\n return HttpResponse(json.dumps({'error': False, 'role_id': role.id, 'role_name': role.name, 'slug': role.slug}), content_type=\"application/json\")\n else:\n return HttpResponse(json.dumps({'error': True, 'errors': form.errors}), content_type=\"application/json\")\n\n\n@login_required\ndef member_role_delete(request, slug, member_role_slug):\n project = Project.objects.get(slug=slug)\n Role.objects.get(slug=member_role_slug, project=project).delete()\n return HttpResponse(json.dumps({'error': False}), content_type=\"application/json\")\n\n@login_required\ndef taskboard(request,slug,milestone_slug):\n project = Project.objects.get(slug=slug)\n milestone = Milestone.objects.get(slug=milestone_slug,project=project)\n ticket_status_list = TicketStatus.objects.filter(project=project)\n return render(request,'project/taskboard.html',{'ticket_status_list':ticket_status_list,'slug':slug,'milestone':milestone})\n\n@login_required\ndef update_taskboard_status(request,slug,status_slug,task_id):\n task = Ticket.objects.get(id=task_id)\n ticket_status = TicketStatus.objects.get(slug=status_slug,project=Project.objects.get(slug=slug))\n task.status = ticket_status\n task.save()\n return HttpResponse(\"\")\n\n@login_required\ndef load_tasks(request,slug,milestone_slug,status_slug):\n project = Project.objects.get(slug=slug)\n status = TicketStatus.objects.get(slug=status_slug,project=project)\n milestone = Milestone.objects.get(slug=milestone_slug,project=project)\n tasks = Ticket.objects.filter(status=status,milestone=milestone) \n\n paginator = Paginator(tasks, 10)\n page = request.GET.get('page')\n try:\n tasks = paginator.page(page)\n except PageNotAnInteger:\n pass\n except EmptyPage:\n pass\n return render_to_response('project/partials/task.html',{'tasks':tasks,'milestone':milestone,'slug':slug})\n\n\n@login_required\ndef requirement_tasks(request,slug,milestone_slug,requirement_id):\n project = Project.objects.get(slug=slug)\n milestone = Milestone.objects.get(slug=milestone_slug,project=project)\n ticket_status_list = TicketStatus.objects.filter(project=project)\n return render(request,'project/partials/requirement_tasks.html',{'ticket_status_list':ticket_status_list,'slug':slug,'requirement_id':requirement_id,'milestone':milestone})\n\n@login_required\ndef requirement_tasks_more(request,slug,milestone_slug,status_slug,requirement_id):\n requirement = Requirement.objects.get(id=requirement_id)\n project = Project.objects.get(slug=slug)\n milestone = Milestone.objects.get(slug=milestone_slug,project=project)\n tasks = requirement.tasks.filter(status__slug=status_slug)\n paginator = Paginator(tasks,10)\n page = request.GET.get('page')\n try:\n tasks = paginator.page(page)\n except PageNotAnInteger:\n pass\n except EmptyPage:\n pass\n return render_to_response('project/partials/task.html',{'tasks':tasks,'milestone':milestone,'slug':slug})\n\n@login_required\ndef task_details(request,slug,milestone_slug,task_id):\n task = Ticket.objects.get(id=task_id)\n return render(request,'task/Task_detail.html',{'task':task,'slug':slug})\n \n\n@login_required\ndef task_comment(request,slug,task_id):\n project = Project.objects.get(slug=slug,organization=request.user.organization)\n task = Ticket.objects.get(id=task_id)\n form = CommentForm(request.POST,task=task,user=request.user,project=project)\n\n if form.is_valid():\n comment = form.save()\n if request.GET.get('parent_id',False):\n comment.parent_id = request.GET.get('parent_id')\n if request.FILES.get('file'):\n attachment = Attachment.objects.create(uploaded_by=request.user,attached_file=request.FILES.get('file'),project=project)\n comment.attachments.add(attachment)\n comment.save()\n return HttpResponse(render_to_response('task/partials/comment_add.html',{'comment':comment,'slug':slug}))\n else:\n return HttpResponse(json.dumps({'error':True,'errors':form.errors}), content_type=\"json/application\")\n\n@login_required\ndef delete_attachment(request,slug,attachment_id):\n attach = Attachment.objects.get(id=attachment_id,project__slug=slug)\n try:\n shutil.rmtree(os.path.abspath(os.path.join(attach.attached_file.path, os.pardir)))\n attach.delete()\n except OSError as e:\n pass\n return HttpResponse(json.dumps({'result':True}), content_type=\"json/application\")\n\n@login_required\ndef milestone_create(request, slug):\n if request.method == 'POST':\n json_data = {}\n milestone_dict = request.POST.copy()\n project_id = Project.objects.get(slug = slug).id\n milestone_dict['project'] = project_id\n milestone_form = MilestoneForm(request.user, milestone_dict)\n if milestone_form.is_valid():\n milestone_form.save()\n json_data['error'] = False\n return HttpResponse(json.dumps(json_data), content_type = 'application/json')\n else:\n json_data['error'] = True\n json_data['form_errors'] = milestone_form.errors\n return HttpResponse(json.dumps(json_data), content_type = 'application/json')\n else:\n return render(request, 'project/milestone.html')\n\n\n@login_required\ndef milestone_edit(request, slug):\n milestone_obj = Milestone.objects.get(slug = slug)\n if request.method == 'POST':\n json_data = {}\n milestone_dict = request.POST.copy()\n project_id = milestone_obj.project.id\n milestone_dict['project'] = project_id\n milestone_form = MilestoneForm(request.user, milestone_dict, instance = milestone_obj)\n if milestone_form.is_valid():\n milestone_form.save()\n json_data['error'] = False\n return HttpResponse(json.dumps(json_data), content_type = 'application/json')\n else:\n json_data['error'] = True\n json_data['form_errors'] = milestone_form.errors\n return HttpResponse(json.dumps(json_data), content_type = 'application/json')\n else:\n return render(request, 'project/milestone.html', {'milestone_obj': milestone_obj})\n\n\n@login_required\ndef milestone_delete(request, slug):\n Milestone.objects.get(slug = slug).delete()\n return HttpResponse(json.dumps({'error': False}))\n\n\n@login_required\ndef project_edit(request, slug):\n milestone_list = Milestone.objects.all()\n project_obj = Project.objects.get(slug = slug)\n member_dict = {}\n for member_iter in project_obj.members.all():\n member_dict[member_iter.email] = [role.name for role in member_iter.user_roles.all()]\n return render(request, 'project/project_edit.html', {'milestone_list': milestone_list, 'member_dict': member_dict, 'project_slug': slug})\n\n\n@login_required\ndef requirement_create(request, slug):\n project_obj = Project.objects.get(slug=slug)\n if request.POST:\n json_data = {}\n requirement_form = RequirementForm(request.POST)\n if requirement_form.is_valid():\n name = request.POST.get('name')\n milestone_obj = Milestone.objects.get(id=request.POST.get('milestone'))\n Requirement.objects.create(name=name, slug=name, description=request.POST.get('description'), project=project_obj, milestone=milestone_obj)\n json_data['error'] = False\n return HttpResponse(json.dumps(json_data), content_type='application/json')\n else:\n json_data['error'] = True\n json_data['form_errors'] = requirement_form.errors\n return HttpResponse(json.dumps(json_data), content_type='application/json')\n else:\n milestone = project_obj.milestones.all()\n return render(request, 'project/requirement.html', {'milestone': milestone})\n","sub_path":"project/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":20943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"436523131","text":"import os\nimport xlwt\n\ndef extract_info(path):\n with open(path+'/'+'OSZICAR','r') as oszicar:\n content_1 = oszicar.readlines()\n energy_list = [i1 for i1 in content_1 if 'F' in i1][-1].strip().split()\n step = int(energy_list[0])\n gE = float(energy_list[2])\n with open(path+'/'+'OUTCAR','r') as outcar:\n content_2 = outcar.readlines()\n gF = float([i2 for i2 in content_2 if 'RMS' in i2][-1].strip().split()[4])\n if 'fort.188' in os.listdir(path):\n dis = float([i3 for i3 in content_2 if 'dis' in i3][-1].strip().split()[3])\n else:\n dis = 'not TS'\n path = '/'.join(path.split('/')[4:])\n return path,gF,gE,step,dis\n\ndirect_path = os.getcwd()\nexcel_sheet_name = direct_path.split('/')[-1]\ndir_list = os.walk(direct_path)\ndata = xlwt.Workbook()\ntable = data.add_sheet(excel_sheet_name)\ntable.write(0,0,'Path')\ntable.write(0,1,'Force')\ntable.write(0,2,'Energy')\ntable.write(0,3,'Steps')\ntable.write(0,4,'TS distance')\n\ni = 0\nfor sub_index in dir_list:\n work_dir = sub_index[0]\n content_list = sub_index[2]\n i+=1\n if 'OUTCAR' in content_list and 'OSZICAR' in content_list:\n info = extract_info(work_dir)\n for j in range(len(info)):\n table.write(i,j,info[j])\ndata.save(direct_path+'.xls')\n","sub_path":"everyday/ex/cbb/day56/all_walk.py","file_name":"all_walk.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"630553865","text":"import wx\r\n\r\nfrom Kernel import Module\r\nfrom icons import icons8_usb_connector_50\r\n\r\n_ = wx.GetTranslation\r\n\r\n\r\nclass UsbConnect(wx.Frame, Module):\r\n def __init__(self, parent, *args, **kwds):\r\n # begin wxGlade: Terminal.__init__\r\n wx.Frame.__init__(self, parent, -1, \"\",\r\n style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT | wx.TAB_TRAVERSAL)\r\n Module.__init__(self)\r\n self.SetSize((915, 424))\r\n self.text_main = wx.TextCtrl(self, wx.ID_ANY, \"\", style=wx.TE_BESTWRAP | wx.TE_MULTILINE | wx.TE_READONLY)\r\n self.text_entry = wx.TextCtrl(self, wx.ID_ANY, \"\", style=wx.TE_PROCESS_ENTER | wx.TE_PROCESS_TAB)\r\n\r\n self.__set_properties()\r\n self.__do_layout()\r\n\r\n self.Bind(wx.EVT_TEXT_ENTER, self.on_entry, self.text_entry)\r\n # end wxGlade\r\n self.Bind(wx.EVT_CLOSE, self.on_close, self)\r\n self.pipe = None\r\n\r\n # OSX Window close\r\n if parent is not None:\r\n parent.accelerator_table(self)\r\n\r\n def on_close(self, event):\r\n if self.state == 5:\r\n event.Veto()\r\n else:\r\n self.state = 5\r\n self.device.close('window', self.name)\r\n event.Skip() # Call destroy as regular.\r\n\r\n def initialize(self, channel=None):\r\n self.device.close('window', 'UsbConnect')\r\n self.Show()\r\n self.device.add_watcher('usb', self.update_text)\r\n\r\n def finalize(self, channel=None):\r\n self.device.remove_watcher('usb', self.update_text)\r\n try:\r\n self.Close()\r\n except RuntimeError:\r\n pass\r\n\r\n def shutdown(self, channel=None):\r\n try:\r\n self.Close()\r\n except RuntimeError:\r\n pass\r\n\r\n def update_text(self, text):\r\n if not wx.IsMainThread():\r\n wx.CallAfter(self.update_text_gui, text + '\\n')\r\n else:\r\n self.update_text_gui(text + '\\n')\r\n\r\n def update_text_gui(self, text):\r\n try:\r\n self.text_main.AppendText(text)\r\n except RuntimeError:\r\n pass\r\n\r\n def __set_properties(self):\r\n _icon = wx.NullIcon\r\n _icon.CopyFromBitmap(icons8_usb_connector_50.GetBitmap())\r\n self.SetIcon(_icon)\r\n # begin wxGlade: Terminal.__set_properties\r\n self.SetTitle(_('UsbConnect'))\r\n self.text_entry.SetFocus()\r\n # end wxGlade\r\n\r\n def __do_layout(self):\r\n # begin wxGlade: Terminal.__do_layout\r\n sizer_2 = wx.BoxSizer(wx.VERTICAL)\r\n sizer_2.Add(self.text_main, 20, wx.EXPAND, 0)\r\n sizer_2.Add(self.text_entry, 1, wx.EXPAND, 0)\r\n self.SetSizer(sizer_2)\r\n self.Layout()\r\n # end wxGlade\r\n\r\n def on_entry(self, event): # wxGlade: Terminal.\r\n if self.pipe is not None:\r\n self.pipe.write(self.text_entry.GetValue() + \"\\n\")\r\n self.text_entry.SetValue('')\r\n event.Skip()\r\n","sub_path":"UsbConnect.py","file_name":"UsbConnect.py","file_ext":"py","file_size_in_byte":2950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"579259006","text":"import tensorflow as tf\nimport os\n\nclass Network:\n def __init__(self):\n self.x_train = None\n self.y_train = None\n self.x_test = None\n self.y_test = None\n self.model = None\n\n def load_datas(self):\n self.mnist = tf.keras.datasets.mnist\n\n def prepare_data(self):\n (self.x_train, self.y_train), (self.x_test, self.y_test) = self.mnist.load_data()\n self.x_train, self.x_test = self.x_train / 255.0, self.x_test / 255.0\n\n\n\n def create_model(self):\n model = tf.keras.Sequential([\n tf.keras.layers.Flatten(input_shape=(28, 28)),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(10, activation='softmax')\n ])\n\n model.compile(\n optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\n #model.fit(self.x_train, self.y_train, epochs=5)\n #model.evaluate(self.x_test, self.y_test)\n return model\n\n def train_model_and_save_checkpoint(self):\n checkpoint_path = \"training_dir/cp.ckpt\"\n checkpoint_dir = os.path.dirname(checkpoint_path)\n\n # Checkpoint callback\n cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path,\n save_weights_only=True,\n verbose=1)\n\n model = self.create_model()\n\n model.fit(self.x_train, self.y_train, epochs=5,\n callbacks = [cp_callback])\n\n # Test accuracy\n loss, acc = model.evaluate(self.x_test, self.y_test)\n\n model.save('mnist.h5')\n\n print(\"Accuracy: {:5.2f}\".format(100*acc))\n\n\nif __name__ == '__main__':\n network = Network()\n\n network.load_datas()\n network.prepare_data()\n network.train_model_and_save_checkpoint()\n","sub_path":"NN/mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"135403898","text":"from django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render, render_to_response, RequestContext\nfrom django.contrib.auth import logout\nfrom django.template import Context\nfrom arbeider.forms import * \nfrom arbeider.models import *\n\ndef home(request):\n \n\tvariables = Context({'user':request.user})\n\treturn render_to_response('home.html', variables)\n\ndef register(request):\n\treturn render_to_response(\"register.html\") \n\ndef logout_page(request):\n\tlogout(request)\n\treturn HttpResponseRedirect('/')\n\ndef register_page(request):\n\tif request.method == 'POST':\n\t\tform = RegistrationForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tuser = User.objects.create_user(\n\t\t\t\tusername=form.cleaned_data['username'], \n\t\t\t\tpassword=form.cleaned_data['password1'],\n\t\t\t\temail=form.cleaned_data['email'])\n\t\t\treturn HttpResponseRedirect('/register/success')\n\telse:\n\t\tform = RegistrationForm() \n\t\tvariables = RequestContext(request, { \n\t\t\t'form':form\n\t\t\t})\n\t\treturn render_to_response('registration/register.html',variables)\n\n\ndef job(request, offset):\n\tif request.method == 'GET':\n\t\tif Job.objects.get(id=offset):\n\t\t\tjob = Job.objects.get(id=offset) \n\t\t\tvariables = {'job':job} \n\t\t\treturn\trender_to_response('job.html', variables)\n","sub_path":"arbeid/arbeider/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"81538925","text":"# Author: Kendra Andersen\n# Huff Research Group\n# Created: 11/26/17\n\n# This file, data_creation.py, provides a set of functions used to create a RF\n# environment test dataset. \n\n# Friis Transmission Equation with decibels is \n# P_r = P_t + D_t + D_r + 20*log(lambda/(4*pi*d))\n# \tP_r is power at the receiver in dB\n# \tP_t is power delivered to the terminals of the transmitter in dB\n# \tD_t is the directivity of the transmitter in dBi\n#\tD_r is the directivity of the receiver in dBi\n#\tlambda is the wavelength of the receiver\n#\td is the distance between the antennas\n# For reference: https://en.wikipedia.org/wiki/Friis_transmission_equation\n\n# This code will generate a dataset of P_r given the location of the transmitter\n# Assumptions: \n#\t- P_t = 0\n#\t- D_t = 0 (omnidirectional transmitter)\n#\t- D_r = 0 (omnidirectional receiver)\n# Thus Friis simplifies to:\n# P_r = 20*log(lambda/(4*pi*d))\n\n# Import libraries\nfrom math import *\nimport matplotlib.pyplot as plt \nimport matplotlib as mpl\nimport numpy as np\n\n# This function takes one transmitter's location in a grid of width x_max\n# and height y_max, then computes received power at all points for a \n# particular wavelength\ndef received_power_grid(wavelength, xy_max, xy_transmit):\n\tX = np.arange(0,xy_max[0],1)\n\tY = np.arange(0,xy_max[1],1)\n\tX, Y = np.meshgrid(X, Y)\n\td = np.sqrt((xy_transmit[0]-X)**2 + (xy_transmit[1]-Y)**2)\n\tP_r = np.log10(wavelength/(4*pi*d))*20\n\tbools = np.isinf(P_r)\n\tfor xindex,yrow in enumerate(bools): \n\t\tfor yindex,b in enumerate(yrow): \n\t\t\tif b == True: \n\t\t\t\tP_r[xindex][yindex] = 0\n\treturn P_r\n\n# This function takes the output from received_power_grid and plots it\n# in a figure as numbered. \ndef plot_received_power(received_power, n=1): \n\tplt.figure(n)\n\tcolors = ['purple','red','orange','yellow','yellowgreen','green','green','black']\n\tcmap = mpl.colors.LinearSegmentedColormap.from_list('my_colormap', colors, 256)\n\timg = plt.imshow(received_power, interpolation='nearest', cmap=cmap, origin='lower')\n\tplt.colorbar(img, cmap=cmap, label='Received Power (dB)')\n\tplt.ylabel('Y Coordinate (m)')\n\tplt.xlabel('X Coordinate (m)')\n\ndef plot_rss_ratio(rss, n=1):\n\tplt.figure(n)\n\tcolors = ['black','green','green','yellowgreen','yellow','orange','red','purple']\n\tcmap = mpl.colors.LinearSegmentedColormap.from_list('my_colormap', colors, 256)\n\timg = plt.imshow(rss, interpolation='nearest', cmap=cmap, origin='lower')\n\tplt.colorbar(img, cmap=cmap, label='SNR (dB/dB)')\n\tplt.ylabel('Y Coordinate (m)')\n\tplt.xlabel('X Coordinate (m)')\n\n# This function takes the output from received_power_grid and a series\n# of (x,y) coordinates and returns an array of received_power over the \n# path traced by the coordinates.\n# The coordinates must describe vertical or horizontal path segments.\ndef received_power_over_path(received_power, xy_coords): \n\tpath_power = []\n\tfor i in range(0, len(xy_coords) - 1): \n\t\t# if horizontal path\n\t\tif xy_coords[i+1][0] != xy_coords[i][0]:\n\t\t\tstep_size_x = 1 if xy_coords[i+1][0]>xy_coords[i][0] else -1\n\t\t\tfor x in range(0, xy_coords[i+1][0]-xy_coords[i][0], step_size_x):\n\t\t\t\tpath_power.append(received_power[xy_coords[i][1],xy_coords[i][0]+x])\n\t\t# if vertical path\n\t\tif xy_coords[i+1][1] != xy_coords[i][1]:\n\t\t\tstep_size_y = 1 if xy_coords[i+1][1]>xy_coords[i][1] else -1\n\t\t\tfor y in range(0, xy_coords[i+1][1]-xy_coords[i][1], step_size_y):\n\t\t\t\tpath_power.append(received_power[xy_coords[i][1]+y,xy_coords[i][0]])\n\treturn path_power\n\n# This function takes a path, set of transmitters, the received power from the\n# transmitters, a plot title, and figure number, and plots the received\n# power curves from each transmitter as well as returning the average RSS from\n# each transmitter over the specified path. \ndef plot_power_over_path(path, Transmitters, received_power, title='Received Power over Specified Path', n=1, plot_on=1, ylim=[0,0]):\n\tpath_power = [None]*len(Transmitters)\n\tpath_rss = [None]*len(Transmitters)\n\tif plot_on == 1: \n\t\tplt.figure(n)\n\t\tlegend = [None]*len(Transmitters)\n\tfor i, transmitter in enumerate(Transmitters):\n\t\tpath_power[i] = received_power_over_path(received_power[i], path)\n\t\tif plot_on == 1: \n\t\t\tplt.plot(path_power[i])\n\t\t\tlegend[i] = str(transmitter)\n\t\tpath_rss[i] = sum(path_power[i]*1)/len(path_power[i])\n\tif plot_on == 1: \n\t\tplt.legend(legend, title='Transmitters at:')\n\t\tplt.title(title)\n\t\tplt.ylabel('Received Power (dB)')\n\t\tplt.xlabel('Distange Along Path (m)')\n\t\tif ylim != [0,0]:\n\t\t\tplt.gca().set_ylim(ylim)\n\treturn path_power, path_rss\n\n# This function takes a list of paths and the power of various transmitters\n# over the path. It then plots the ratio of good power/bad power for each\n# point on the paths. \ndef plot_ratio_over_paths(paths, path_powers, good_index, bad_index, n=1):\n\tplt.figure(n)\n\tlegend = [None]*len(paths)\n\tfor i, path in enumerate(paths):\n\t\tratio = np.array(path_powers[i][good_index])/np.array(path_powers[i][bad_index])\n\t\tplt.plot(ratio)\n\t\tlegend[i] = 'Path '+str(i+1)\n\tplt.title('SNR Over Specified Paths')\n\tplt.ylabel('Signal/Noise Ratio')\n\tplt.xlabel('Distance Along Path (m)')\n\tplt.legend(legend)","sub_path":"KendraAndersen/Code/Restart/data_creation.py","file_name":"data_creation.py","file_ext":"py","file_size_in_byte":5074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"259657717","text":"import tensorflow as tf\r\nfrom tensorflow.python.keras import models\r\nfrom tensorflow.python.keras import losses\r\nfrom tensorflow.keras.optimizers import Adam\r\n\r\nfrom network_3d import build_unet_3d\r\n\r\n\r\ndef dice_coeff(y_true, y_pred):\r\n smooth = 1\r\n # Flatten\r\n y_true_f = tf.reshape(y_true, [-1])\r\n y_pred_f = tf.reshape(y_pred, [-1])\r\n intersection = tf.reduce_sum(y_true_f * y_pred_f)\r\n score = (2. * intersection + smooth) / (tf.reduce_sum(y_true_f) + tf.reduce_sum(y_pred_f) + smooth)\r\n return score\r\n\r\n\r\ndef dice_loss(y_true, y_pred):\r\n loss = 1 - dice_coeff(y_true, y_pred)\r\n return loss\r\n\r\n\r\ndef bce_dice_loss(y_true, y_pred):\r\n loss = losses.binary_crossentropy(y_true, y_pred) + dice_loss(y_true, y_pred)\r\n return loss\r\n\r\n\r\ndef cce_dice_loss(y_true, y_pred):\r\n loss = losses.categorical_crossentropy(y_true, y_pred) + dice_loss(y_true, y_pred)\r\n return loss\r\n\r\n\r\ndef soft_dice(y_true, y_pred):\r\n # y_pred is softmax output of shape (num_samples, num_classes)\r\n # y_true is one hot encoding of target (shape= (num_samples, num_classes))\r\n y_true = tf.reshape(y_true, [-1])\r\n y_pred = tf.reshape(y_pred, [-1])\r\n intersect = tf.reduce_sum(y_true * y_pred, axis=0)\r\n denominator = tf.reduce_sum(y_pred, axis=0) + tf.reduce_sum(y_true, axis=0)\r\n dice_scores = (2. * intersect) / (denominator + 1e-6)\r\n return dice_scores\r\n\r\n\r\ndef soft_dice_coeff(y_true, y_pred):\r\n return tf.reduce_mean(soft_dice(y_true, y_pred))\r\n\r\n\r\ndef hard_dice(y_true, y_pred, class_value):\r\n # y_true must be label map, not one hot encoding\r\n y_true = tf.argmax(y_true, axis=-1)\r\n y_pred = tf.argmax(y_pred, axis=-1)\r\n\r\n y_true = tf.reshape(y_true, [-1])\r\n y_pred = tf.reshape(y_pred, [-1])\r\n\r\n y_true_val = tf.cast(tf.math.equal(y_true, class_value), tf.float32)\r\n y_pred_val = tf.cast(tf.math.equal(y_pred, class_value), tf.float32)\r\n\r\n return (2. * tf.reduce_sum(y_true_val * y_pred_val) + 1e-7) / (tf.reduce_sum(y_true_val) + tf.reduce_sum(y_pred_val) + 1e-7)\r\n\r\n\r\ndef hard_dice_0(y_true, y_pred):\r\n return hard_dice(y_true, y_pred, 0)\r\n\r\n\r\ndef hard_dice_1(y_true, y_pred):\r\n return hard_dice(y_true, y_pred, 1)\r\n\r\n\r\ndef hard_dice_2(y_true, y_pred):\r\n return hard_dice(y_true, y_pred, 2)\r\n\r\n\r\ndef accuracy(y_true, y_pred):\r\n y_true = tf.argmax(y_true, axis=-1)\r\n y_pred = tf.argmax(y_pred, axis=-1)\r\n\r\n y_true = tf.reshape(y_true, [-1])\r\n y_pred = tf.reshape(y_pred, [-1])\r\n\r\n return tf.reduce_mean(tf.cast(tf.math.equal(y_true, y_pred), tf.float32))\r\n\r\n\r\ndef hard_dice_3(y_true, y_pred):\r\n return hard_dice(y_true, y_pred, 3)\r\n\r\n\r\ndef get_unet_3d(\r\n input_shape=(10, 224, 224, 1),\r\n num_filters=26,\r\n loss=cce_dice_loss,\r\n n_class=4,\r\n dropout=0.3\r\n):\r\n\r\n net, out = build_unet_3d(n_input_channels=input_shape[3], n_output_classes=n_class, input_dim=input_shape[0:3], base_n_filters=num_filters, dropout=dropout)\r\n\r\n model = models.Model(inputs=[net['input']], outputs=[out])\r\n model.compile(optimizer=Adam(learning_rate=0.0005), loss=loss, metrics=[dice_coeff, soft_dice_coeff, hard_dice_0, hard_dice_1, hard_dice_2, hard_dice_3])\r\n\r\n return model\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n SLICES = 10\r\n HEIGHT = 144\r\n WIDTH = 144\r\n N_CHANNELS = 1\r\n N_CLASSES = 4\r\n\r\n model = get_unet_3d(\r\n input_shape=(SLICES, HEIGHT, WIDTH, N_CHANNELS),\r\n n_class=N_CLASSES\r\n )\r\n model.summary()\r\n\r\n\r\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"75903194","text":"#!/usr/bin/env python3\n''' itsOrD | practicing taking user input '''\n\ndef main():\n '''main point of file'''\n name = input(f'''What's your name? ''')\n print(f'''Hi there {name.capitalize()}!''')\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"08Aug/inputb4lunch.py","file_name":"inputb4lunch.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"435431914","text":"from sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom nltk.corpus import stopwords\nfrom nltk.stem.wordnet import WordNetLemmatizer\nimport csv\nimport pandas as pd\nimport re\nimport nltk\nimport joblib\n\nnltk.download('punkt')\nnltk.download('wordnet')\nnltk.download('stopwords')\n\n\nclass Predictor:\n def __init__(self):\n self.model = joblib.load(\"my_pipeline.joblib\")\n self.tokeniser = nltk.tokenize.RegexpTokenizer(r'\\w+')\n self.lemmatizer = WordNetLemmatizer()\n self.stop_words = set(stopwords.words(\"english\"))\n # need to add title into this bitch\n\n def input_tokenisation(self, par):\n tmp = []\n if \"(Reuters) - \" in par:\n par = par.split(\" - \")[1]\n sentences = nltk.sent_tokenize(par)\n for sent in sentences:\n sent = sent.lower()\n tokens = self.tokeniser.tokenize(sent)\n filtered_words = [w.strip()\n for w in tokens if w not in self.stop_words and len(w) > 1]\n tmp.extend(filtered_words)\n tmp = [self.lemmatizer.lemmatize(j) for j in tmp]\n tmp = ','.join(tmp)\n return tmp\n\n def read_data(self, request):\n # might have to change this to accomendate the string\n data = []\n foo = self.input_tokenisation(request)\n data.append(foo)\n # data.append(request.form['title'])\n # data.append(request.form['body'])\n return data\n\n def predict(self, request):\n prediction = self.model.predict(self.read_data(request))\n return prediction\n","sub_path":"FinalProject/predictor.py","file_name":"predictor.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"549006468","text":"#!/usr/bin/env pypy\nimport sys\n\ndata = list(map(int, sys.stdin.read().split(\",\")))\nlast = {}\n\nprevious = None\nfor i in range(30 * 1000 * 1000):\n if i < len(data):\n answer = data[i]\n elif previous not in last:\n answer = 0\n else:\n answer = i - last[previous]\n last[previous] = i\n previous = answer\n\nprint(previous)\n","sub_path":"problems/day-15/part_2.py","file_name":"part_2.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"511116188","text":"\"\"\"\nImplement atoi which converts a string to an integer.\n\nThe function first discards as many whitespace characters as necessary until\nthe first non-whitespace character is found. Then, starting from this\ncharacter, takes an optional initial plus or minus sign followed by as many\nnumerical digits as possible, and interprets them as a numerical value.\n\nThe string can contain additional characters after those that form the integral\nnumber, which are ignored and have no effect on the behavior of this function.\n\nIf the first sequence of non-whitespace characters in str is not a valid\nintegral number, or if no such sequence exists because either str is empty or\nit contains only whitespace characters, no conversion is performed.\n\nIf no valid conversion could be performed, a zero value is returned.\n\nNote:\n\n Only the space character ' ' is considered as whitespace character.\n Assume we are dealing with an environment which could only store integers\n within the 32-bit signed integer range: [−2^31, 2^31 − 1]. If the\n numerical value is out of the range of representable values,\n INT_MAX (2^31 − 1) or INT_MIN (−2^31) is returned.\n\nExample 1:\n\nInput: \"42\"\nOutput: 42\n\nExample 2:\n\nInput: \" -42\"\nOutput: -42\nExplanation: The first non-whitespace character is '-',\n which is the minus sign.\n Then take as many numerical digits as possible, which gets 42.\n\nExample 3:\n\nInput: \"4193 with words\"\nOutput: 4193\nExplanation: Conversion stops at digit '3' as the next character is not a\n numerical digit.\n\nExample 4:\n\nInput: \"words and 987\"\nOutput: 0\nExplanation: The first non-whitespace character is 'w', which is not a\n numerical digit or a +/- sign.\n Therefore no valid conversion could be performed.\n\nExample 5:\n\nInput: \"-91283472332\"\nOutput: -2147483648\nExplanation: The number \"-91283472332\" is out of the range of a 32-bit signed\n integer. Therefore INT_MIN (−2^31) is returned.\n\nhttps://leetcode.com/problems/string-to-integer-atoi/\n\"\"\"\n\nMAX_INT = 2**31 - 1\nMIN_INT = -2**31\n\n\n# noinspection PyPep8Naming,PyMethodMayBeStatic,PyShadowingBuiltins\nclass Solution:\n def myAtoi(self, str):\n \"\"\"\n :type str: str\n :rtype: int\n \"\"\"\n trimmed = str.strip()\n for index, ch in enumerate(trimmed):\n if index == 0 and self.is_sign(ch):\n continue\n\n if not ch.isdigit():\n end = index\n break\n else:\n end = len(trimmed)\n\n num_str = trimmed[0:end]\n try:\n num = int(num_str)\n except ValueError:\n return 0\n\n if num < MIN_INT:\n return MIN_INT\n elif num > MAX_INT:\n return MAX_INT\n else:\n return num\n\n def is_sign(self, ch):\n return ch in ('+', '-')\n","sub_path":"python/src/leetcode/string_to_integer_atoi.py","file_name":"string_to_integer_atoi.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"273524246","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 20 23:44:24 2021\n\n@author: alex\n\"\"\"\n\nimport sys\nsys.path.append('../')\n\nimport pandas as pd\nfrom pylab import *\nimport os\nimport matplotlib.pyplot as plt\n# %matplotlib qt\ndatadir=sort(os.listdir(os.path.join(os.getcwd())))\ndatadir=np.setdiff1d(datadir,np.array([\"plot.py\"]))[-1]\ndata=pd.read_csv(os.path.join(os.getcwd(),datadir,'log.txt'))\n\nf,axes=plt.subplots(nrows=6,ncols=6)\n\nfor i,key in enumerate([i for i in data.keys() if i!=\"t\"]):\n \n cu_ax=axes.flatten()[i]\n cu_ax.plot(data['t'],data[key], label=key)\n cu_ax.grid()\n cu_ax.legend()\n\n if \"acc\" in key:\n cu_ax.set_ylim(-10,10)\n if \"speed\" in key:\n cu_ax.set_ylim(-50,50)\n if \"pos\" in key:\n cu_ax.set_ylim(-250,250)\n if \"omegadot\" in key:\n cu_ax.set_ylim(-100,100)\n if \"omega\" in key:\n cu_ax.set_ylim(-10,10)\n if \"q\" in key:\n cu_ax.set_ylim(-1,1)\n if \"forces\" in key:\n cu_ax.set_ylim(-450,450)\n if \"torque\" in key:\n cu_ax.set_ylim(-100,100)\n if \"alpha\" in key:\n cu_ax.set_ylim(-2,2)\n if \"joystick\" in key:\n cu_ax.set_ylim(min(data[key]), max(data[key]))\n\n \n","sub_path":"Logs/log_sim/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"226819329","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.contrib import admin\n\n# Register your models here.\n\nfrom .models import Question,Choice\n\nclass ChoiceInline(admin.TabularInline):\n\tmodel = Choice\n\textra = 3\n\nclass QuestionAdmin(admin.ModelAdmin):\n\tinlines = [ChoiceInline]\n\tlist_display=('question_text','pub_date', 'was_published_recently')\n\nadmin.site.register(Question, QuestionAdmin)\n","sub_path":"pools/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"346852905","text":"# Process pipeline draft\n# run with RETINANET: python process_all_video.py -v ../data/train_videos/ -m retinanet -w ../model/resnet50_sub1.h5.frozen\n# or with YOLOV4 python process_video.py -v ../data/train_videos/\n\nfrom yolotf_wrapper import yolov4_inference\nfrom retinanet_wrapper import retinanet_inference\nimport signate_sub\nfrom object_tracker import Tracker\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport argparse, time, os\n\ndef main():\n # Get parameters\n parser = argparse.ArgumentParser()\n parser.add_argument('-v', '--video_path', type=str, help='Path to video folder', dest='videos_path', default='../data/train_videos/')\n parser.add_argument('-w', '--weights', type=str, help='Path to weight.h5', dest='weight_path', default='yolov4.h5')\n parser.add_argument('-m', '--model', type=str, help='Model version', dest='model_arch', default='yolov4')\n parser.add_argument('-d', '--display', help='display frame', dest='display', action='store_const', const=True)\n parser.add_argument('-o', '--ouput', help='video output', dest='video_out', action='store_const', const=True)\n parser.set_defaults(display=False)\n parser.set_defaults(video_out=False)\n args = parser.parse_args()\n\n # Init model\n if args.model_arch == \"yolov4\":\n print(\"Detection backend running YOLO\")\n model = yolov4_inference(args.weight_path)\n else:\n # Set retinanet_inference_wrapper here\n print(\"Detection backend running RETINANET\")\n model = retinanet_inference(args.weight_path)\n\n # Prepare for submittion\n signate_output = signate_sub.signate_submission(model.classes_list)\n\n ## Main process loop:\n # Extract video list:\n start_time = time.time()\n list_of_videos = os.listdir(args.videos_path)\n for video in list_of_videos:\n video_name = video\n video_full_path = args.videos_path + video\n\n # Load video\n cap = cv2.VideoCapture(video_full_path)\n w = cap.get(cv2.CAP_PROP_FRAME_WIDTH)\n h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)\n\n if args.video_out:\n out = cv2.VideoWriter('output.mp4', cv2.VideoWriter_fourcc(*'mp4v'), 15.0, (int(w), int(h)))\n\n # Init Tracker\n tracker = Tracker((w, h))\n\n ret = True\n while ret:\n prev_time = time.time()\n ret, frame = cap.read()\n\n try:\n # Detection\n boxes, scores, classes_pred, pred_detection = model.detect(frame)\n print(\"\\nInference time: {} ms.\".format(round(1/(time.time()-prev_time), 3)))\n print(\"pred_detection: {}\".format(pred_detection))\n\n # Tracking\n pred_tracking = tracker.assign_ids(pred_detection, frame)\n print(\"Tracking: {}\".format(pred_tracking))\n\n # Generate Signate format\n signate_output.add_frame(pred_tracking)\n\n # Display on frame\n signate_output.display_on_frame(frame, pred_tracking)\n if args.display:\n cv2.imshow('Demo', frame)\n cv2.waitKey(3)\n\n # Write output video\n if args.video_out:\n out.write(frame)\n\n except Exception as e:\n print(\"Unable to process frame: {}\".format(e))\n\n # Write video prediction to output file\n signate_output.write_video(video_name)\n\n # Save output\n cap.release()\n if args.video_out:\n print(\"Saving video output\")\n out.release()\n\n # Generate Submittion\n signate_output.write_submit()\n print(\"Processed all video {} in {}ms.\".format(len(list_of_videos), round(1/(time.time()-start_time), 3)))\n\nif __name__ == \"__main__\":\n main()","sub_path":"src/process_all_video.py","file_name":"process_all_video.py","file_ext":"py","file_size_in_byte":3765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"214130845","text":"from .Bash import Bash\nfrom Jumpscale import j\n\n\nclass BashFactory(j.baseclasses.object):\n\n __jslocation__ = \"j.tools.bash\"\n\n def _init(self, **kwargs):\n self._home = None\n self._sandbox = None\n\n @property\n def home(self):\n if not self._home:\n self._home = Bash()\n return self._home\n\n @property\n def sandbox(self):\n if not self._sandbox:\n self._sandbox = self.get(j.core.tools.text_replace(\"{DIR_BASE}\"))\n return self._sandbox\n\n def get(self, path=None, profile_name=None, executor=None):\n \"\"\"\n\n :param path: if None then will be '~' = Home dir\n :param executor:\n :param profile_name: if None will look for env.sh, .bash_profile, .bashrc, .profile in this order\n :return:\n \"\"\"\n return Bash(executor=executor, path=path, profile_name=profile_name)\n\n def test(self):\n \"\"\"\n kosmos 'j.tools.bash.test()'\n :return:\n \"\"\"\n\n bash = self.get(path=\"/tmp/\")\n p = bash.profile\n p.delete()\n\n assert p.paths == []\n\n p.path_add(\"/tmp/1/\", check_exists=False)\n\n assert p.paths == [\"/tmp/1\", \"/bin\", \"/sbin\", \"/usr/bin\", \"/usr/sbin\", \"/usr/local/bin\", \"/usr/local/sbin\"]\n p.path_add(\"/tmp/1/\", check_exists=False)\n assert p.paths == [\"/tmp/1\", \"/bin\", \"/sbin\", \"/usr/bin\", \"/usr/sbin\", \"/usr/local/bin\", \"/usr/local/sbin\"]\n p.path_add(\"/tmp/2\", end=True, check_exists=False)\n assert p.paths == [\n \"/tmp/1\",\n \"/tmp/2\",\n \"/bin\",\n \"/sbin\",\n \"/usr/bin\",\n \"/usr/sbin\",\n \"/usr/local/bin\",\n \"/usr/local/sbin\",\n ]\n\n assert p.env == {\"PATH\": \"/tmp/1:/tmp/2:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin\"}\n\n p.path_delete(\"/tmp/1\")\n\n assert p.env == {\"PATH\": \"/tmp/2:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin\"}\n\n p.env_set_part(\"TEST\", \"A\", 1)\n\n p.env_set_part(\"TEST\", \"A\")\n p.env_set_part(\"TEST\", \"B\")\n\n assert p.env == {\"PATH\": \"/tmp/2:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin\", \"TEST\": \"B:A\"}\n\n self._log_info(\"TEST FOR j.tools.bash is OK\")\n","sub_path":"JumpscaleCore/tools/bash/BashFactory.py","file_name":"BashFactory.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"297022517","text":"# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.\n#\n#Licensed under the Apache License, Version 2.0 (the \"License\");\n#you may not use this file except in compliance with the License.\n#You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n#Unless required by applicable law or agreed to in writing, software\n#distributed under the License is distributed on an \"AS IS\" BASIS,\n#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#See the License for the specific language governing permissions and\n#limitations under the License.\n\nimport os\nimport sys\nimport argparse\nimport ast\nimport logging\nimport numpy as np\nimport paddle.fluid as fluid\nfrom paddle.fluid.dygraph.base import to_variable\nfrom paddle.io import DataLoader, Dataset, DistributedBatchSampler\nfrom paddle.hapi.model import _all_gather\nfrom paddle.fluid.dygraph.parallel import ParallelEnv\n\nfrom model import *\nfrom config_utils import *\nfrom kinetics_dataset import KineticsDataset\n\nlogging.root.handlers = []\nFORMAT = '[%(levelname)s: %(filename)s: %(lineno)4d]: %(message)s'\nlogging.basicConfig(level=logging.INFO, format=FORMAT, stream=sys.stdout)\nlogger = logging.getLogger(__name__)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n \"SLOWFAST test for performance evaluation.\")\n parser.add_argument(\n '--config_file',\n type=str,\n default='slowfast.yaml',\n help='path to config file of model')\n parser.add_argument(\n '--batch_size',\n type=int,\n default=None,\n help='total eval batch size of all gpus.')\n parser.add_argument(\n '--use_gpu',\n type=ast.literal_eval,\n default=True,\n help='default use gpu.')\n parser.add_argument(\n '--use_data_parallel',\n type=ast.literal_eval,\n default=True,\n help='default use data parallel.')\n parser.add_argument(\n '--weights',\n type=str,\n default=None,\n help='Weight path, None to use config setting.')\n parser.add_argument(\n '--log_interval',\n type=int,\n default=1,\n help='mini-batch interval to log.')\n args = parser.parse_args()\n return args\n\n\n# Performance Evaluation\ndef test_slowfast(args):\n config = parse_config(args.config_file)\n test_config = merge_configs(config, 'test', vars(args))\n print_configs(test_config, \"Test\")\n\n if not args.use_gpu:\n place = fluid.CPUPlace()\n elif not args.use_data_parallel:\n place = fluid.CUDAPlace(0)\n else:\n place = fluid.CUDAPlace(fluid.dygraph.parallel.Env().dev_id)\n\n _nranks = ParallelEnv().nranks # num gpu\n bs_single = int(test_config.TEST.batch_size /\n _nranks) # batch_size of each gpu\n\n with fluid.dygraph.guard(place):\n #build model\n slowfast = SlowFast(cfg=test_config, num_classes=400)\n if args.weights:\n assert os.path.exists(args.weights + '.pdparams'),\\\n \"Given weight dir {} not exist.\".format(args.weights)\n\n logger.info('load test weights from {}'.format(args.weights))\n model_dict, _ = fluid.load_dygraph(args.weights)\n slowfast.set_dict(model_dict)\n\n if args.use_data_parallel:\n strategy = fluid.dygraph.parallel.prepare_context()\n slowfast = fluid.dygraph.parallel.DataParallel(\n slowfast, strategy, find_unused_parameters=False)\n\n #create reader\n test_data = KineticsDataset(mode=\"test\", cfg=test_config)\n test_sampler = DistributedBatchSampler(\n test_data, batch_size=bs_single, shuffle=False, drop_last=False)\n test_loader = DataLoader(\n test_data,\n batch_sampler=test_sampler,\n places=place,\n feed_list=None,\n num_workers=8,\n return_list=True)\n\n # start eval\n num_ensemble_views = test_config.TEST.num_ensemble_views\n num_spatial_crops = test_config.TEST.num_spatial_crops\n num_cls = test_config.MODEL.num_classes\n num_clips = num_ensemble_views * num_spatial_crops\n num_videos = len(test_data) // num_clips\n video_preds = np.zeros((num_videos, num_cls))\n video_labels = np.zeros((num_videos, 1), dtype=\"int64\")\n clip_count = {}\n\n print(\n \"[EVAL] eval start, number of videos {}, total number of clips {}\".\n format(num_videos, num_clips * num_videos))\n slowfast.eval()\n for batch_id, data in enumerate(test_loader):\n # call net\n model_inputs = [data[0], data[1]]\n preds = slowfast(model_inputs, training=False)\n labels = data[2]\n clip_ids = data[3]\n\n # gather mulit card, results of following process in each card is the same.\n if _nranks > 1:\n preds = _all_gather(preds, _nranks)\n labels = _all_gather(labels, _nranks)\n clip_ids = _all_gather(clip_ids, _nranks)\n\n # to numpy\n preds = preds.numpy()\n labels = labels.numpy().astype(\"int64\")\n clip_ids = clip_ids.numpy()\n\n # preds ensemble\n for ind in range(preds.shape[0]):\n vid_id = int(clip_ids[ind]) // num_clips\n ts_idx = int(clip_ids[ind]) % num_clips\n if vid_id not in clip_count:\n clip_count[vid_id] = []\n if ts_idx in clip_count[vid_id]:\n print(\n \"[EVAL] Passed!! read video {} clip index {} / {} repeatedly.\".\n format(vid_id, ts_idx, clip_ids[ind]))\n else:\n clip_count[vid_id].append(ts_idx)\n video_preds[vid_id] += preds[ind] # ensemble method: sum\n if video_labels[vid_id].sum() > 0:\n assert video_labels[vid_id] == labels[ind]\n video_labels[vid_id] = labels[ind]\n if batch_id % args.log_interval == 0:\n print(\"[EVAL] Processing batch {}/{} ...\".format(\n batch_id, len(test_data) // test_config.TEST.batch_size))\n\n # check clip index of each video\n for key in clip_count.keys():\n if len(clip_count[key]) != num_clips or sum(clip_count[\n key]) != num_clips * (num_clips - 1) / 2:\n print(\n \"[EVAL] Warning!! video [{}] clip count [{}] not match number clips {}\".\n format(key, clip_count[key], num_clips))\n\n video_preds = to_variable(video_preds)\n video_labels = to_variable(video_labels)\n acc_top1 = fluid.layers.accuracy(\n input=video_preds, label=video_labels, k=1)\n acc_top5 = fluid.layers.accuracy(\n input=video_preds, label=video_labels, k=5)\n print('[EVAL] eval finished, avg_acc1= {}, avg_acc5= {} '.format(\n acc_top1.numpy(), acc_top5.numpy()))\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n logger.info(args)\n test_slowfast(args)\n","sub_path":"dygraph/slowfast/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":7109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"274962092","text":"''' Program make an abstract calculator '''\nimport math\n\n# This function adds two numbers \ndef add(x, y):\n return x + y\n\n# This function subtracts two numbers \ndef subtract(x, y):\n return x - y\n\n# This function multiplies two numbers\ndef multiply(x, y):\n return x * y\n\n# This function divides two numbers\ndef divide(x, y):\n return x / y\n\n# Takes the square of a number\ndef square(x):\n return x * x\n\n# Gets a number to a certain power\ndef power(x, y):\n num = 1\n for i in range(y):\n num *= x\n i = i + 1\n return num\n\n# Gets the remaining value\ndef remainder(x, y):\n return x % y\n\n# Gets the square root of a number\ndef root(x):\n return x ** (0.5)\n\n# Get the number in Scientific Notation\ndef science_notation(x,y):\n num = x * 10**y\n return num\n\n## AREA FORMULAS ##\n#Area of A Square\ndef squarea(x):\n return square(x)\n\n#Area of a Rectangle\ndef rectarea(x, y):\n return multiply(x, y)\n\n#Area of a triangle with 2 sides\ndef triarea(x, y):\n return 0.5 * multiply(x, y)\n\n#Area of triangle with all 3 sides\ndef side_triarea(a, b, c):\n N = (a + b + c)/2\n num = (N - a)*(N - b)*(N - c)\n value = N*num\n return root(value)\n\n#Area of a trapezoid\ndef trapezarea(x, y, z):\n n = (x + y)/2\n return multiply(n, z)\n\n#Area of Circle\ndef cirlerea(x):\n return math.pi * square(x)\n\n##CIRCUMFERENCE##\ndef circumrad(x):\n return math.pi * (x**2)\n\ndef circumdi(x):\n return math.pi * x\n\n##TRIGNOMETRY##:\ndef sine_for_sides(x,y,z):\n a = y/math.sin(y)\n value = a * math.sin(x)\n return value\n\ndef cos_for_sides(x,y,z):\n num = (y**2) + (z**2) - (2*y*z)*math.cos(x)\n return num\n\ndef sine_for_angles(x,y):\n a = math.sin(y)/y\n b = a * x\n num = math.asin(b)\n return num * 100\n\ndef cos_for_angles(x,y,z):\n num = (y**2) + (z**2) - (x**2)\n return (num / (2 * y * z)) * 100\n\n\n## CALCULATOR ##\nprint(\"Select operation.\")\nprint(\"1.Add\")\nprint(\"2.Subtract\")\nprint(\"3.Multiply\")\nprint(\"4.Divide\")\nprint(\"5.Square\")\nprint(\"6.Power\")\nprint(\"7.Remainder\")\nprint(\"8.Root\")\nprint(\"9.Scientific Notation\")\nprint(\"10.Area\")\nprint(\"11.Trignometry\")\n\n# Take input from the user \nchoice = input(\"Enter choice(1/2/3/4/5/6/7/8/9/10/11):\")\nnum1 = int(input(\"Enter first number: \"))\nnum2 = int(input(\"Enter second number: \"))\n\nif choice == '1':\n print(num1,\"+\",num2,\"=\", add(num1,num2))\n\nelif choice == '2':\n print(num1,\"-\",num2,\"=\", subtract(num1,num2))\n\nelif choice == '3':\n print(num1,\"*\",num2,\"=\", multiply(num1,num2))\n\nelif choice == '4':\n print(num1,\"/\",num2,\"=\", divide(num1,num2))\n\nelif choice == '5':\n print(num1,\"*\", num1, \"=\", square(num1))\n\nelif choice == '6':\n print(num1,\"**\",num2,\"=\", power(num1,num2))\n\nelif choice == '7':\n print(num1,\"%\",num2,\"=\", remainder(num1,num2))\n\nelif choice == '8':\n print(num1,\"**(1/2)**\", \"=\", root(num1))\n\nelif choice == '9':\n print(num1,\"e\",num2,\"=\", science_notation(num1,num2))\n\nelif choice == '10':\n print(\"1.Square\")\n print(\"2.Rectangle\")\n print(\"3.Triangle\")\n print(\"4.Sides of Triangle\")\n print(\"5.Trapezoid\")\n print(\"6.Circle\")\n area_choices = input(\"Enter choice(1/2/3/4/5/6):\")\n if area_choices == '1':\n print(squarea(num1))\n elif area_choices == \"2\":\n print(rectarea(num1, num2))\n elif area_choices == \"3\":\n print(triarea(num1, num2))\n elif area_choices == \"4\":\n num3 = int(input(\"Enter third number: \"))\n print(side_triarea(num1, num2, num3))\n elif area_choices == \"5\":\n num3 = int(input(\"Enter third number: \"))\n print(trapezarea(num1, num2, num3))\n elif area_choices == \"6\":\n print(cirlerea(num1))\n\nelif choice == '11':\n print(\"1. Find Sides\")\n print(\"2. Find Angles\")\n num3 = int(input(\"Enter third number: \"))\n options = input(\"Enter choice(1/2):\")\n if options == '1':\n print(\"1.Sine\")\n print(\"2.Cosine\")\n trig_choices= input(\"Enter choice(1/2):\")\n if trig_choices == '1':\n print(sine_for_sides(num1, num2, num3))\n if trig_choices == '2':\n print(cos_for_sides(num1, num2, num3))\n elif options == '2':\n print(\"1.Sine\")\n print(\"2.Cosine\")\n angle_choices= input(\"Enter choice(1/2):\")\n if angle_choices == '1':\n print(sine_for_angles(num1, num2, num3))\n if angle_choices == '2':\n print(cos_for_angles(num1, num2, num3))\n\n \n\n","sub_path":"Calculator.py","file_name":"Calculator.py","file_ext":"py","file_size_in_byte":4329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"70715380","text":"##!/usr/bin/env python3 \n\nif True:\n import datetime\n import time\n import shlex, requests\n import logging\n from datetime import datetime\n import sys\n import os\n import RPi.GPIO as GPIO\n sys.path.append('/home/pi/droneponics')\n from AtlasI2C import (\n\t AtlasI2C\n )\n import blynklib\n import blynktimer\n \n import subprocess\n import re\n import drone\n\n\n\n # tune console logging\n _log = logging.getLogger('BlynkLog')\n logFormatter = logging.Formatter(\"%(asctime)s [%(levelname)s] %(message)s\")\n consoleHandler = logging.StreamHandler()\n consoleHandler.setFormatter(logFormatter)\n _log.addHandler(consoleHandler)\n _log.setLevel(logging.DEBUG)\n\n nutrientMix = []\n nutrientMix = drone.buildNutrientMix(nutrientMix, _log)\n\t\n\n answer = input(\"Are you sure you want to calibrate (y/n)\")\n if answer is None or answer != 'y':\n _log.info(\"User Exit\")\n quit()\n \n # Initialize the sensor.\n try:\n # Create the I2C bus\n for dosage in nutrientMix:\n dosage.pump = AtlasI2C(dosage.pumpId)\n _log.info(\"pump created\")\n except:\n _log.info(\"Unexpected error: Atlas\")\n else:\n try:\t\n _log.info(\"Try Use Pump\")\n for dosage in nutrientMix:\n if(dosage.pump is not None):\n answer = input(\"Are you sure you want to calibrate pump \" + dosage.name + \"(y/n to skip)\")\n if answer is None or answer != 'y':\n _log.info(\"User Exit\")\n continue\n answer = input(\"Going to dose 10ml of \" + dosage.name + \". Enter y when you are ready(y/n to skip)\")\n if answer is None or answer != 'y':\n _log.info(\"User Exit\")\n continue\n dosage.pump.query(\"D,10\")\t\n\t\t\n\t\t\n while (True):\n dosed = dosage.pump.query(\"R\").split(\":\")[1].strip().rstrip('\\x00')\n _log.info( \"Pump id \" + str(dosage.pumpId) + \" has dosed = \" + str(dosed) + \"ml of 10ml\")\n if (str(dosed) == \"10.00\"):\n break\n \t\t\n\t\t\n\t\t\n aDose = input(\"How much in ml did pump dose?\")\n answer = input(\"Going to calibrate pump. It dosed [\" + str(aDose) + \"]. Enter y when you are ready(y/n to skip)\")\n if answer is None or answer != 'y':\n _log.info(\"User Exit\")\n continue\n dosage.pump.query(\"Cal,clear\")\t\n dosage.pump.query(\"Cal,\"+str(aDose))\n\t\t \n answer = input(\"Going to dose 10ml of \" + dosage.name + \" over 1 min. Enter y when you are ready(y/n to skip only done 1 part cal)\")\n if answer is None or answer != 'y':\n _log.info(\"User Exit\")\n continue\n dosage.pump.query(\"D,10,1\")\t\n\t\t\n while (True):\n dosed = dosage.pump.query(\"R\").split(\":\")[1].strip().rstrip('\\x00')\n _log.info( \"Pump id \" + str(dosage.pumpId) + \" has dosed = \" + str(dosed) + \"ml of 10ml in 1 min\")\n if (str(dosed) == \"10.00\"):\n break\t\t\n\t\t\n aDose = input(\"How much in ml did pump dose?\")\n answer = input(\"Going to calibrate pump. It dosed [\" + str(aDose) + \"]. Enter y when you are ready(y/n to skip only done 1 part cal)\")\n if answer is None or answer != 'y':\n _log.info(\"User Exit\")\n continue\n dosage.pump.query(\"Cal,\"+str(aDose))\n\t\t \t\n\t \n except:\n _log.info(\"Expected error: Use Atlas Error\")\n \n \n","sub_path":"atlas/calibration/atlasPumpCal.py","file_name":"atlasPumpCal.py","file_ext":"py","file_size_in_byte":3875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"339926701","text":"from mrjob.job import MRJob\nfrom mrjob.protocol import JSONValueProtocol\nimport re\n\nWORD_RE = re.compile(r\"[\\w']+\")\nSTOP_WORDS = [\"a\", \"an\", \"and\", \"are\", \"as\", \"at\", \"be\", \"but\", \"by\",\"for\", \"if\", \"in\", \"into\", \"is\", \"it\", \"no\", \"not\", \"of\", \"on\", \"or\", \"such\",\"that\", \"the\", \"their\", \"then\", \"there\", \"these\",\"they\", \"this\", \"to\", \"was\", \"will\", \"with\"]\nNUM = re.compile('[0-9]+')\n\nclass MostUsedWord(MRJob):\n\n #OUTPUT_PROTOCOL = JSONValueProtocol\n\n def mapper_get_words(self, _, line):\n # yield each word in the line\n for word in WORD_RE.findall(line):\n if (word not in STOP_WORDS and not NUM.match(word)):\n yield (word.lower(), 1)\n\n def combiner_count_words(self, word, counts):\n # sum the words we've seen so far\n yield (word, sum(counts))\n\n def reducer_count_words(self, word, counts):\n # send all (num_occurrences, word) pairs to the same reducer.\n # num_occurrences is so we can easily use Python's max() function.\n yield None, (sum(counts), word)\n \n # discard the key; it is just None\n def reducer_find_max_word(self, _, word_count_pairs):\n # each item of word_count_pairs is (count, word),\n # so yielding one results in key=counts, value=word\n yield max(word_count_pairs)\n \n def steps(self):\n return [\n self.mr(mapper=self.mapper_get_words,\n combiner=self.combiner_count_words,\n reducer=self.reducer_count_words),\n self.mr(reducer=self.reducer_find_max_word)\n ]\n\n\nif __name__ == '__main__':\n MostUsedWord.run()\n","sub_path":"lab3/code/most_used_word.py","file_name":"most_used_word.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"596883371","text":"from django.shortcuts import render\nfrom django.http import HttpResponseRedirect\nfrom enroll.forms import StudentInfo\n# Create your views here.\n\ndef thankyou(request):\n return render(request, 'enroll/success.html')\n\n\n\n\ndef showmoredata(request):\n if request.method == 'POST':\n fm = StudentInfo(request.POST)\n if fm.is_valid():\n print('form validated')\n name = fm.cleaned_data['name']\n #print('Name: ', fm.cleaned_data['name'])\n #print('Email: ', fm.cleaned_data['email'])\n #print('Password: ', fm.cleaned_data['password'])\n #return render(request, 'enroll/success.html', {'nm':name})\n return HttpResponseRedirect('/reg/success')\n #fm = StudentInfo()\n else:\n fm = StudentInfo()\n return render(request, 'enroll/home.html', {'form':fm})","sub_path":"gs35HttpResponseRedirect/enroll/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"61486143","text":"\"\"\"\nThe constants used for Lobe model exports\n\"\"\"\n\n# predicted label from the 'outputs' top-level\nPREDICTED_LABEL = 'Prediction'\nPREDICTED_LABEL_COMPAT = ['Value'] # list of other previous keys to be backwards-compatible\n# predicted confidence values from the 'outputs' top-level\nLABEL_CONFIDENCES = 'Confidences'\nLABEL_CONFIDENCES_COMPAT = ['Labels'] # list of other previous keys to be backwards-compatible\n\n# 'classes' top-level key\nCLASSES_KEY = 'classes'\n\n# labels from signature.json 'classes' top-level key\nLABELS_LIST = 'Label'\n\n# inputs top-level key\nINPUTS = 'inputs'\n\n# outputs top-level return key\nOUTPUTS = 'outputs'\n\nID = 'doc_id'\nNAME = 'doc_name'\nVERSION = 'doc_version'\nFORMAT = 'format'\nFILENAME = 'filename'\nTAGS = 'tags'\n\n# Input or output properties\nTENSOR_NAME = 'name'\nTENSOR_SHAPE = 'shape'\n\nIMAGE_INPUT = 'Image'\n","sub_path":"src/lobe/signature_constants.py","file_name":"signature_constants.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"598133573","text":"from rest_framework import serializers\nfrom . import models\n\n\nclass EntrySerializer(serializers.ModelSerializer):\n class Meta:\n extra_kwargs = {\n 'user': {'write_only': True}\n }\n model = models.Entry\n fields = [\n 'user',\n 'title',\n 'first_name',\n 'last_name',\n 'mobile_number',\n 'address',\n ]","sub_path":"address_book/entries/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"81046487","text":"# -*- coding: utf-8 -*-\nimport test\n\n# -*- coding: utf-8 -*-\n#\n'''\n题目:给如下的数据格式:\n\n比如有一组数据:\n1, 3, 100\n2, 4, 200\n5, 6, 300\n……\n这些数据时间区间可能有重合的部分。比如在时间段2~3之间,value的和是100+200 = 300.。\n要求找出这组数据中最高的value和。\n'''\n\n\n# do it using stack, sort the time interval according to start time, end time, once \n# there is start time, push on stack, once there is end time, pop it out of the stack\n# keep track of the current maximum\n\n\n# input format: a: [[start1,end1,val1],[start2,end2,val2]...]\n# first break the input into two parts\ndef interval_max(a):\n pair = []\n one = []\n length = len(a)\n for i in range(length):\n one = []\n one.append(a[i][0])\n one.append(a[i][2])\n pair.append(one)\n one = []\n one.append(a[i][1])\n one.append(-a[i][2])\n pair.append(one)\n \n pair.sort()\n max_sum = 0\n cur = pair[0][1]\n for i in range(2*length):\n max_sum = max_sum+pair[i][1]\n if (max_sum > cur):\n cur = max_sum \n \n return cur \n\n\ntest.testEqual(interval_max([[1,3,100],[2,4,200],[5,6,300]]),300)\n\n\n","sub_path":"PforI/interval_maximum.py","file_name":"interval_maximum.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"285823634","text":"from tkinter import *\n\nmenu = Tk()\n\n\nmenu.title(\"Zombie\")\nmenu.geometry(\"1920x1080\")\n\ncanv = Canvas(menu, width=1200, height=675, bg='green')\n#canv.grid(row=0, column=0)\n#c = Canvas(menu,)\ncanv.pack()\n\nfond = PhotoImage(file=\"Fondzombie3.gif\")\ncanv.create_image(600, 337.5, image=fond)\n\n\n# bouton cliquable (50, 50)\n#canv = Canvas(menu, width=128, height=128, bg='blue')\n#canv.pack()\nimage_button = PhotoImage (file=\"quitter.gif\")\n#canv.create_image(64, 64, image=image_button)\nbouton_quitter = Button(menu, image=image_button, command=menu.quit)\nbouton_quitter.pack()\n\nLabel(menu, text=\"Anthony\").pack()\n\nmenu.mainloop()","sub_path":"Jeu Zombie/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"269856839","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n###############################################################################\n# Copyright Kitware Inc.\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\nimport six\n\n\ndef generateLines(stream):\n \"\"\"\n Generate individual unicode lines of text from a stream.\n\n Newlines are retained in the output. Decoding using 'utf-8-sig' removes Unicode BOM\n (byte order mark).\n \"\"\"\n lastLine = None\n keepends = True\n try:\n # Read chunk from stream and split into lines. Always process the\n # last line with the next chunk, or at the end of the stream,\n # because it may be incomplete.\n while True:\n chunk = ''.join(next(stream))\n if lastLine is not None:\n chunk = lastLine + chunk\n lines = chunk.splitlines(keepends)\n lastLine = lines.pop()\n for line in lines:\n yield six.text_type(line, encoding='utf-8-sig')\n except StopIteration:\n if lastLine is not None:\n yield six.text_type(lastLine, encoding='utf-8-sig')\n raise StopIteration\n","sub_path":"server/utility/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"55011540","text":"from django.shortcuts import render\nfrom .forms import *\nfrom .models import *\nfrom django.core.paginator import PageNotAnInteger,Paginator,EmptyPage\nfrom django.db.models import Q , F\nfrom django.shortcuts import render,get_object_or_404\n\n# Create your views here.\ndef home(request):\n categories = Category.objects.all()\n posts = Post.objects.filter(active=True)\n paginator = Paginator(posts, 12)\n page = request.GET.get('page')\n try:\n posts = paginator.page(page)\n except PageNotAnInteger:\n posts = paginator.page(1)\n except EmptyPage:\n posts = paginator.page(paginator.num_page)\n context = {\n 'categories': categories,\n 'posts':posts,\n 'page':page,\n\n }\n\n return render(request, 'home.html', context)\n\n\ndef searchposts(request):\n if request.method == 'GET':\n query= request.GET.get('q')\n\n submitbutton= request.GET.get('submit')\n\n if query is not None:\n lookups= Q(title__icontains=query) | Q(content__icontains=query)\n\n results= Post.objects.filter(lookups).distinct()\n paginator = Paginator(results, 12)\n categories = Category.objects.all()\n\n page = request.GET.get('page')\n try:\n results = paginator.page(page)\n except PageNotAnInteger:\n results = paginator.page(1)\n except EmptyPage:\n results = paginator.page(paginator.num_page)\n\n context={'results': results,\n 'submitbutton': submitbutton,\n 'page':page,\n 'categories':categories,}\n\n return render(request, 'search.html', context)\n\n else:\n return render(request, 'search.html')\n\n else:\n return render(request, 'search.html')\n\n\ndef post_detail(request,slug):\n categories = Category.objects.all()\n\n post = get_object_or_404(Post,slug=slug,active=True)\n cc = post.category.slug\n cat = get_object_or_404(Category,slug=cc)\n esp = cat.posts.filter(active = True)\n Post.objects.filter(pk=post.id).update(views=F('views') + 1)\n views = post.views + 1 # to show valid counter in the template\n\n\n\n context={\n 'title':post.title,\n 'post': post,\n 'esp':esp,\n 'categories':categories\n\n\n\n }\n\n return render(request,'detail.html',context)\n\n\ndef cat_detail(request,slug):\n cat = get_object_or_404(Category,slug=slug)\n esp = cat.posts.filter(active = True)\n categories = Category.objects.all()\n\n\n\n context={\n 'title':cat,\n 'esp':esp,\n 'cat':cat,\n 'categories': categories\n\n }\n\n return render(request,'category.html',context)","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"467793711","text":"\r\nd=[567,788,99,100, 887]\r\n\r\nwhile True:\r\n try:\r\n nb=input(\"Entrer un index entre 0 et 4: \")\r\n nb=int(nb)\r\n print(f\"Element a la position {nb} est {d[nb]}\")\r\n break\r\n except ValueError as ex:\r\n print(f\"Traitement 1:\")\r\n except IndexError as ex:\r\n print(f\"Traitement 2: {ex}\") \r\n except:\r\n print(\"Autre traitement\")\r\n finally:\r\n print(\"Toujours execute\")\r\n \r\nprint(\"The end\")","sub_path":"testExcept.py","file_name":"testExcept.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"369436165","text":"# -*- coding: utf-8 -*-\nimport random\n\nfrom django.core.management.base import BaseCommand, CommandError\n\nfrom tab import models\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n while True:\n SAMPLE_ITEMS = [\n models.Item(name=\"Gin & Tonic\", amount=600,\n quantity=random.randint(1, 2)),\n models.Item(name=\"Beer\", amount=400,\n quantity=random.randint(1, 2)),\n models.Item(name=\"Jack & Coke\", amount=500,\n quantity=random.randint(1, 2))\n ]\n\n number = raw_input('ready to scan: ')\n\n if number[:4] != '4040':\n print('incorrect prefix')\n continue\n\n tab_id = int(number[4:])\n\n print('tab id is {}'.format(tab_id))\n\n try:\n tab = models.Tab.objects.get(pk=tab_id)\n except models.Tab.DoesNotExist as e:\n print('tab does not exist')\n continue\n\n if tab.status != tab.ACTIVE:\n print('tab is no longer active')\n continue\n\n # SAMPLE\n items = random.sample(SAMPLE_ITEMS, random.randint(1, 3))\n for item in items:\n item.save()\n total = sum(i.amount for i in items)\n\n if tab.transaction.total() + total > tab.max_amount:\n print('Tab limit reached 😭')\n continue\n\n tab.transaction.items.add(*items)\n tab.transaction.save()\n\n print('processed')\n","sub_path":"tabhack/tab/management/commands/epos.py","file_name":"epos.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"277383155","text":"from __future__ import division\nfrom collections import deque\n\nfrom desmod.component import Component\nfrom desmod.queue import Queue\nimport simpy\nfrom itertools import chain, count\n\n\ncid_counter = count(start=0)\n\nclass Customer(object):\n\n __slots__ = ('num_items', 'cid')\n\n def __init__(self):\n self.reset()\n\n def setup(self, num_items):\n self.num_items = num_items\n self.cid = next(cid_counter)\n\n def reset(self):\n self.num_items = None\n self.cid = None\n\n def __str__(self):\n if self.cid is None:\n return ('Customer(cid=None'.format(self))\n\n return ('Customer(cid={0.cid:06x}'.format(self))\n\n\nclass CustomerGen(Component):\n \"\"\"Host I/O traffic model.\n\n The host issues LBA (sector) oriented read and write traffic to the FE. The\n host maintains a configurable queue depth which defines how many IO\n commands may be in-flight in parallel.\n\n \"\"\"\n\n base_name = 'cgen'\n\n def __init__(self, *args, **kwargs):\n super(CustomerGen, self).__init__(*args, **kwargs)\n\n max_customers = 50\n self.customers_per_hour = 120\n\n\n self.idle_queue = Queue(self.env, capacity=max_customers,\n items=(Customer()\n for _ in range(max_customers)))\n self.return_queue = Queue(self.env, capacity=max_customers)\n\n self.submit_queue = Queue(self.env, capacity=max_customers)\n\n\n #self.auto_probe('queue_depth_{}'.format(stream_id),\n #self.submit_queue, trace_remaining=True,\n #vcd={})\n\n self.add_process(self._submit_loop)\n\n self.add_processes(self._complete_loop)\n\n\n\n def _submit_loop(self):\n idle_queue = self.idle_queue\n cust_per_sec = self.customers_per_hour / 3600.0\n\n rand = self.env.rand\n prev_cmd_submit = self.env.now\n\n while True:\n customer = yield idle_queue.get()\n num_items = 2\n delay = rand.expovariate(cust_per_sec)\n yield self.env.timeout(delay)\n\n # Update the previous customer submission time\n prev_cmd_submit = self.env.now\n\n customer.setup(num_items)\n\n yield self.submit_queue.put(customer)\n\n\n def _complete_loop(self):\n while True:\n customer = yield self.return_queue.get()\n\n customer.reset()\n\n # The following shouldn't ever wait as then one stream\n # can block another one from progress\n yield self.idle_queue.put(customer)\n\n\n def post_sim_hook(self):\n pass\n\n def get_result_hook(self, result):\n pass\n\n","sub_path":"examples/grocery/grocery/customer.py","file_name":"customer.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"101036800","text":"\r\n# assign tab and string to tabby_cat\r\ncf = \"Cat Food\"\r\nx = \"Fishies\"\r\ny = \"\\t* Catnip\\n\\t* Grass\\n\\t* Litter\\n\\t* kibble\"\r\nz = \"\\t* NothingBurger\\n\\t* Hairball\\n\\t* cat bell\\n\\t* Christmas cat photo\"\r\n\r\ntabby_cat = \"\\tI'm tabbed in.\"\r\n\r\n# assign return in the middle of string and call it\r\n# persian_cat\r\npersian_cat = \"I'm split\\non a line\"\r\n\r\n# assign string and backslashes to backslash_Cat\r\nbackslash_cat = \"I'm \\\\ a \\\\ cat\"\r\n\r\n# assign list values to a multi-line string\r\nfat_cat = f'''\r\nI'll do a list:\r\n\\n\\t* {cf}\r\n\\t* {x}\r\n{y}\r\n{z}\r\n'''\r\n# print the 4 variables in this file\r\nprint(tabby_cat)\r\nprint(persian_cat)\r\nprint(backslash_cat)\r\nprint(fat_cat)\r\n","sub_path":"ex10.py","file_name":"ex10.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"535785225","text":"import unittest\r\nimport requests\r\nimport json\r\n\r\n\r\nclass TestMicroService(unittest.TestCase):\r\n headers = {'Content-type': 'application/json'}\r\n\r\n @classmethod\r\n def setUpClass(cls):\r\n with open(\"tests/settings.json\") as f:\r\n url = json.load(f)[\"url\"]\r\n cls.url = url\r\n\r\n def test_post_request_string(self):\r\n data = '{\"text\":\"Hello, World!\"}'\r\n response = requests.post('{}/revert'.format(self.url), headers=self.headers, data=data)\r\n\r\n self.assertEqual(response.status_code, 201)\r\n self.assertEqual(response.text, '{\"response\": \"!dlroW ,olleH\"}')\r\n\r\n def test_post_request_string_with_error_key(self):\r\n data = '{\"not_text\":\"Hello, World!\"}'\r\n response = requests.post(r'{}/revert'.format(self.url), headers=self.headers, data=data)\r\n\r\n self.assertEqual(response.status_code, 400)\r\n\r\n def test_get_request_string(self):\r\n data = '{\"text\":\"Hello, World!\"}'\r\n response = requests.get(r'{}/revert'.format(self.url), headers=self.headers, data=data)\r\n\r\n self.assertEqual(response.status_code, 405)\r\n\r\n def test_post_request_not_string(self):\r\n data = '{\"text\":[1,2,3]}'\r\n response = requests.post(r'{}/revert'.format(self.url), headers=self.headers, data=data)\r\n\r\n self.assertEqual(response.status_code, 400)\r\n self.assertEqual(response.text, '{\"response\": null}')\r\n\r\n def test_get_request_not_string(self):\r\n data = '{\"text\":[1,2,3]}'\r\n response = requests.get(r'{}/revert'.format(self.url), headers=self.headers, data=data)\r\n\r\n self.assertEqual(response.status_code, 405)\r\n","sub_path":"tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"404506947","text":"from django.contrib.postgres.fields import JSONField\nfrom django.contrib.postgres.fields import ArrayField\nfrom django.db import models\n\nclass Update(models.Model):\n project = models.ForeignKey(\n 'Project',\n on_delete=models.CASCADE,\n )\n title = models.CharField(max_length=60)\n body = models.TextField()\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return self.title\n\nclass Tag(models.Model):\n project = models.ForeignKey(\n 'Project',\n on_delete=models.CASCADE,\n )\n title = models.CharField(max_length=20)\n info = models.CharField(max_length=20, blank=True, null=True)\n\n def __str__(self):\n return self.title\n\nclass Project(models.Model):\n STATUS_CHOICES = (\n ('LI', 'Limbo'),\n ('IP', 'In Progress'),\n ('CO', 'Complete'),\n )\n status = models.CharField(\n max_length=2,\n choices=STATUS_CHOICES,\n default='IP'\n )\n CATEGORY_CHOICES = (\n ('WR', 'Work'),\n ('PR', 'Personal'),\n )\n category = models.CharField(\n max_length=2,\n choices=CATEGORY_CHOICES,\n default='WR'\n )\n title = models.CharField(max_length=60)\n description = models.TextField(null=True)\n github = models.URLField(null=True)\n started_at = models.DateField(null=True)\n ended_at = models.DateField(null=True, blank=True)\n ongoing = models.BooleanField(default=False)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return self.title\n","sub_path":"projects/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"60697374","text":"\nfrom math import sqrt\n#导入数学模块 sqrt 开平方根\n\n# reversed 得到一个反转的迭代器\n# str=[1,2,3,4,5]\n# a=reversed(str)\n# for i in a:\n# print(i)\n# sli=slice(3,4,1)\n# print(str[sli])\n\n# #去掉空和None\n# def aa(x):\n# if type(x)==str:\n# return x and x.strip()\n# return x or x==0\n# c=[0,3,1,'qq','',' ',0, None,'aa',546,'dd',5,5,2,21,4323,24]\n# # 前面必须是个函数的名字\n# ret=filter(aa,c)\n# for i in ret:\n# print(i)\n# # filter 返回的是一个迭代器\n\n# def bb(x):\n# return sqrt(x)% 1==0\n# a1=filter(bb,range(1,101))\n# for i in a1:\n# print(i)\n#\n# #abs取绝对值\n# ret=map(abs,[1,-2,4,-5,2])\n# for i in ret:\n# print(i)\n\n#filter 执行后的结果集合<=执行前的个数\n #filter 只管筛选,不会改变原来的值\n\n#map 执行前后元素个数不变\n # 值可能发生改变\n\nq=[1,2,-3,4,123,55,6,-7]\nprint(sorted(q,reverse= True))\n #生成一个新列表 不改变原列表 占内存\nq3=[' ',[33,44],'hello sorted']\nprint(sorted(q3,key=len))\n #按字符串长度进行排序\n\n","sub_path":"day03/05内置函数.py","file_name":"05内置函数.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"466354249","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Про что этот файл?\"\"\"\nfrom api import *\nfrom squtils import *\nfrom prof_standards import *\n__all__ = [\"get_refs_data\", \"get_entity_lines_data\", \"get_session\", \"get_organization_poll\", \"get_entity_data\",\n \"set_entity_data\", \"set_entity_lines_data\", \"ProfStandard\", \"ProfStandardOkso\",\"UtlSPOGosFgos\",\n \"ProfStandardOkved\",\n \"ProfStandardOkz\",\n \"ProfTf\",\n \"ProfTfAccessReq\",\n \"ProfTfEducReq\",\n \"ProfTfOkdptr\",\n \"ProfTfOkso\",\n \"ProfTfProfession\",\n \"ProfTfStageReq\",\n \"get_ps_access_reqs\",\n \"get_ps_educ_reqs\",\n \"get_ps_okdptr\",\n \"get_ps_okso\",\n \"get_ps_okved\",\n \"get_ps_okz\",\n \"get_ps_standart\",\n \"get_ps_tf\",\n \"get_ps_tf_okso\",\n \"get_ps_tf_prof\",\n \"get_ps_tf_stage\"]\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.DEBUG, format='%(lineno)d %(asctime)s %(message)s')\n","sub_path":"entity/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"155271546","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\n\"\"\"\n继承式调用\n\"\"\"\n\nimport threading\n\n\nclass MyThreading(threading.Thread):\n def __init__(self, n):\n super(MyThreading, self).__init__()\n self.n = n\n\n def run(self): # 定义每个线程要运行的函数\n print(\"running task:\", self.n)\n\n\nif __name__ == '__main__':\n t1 = MyThreading('t1')\n t2 = MyThreading('t2')\n t1.start()\n t2.start()\n","sub_path":"day9/threading_ex2.py","file_name":"threading_ex2.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"472128686","text":"import sys\nimport time\n\nimport numpy as np\n\nfrom datetime import datetime\n\n# Custom imports\nfrom .decision_tree import Tree\n\nfrom .utils import calculate_MSE\n\n\nclass RandomForestRegressor():\n \"\"\"\n Random Forest class for REGRESSION\n \n Attributes\n ----------\n params: dict\n Set of building options\n\n max_depth: int, default=None\n The maximum depth of the tree. If None, then nodes are expanded \n until all leaves are pure or until all leaves contain less than\n min_samples_split samples.\n\n min_samples_split: int, default=2\n The minimum number of samples required to split an internal node.\n\n min_samples_leaf: int, default=1\n The minimum number of samples required to be at a leaf node.\n A split point at any depth will only be considered if it produces\n at least min_samples_leaf training samples in each of the left\n and right branches.\n\n min_impurity_decrease: float, default=0.0\n A node will be split if this split induces a decrease of the \n impurity greater than or equal to this value.\n\n n_estimators: int, default=10\n The number of trees in the forest.\n\n max_features: int, default=None\n The number of features to consider when looking for\n the best split\n\n\n models: array\n Array of CART learners (decision trees which make up the forest)\n\n \"\"\"\n\n def __init__(self):\n \n # Init default params\n self.params = {\n 'min_split_gain': 0.0,\n 'max_depth': None,\n 'min_samples_leaf': 1,\n 'min_samples_split': 2,\n 'n_estimators': 10,\n 'max_features': None\n }\n\n self.models = None\n\n\n def _build_CART_learner(self, X_instances, Y_instances):\n \"\"\"\n Create a CART learner (regression tree)\n \n\n Parameters\n ----------\n X_instances: np.ndarray\n Training set input\n\n Y_instances: np.ndarray\n Training set Output\n\n \"\"\"\n\n # Create a Tree object (from decision_tree.py)\n CART_learner = Tree()\n \n # Start the building of the tree\n CART_learner.build(X_instances, Y_instances, self.params)\n\n return CART_learner\n\n\n def train(self, X_train, Y_train, X_val=None, Y_val=None, params=None):\n \"\"\"\n Train a random forest regression model.\n Note: If the validation set is not specified, a random 70-30 splitting\n is automatically done on the training set.\n \n\n Parameters\n ----------\n X_train: np.ndarray\n Training set input\n\n Y_train: np.ndarray\n Training set Output\n\n X_val: np.ndarray [optional]\n Validation set input\n \n Y_val: np.ndarray [optional]\n Validation set output\n\n params: dict\n Set of building options\n\n max_depth: int, default=None\n The maximum depth of the tree. If None, then nodes are expanded \n until all leaves are pure or until all leaves contain less than\n min_samples_split samples.\n \n n_estimators: int, default=10\n The number of trees in the forest.\n \n max_features: int, default=None\n The number of features to consider when looking for\n the best split\n\n min_samples_split: int, default=2\n The minimum number of samples required to split an internal node.\n\n min_samples_leaf: int, default=1\n The minimum number of samples required to be at a leaf node.\n A split point at any depth will only be considered if it produces\n at least min_samples_leaf training samples in each of the left\n and right branches.\n\n min_impurity_decrease: float, default=0.0\n A node will be split if this split induces a decrease of the\n objective function greater than or equal to this value.\n\n\n\n \"\"\"\n\n # Set the specified parameters if any\n if params is not None:\n self.params.update(params)\n \n print(\"Model parameters:\")\n print(self.params)\n\n # Initialize the list that will contain the trees\n models = []\n\n # If the validation set is not specified, use a random\n # 70 - 30 % splitting (non repeatable random choice)\n np.random.seed(None)\n if (X_val is None) or (Y_val is None):\n from sklearn.model_selection import train_test_split\n X_train, X_val, Y_train, Y_val = train_test_split(X_train,\n Y_train, test_size=0.3)\n \n num_rows = X_train.shape[0]\n\n training_start_time = datetime.now()\n\n print(\"Training started...\")\n\n # Create the forest\n for iter_cnt in range(self.params['n_estimators']):\n \n # Bagging\n # Get a random permutation of the index with replacement\n rnd_idx = np.random.choice(num_rows,\n size=num_rows, replace=True)\n # Get a random sample of the dataset with replacement\n X_train_bagging = X_train[rnd_idx]\n Y_train_bagging = Y_train[rnd_idx]\n\n iter_start_time = datetime.now()\n \n # Create a single tree\n CART_learner = self._build_CART_learner(X_train_bagging, Y_train_bagging)\n\n # Append the tree to the list\n models.append(CART_learner)\n\n # Measure performance\n training_loss = self._calculate_loss(X_train_bagging, Y_train_bagging, CART_learner)\n val_loss = self._calculate_loss(X_val, Y_val, CART_learner)\n\n print(\"Tree number {:>3}, Training L2 error: {:.10f}, Validation L2 error: {:.10f}, Elapsed time: {}\"\n .format(iter_cnt+1, training_loss, val_loss, datetime.now() - iter_start_time))\n\n\n # Update\n self.models = models\n\n print(\"Training finished. Elapsed time: {}\\n\"\n .format(datetime.now() - training_start_time))\n \n\n\n\n def _predict_single_tree(self, X, tree):\n \"\"\"\n Predict each i-th output of a dataset X\n according to a single decision tree\n \n \n Attributes\n ----------\n X: np.ndarray\n Input dataset\n\n tree: Tree\n Regression tree \n \n \"\"\"\n\n # Initialize\n Y_scores = np.zeros(len(X))\n\n # Obtain the prediction for each sample\n # of the dataset\n for i in range(len(X)):\n \n # Cast to positive integers! (because of OUR output)\n Y_scores[i] = max(0,round(tree.predict(X[i])))\n\n\n return Y_scores\n \n\n\n\n def _calculate_loss(self, X, Y, tree):\n \"\"\"\n Compute the loss function (Mean Squared Error)\n on a dataset with respect to the predictions \n obtained from a single regression tree.\n \n \n Attributes\n ----------\n X: np.ndarray\n Input dataset\n\n Y: np.ndarray\n True output of the dataset X\n\n tree: Tree\n Regression tree to be used for predicting the\n output of X \n \n \"\"\"\n\n # Get the prediction\n Y_scores = self._predict_single_tree(X, tree)\n \n # function imported from utils.py\n return calculate_MSE(Y, Y_scores)\n\n\n\n\n def predict(self, X):\n \"\"\"\n Predict each i-th output of a dataset X\n according to the random forest model.\n \n See par. 'From CART models to Random Forests'\n of the report\n\n Attributes\n ----------\n X: np.ndarray\n Input dataset \n \n \"\"\"\n\n # Initialize\n Y_scores = np.zeros(len(X))\n\n # For each tree of the forest\n for tree in self.models:\n\n # Accumulate the prediction\n Y_scores += self._predict_single_tree(X, tree)\n\n # Return the mean\n return Y_scores / len(self.models)\n\n \n \n","sub_path":"Code/Random_Forest/src/.ipynb_checkpoints/rf-checkpoint.py","file_name":"rf-checkpoint.py","file_ext":"py","file_size_in_byte":8163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"212920636","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.3 (3230)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/dvdje/htmlparser.py\n# Compiled at: 2013-10-29 23:55:47\n# Size of source mod 2**32: 7141 bytes\n\"\"\"HTML parser classes.\"\"\"\nimport datetime, getpass, html.entities, html.parser, http.cookiejar, logging\nlogger = logging.getLogger(__name__)\n\nclass EditEntryLinks(html.parser.HTMLParser):\n __doc__ = 'Makes a list of all of the entry editor URLs on a VBulletin Blogs page.\\n\\n Instance attributes:\\n urls -- the list of entry editor URLs found on the page\\n next_page_url -- the URL of the next page of blog entries or None\\n '\n\n def __init__(self):\n super().__init__(strict=False)\n self.urls = []\n self.next_page_url = None\n return\n\n def handle_starttag(self, tag, attrs):\n attrs = dict(attrs)\n if tag == 'a':\n if 'rel' in attrs:\n rel = attrs['rel']\n if rel == 'nofollow' and attrs.get('class') == 'edit_blog':\n logger.debug('Found entry editor URL: %s', attrs['href'])\n self.urls.append(attrs['href'])\n elif rel == 'next':\n self.next_page_url = attrs['href']\n logger.debug('Found next page URL: %s', self.next_page_url)\n\n\nclass DJParser(html.parser.HTMLParser):\n __doc__ = 'Parses DV dream journal entries.\\n\\n Class attributes:\\n category_map -- mapping of checkbox id names to the tag they represent\\n\\n Instance attributes:\\n date -- date of the dream journal entry\\n title -- title of the entry\\n tags -- category tags describing the type of journal entry\\n '\n category_map = {'cb_2': 'lucid', \n 'cb_3': 'non-lucid', \n 'cb_4': 'nightmare', \n 'cb_5': 'false awakening', \n 'cb_6': 'memorable', \n 'cb_7': 'task of the month', \n 'cb_8': 'task of the year', \n 'cb_9': 'dream fragment', \n 'cb_10': 'side notes'}\n\n def __init__(self):\n super().__init__(strict=False)\n self.reset()\n\n def reset(self):\n logger.debug('Reset parser')\n super().reset()\n self._date = {'year': None, \n 'month': None, \n 'day': None, \n 'hour': None, \n 'minute': None}\n self.date = None\n self.title = None\n self.tags = []\n self.entry = []\n self.keep_reading_entry = False\n return\n\n def handle_starttag(self, tag, attrs):\n attrs = dict(attrs)\n if tag == 'input':\n eid = attrs.get('id')\n if eid == 'titlefield':\n self.title = attrs['value']\n logger.debug('Found entry title: %s', self.title)\n else:\n if attrs.get('name') == 'categories[]' and 'checked' in attrs:\n category = DJParser.category_map.get(attrs['id'])\n logger.debug('Found entry category tag: %s', category)\n self.tags.append(category)\n else:\n if eid == 'publish_date':\n n = int(attrs['value'])\n logger.debug('Found entry publish day: %s', n)\n self._date['day'] = n\n else:\n if eid == 'publish_year':\n n = int(attrs['value'])\n logger.debug('Found entry publish year: %s', n)\n self._date['year'] = n\n else:\n if eid == 'publish_hour':\n n = int(attrs['value'])\n logger.debug('Found entry publish hour: %s', n)\n self._date['hour'] = n\n elif attrs.get('name') == 'publish[minute]':\n n = int(attrs['value'])\n logger.debug('Found entry publish minute: %s', n)\n self._date['minute'] = n\n else:\n if tag == 'select' and attrs.get('name') == 'publish[month]':\n logger.debug('Found entry publish month selection area')\n self._date['month'] = 0\n else:\n if self._date['month'] == 0 and tag == 'option' and 'selected' in attrs:\n n = int(attrs['value'])\n logger.debug('Found entry publish month: %s', n)\n self._date['month'] = n\n elif tag == 'textarea':\n if attrs.get('id') == 'vB_Editor_001_editor':\n self.keep_reading_entry = True\n logger.debug('Found entry text area')\n\n def handle_data(self, data):\n if self.keep_reading_entry:\n logger.debug('Append chunk: %s char(s)', len(data))\n self.entry.append(data)\n\n def handle_entityref(self, name):\n if self.keep_reading_entry:\n c = chr(html.entities.name2codepoint.get(name, 32))\n logger.debug('Append entity: %s -> %s', name, c)\n self.entry.append(c)\n\n def handle_charref(self, name):\n if self.keep_reading_entry:\n c = chr(int(name[1:], 16)) if name.startswith('x') else chr(int(name))\n logger.debug('Append char ref: %s -> %s', name, c)\n self.entry.append(c)\n\n def handle_endtag(self, tag):\n if tag == 'textarea' and self.keep_reading_entry:\n logger.debug('Concatenating')\n self.entry = ''.join(self.entry).replace('\\r', '')\n logger.debug('Done parsing entry text area')\n self.keep_reading_entry = False\n elif tag == 'body':\n self.date = datetime.datetime(**self._date)","sub_path":"pycfiles/dvdje-20131030_2-py3.3/htmlparser.cpython-33.py","file_name":"htmlparser.cpython-33.py","file_ext":"py","file_size_in_byte":5826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"105106175","text":"# Python所有的错误都是从BaseException类派生的,常见的错误类型和继承关系看这里:\n\n# https://docs.python.org/3/library/exceptions.html#exception-hierarchy\n\ndef tryTest():\n try:\n r = 10/0\n print('result:',r)\n except ZeroDivisionError as e:\n print('except:',e)\n finally:\n print('finally...')\n \n print('funtion end')\n\n\n\n\ntryTest()\n# import pdb\n# pdb.set_trace()\n#利用raise来抛出错误,或抛出自定义错误\nclass myError(ValueError):\n pass\ndef foo():\n raise myError('my error')\n\n#foo()\n\n\n#调式\n#1.在合适的地方使用print,但是不方便\n#2.在合适的地方使用assert,在启动python解释器时利用-O参数可以关闭assert,关闭后相当于pass\n#assert当不满足条件,就会输出error:n==0\ndef foo2(n):\n #assert n!=0,'error:n==0'\n print(n)\nfoo2(1)\nfoo2(0)\n#3.使用logging记录到文件\nimport logging\nlogging.basicConfig(level=logging.INFO)\ns='0'\nn = int(s)\nlogging.info('n=%d' % n)\nprint(10/n)\n#4.使用pdb调式,输入n单步执行代码,输入p+变量名查看变量,输入q结束调式\n#利用pdb.set_trace()设置断点,运行代码,程序会自动在pdb.set_trace()暂停并进入pdb调试环境,可以用命令p查看变量,或者用命令c继续运行\n\n\n","sub_path":"PythonBase/tryexcept.py","file_name":"tryexcept.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"179495447","text":"'''Controls the screen and user input. The main loop is located here.'''\n\n'''Make sure program works as possible. And CSV.'''\nimport pygame\nfrom pygame.locals import *\n\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\nfrom OpenGL.GLUT import *\n\nfrom Output2d import *\n\nimport random #To choose which path\n\nfrom User import *\nfrom Globals import *\n\nimport GLComponents\n\nfrom Camera import *\nfrom math import sin, cos\n\nfrom Maze import *\nfrom MazeComponent import *\nfrom WriteFile import *\nfrom Time import *\nfrom Dead import *\nimport PyGameFuncs\n\nfrom sys import argv ###################\n#######################################################################\n\nsubject_num = ''\nif len(sys.argv)>1: #ie if a subject number was input\n\tsubject_num = str(sys.argv[1])\nelse:\n\tprint(\"PLEASE ENTER THE PARTICIPANT NUMBER. (Open program by typing eg 'python Output.py 001'\")\n\ncamera = Camera()\nuser = MazeMove(camera)\n\nmaze = Maze()\nhallway_type = maze.current_type()\ninventory = Inventory(maze)\noutput2d = Output2d(camera, inventory, maze)\nwritefile = WriteFile(maze, subject_num)\ntime = Time(maze)\ndead = Dead(output2d, time, writefile)\nglutInit()\nwas_focused = False\n\nfps = 1000 #added this to try sotp flickering (frames per sec) -didn't work :(\n\n##\n\ndef display():\n\toutput2d.draw_images()\n\toutput2d.draw_inv_text()\n\t\n\thallway_type = maze.current_type()\n\n\tGLComponents.hallway(hallway_type, True, maze.position.colours)\n\n\tpygame.display.flip()\t#Refresh screen\n\t#pygame.time.Clock().tick(fps) ############\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\t#Clear buffer\n\ndef display_selected(direction_string):\n\toutput2d.draw_images()\n\toutput2d.draw_inv_text()\t\n\toutput2d.draw_selected_dirn(direction_string) \n\tpygame.display.flip() \n\t#pygame.time.Clock().tick(fps) ##########\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n\t\ndef refresh_focus():\t#refresh the screen when someone focuses on it (needed on windows)\n\tglobal was_focused\n\tif pygame.key.get_focused() and not was_focused:\t#Update when screen selected\n\t\tdisplay()\n\t\twas_focused = True\n\twas_focused = pygame.key.get_focused()\n\t\t\ndef display_straight(delay, winning_spot):\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n\t\n\tif winning_spot and maze.give_prize(inventory):\t#Note the use of short circuit operators here. Be careful\n\t\toutput2d.winning_message()\n\t\t#GLComponents.prize_picture(maze.position.prize[0]) #can add this for images I think??????not quite sure what it does, only seems to work sometimes (maybe its selecting nones sometimes)\n\t\n\t#GLComponents.prize_picture('food')\n\toutput2d.draw_inv_text() \n\tGLComponents.hallway(Hallways.STRAIGHT, True, MazeComponent.generate_colours(Hallways.STRAIGHT)) \n\n\tpygame.display.flip() \n\ttime.mri_delay(delay)\t\t#Show first hallway\t\t\n\t#pygame.time.Clock().tick(fps) #####################\t\n\ndef three_hallways_step():\t#When an option is selected, show hallway, prize, hallway\n\tdisplay_straight(time.get_wait_time(), False)\n\ttime.reset()\n\tdisplay_straight(PRIZE_DELAY, True)\n\n\tdead_inventory = inventory.is_dead()\t#Did an inventory item drop below minimum?\n\tif True in dead_inventory:\t#Might have died here\n\t\tdead.death(dead_inventory)\n\t\t#if i want to make multiple lives, after here, reinitialize hte maze stuff from above that i want to reset, and return false, break out of this function, then make sure the functions caling it (step?) breaks when it recieves false from this guy (increment # lives either here or in the dead.py stuff)\n\ttime.reset()\n\tdisplay_straight(time.get_wait_time(), False)\n\ttime.reset()\n\t\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n\n\thallway_type = maze.current_type()\n\t\t\t\t\n#Whenever the user steps from a choice room\ndef step(direction, key_pressed, direction_string):\n\t\n\tif MRI_ON:\n\t\twhile not (time.mri_increment() and time.num_chars >= TIME_DECIDE/MRI_TIME):\n\t\t\tPyGameFuncs.event_loop()\n\t\t\trefresh_focus() #so this displays screen for MIN of time decide, and then moves on at hte next 5 keypress??\n\telse:\n\t\ttime.mri_delay(TIME_DECIDE) #############Displays for n secs after decision???\n\t\t\n\ttime.reset()\t#Start from 0\n\t\n\tdisplay_selected(direction_string)##maybe move this???\n\ttime.mri_delay(CHOICE_DELAY)#?\n\t#time.reset()#?\n\t\t\n\twritefile.add_output_buffer_prelim(subject_num)\t#Write to file with preliminary info. \n\tcurrent_inventory = inventory.inventory\n\t\n\tmaze.step(direction)\t#Move\n\tmaze.increment_step_count()\n\t#display()\t#Just in case, refresh\n\t\t\n\tdecrement_amounts = inventory.decrement()\n\t\n\tPyGameFuncs.wait_key_up(key_pressed)\t#Present message about prize, wait for key release \n\t#########not sure why this is here. ie about timing and stuff (go test if it works ok later)\n\twritefile.add_output_buffer_postlim(direction_string, current_inventory, decrement_amounts)\t#Add more to output\n\twritefile.flush_output(subject_num)\t#Output to file\n\t\n\t\t#Display \n\t#pygame.display.flip()\n\t\n\tthree_hallways_step()\n\t#print 'depth ' + str(maze.position.depth)\n\tdisplay()\n\t\n#######################################################################\ndef run():\t\n\twhile True:\n\t\tPyGameFuncs.event_loop()\n\t\t\n\t\ttime.mri_increment()\n\t\t\t\t\n\t\tif pygame.key.get_pressed()[pygame.K_UP]:\n\t\t\tif hallway_type not in [Hallways.LEFT, Hallways.RIGHT, Hallways.BIFURC]:\n\t\t\t\tstep(Directions.FORWARDS, pygame.K_UP, \"centre\")\n\n\t\telif BACKWARDS_MOVE and pygame.key.get_pressed()[pygame.K_DOWN] and maze.position.adjacent[Directions.BACKWARDS] != None:\n\t\t\tstep(Directions.BACKWARDS, pygame.K_DOWN, \"back\")\n\t\t\t\n\t\telif pygame.key.get_pressed()[pygame.K_LEFT]:\n\t\t\tif hallway_type not in [Hallways.STRAIGHT, Hallways.RIGHT, Hallways.RIGHT_BIFURC]:\n\t\t\t\tstep(Directions.LEFT, pygame.K_LEFT, \"left\")\n\t\t\t\t\n\t\telif pygame.key.get_pressed()[pygame.K_RIGHT]:\n\t\t\tif hallway_type not in [Hallways.STRAIGHT, Hallways.LEFT, Hallways.LEFT_BIFURC]:\n\t\t\t\tstep(Directions.RIGHT, pygame.K_RIGHT, \"right\")\n\t\t\t\t\n\t\trefresh_focus()\n\t\t\n\t\thallway_type = maze.current_type()\n\t\t#pygame.time.Clock().tick(fps) #arg is frames per sec. not the most accurate timing??? #may not be good\n\t\t\n#############\ndisplay()\n#pygame.display.set_mode(SCREEN_SIZE, pygame.FULLSCREEN|pygame.HWSURFACE|pygame.OPENGL| pygame.DOUBLEBUF) # pygame.FULLSCREEN| #not sure the doublebuf worked (I think it did...) but fullscreen is fun.\n\nrun()\n\n","sub_path":"Maze_2.3/Output.py","file_name":"Output.py","file_ext":"py","file_size_in_byte":6208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"385187416","text":"#!/usr/bin/python\nimport json\nimport logging\nimport tempfile\nfrom hashlib import sha1\n\nimport ipfsapi\nimport magic\n\nfrom classes.exceptions import *\nfrom config import *\n\n\ndef ipfs_connect(func):\n def connection(self):\n logging.debug(\n \"Start connection with IPFS Server IP: %s, Port: %s, Transmit connection timeout: %s,\"\n \" Connection timeout: %s\",\n SERVER_IP,\n IPFS_PORT,\n IPFS_TRANSMIT_CONNECT_TIMEOUT,\n IPFS_CONNECT_TIMEOUT)\n\n if self.ipfs is None:\n self.ipfs = ipfsapi.connect(SERVER_IP, IPFS_PORT)\n\n function_return = func(self)\n\n return function_return\n\n return connection\n\n\nclass IPFSDocument:\n def __init__(self, hash_key, replace_tags=None, extension=None):\n self.ipfs = None\n self.extension = extension\n self.hash = hash_key\n self._check_valid_hash_key()\n\n self.replace_tags = replace_tags or {}\n self.encoded_hash = sha1((hash_key + json.dumps(self.replace_tags, sort_keys=True)).encode('utf-8')).hexdigest()\n\n self.converted_file_path = '%s/%s.%s' % (CONVERTED_DIR, self.encoded_hash, self.extension)\n self.pdf_file_path = '%s/%s.pdf' % (CONVERTED_DIR, self.encoded_hash)\n\n # Check if hash is valid\n def _check_valid_hash_key(self):\n if not isinstance(self.hash, str):\n raise UndefinedIPFSHashException(self.hash)\n\n # Check if the document is pinned in the ipfs server\n @ipfs_connect\n def _is_document_pinned(self):\n pin_files = self.ipfs.pin_ls()\n return self.hash in list(pin_files['Keys'].keys())\n\n @ipfs_connect\n def download_pinned_ipfs_document_into_cache(self):\n \"\"\"\n - Download ipfs document into cache folder\n \"\"\"\n\n ipfs_cached_file_path = '%s/%s' % (IPFS_CACHE_DIR, self.hash)\n\n # If the original document exists in the cache, return the path.\n if os.path.exists(ipfs_cached_file_path):\n return ipfs_cached_file_path\n\n # If the is not pinned in the IPFS node raise access denied exception.\n if not self._is_document_pinned():\n logging.error(\"%s document is not pinned in the ipfs and the user had permission denied.\" % self.hash)\n raise AccessDeniedException('You don\\'t have permission to access.')\n\n content = self.ipfs.cat(self.hash)\n logging.debug('Start downloading IPFS document: %s' % self.hash)\n\n temp_ipfs_cached_file_path = tempfile.NamedTemporaryFile(prefix='document_', dir=IPFS_CACHE_DIR, delete=False)\n\n # write the content of the downloaded file temporary\n with temp_ipfs_cached_file_path:\n temp_ipfs_cached_file_path.write(content)\n\n # Check if file extension is the same in requested\n self._check_file_extension(temp_ipfs_cached_file_path.name)\n\n # Rename the cached file to ipfs file name\n os.rename(temp_ipfs_cached_file_path.name, ipfs_cached_file_path)\n\n return ipfs_cached_file_path\n\n def _check_file_extension(self, file_path):\n file_type = magic.from_file(file_path)\n\n logging.debug(\"File type is %s\" % file_type)\n\n if not file_type:\n os.remove(file_path)\n raise UnKnownFileTypeException(file_type)\n\n checked_file_extension = [file for file in SUPPORTED_FILE_TYPES if file in file_type.lower()]\n if len(checked_file_extension) == 0:\n os.remove(file_path)\n raise UnSupportedFileException(file_type)\n\n if self.extension != checked_file_extension[0]:\n os.remove(file_path)\n raise UnSupportedFileException(file_type)\n","sub_path":"classes/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"31946589","text":"# !/usr/bin/python\n# -*- coding: utf8 -*-\n\n\nclass ImageError(Exception):\n pass\n\n\nclass Imagem():\n \"\"\"\n Classe Imagem armazena uma imagem MxN em um matriz e implementa as\n operações sobre esta matriz.\n Construtor: img = Imagem(M, N), onde M é a largura em pixels e N é a\n altura em pixels.\n \"\"\"\n\n # Mapeia as coordenas ao redor de um pixel na imagem.\n _coord = [(x, y) for y in range(-1, 2) for x in range(-1, 2)]\n\n def __init__(self, M, N):\n if M <= 0 or N <= 0:\n raise ImageError(\"tamanho da imagem é inválido\")\n self._largura = M\n self._altura = N\n self._img = [[\"O\" for x in range(M)] for y in range(N)]\n\n def limpa(self):\n \"\"\"\n Deixa todos os pixels da matriz igua a O. Não altera o tamanho da\n matriz.\n \"\"\"\n for j in xrange(self._altura):\n for i in xrange(self._largura):\n self._img[j][i] = 'O'\n\n def cor(self, x, y):\n \"\"\"\n cor retorna a cor do pixel em x.\n \"\"\"\n try:\n return self._img[y][x]\n except IndexError:\n raise ImageError(\"coordenadas do pixel inválidas\")\n\n def colore(self, x, y, c):\n \"\"\"\n colore um pixel em (x,y) na cor c.\n \"\"\"\n try:\n self._img[y][x] = c\n except IndexError:\n raise ImageError(\"coordenadas do pixel inválidas\")\n\n def seguimento_vertical(self, x, yintv0, yintv1, c):\n \"\"\"\n Desenha um segmento vertical na cor c em x de yintv[0] até yintv[1],\n onde yintv é uma tupla.\n \"\"\"\n try:\n for j in xrange(yintv0, yintv1+1):\n self._img[j][x] = c\n except IndexError:\n raise ImageError(\"coordenadas do pixel inválidas\")\n\n def seguimento_horizontal(self, xinth0, xinth1, y, c):\n \"\"\"\n Desenha um segmento horizontal na cor c em y de xintv[0] até xintv[1],\n onde xintv é uma tupla.\n \"\"\"\n try:\n linha = self._img[y]\n for x in xrange(xinth0, xinth1+1):\n linha[x] = c\n except IndexError:\n raise ImageError(\"coordenadas do pixel inválidas\")\n\n def retangulo(self, x1, y1, x2, y2, c):\n \"\"\"\n Desenha um reatangulo na cor c com canto superior esquerdo em x1 e\n canto inferior direito em x2. x1 e x2 são tuplas com as coordenadas\n dos cantos.\n \"\"\"\n for y in xrange(y1, y2 + 1):\n self.seguimento_horizontal(x1, x2, y, c)\n\n def _oito_conectada(self, x, cor):\n s = set([])\n for c in self._coord:\n try:\n b = x[1]+c[1]\n a = x[0]+c[0]\n if a < 0 or b < 0:\n continue\n pixel = self._img[b][a]\n if pixel == cor:\n s.add((a, b))\n except:\n pass\n return s\n\n def preenche(self, x, y, c):\n \"\"\"\n Operação de flood a partir das coordenadas x. A região preenchida será\n colorida com a cor c. É considerada uma vizinhaça 8-conectada.\n \"\"\"\n cor = self.cor(x, y)\n p = (x, y)\n s = set([p])\n while len(s) > 0:\n s = s.union(self._oito_conectada(p, cor))\n p = s.pop()\n self.colore(p[0], p[1], c)\n\n def salva(self, nome):\n \"\"\"\n Escreve a imagem para um arquivo.\n \"\"\"\n try:\n f = open(nome, 'w')\n for j in xrange(self._altura):\n for i in xrange(self._largura):\n f.write(self._img[j][i])\n if j < self._altura:\n f.write('\\n')\n except Exception as e:\n raise ImageError(\"não foi possível salvar o arquivo:\" + e.message)\n finally:\n f.close()\n\n def __str__(self):\n s = \"\"\n for j in xrange(self._altura):\n for i in xrange(self._largura):\n s += self._img[j][i]\n if i < self._largura - 1:\n s += ' '\n if j < self._altura:\n s += '\\n'\n return s\n","sub_path":"imagem.py","file_name":"imagem.py","file_ext":"py","file_size_in_byte":4151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"176459737","text":"#script to load .csv data into database\nimport sys, os, csv, django\n\ncsv_filepathname = \"F:/python/km_bx_plot/test_data.csv\"\nproject_path = \"F:\\python\\km_bx_plot\"\n\nsys.path.append(project_path)\nos.environ['DJANGO_SETTINGS_MODULE'] = \"km_bx_plot.settings\"\ndjango.setup()\n\nfrom kb_app.models import Patient, Patient_Data\n\n\ndataReader = csv.reader(open(csv_filepathname), delimiter = ',', quotechar = '\"')\n\ntpatient = None\nheader = dataReader.__next__()\nfor row in dataReader:\n\tif tpatient != row[0]:\n\t\ttpatient = row[0]\n\t\tpatient = Patient()\n\n\t\tpatient.pt_id = tpatient\n\t\tpatient.save()\n\ndataReader = csv.reader(open(csv_filepathname), delimiter = ',', quotechar = '\"')\n\nheader = dataReader.__next__()\nfor row in dataReader:\n\tpatient_data = Patient_Data()\n\n\tpatient_data.lastContact = row[1]\n\tpatient_data.exp_brca1 = row[2]\n\tpatient_data.exp_usp1 = row[3]\n\tpatient_data.vital_status = row[4]\n\tpatient_data.patient = Patient.objects.get(pt_id = row[0])\n\n\tpatient_data.save()\n","sub_path":"load_csv.py","file_name":"load_csv.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"144605567","text":"units = int(input(\"Enter the number of units : \"))\nanswer = 0\nif (units <= 199):\n answer = units * 1.20\nelif (units <= 200) and (units < 400):\n answer = 238.8 + (units - 199) * 1.50\nelif ( 400 <= units and units < 600):\n answer = 238.8 + 300 + (units - 199) * 1.80\nelse:\n answer = 238.8 + 300 + 360 + (units - 600) * 2\n#print(\"The bill is \" + str(answer)) \n \nif(answer >= 400):\n answer += answer * 0.15 \n print(\"The bill is \" + str(answer)) \nif(answer < 100):\n print(\"Invalid units\")\n\n","sub_path":"Codes/Lab_1/Set6/electricity.py","file_name":"electricity.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"525326634","text":"\"\"\"\nWord reverse:\n\nInput String S:\n1. lower letters a to z\n2. numbers 0 to 9\n3. special characters: <. >\n4. space ' '\n\nStrings inside special characters <, > are called tags:\n- String in tag is not reversed\n- Tag is not a word\n- No space between tag and word\n\"\"\"\n\nS = input() # Input string\ntemp = \"\" # String to add to result\nresult = \"\" # Result string\nfor ch in S: # Inspect each character in String S\n temp += ch # Add the character to the temp string\n\n if (\n len(temp) > 1 and temp[0] == \"<\" and ch == \">\"\n ): # If a tag is completely counted,\n result += temp # Add a temp to result\n temp = \"\" # Flush temp\n continue # Go to next iteration\n\n if len(temp) > 1 and ch == \"<\": # If another tag is started,\n result += temp[-2::-1] # Add the reversed word to result,\n temp = \"<\" # Flush except the tag opening\n continue # Go to next iteration\n\n if (\n len(temp) > 1 and temp[0] != \"<\" and ch == \" \"\n ): # If a word is completely counted with blank at the end\n result += (\n temp[-2::-1] + \" \"\n ) # Add a reversed word and blank to divide with next words\n temp = \"\" # Flush the string in temp\n continue\n\nif temp: # If word is left\n result += temp[::-1]\nprint(result) # Print the result\n","sub_path":"onlypractice/string/boj17413.py","file_name":"boj17413.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"57609416","text":"from django.urls import path\nfrom .views import *\n\napp_name = \"urlschecker\"\n\nurlpatterns = [\n path('', home, name=\"home\"),\n path('update_status/', update_urls_status, name=\"update_status\"),\n path('load_urls/', load_urls, name=\"load_urls\"),\n]\n","sub_path":"urlschecker/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"317385397","text":"import turtle\nimport random\n\ndw = turtle.Turtle() #Drawing turtle\ndw.penup()\ndw.shape(\"circle\")\ndw.speed(0)\nwindow = turtle.Screen() #Screen turtle\nwindow.tracer(0)\n\n#Lookup list of turtles, made of shape_info dictionaries\nshape_list = [] \n#Each entry will be a dictionary of entries\nprogram_on = True\n#shape class prototype=> {\"name\":\"\",\"function\": pass,\"colours\":[],\"xcor\":0.0, \"ycor\":0.0}\n#shape names is a lookup table mapping the number of sides to the shape name... for convenience\nshapenames = {\"0\":\"Circle\",\"3\":\"Triangle\", \"4\":\"Square\", \"5\":\"Pentagon\"}\n#This function is only called by program. Not by user!\ndef draw_shape(sides):\n dw.pendown()\n dw.begin_fill()\n #Special case of circle\n if sides == 0:\n dw.circle(25)\n for _ in range(sides):\n dw.forward(50)\n dw.left(360/sides)\n dw.end_fill()\n dw.penup()\n\ndef shape_instantiator(passthrough, var1):\n #passthrough=True <=> New instance of shape being drawn\n #passthrough=True => var1=number of sides the shape should have\n #passthrough=False => var1=offset into list of shapes drawn\n dw.hideturtle() #Dont show cursor moving to new location\n tempx=dw.xcor() #Temporary coordinate storage variables\n tempy=dw.ycor()\n sides=0 #Empty declare to allow for later type appropriate referencing\n\n if passthrough == True: #Create a new instance of shape\n sides=var1\n red = random.random()\n green = random.random()\n blue = random.random()\n dw.color(red, green, blue)\n colourtriple = [red, green, blue]\n newshape = {\"name\":shapenames[str(sides)],\"sides\": sides,\"colours\":colourtriple,\"xcor\":tempx, \"ycor\":tempy}\n shape_list.append(newshape)\n else: #Focus a previous instance of the shape\n instance = shape_list[var1]\n sides = instance[\"sides\"]\n dw.setpos(instance[\"xcor\"],instance[\"ycor\"])\n dw.color(instance[\"colours\"][0],instance[\"colours\"][1], instance[\"colours\"][2])\n\n draw_shape(sides) #Draw a shape with n sides\n #Return cursor to original position\n dw.setpos(tempx, tempy) #Return cursor to original position, if it was moved\n dw.color(\"black\") #Return cursor to normal colour\n dw.showturtle() #Reactivate cursor\n\ndef list_shapes():\n print(\"Shapes List:\")\n for i in range(len(shape_list)):\n shape = shape_list[i]\n print(\"Shape number: \"+str(i+1)+\" || Shape Type: \"+shape[\"name\"])\n\ndef move_up():\n dw.sety(dw.ycor() + 5)\n\ndef move_down():\n dw.sety(dw.ycor() - 5)\n\ndef move_right():\n dw.setx(dw.xcor() + 5)\n\ndef move_left():\n dw.setx(dw.xcor() - 5)\n\ndef square_stub():\n shape_instantiator(True, 4) #New shape, four sides\n\ndef triangle_stub():\n shape_instantiator(True, 3)\n\ndef pentagon_stub():\n shape_instantiator(True, 5)\n\ndef circle_stub():\n shape_instantiator(True, 0)\n\ndef quit_stub():\n program_on = False\n\ndef focus_handler(): #Will prompt at console for a number\n incorrect_input1 = True #Assume the user will input poorly!\n window.bgcolor(\"red\") #Pause, return to console to enter somth at the prompt\n usrinput = \"0\"\n while incorrect_input1:\n nullifyAsyncFunctions() #Kill async functionality\n print(\"Shape Menu: Press r to return to unfreeze drawing window!\")\n list_shapes() #List the shapes\n usrinput = input(\"\\nShape#>\")\n if usrinput == \"r\":\n incorrect_input1 = False\n else:\n try:\n usrinput = int(usrinput)\n except ValueError:\n print(\"Please type a valid number!\\a\\a\\n\")\n else:\n usrinput -= 1 #dec usrinput!\n if usrinput >= 0 and usrinput < len(shape_list):\n shape_instantiator(False, usrinput) #Call the shape drawer to bring up shape\n incorrect_input1 = False\n else: #Invalid input\n print(\"Please type a valid number or r to return\\a\\n\")\n instantiateAsyncFunctions() #Return async functionality to keys\n window.bgcolor(\"white\") #Return to game!\n\ndef print_help():\n print(\"Use arrow keys to move, c to draw a circle, s for a square, p for a pentagon, t for a triangle\")\n print(\"Alternatively, press space to select a shape to focus!\")\n print(\"Type l for a list of drawn shapes!\")\n\ndef null():\n pass\n\ndef nullifyAsyncFunctions():\n window.onkeypress(null, \"Up\")\n window.onkeypress(null, \"Down\")\n window.onkeypress(null, \"Left\")\n window.onkeypress(null, \"Right\")\n window.onkeypress(null,\"space\")\n window.onkeypress(null, \"s\")\n window.onkeypress(null, \"S\")\n window.onkeypress(null, \"t\")\n window.onkeypress(null, \"T\")\n window.onkeypress(null, \"p\")\n window.onkeypress(null, \"P\")\n window.onkeypress(null, \"c\")\n window.onkeypress(null, \"C\")\n window.onkeypress(null, \"l\")\n window.onkeypress(null,\"L\")\n window.onkeypress(null, \"h\")\n window.onkeypress(null, \"H\")\n\ndef instantiateAsyncFunctions():\n window.onkeypress(move_up, \"Up\")\n window.onkeypress(move_down, \"Down\")\n window.onkeypress(move_left, \"Left\")\n window.onkeypress(move_right, \"Right\")\n window.onkeypress(focus_handler,\"space\")\n window.onkeypress(square_stub, \"s\")\n window.onkeypress(square_stub, \"S\")\n window.onkeypress(triangle_stub, \"t\")\n window.onkeypress(triangle_stub, \"T\")\n window.onkeypress(pentagon_stub, \"p\")\n window.onkeypress(pentagon_stub, \"P\")\n window.onkeypress(circle_stub, \"c\")\n window.onkeypress(circle_stub, \"C\")\n window.onkeypress(list_shapes, \"l\")\n window.onkeypress(list_shapes,\"L\")\n window.onkeypress(print_help, \"h\")\n window.onkeypress(print_help, \"H\")\n\n###################################\n############ Main Proc ############\n###################################\nprint(\"Welcome to PyDraw 3000!!\")\nprint(\"Written by Yll Buzoku\")\ninstantiateAsyncFunctions()\nprint_help()\n\nwhile program_on:\n window.update()\n window.listen()\n\nwindow.bgcolor(\"blue\")\nturtle.done()\n###################################\n###################################\n###################################","sub_path":"classlessDraw.py","file_name":"classlessDraw.py","file_ext":"py","file_size_in_byte":6180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"588973591","text":"#coding: utf-8\n\nfrom django.core.urlresolvers import reverse, resolve, Resolver404\nfrom django.template import loader, RequestContext\nfrom django.utils.http import urlencode\n\nclass PaginatorRenderer(object):\n def __init__(self, request, items, items_range, page_param_name='page_nr'):\n self.page_param_name = page_param_name\n self.items = items\n self.items_range = items_range\n self.request = request\n \n def url(self, request, page):\n try:\n resolver = resolve(request.get_full_path())\n except Resolver404:\n resolver = resolve(request.path_info)\n kwargs = resolver.kwargs\n kwargs[self.page_param_name] = page\n new_url = reverse(resolver.url_name, args=resolver.args, kwargs=kwargs)\n query = request.GET.copy()\n get_str = urlencode(query)\n if get_str:\n get_str = \"?%s\" % get_str\n return new_url + get_str\n \n def to_html(self):\n data= {}\n data['items'] = self.items\n data['items_range'] = self.items_range\n data['obj'] = self\n \n t = loader.get_template('paginator/paginator.html')\n c = RequestContext(self.request, data)\n \n return t.render(c)\n","sub_path":"paginator/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"113537352","text":"import csv\nfrom django.contrib import admin\nfrom django.urls import path\n#from JangoProj.jangoapp.views import book_list\nfrom jangoapp import views\n\nurlpatterns = [\n path('',views.home,name=\"home\"),\n path('test/',views.test,name=\"test\"),\n path('contact/',views.contact,name=\"contact\"),\n path('result/',views.result,name=\"result\"),\n path('upload_book/',views.upload_book,name=\"upload_book\"),\n path('book_list/',views.book_list,name=\"book_list\"),\n path('book_delete/',views.book_delete,name=\"book_delete\"),\n path('send_email/',views.send_email,name=\"send_email\"),\n \n path('ssession/',views.ssession,name=\"ssession\"),\n path('gsession/',views.gsession,name=\"gsession\"),\n\n path('scookie/',views.scookie,name=\"scookie\"),\n path('gcookie/',views.gcookie,name=\"gcookie\"),\n\n path('csvs/',views.csvs,name=\"csvs\"),\n]\n","sub_path":"jangoapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"106236395","text":"import json\nimport logging\nfrom collections import defaultdict\nfrom emmaa.util import find_latest_s3_file, get_s3_client\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef load_test_results_from_s3(model_name):\n base_key = f'results/{model_name}'\n latest_result_key = find_latest_s3_file('emmaa', f'{base_key}/results_',\n extension='.json')\n client = get_s3_client()\n logger.info(f'Loading test results from {latest_result_key}')\n obj = client.get_object(Bucket='emmaa', Key=latest_result_key)\n test_results = json.loads(obj['Body'].read().decode('utf8'))\n return test_results\n\n\ndef show_statistics(model_name):\n try:\n test_results = load_test_results_from_s3(model_name)\n except IndexError:\n print('No test results for ' + model_name + ' model available.')\n else:\n total_tests = len(test_results)\n path_count = 0\n result_codes = defaultdict(int)\n for res in test_results:\n if res['result_json']['path_found']:\n path_count += 1\n else:\n result_codes[res['result_json']['result_code']] += 1\n return {'Model name': model_name, 'Total applied tests': total_tests,\n 'Passed tests': path_count, 'Failed tests':\n [(key, value) for key, value in result_codes.items()]}\n\nif __name__ == '__main__':\n cancer_types = ('aml', 'brca', 'luad', 'paad', 'prad', 'skcm')\n\n for ctype in cancer_types:\n print(show_statistics(ctype))","sub_path":"scripts/get_model_test_stats.py","file_name":"get_model_test_stats.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"37354032","text":"\"\"\"\n\"\"\"\nimport random\nimport copy\nimport numpy as np\nimport utils # local module\nfrom music_elements import Note, Bar, NOTE_DURATIONS, Mood # local module\n\ndef fitnessFunction(fitnessArray: np.array, generation_number):\n ''' rates the quality of the individuals '''\n\n amountInd = len(fitnessArray)\n\n for i in range(amountInd):\n file_name = f\"{generation_number}-{i+1}.mid\"\n utils.play_midi(\"product/\" + file_name)\n\n print(\"Rating for\", i+1 ,\"(1-10): \", end='')\n\n # dev code\n random_value = random.randint(1, 10)\n fitnessArray[i] = random_value\n print(f\"value assigned: {random_value}\")\n\n # fitnessArray[i] = (input())\n\n\n return fitnessArray\n\ndef selectionFunction(amountInd: int, populationFitness: np.array):\n ''' selects individuals to generate the next population,\n this is done using propabilities and roulette wheel selection\n # https://www.youtube.com/watch?v=-B15r-8WX48 (roulette wheel selection)\n '''\n\n totalFitness = np.sum(populationFitness)\n relativeFitness = np.zeros(amountInd)\n for i in range(amountInd):\n relativeFitness[i] = populationFitness[i] / totalFitness\n\n cumulativeProbabilityArray = np.zeros(amountInd)\n currentSum = 0\n for i in range(amountInd):\n cumulativeProbabilityArray[i] = relativeFitness[i] + currentSum\n currentSum = cumulativeProbabilityArray[i]\n\n # print(\"Cumulative probability vector\")\n # for i in range(amountInd):\n # print(cumulativeProbabilityArray[i], \" \", end='')\n # print(\"\\n\")\n\n #ahora que tenemos la probabilidad cumulativa\n #debemos retornar el vector que indica los pares que\n #debemos cruzar entre si para obtener los hijos\n\n def getParent(value: int, probArray: np.array):\n # REVISAR !!!\n # La defini aqui, porque solo se usa en esta misma funcion\n for i in range(len(probArray)):\n if (value <= probArray[i]):\n #print(\"found at\",i, \"| value is\", value)\n return i\n\n #SELECCION\n #iremos tomando valores random entre 0-1\n #para ir tomando pares segun la prob anterior\n #por ahora, se entregara un arreglo con tamano\n #2*numeroIndividuos\n\n selectedParents = []\n for i in range(amountInd*2):\n #generamos valor random entre 0-1\n value = random.uniform(0,1)\n parent = getParent(value, cumulativeProbabilityArray)\n #print(\"parent is\", parent)\n selectedParents.append(int(parent))\n\n return selectedParents\n\ndef crossoverFunction(selected_index: list, population: list):\n ''' cross the selected individuals '''\n\n num_ind = len(population)\n num_bars = len(population[0])\n\n new_population = []\n\n # por cada nuevo individuo\n for i in range(num_ind):\n # obtenemos los padres\n parent1 = population[selected_index[i*2]]\n parent2 = population[selected_index[i*2 + 1]]\n\n # generamos un splitpoint\n split_point = random.randint(1, num_bars - 1)\n\n # creamos al nuevo ind\n new_ind = []\n for j in range(num_bars):\n if j < split_point:\n # usamos deepcopy para generar un nuevo elemento,\n # en vez de pushear la referencia al antiguo elemento\n new_ind.append(copy.deepcopy(parent1[j]))\n else:\n new_ind.append(copy.deepcopy(parent2[j]))\n\n # lo agregamos a la nueva population\n new_population.append(new_ind)\n\n return new_population\n\ndef mutationFunction(population: list, mutationRate: float, scale: list):\n ''' mutates notes from individuals '''\n\n for ind in population:\n for bar in ind:\n for note in bar.notes:\n value = random.uniform(0,1)\n\n if value < mutationRate:\n note_index = bar.notes.index(note)\n bar.notes[note_index].tone = random.choice(scale)\n bar.notes[note_index].duration = random.choice(NOTE_DURATIONS)\n\n bar.renew_integrity(scale)\n\n return population\n\ndef generateInitialPop(scale: list, num_bars: int, num_ind: int):\n ''' generates the intial population '''\n\n #startNote unused por ahora\n #scale es la escala de notas que usaremos\n #barNumber es la cantidad de compases\n # num_ind es la cantidad de individuos\n\n population = []\n for _ in range(num_ind):\n bars = []\n\n for _ in range(num_bars):\n foo = Bar.from_scale(scale, 4, 4)\n bars.append(foo)\n\n population.append(bars)\n\n return population\n\n\ndef makeScale():\n\n scale = []\n\n # Tonics in a dictionary first\n dictyNotes = {\n \"C\": 48,\n \"C#\": 49,\n \"D\": 50,\n \"D#\": 51,\n \"E\": 52,\n \"F\": 53,\n \"F#\": 54,\n \"G\": 55,\n \"G#\": 56,\n \"A\": 57,\n \"A#\": 58,\n \"B\": 59\n }\n #Scales and moods\n ##Las escalas NO repiren su ultima nota\n ##Todas DEBEN sumar 12\n majorScale = (\"Major\", [2, 2, 1, 2, 2, 2, 1]) # Sweet, Love \"Ionic Scale\"\n dorian = (\"Dorian\", [2, 1, 2, 2, 2, 1, 2]) # melancolic, deep\n phrygian = (\"Phrygian\", [1, 2, 2, 2, 1, 2, 2]) # depressed, mistery\n lydian = (\"Lydian\", [2, 2, 2, 1, 2, 2, 1]) # floaty, otherworld, space\n mixolydian = (\"Mixolydian\", [2, 2, 1, 2, 2, 1, 2]) # contemplative, sentimental\n aeolian = (\"Aeolian\", [2, 1, 2, 2, 1, 2, 2]) # sad, emotional MINOR SCALE\n locrian = (\"Locrian\", [1, 2, 2, 1, 2, 2, 2]) # inquientante\n bluesScale = (\"Blues\", [3, 2, 1, 1, 3, 2]) # emotional, regrets, soulful\n chromatic = (\"Chromatic\", [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) # abstract, free, anxiety\n wholeTone = (\"Whole Tone\", [2, 2, 2, 2, 2, 2]) # dreamy, cosmic\n phrigianDominant = (\"Phrygian Dominant\", [1, 3, 1, 2, 1, 2 ,2]) # serious, severe\n pentatonicScale = (\"Pentatonic\", [2, 2, 3, 2, 3]) # Joy \n\n print(\"Please, enter the Tonic of your scale\\n C C# D D# E F F# G G# A A# B\")\n tonic = input()\n mood = Mood(tonic, dictyNotes[tonic])\n \n # Identificamos que escalas dan un mood en especifico\n print(\"Please, give us the number of your mood\\n\" + \"1. Sad/Sentimental/Depressive\\n2. Contemplative/Dreamy/Cosmic/Deep\\n3. Emotional/Nostalgic\\n4. Love\\n5. Abstract/Free\")\n mood_t = int(input())\n\n if mood_t == 1:\n mood.set_mood(\"Sad\")\n mood.set_bpm(random.randint(65, 75))\n mood.append_scale(dorian)\n mood.append_scale(phrygian)\n mood.append_scale(aeolian)\n mood.append_scale(bluesScale)\n \n if mood_t == 2:\n mood.set_mood(\"Dreamy/Contemplative\")\n mood.set_bpm(random.randint(85, 95))\n mood.append_scale(lydian)\n mood.append_scale(mixolydian)\n mood.append_scale(bluesScale)\n mood.append_scale(wholeTone)\n \n if mood_t == 3:\n mood.set_mood(\"Nostalgic\")\n mood.set_bpm(random.randint(70, 85))\n mood.append_scale(dorian)\n mood.append_scale(mixolydian)\n mood.append_scale(aeolian)\n mood.append_scale(bluesScale)\n mood.append_scale(phrigianDominant)\n \n if mood_t == 4:\n mood.set_mood(\"Love\")\n mood.set_bpm(random.randint(90, 100))\n mood.append_scale(majorScale)\n mood.append_scale(pentatonicScale)\n \n if mood_t == 5:\n mood.set_mood(\"Abstract/Free\")\n mood.set_bpm(random.randint(66, 76))\n mood.append_scale(chromatic)\n mood.append_scale(lydian)\n\n mood.select_scale()\n\n return mood\n\n\ndef main():\n #https://github.com/kiecodes/genetic-algorithms/blob/master/algorithms/genetic.py\n #https://github.com/kiecodes/generate-music/blob/main/algorithms/genetic.py\n \"\"\"\n ##Las escalas NO repiren su ultima nota\n ##Todas DEBEN sumar 12\n majorScale = [2, 2, 1, 2, 2, 2, 1] #Jonico Sweet, Love\n dorian = [2, 1, 2, 2, 2, 1, 2] # melancolic, deep\n phrygian = [1, 2, 2, 2, 1, 2, 2] # depressed, mistery\n lydian = [2, 2, 2, 1, 2, 2, 1] # floaty, otherworld, space\n mixolydian = [2, 2, 1, 2, 2, 1, 2] # contemplative, sentimental\n aeolian = [2, 1, 2, 2, 1, 2, 2] # sad, emotional MINOR SCALE\n locrian = [1, 2, 2, 1, 2, 2, 2] # inquientante\n bluesScale = [3, 2, 1, 1, 3, 2] # emotional, regrets, soulful\n chromatic = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # abstract, free, anxiety\n wholeTone = [2, 2, 2, 2, 2, 2] # dreamy, cosmic\n phrigianDominant = [1, 3, 1, 2, 1, 2 ,2] # serious, severe\n pentatonicScale = [2, 2, 3, 2, 3] # Joy\n \"\"\"\n # randDuration = [0.5, 1, 1, 1, 1, 1, 1, 2, 2]\n\n # mood = makeScale()\n\n # scale = mood.scale_\n\n scale = [48, 50, 52, 55, 57, 60, 62, 64, 67, 69, 72, 0] # 0 means silence\n\n\n ### === INPUT === ###\n\n #Ahora calculamos las notas que puede tener el codigo\n # print(\"Enter base note: \")\n # baseNote = int(input())\n\n #print(\"Pauses? (1/0)\")\n #pauses = int(input())\n\n # print(\"Enter tracks amount: \")\n # numIndividuals = int(input())\n numInd = 4\n\n # print(\"Enter bar amount: \")\n # numBars = int(input())\n numBars = 4\n\n # print(\"Enter mutation rate amount (0-1): \")\n # mutationRate = float(input())\n mutationRate = 0.5\n\n ### === INITIAL POPULATION === ###\n\n generation_number = 0\n\n # esto sera una lista de listas de Bars\n population = generateInitialPop(scale, numBars, numInd)\n\n # creamos los archivos midi\n for i in range(numInd):\n utils.toMidi(population[i], generation_number, i + 1, 70)#mood.bpm) comentado x mientras\n\n\n ### === GENETIC ITERATIONS === ###\n run = 1\n while run:\n # show inds\n i = 1\n for ind in population:\n ind_str = ''\n\n for bar in ind:\n ind_str = f\"{ind_str} {bar}\"\n\n print(f\"Individual #{i}: {ind_str}\")\n print('')\n i += 1\n\n ##### rateamos la poblacion\n individual_rating = np.zeros(numInd)\n population_fitness = fitnessFunction(individual_rating, generation_number)\n\n ##### seleccionamos individuos de poblacion inicial\n selected_individuals = selectionFunction(numInd, population_fitness)\n\n #### Realizamos el crossover\n population = crossoverFunction(selected_individuals, population)\n\n #### Realizamos la mutacion\n population = mutationFunction(population, mutationRate, scale)\n\n generation_number = generation_number + 1\n\n # creamos los archivos midi\n for i in range(numInd):\n utils.toMidi(population[i], generation_number, i + 1, 70)#mood.bpm)\n\n print(\"Continue? (1/0)\")\n run = int(input())\n\nmain()\n\n\n# \"\"\"\n# if (pauses):\n# if (90 < random.randint(1,100)):\n# print (\"pause for \", time)\n# time = time + duration\n# continue\"\"\"\n\n########## DEPRECATED CODE BELOW\n\n# def generateNotes(scale: list, startNote: int):\n# #*scale = lista de la escala\n# #startNote = nota startNote de donde empezamos\n# #DESC: Genera las notas posibles que podra usar\n# #el algoritmo\n# print(\"generating notes...\")\n# offset = 8 - len(scale)\n# print(\"offset:\", offset)\n\n# startNote = startNote - 12\n# currentNote = startNote\n# listNotes = [currentNote]\n\n# scaleLength = len(scale*2)\n# for i in range(scaleLength):\n# currentNote = currentNote + scale[i%len(scale)]\n# listNotes.append(currentNote)\n# print(scaleLength, \"notes were generated\")\n\n# if (scaleLength < 16):\n# print(\"need\", 16 - scaleLength,\"more\")\n# else:\n# print(\"need\", 16 - scaleLength,\"less\")\n\n\n\n# return listNotes\n# #generateNotesEnd\n\n\n# def geneticIteration(population: list, mutationRate: float, scale: list, generation_number: int):\n# ''' generates a new population '''\n\n# numInd = len(population)\n# # numDNA = int(np.shape(population)[1])\n\n# i = 1\n# for ind in population:\n# print(f\"Individual #{i}: {ind}\")\n# print('')\n# i = i + 1\n\n# #####rateamos la poblacion\n# individualRating = np.zeros(numInd)\n# populationFitness = fitnessFunction(individualRating, generation_number)\n\n# #####seleccionamos individuos de poblacion inicial\n# selectedIndividuals = selectionFunction(population, populationFitness)\n\n\n# \"\"\"print(\"Selected parents\")\n# for i in range(len(selectedIndividuals)):\n# print(selectedIndividuals[i], \" \", end='')\n# print(\"\\n\")\n# \"\"\"\n\n# #####Realizamos el crossover\n# population = crossoverFunction(selectedIndividuals, population)\n\n# \"\"\"print(\"Printing possible notes\")\n# for i in range(len(generatedNotes)):\n# print(generatedNotes[i])\"\"\"\n\n# \"\"\"for i in range(numIndividuals):\n# print(\"Individual\", i)\n# for j in range(4*4):\n# print(population[i][j], \" \", end='')\n# print(\"\\n\")\"\"\"\n\n# mutationFunction(population, mutationRate, scale)\n\n# print(\"Mutated population\")\n# for i in range(numInd):\n# print(\"Individual\", i)\n# for j in range(4*4):\n# print(population[i][j], \" \", end='')\n# print(\"\\n \")\n # return population\n","sub_path":"generation/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":13452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"29168134","text":"from xlrd import open_workbook\nimport math\nclass Data(object):\n\tdef __init__(self, idberita, like, provokasi, komentar, emosi, hoax):\n\t\tself.idberita= idberita\n\t\tself.like= like\n\t\tself.provokasi= provokasi\n\t\tself.komentar= komentar\n\t\tself.emosi= emosi\n\t\tself.hoax= hoax\n\ndef euclidean(a, b):\n\treturn math.sqrt(((a[0]-b[0])**2) + ((a[1]-b[1])**2) + ((a[2]-b[2])**2) + ((a[3]-b[3])**2))*1.0\n\n#rr adalah array yg digunakan untuk ngecek class// harusnya datatraining punya\ndef findMaxClass(indeks, riri):\n\tjum_nol=0\n\tjum_satu=0\n\tfor i in range(len(indeks)):\n\t\tcek= riri[indeks[i]]\n\t\tif (int(cek[4])==0):\n\t\t\tjum_nol+=1\n\t\telse:\n\t\t\tjum_satu+=1\n\t# if jum_nol==jum_satu:\n\t\t# return 9999\n\treturn 0 if jum_nol>jum_satu else 1\n\ndef manipulasiNol(aduhhh):\n\tpanteque=aduhhh\n\n\tfor i in range (len(panteque)):\n\t\tif(panteque[i]==0):\n\t\t\tpanteque[i]=6666666\n\treturn panteque\n\ndef carimin(array):\n\ts=999\n\tindeks=0;\n\tfor i in range(len(array)):\n\t\tif array[i]a\ndef loadData(a,b):\n\tif a==0:\n\t\ta=1\n\teksel= open_workbook('Dataset Tugas 3 AI 1718.xlsx')\n\tdata_kereta = eksel.sheets()[0]\n\n\tjum_row= data_kereta.nrows\t\n\tjum_col= data_kereta.ncols\n\tall_data=[]\n\tfor row in range(a, b):\n\t\tone_row= []\n\t\tfor col in range(1, jum_col):\n\t\t\tone_cell= data_kereta.cell(row,col).value\n\t\t\tone_row.append(one_cell)\n\t\tall_data.append(one_row)\n\n\treturn all_data\n\ndef cekAkurasi(hasil, dataTest):\n\ta=0\n\tfor i in range(len(hasil)):\n\t\t# print(\"if \", hasil[i], \"==\", dataTest[i][4])\n\t\tif hasil[i]== int(dataTest[i][4]):\n\t\t\ta+=1\n\treturn (a*1.0/len(hasil))*100\n\ndef kfold(k, jum_row, jum_knn):\n\t#inisialisasi indeks fold \n\tkece= jum_row/k\n\ttest_index=[]\n\tfor i in range(0, k):\n\t\ttest_index.append(i*kece)\n\ttest_index.append(jum_row-1)\n\tcontent=[]\n\t#masukin data ke content\n\tfor i in range(len(test_index)-1):\n\t\tcontent.append(loadData(test_index[i], test_index[i+1]))\n\n\t#mulai kfold\n\tdata_train=[]\n\thasilakurasi=[]\n\thasil=[]\n\tfor i in range(len(content)):\n\t\thasil=[]\n\t\tdata_test= content[i]\n\t\tfor j in range(len(content)):\n\t\t\tif(i!=j):\n\t\t\t\tdata_train= data_train+ content[j]\n\t\t#KNN 3\n\n\t\thasil.append(knn(data_test, data_train, jum_knn))\n\n\t\takurasi= cekAkurasi(hasil[0], data_test)\n\t\thasilakurasi.append(akurasi)\n\ttotal=0\n\tfor i in range(len(hasilakurasi)):\n\t\ttotal= total+hasilakurasi[i]\n\n\n\treturn total/len(hasilakurasi)\n\n#main\n\nfor i in range(2):\n\tjum_k=1\n\tjum_fold=(i+1)*4\n\tfor j in range(2):\n\t\tjum_k+=2\n\t\takurasi=kfold(jum_fold, 4002,jum_k)\n\t\tprint(\"Akurasi \", i, j, \" \", akurasi, \" Jumlah Fold: \", jum_fold, \" Jumlah kNN: \", jum_k)\n\n","sub_path":"k-Nearest Neighbour/knn2.py","file_name":"knn2.py","file_ext":"py","file_size_in_byte":3283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"620832745","text":"# encoding=utf-8\nfrom conn_封装 import *\nsname = input(\"请输入添加的学生姓名\")\nsql = \"insert into students(sname) values('{0}')\".format(sname)\n\nconn = MysqlHelper('192.168.1.7', 3306, 'study', 'root', '123456')\ncount = conn.insert(sql)\nif count == 1:\n print(\"success\")\nelse:\n print(\"fail\")\n\n# 查询全部\n# sql = 'select sname from students order by id desc'\n# helper = MysqlHelper('192.168.1.7', 3306, 'study', 'root', '123456')\n# all = helper.get_all(sql)\n# print(all)\n","sub_path":"Conn_DB/conn_调用.py","file_name":"conn_调用.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"174762432","text":"#!/usr/bin/env python\nimport socket\nimport threading\nimport time\nimport Interconnector as ic\n\nhost = '127.0.0.1'\nport = 5050\nstatuses = ['Available', 'Unavailablex']\ncurrent_status = 0\nwait_time_between_msg = 5\nbattery = 100\n\nclass LobbyClient():\n\tdef __init__(self, host, port):\n\t\tself.name = socket.gethostname()\n\t\tself.host = host\n\t\tself.port = port\n\t\tself.__stop = False\n\n\tdef start_connection(self, wait_time):\n\t\tself.__stop = False\n\t\tthreading.Thread(None, LobbyClient.__connect_to_lobby, args=(self.host, self.port, self.name, self, wait_time)).start()\n\n\tdef is_stopping(self):\n\t\treturn self.__stop\n\n\tdef stop_connection(self):\n\t\tself.__stop = True\n\n\t@staticmethod\n\tdef __connect_to_lobby(host, port, name, parent, wait_time=1):\n\t\twhile not parent.is_stopping():\n\t\t\twith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n\t\t\t\twhile not parent.is_stopping():\n\t\t\t\t\ttry:\n\t\t\t\t\t\ts.connect((host, port))\n\t\t\t\t\t\tprint('Connected to', (host, port))\n\t\t\t\t\t\tbreak\n\t\t\t\t\texcept:\n\t\t\t\t\t\tpass\n\n\t\t\t\twhile not parent.is_stopping():\n\t\t\t\t\ttry:\n\t\t\t\t\t\tmsg = ic.CarStatusMsg(name, statuses[current_status], battery)\n\t\t\t\t\t\tmsg_str = msg.to_json()\n\t\t\t\t\t\ts.sendall(msg_str.encode('UTF-8'))\n\n\t\t\t\t\t\tdata = s.recv(32)\n\t\t\t\t\t\tif not data: \n\t\t\t\t\t\t\tprint('Status update: NONE')\n\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\tprint('Status update: {}'.format(data.decode('UTF-8')))\n\t\t\t\t\t\ttime.sleep(wait_time)\n\t\t\t\t\texcept:\n\t\t\t\t\t\tbreak\n\t\t\t\t\t\n\t\t\t\tprint('Disconnected from', (host, port))\n\nlc = LobbyClient(host, port)\nlc.start_connection(wait_time_between_msg)","sub_path":"Python Project/RC car project/Car/Car.py","file_name":"Car.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"270454558","text":"from django.shortcuts import render,redirect\nfrom .models import todos\n\n\ndef todo(request):\n todo1=todos.objects.all()\n if request.method=='POST':\n title=request.POST['title']\n new=todos(title=title)\n new.save()\n return redirect(\"/\")\n \n else: \n return render(request,\"Todo.html\",{'todos':todo1})\n\ndef delete(request,id):\n todo1=todos.objects.get(id=id)\n todo1.delete()\n return redirect('/')\n \n return render(request,\"Todo.html\",{'todos':todo1})\n\n","sub_path":"do/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"490981402","text":"import tensorflow as tf\n\nfrom src.components.losses import Losses\nfrom src.components.networks import Networks\nfrom src.components.placeholders import Placeholders\n\n\nclass Optimizers:\n def __init__(self, networks: Networks, losses: Losses, placeholders: Placeholders, train_videos, tb_threshold):\n\n adam = tf.train.AdamOptimizer(learning_rate=placeholders.lr, beta1=0.5)\n def optimize_conditionally(loss, var_list, global_step = None):\n with tf.control_dependencies([adam.minimize(loss, var_list=var_list, global_step=global_step)]):\n return tf.constant(0,dtype=tf.float32)\n\n\n if (train_videos):\n self.optimizer_D_temp = tf.cond(tf.less(placeholders.tb_temporal, tb_threshold), lambda: optimize_conditionally(losses.loss_D_temp, var_list=networks.discriminator_temporal.var_list), lambda: tf.constant(0, dtype=tf.float32))\n self.optimizer_D_a = tf.cond(tf.less(placeholders.tb_spatial_a, tb_threshold),\n lambda: optimize_conditionally(losses.loss_D_a,\n var_list=networks.discriminator_spatial_a.var_list,\n global_step=placeholders.global_step),\n lambda: tf.constant(0, dtype=tf.float32))\n self.optimizer_D_b = tf.cond(tf.less(placeholders.tb_spatial_b, tb_threshold),\n lambda: optimize_conditionally(losses.loss_D_b,\n var_list=networks.discriminator_spatial_b.var_list),\n lambda: tf.constant(0, dtype=tf.float32))\n else:\n self.optimizer_D_temp = tf.constant(0, dtype=tf.float32)\n self.optimizer_D_a = tf.train.AdamOptimizer(learning_rate=placeholders.lr, beta1=0.5) \\\n .minimize(losses.loss_D_a,var_list=networks.discriminator_spatial_a.var_list)\n self.optimizer_D_b = tf.train.AdamOptimizer(learning_rate=placeholders.lr, beta1=0.5) \\\n .minimize(losses.loss_D_b, var_list=networks.discriminator_spatial_b.var_list)\n\n\n self.optimizer_G_ab = tf.train.AdamOptimizer(learning_rate=placeholders.lr, beta1=0.5) \\\n .minimize(losses.loss_G_ab_final, var_list=networks.generator_ab.var_list,global_step=placeholders.global_step)\n self.optimizer_G_ba = tf.train.AdamOptimizer(learning_rate=placeholders.lr, beta1=0.5) \\\n .minimize(losses.loss_G_ba_final, var_list=networks.generator_ba.var_list)","sub_path":"src/components/optimizers.py","file_name":"optimizers.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"466502349","text":"import math\nimport matplotlib.pyplot as plt\nimport scipy.integrate as intg\nimport numpy as np\n\n\n# Global Variables\nrho_max = 1.\nu_max = 1.\nx_center = .5\nlam = .1\nn = 150\nperturbation = 10.**(-3.)\n\n\ndef init_grid(delta_rho,rho_bar):\n\n h = 1./n\n \n cells = []\n xs = []\n\n for i in range(n):\n x = (i*h)+(h/2.)\n exp_term = math.exp((-(x-x_center)**2.)/(lam**2.))\n\n if (i == n-1):\n cells.append(cells[0])\n else:\n cells.append(rho_bar+(delta_rho*exp_term))\n\n xs.append(x)\n\n #plt.plot(xs,cells)\n plt.show()\n\n return cells, xs\n\n\ndef f(rho):\n return (rho*u_max)*(1.-(rho/rho_max))\n\n\ndef rho_system(cells,t):\n \n #print(cells)\n\n n = len(cells)\n h = 1./n\n\n df = []\n drho = []\n\n for i in range(n):\n if (i == n-1):\n f_plus = f(cells[0])\n f_minus = f(cells[i-1])\n\n dfdx = (f_plus-f_minus)/(2.*h)\n drhodt = -dfdx\n\n df.append(dfdx)\n drho.append(drhodt)\n\n else:\n f_plus = f(cells[i+1])\n f_minus = f(cells[i-1])\n\n dfdx = (f_plus-f_minus)/(2.*h)\n drhodt = -dfdx\n\n df.append(dfdx)\n drho.append(drhodt)\n \n return drho\n\n\n\ndef SHOCK_CAPTURE(cells, t):\n drho = []\n\n \n #Reconstruction step\ndef minmod(a,b):\n \n if (a*b > 0):\n if abs(a)>abs(b):\n val = b\n else:\n val = a\n else:\n val = 0\n \n return val\n\n \ndef U_Left(Ui, Ui_plus_1, Ui_minus_1):\n a = Ui_plus_1 - Ui\n b = Ui - Ui_minus_1\n \n UL = Ui + 0.5*minmod(a,b)\n \n return UL\n\n\ndef U_Right(Ui, Ui_plus_1, Ui_plus_2):\n a = Ui_plus_2 - Ui_plus_1\n b = Ui_plus_1 - Ui\n \n UR = Ui_plus_1 - 0.5*minmod(a,b)\n \n return UR\n\n #Solving Riemann Probem step\n\n \ndef check_S(rho_L, rho_R):\n \n f_of_rho_L = f(rho_L)\n #print(\"rho_L\", rho_L)\n #print(\"f_of_rho_L\", f_of_rho_L)\n f_of_rho_R = f(rho_R)\n #print(\"rho_R\", rho_R)\n #print(\"f_of_rho_R\", f_of_rho_R)\n \n S = (f_of_rho_L - f_of_rho_R) / (rho_L - rho_R)\n #print(\"S\", S)\n \n if S > 0:\n fi_plus_one_half = f_of_rho_L\n elif S < 0:\n fi_plus_one_half = f_of_rho_R\n else:\n fi_plus_one_half = f_of_rho_R #this is for the n-1 term, where S will equal 0/0\n \n return fi_plus_one_half\n\n\ndef METH(cells, t):\n \n #print(\"cells\", cells)\n #print(\"t\", t)\n n = len(cells)\n #print(\"length\", n)\n h = 1./n\n f_i = []\n drho = []\n \n\n for i in range(n):\n if (i == n-1):\n U__i = cells[i]\n U__i_minus_one = cells[i-1]\n U__i_plus_one = cells[0]\n U__i_plus_two = cells[1]\n \n #print(\"Ui for n-1\", U__i)\n #print(\"U i-1 for n-1\", U__i_minus_one)\n #print(\"U i+1 for n-1\", U__i_plus_one)\n #print(\"U i+2 for n-1\", U__i_plus_two)\n \n \n elif (i == n-2):\n U__i = cells[i]\n U__i_minus_one = cells[i-1]\n U__i_plus_one = cells[i+1]\n U__i_plus_two = cells[0]\n \n #print(\"Ui for n-2\", U__i)\n #print(\"U i-1 for n-2\", U__i_minus_one)\n #print(\"U i+1 for n-2\", U__i_plus_one)\n #print(\"U i+2 for n-2\", U__i_plus_two)\n \n else:\n U__i = cells[i]\n U__i_minus_one = cells[i-1]\n U__i_plus_one = cells[i+1]\n U__i_plus_two = cells[i+2]\n \n #print(\"Ui for\", i, U__i)\n #print(\"U i-1 for\", i, U__i_minus_one)\n #print(\"U i+1 for\", i, U__i_plus_one)\n #print(\"U i+2 for\", i, U__i_plus_two)\n \n \n ULeft = U_Left(U__i, U__i_plus_one, U__i_minus_one)\n #print(\"UL\", ULeft)\n URight = U_Right(U__i, U__i_plus_one, U__i_plus_two)\n #print(\"UR\", URight)\n \n f_i.append(check_S(ULeft, URight))\n \n for j in range(n):\n \n if (j == n-1):\n f_iplus = f_i[0]\n f_iminus = f_i[j-1]\n\n dfdx = (f_iplus-f_iminus)/(h)\n drhodt = -dfdx\n \n drho.append(drhodt)\n\n else:\n f_iplus = f_i[j+1]\n f_iminus = f_i[j-1]\n\n dfdx = (f_iplus-f_iminus)/(h)\n drhodt = -dfdx\n\n drho.append(drhodt)\n \n return drho\n \n \n \ndef integrate_d(func,rhos):\n t = range(n)\n solution = intg.odeint(func,rhos,t)\n return solution\n\ndef rho_plots():\n cells, x_vals = init_grid(rho_max*(10**-2),rho_max*.6)\n rho_t = integrate_d(METH,cells)\n\n for num in range(5):\n maximum = max(rho_t[num])\n print(\"y-max at t\", num, \":\", maximum)\n counter = 0\n for val in rho_t[num]:\n if val == maximum:\n x_max = x_vals[counter]\n else:\n counter += 1\n print(\"x-max at t\", num, \":\", x_max, \"\\n\")\n\n plt.plot(x_vals,rho_t[0],label='t0')\n plt.plot(x_vals,rho_t[5],label='t5')\n plt.plot(x_vals,rho_t[10],label='t10')\n plt.plot(x_vals,rho_t[20],label='t20')\n plt.plot(x_vals,rho_t[45],label='t45')\n plt.plot(x_vals,rho_t[60],label='t60')\n plt.plot(x_vals,rho_t[75],label='t75')\n #plt.plot(x_vals,rho_t[100],label='t100')\n plt.xlabel('x')\n plt.ylabel('rho')\n plt.title('Rho vs. position (with rho_bar=rho_max/2, perturbation=.001*rho_max)')\n plt.legend(loc='best')\n plt.show()\n\nrho_plots()\n\n\n\n#integrate_d(rho_system,init_grid(10.**-3.,rho_max/2.)[0])\n","sub_path":"Project_3_v3.py","file_name":"Project_3_v3.py","file_ext":"py","file_size_in_byte":5573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"171332565","text":"#!/usr/bin/env python\n\nimport argparse\nimport yaml\n\nfrom golos import Steem\nfrom golos.account import Account\nfrom golos.converter import Converter\nfrom pprint import pprint\n\ndef main():\n\n parser = argparse.ArgumentParser(\n description='show user balances',\n epilog='Report bugs to: https://github.com/bitfag/golos-scripts/issues')\n parser.add_argument('account',\n help='account name')\n parser.add_argument('-c', '--config', default='./common.yml',\n help='specify custom path for config file')\n args = parser.parse_args()\n\n # parse config\n with open(args.config, 'r') as ymlfile:\n conf = yaml.load(ymlfile)\n\n golos = Steem(nodes=conf['nodes_old'], no_broadcast=True)\n\n a = Account(args.account, steemd_instance=golos)\n b = a.get_balances()\n cv = Converter(golos)\n gp = cv.vests_to_sp(b['total']['GESTS'])\n\n for asset in b['savings']:\n print('{:<15}{:>18.3f}'.format('SAVINGS_{}'.format(asset), b['savings'][asset]))\n for asset in b['total']:\n print('{:<15}{:>18.3f}'.format('{}:'.format(asset), b['available'][asset]))\n\n print('{:<15}{:>18.3f}'.format('GP:', gp))\n print('{:<15}{:>18.3f}'.format('MGESTS:', b['total']['GESTS']/1000000))\n\nif __name__ == '__main__':\n main()\n","sub_path":"get_balance.py","file_name":"get_balance.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"176025486","text":"# SingularitySurfer 2020\n\n\nimport numpy as np\nfrom migen import *\nfrom litex.soc.interconnect.csr import *\nfrom functools import reduce\nfrom operator import and_\n\n\nclass ADC(Module, AutoCSR):\n \"\"\"Basic sigma-delta ADC with a CIC decimator running at sys clock.\n The decimator gain is such that the output bitwidth will always be maximized.\n \"\"\"\n def __init__(self, cic_order=6, cic_ratechange=2**7, width_o=32, clk_div=0):\n self.inp = Signal() # analog in\n self.sd = Signal() # sigma-delta switching pin\n self.dout = Signal(width_o)\n self.stb = Signal() # data out strobe\n ###\n\n width_csr = 32\n self.adc_val = CSRStatus(width_csr, name=\"adc_value\", description=\"adc conversion value (continuously updated)\")\n\n\n if not(cic_ratechange & (cic_ratechange-1) == 0) and not cic_ratechange != 0:\n raise ValueError() # not a power of two\n\n\n if clk_div != 0:\n divcnt = Signal(clk_div)\n self.sync += divcnt.eq(divcnt+1)\n\n b_max = np.ceil(np.log2(cic_ratechange)) # max bit growth\n\n if clk_div != 0:\n self.sync += [\n If(reduce(and_, divcnt), # do the sigma-delta\n self.sd.eq(self.inp))\n ]\n else:\n self.sync += [ # do the sigma-delta\n self.sd.eq(self.inp)\n ]\n\n width = (int(b_max)*cic_order)+1\n sig = Signal((width, True), reset_less=True)\n self.comb += sig.eq(self.sd)\n for _ in range(cic_order): # integrator cascade\n sum = Signal((width, True), reset_less=True)\n self.sync += [\n sum.eq(sum + sig)\n ]\n sig = sum\n\n cnt = Signal(int(b_max))\n self.sync += cnt.eq(cnt+1)\n for _ in range(cic_order): # comb cascade\n dif = Signal((width, True), reset_less=True)\n reg = Signal((width, True), reset_less=True)\n self.sync += [\n self.stb.eq(0),\n If(reduce(and_, cnt), # counter up and therefore new output sample\n self.stb.eq(1),\n reg.eq(sig),\n dif.eq(sig - reg)\n )\n ]\n sig = dif\n\n self.comb += self.dout.eq(sig[-width_o:]) # highest bits are the data output\n self.sync += self.adc_val.status.eq(sig[-width_csr:]) # continuously update CSR\n\n\n def sim(self):\n yield \n yield self.inp.eq(1)\n for i in range(10000):\n yield\n if(i==3000):\n yield self.inp.eq(~self.inp)\n if (i == 5000):\n yield self.inp.eq(~self.inp)\n if i>7000:\n yield self.inp.eq(~self.inp)\n\n\nif __name__ == \"__main__\":\n test = ADC(6,2**8,16)\n run_simulation(test, test.sim(), vcd_name=\"adc.vcd\")","sub_path":"soc/adc.py","file_name":"adc.py","file_ext":"py","file_size_in_byte":2985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"624894703","text":"import matplotlib.pyplot as plt\nimport learners\nimport numpy as np\n\nlearner = learners.FirstChoiceHillClimbing(0.5)\n# learner = learners.RandomGuess()\nweights = [0]\n\n\nresults = [[] for i in range(len(weights))]\n\nfor m in range(10):\n weights = learner.initial_weights(1, weights)\n for n in range(10):\n weights = learner.modify_weights(weights, n)\n for i in range(len(weights)):\n results[i].append(weights[i])\n\n\nprint(results)\n\nfor i in range(len(weights)):\n plt.hist(results[i], bins=100)\n fig = plt.gcf()\n fig.suptitle(\"Mean : {}, SD : {}\".format(np.round(np.mean(results[i]), 2), np.round(np.std(results[i]), 2)))\n filename = \"results/test_hist_{}_{}.png\".format(learner, i)\n fig.savefig(filename)\n plt.clf()\n\n\n\n# Uncomment below to graph the modifications used by the hill climber\nmods = learner.get_mods()\nprint(mods)\nplt.hist(mods, bins=100)\nfig = plt.gcf()\nfig.suptitle(\"Mean : {}, SD : {}\".format(np.round(np.mean(mods), 2), np.round(np.std(mods), 2)))\nfilename = \"results/test_mods_{}_{}.png\".format(learner, i)\nfig.savefig(filename)\n\n","sub_path":"openai/cartpole/learner_tests.py","file_name":"learner_tests.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"56522740","text":"import torch\nimport torch.nn.functional as F\nfrom torch import nn\nfrom models.Pearattention.func.vif import mycorr\nfrom torch.nn.parameter import Parameter\n\n\"\"\"\nFigure 1: Graph Attention Module\n\"\"\"\n\n\nclass PearsonAttention(nn.Module):\n def __init__(self, feature_dim, node_size, dropout=0.5):\n super(PearsonAttention, self).__init__()\n self.feature_dim = feature_dim\n self.node_size = node_size\n self.dropout = nn.Dropout(dropout)\n self.W_h = nn.Linear(self.feature_dim, self.feature_dim, bias=False)\n self.beta = Parameter(torch.Tensor(1).uniform_(0, 1), requires_grad=True)\n self.A = nn.Sequential(nn.Linear(self.node_size, self.node_size*4, bias=False),\n nn.ReLU(),\n nn.Linear(self.node_size*4, self.node_size, bias=False))\n self.relu = nn.ReLU()\n\n def forward(self, h):\n Wh = self.W_h(h)\n corr_p = mycorr(Wh)\n e = self.beta * torch.absolute(corr_p)\n \"Adaptive Graph Structure Learning\"\n adj = e + self.A(e)\n adj = self.relu(adj)\n zero_vec = -1e12 * torch.ones_like(e)\n \"Construct the connections for the nodes whose values greater than 0.\"\n attention = torch.where(adj > 0, e, zero_vec)\n attention = F.softmax(attention, dim=-1)\n attention = self.dropout(attention)\n h_prime = torch.matmul(attention, Wh)\n return h_prime\n\n\n\n\n\n\n","sub_path":"PearNet/models/Pearattention/func/pearson_attention.py","file_name":"pearson_attention.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"215618275","text":"import math\nimport html\nfrom datetime import datetime\n\nimport constants as CN\n\n\ndef url_encoded_to_json(encoded_form):\n \"\"\"\n Transform url-encoded data (type \"application/x-www-form-urlencoded\")\n into JSON and lowercase the argument names on the fly\n :param encoded_form: the request arguments\n :return: JSON dictionary\n \"\"\"\n json_dict = {}\n for key, value in encoded_form.items():\n decoded_key = key.decode(CN.UTF8)\n escaped_key = html.escape(decoded_key)\n if len(value) > 1:\n raise IndexError(\n \"The field {} has too many values\".format(escaped_key))\n decoded_value = value[0].decode(CN.UTF8)\n escaped_value = html.escape(decoded_value)\n json_dict[escaped_key] = escaped_value\n return json_dict\n\n\ndef change_endianness(hex_string):\n hex_string = hex_string.replace(\"0x\", \"\")\n try:\n ba = bytearray.fromhex(hex_string)\n except ValueError as v:\n print(f\"This is the hex string {hex_string}\")\n raise v\n ba.reverse()\n other_endianness = \"\".join(format(x, \"02x\") for x in ba)\n return other_endianness\n\n\ndef generate_mask(n):\n # Generate a mask with n bits set\n two_power_n = 1 << n\n mask = two_power_n - 1\n return mask\n\n\ndef get_timestamp():\n return datetime.now().strftime(\"%Y-%m-%d %H:%M:%S:%f\")[:-4]\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"359036113","text":"#!/usr/bin/env python2.5\n#\n# Copyright 2009 the Melange authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"This module contains the GSoC Proposal Model.\n\"\"\"\n\n__authors__ = [\n '\"Daniel Hans ',\n]\n\n\nfrom google.appengine.ext import db\n\nfrom django.utils.translation import ugettext\n\nimport soc.models.base\nimport soc.modules.gsoc.models.organization\nimport soc.modules.gsoc.models.profile\nimport soc.modules.gsoc.models.program\n\n\nclass GSoCProposal(soc.models.base.ModelWithFieldAttributes):\n \"\"\"Model for a student proposal used in the GSoC workflow.\n \"\"\"\n\n #: Required field indicating the \"title\" of the proposal\n title = db.StringProperty(required=True,\n verbose_name=ugettext('Project Title'))\n title.help_text = ugettext('Title of the proposal')\n\n #: required, text field used for different purposes,\n #: depending on the specific type of the proposal\n abstract = db.TextProperty(required=True,\n verbose_name=ugettext('Short Description'))\n abstract.help_text = ugettext(\n 'Short abstract, summary, or snippet;'\n ' 500 characters or less, plain text displayed publicly')\n\n #: Required field containing the content of the proposal.\n content = db.TextProperty(required=True,\n verbose_name=ugettext('Content'))\n content.help_text = ugettext('This contains your actual proposal')\n\n #: an URL linking to more information about this students proposal\n additional_info = db.URLProperty(required=False,\n verbose_name=ugettext('Additional Info'))\n additional_info.help_text = ugettext(\n 'Link to a resource containing more information about your proposal')\n\n #: indicates whether the proposal's content may be publicly seen or not\n is_publicly_visible = db.BooleanProperty(required=False, default=False,\n verbose_name=ugettext('Publicly visible'))\n is_publicly_visible.help_text = ugettext(\n 'If you check here, the content of your proposal will be visible '\n 'for others. Please note that they still will not be able to see '\n 'any public comments and reviews of the proposal.')\n\n #: A property containing which mentor has assigned himself to this proposal.\n #: Only a proposal with an assigned mentor can be turned into\n #: a accepted proposal. A proposal can only have one mentor.\n mentor = db.ReferenceProperty(\n reference_class=soc.modules.gsoc.models.profile.GSoCProfile,\n required=False,\n collection_name='proposals')\n\n #: A property containing a list of possible Mentors for this proposal\n possible_mentors = db.ListProperty(item_type=db.Key, default=[])\n\n #: the current score of this proposal, used to determine which proposals\n #: should be assigned a project slot.\n score = db.IntegerProperty(required=True, default=0)\n\n #: the status of this proposal\n #: new : the proposal has not been ranked/scored yet\n #: pending: the proposal is in the process of being ranked/scored\n #: accepted: the proposal has been assigned a project slot\n #: rejected: the proposal has not been assigned a slot\n #: invalid: the student or org admin marked this as an invalid proposal.\n status = db.StringProperty(required=True, default='new',\n choices=['new', 'pending', 'accepted', 'rejected', 'invalid'])\n\n #: organization to which this proposal is directed\n org = db.ReferenceProperty(\n reference_class=soc.modules.gsoc.models.organization.GSoCOrganization,\n required=False,\n collection_name='proposals')\n\n #: program in which this proposal has been created\n program = db.ReferenceProperty(\n reference_class=soc.modules.gsoc.models.program.GSoCProgram,\n required=True,\n collection_name='proposals')\n\n #: date when the proposal was created\n created_on = db.DateTimeProperty(required=True, auto_now_add=True)\n\n #: date when the proposal was last modified, should be set manually on edit\n last_modified_on = db.DateTimeProperty(required=True, auto_now_add=True)\n","sub_path":"app/soc/modules/gsoc/models/proposal.py","file_name":"proposal.py","file_ext":"py","file_size_in_byte":4425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"350467107","text":"import pytest\n\nfrom eth_utils import (\n is_address,\n to_checksum_address,\n)\nfrom ethpm import (\n Package,\n)\nfrom ethpm.contract import (\n LinkableContract,\n)\n\nfrom web3 import Web3\nfrom web3.exceptions import (\n PMError,\n)\nfrom web3.pm import (\n ERCRegistry,\n VyperReferenceRegistry,\n get_vyper_registry_manifest,\n)\n\n\n@pytest.fixture\ndef fresh_w3():\n w3 = Web3(Web3.EthereumTesterProvider())\n w3.eth.defaultAccount = w3.eth.accounts[0]\n w3.eth.defaultContractFactory = LinkableContract\n w3.enable_unstable_package_management_api()\n return w3\n\n\ndef test_pm_get_package_from_manifest(w3):\n manifest = get_vyper_registry_manifest()\n package = w3.pm.get_package_from_manifest(manifest)\n assert isinstance(package, Package)\n assert package.name == \"vyper-registry\"\n\n\ndef test_pm_deploy_and_set_registry(fresh_w3):\n assert not hasattr(fresh_w3.pm, \"registry\")\n registry_address = fresh_w3.pm.deploy_and_set_registry()\n assert isinstance(fresh_w3.pm.registry, VyperReferenceRegistry)\n assert is_address(registry_address)\n\n\ndef test_pm_set_registry_with_vyper_default(empty_vy_registry, fresh_w3):\n assert not hasattr(fresh_w3.pm, \"registry\")\n fresh_w3.pm.set_registry(address=to_checksum_address(empty_vy_registry.address))\n assert isinstance(fresh_w3.pm.registry, ERCRegistry)\n assert is_address(fresh_w3.pm.registry.address)\n\n\ndef test_pm_set_solidity_registry(empty_sol_registry, fresh_w3):\n assert not hasattr(fresh_w3.pm, \"registry\")\n fresh_w3.pm.registry = empty_sol_registry\n assert isinstance(fresh_w3.pm.registry, ERCRegistry)\n assert is_address(fresh_w3.pm.registry.address)\n\n\ndef test_pm_must_set_registry_before_all_registry_interaction_functions(fresh_w3):\n with pytest.raises(PMError):\n fresh_w3.pm.release_package(\n \"package\", \"1.0.0\", \"ipfs://QmbeVyFLSuEUxiXKwSsEjef6icpdTdA4kGG9BcrJXKNKUW\"\n )\n with pytest.raises(PMError):\n fresh_w3.pm.get_release_id_data(b\"invalid_release_id\")\n with pytest.raises(PMError):\n fresh_w3.pm.get_release_id(\"package\", \"1.0.0\")\n with pytest.raises(PMError):\n fresh_w3.pm.get_release_data(\"package\", \"1.0.0\")\n with pytest.raises(PMError):\n fresh_w3.pm.get_package(\"package\", \"1.0.0\")\n with pytest.raises(PMError):\n fresh_w3.pm.get_all_package_names()\n with pytest.raises(PMError):\n fresh_w3.pm.get_all_package_releases(\"package\")\n with pytest.raises(PMError):\n fresh_w3.pm.get_release_count(\"package\")\n with pytest.raises(PMError):\n fresh_w3.pm.get_package_count()\n\n\n@pytest.mark.parametrize(\n \"registry_getter\", [\"empty_vy_registry\", \"empty_sol_registry\"], indirect=True\n)\ndef test_pm_release_package(registry_getter, w3):\n w3.pm.registry = registry_getter\n w3.pm.release_package(\n \"escrow\", \"1.0.0\", \"ipfs://QmPDwMHk8e1aMEZg3iKsUiPSkhHkywpGB3KHKM52RtGrkv\"\n )\n w3.pm.release_package(\n \"owned\", \"1.0.0\", \"ipfs://QmbeVyFLSuEUxiXKwSsEjef6icpdTdA4kGG9BcrJXKNKUW\"\n )\n release_id_1 = w3.pm.get_release_id(\"escrow\", \"1.0.0\")\n release_id_2 = w3.pm.get_release_id(\"owned\", \"1.0.0\")\n package_data_1 = w3.pm.get_release_id_data(release_id_1)\n package_data_2 = w3.pm.get_release_id_data(release_id_2)\n assert package_data_1[0] == \"escrow\"\n assert package_data_1[1] == \"1.0.0\"\n assert package_data_1[2] == \"ipfs://QmPDwMHk8e1aMEZg3iKsUiPSkhHkywpGB3KHKM52RtGrkv\"\n assert package_data_2[0] == \"owned\"\n assert package_data_2[1] == \"1.0.0\"\n assert package_data_2[2] == \"ipfs://QmbeVyFLSuEUxiXKwSsEjef6icpdTdA4kGG9BcrJXKNKUW\"\n\n\n@pytest.mark.parametrize(\n \"registry_getter\", [\"loaded_vy_registry\", \"loaded_sol_registry\"], indirect=True\n)\ndef test_pm_get_release_data(registry_getter, w3):\n registry, _, _ = registry_getter\n w3.pm.registry = registry\n package_data = w3.pm.get_release_data(\"package\", \"1.0.0\")\n assert package_data[0] == \"package\"\n assert package_data[1] == \"1.0.0\"\n assert package_data[2] == \"ipfs://Qme4otpS88NV8yQi8TfTP89EsQC5bko3F5N1yhRoi6cwGV\"\n\n\n@pytest.mark.parametrize(\n \"registry_getter\", [\"loaded_vy_registry\", \"loaded_sol_registry\"], indirect=True\n)\ndef test_pm_get_all_package_names(registry_getter, w3):\n registry, _, _ = registry_getter\n w3.pm.registry = registry\n all_pkgs = w3.pm.get_all_package_names()\n assert all_pkgs == (\n \"package\",\n \"package1\",\n \"package2\",\n \"package3\",\n \"package4\",\n \"package5\",\n )\n\n\n@pytest.mark.parametrize(\n \"registry_getter\", [\"loaded_vy_registry\", \"loaded_sol_registry\"], indirect=True\n)\ndef test_pm_package_count(registry_getter, w3):\n registry, _, _ = registry_getter\n w3.pm.registry = registry\n assert w3.pm.get_package_count() == 6\n\n\n@pytest.mark.parametrize(\n \"registry_getter\", [\"loaded_vy_registry\", \"loaded_sol_registry\"], indirect=True\n)\ndef test_pm_get_release_count(registry_getter, w3):\n registry, _, _ = registry_getter\n w3.pm.registry = registry\n pkg_0_release_count = w3.pm.get_release_count(\"package\")\n pkg_1_release_count = w3.pm.get_release_count(\"package1\")\n pkg_2_release_count = w3.pm.get_release_count(\"package2\")\n assert pkg_0_release_count == 6\n assert pkg_1_release_count == 1\n assert pkg_2_release_count == 1\n\n\n@pytest.mark.parametrize(\n \"registry_getter\", [\"loaded_vy_registry\", \"loaded_sol_registry\"], indirect=True\n)\ndef test_pm_get_all_package_versions(registry_getter, w3):\n registry, _, _ = registry_getter\n w3.pm.registry = registry\n all_rls_pkg_0 = w3.pm.get_all_package_releases(\"package\")\n all_rls_pkg_1 = w3.pm.get_all_package_releases(\"package1\")\n all_rls_pkg_2 = w3.pm.get_all_package_releases(\"package2\")\n assert all_rls_pkg_0 == (\n (\"1.0.0\", \"ipfs://Qme4otpS88NV8yQi8TfTP89EsQC5bko3F5N1yhRoi6cwGV\"),\n (\"1.0.1\", \"ipfs://Qme4otpS88NV8yQi8TfTP89EsQC5bko3F5N1yhRoi6cwGW\"),\n (\"1.0.2\", \"ipfs://Qme4otpS88NV8yQi8TfTP89EsQC5bko3F5N1yhRoi6cwGX\"),\n (\"1.0.3\", \"ipfs://Qme4otpS88NV8yQi8TfTP89EsQC5bko3F5N1yhRoi6cwGJ\"),\n (\"1.0.4\", \"ipfs://Qme4otpS88NV8yQi8TfTP89EsQC5bko3F5N1yhRoi6cwGK\"),\n (\"1.0.5\", \"ipfs://Qme4otpS88NV8yQi8TfTP89EsQC5bko3F5N1yhRoi6cwGH\"),\n )\n assert all_rls_pkg_1 == (\n (\"1.0.1\", \"ipfs://Qme4otpS88NV8yQi8TfTP89EsQC5bko3F5N1yhRoi6cwGZ\"),\n )\n assert all_rls_pkg_2 == (\n (\"1.0.1\", \"ipfs://Qme4otpS88NV8yQi8TfTP89EsQC5bko3F5N1yhRoi6cwGT\"),\n )\n\n\n@pytest.mark.parametrize(\n \"registry_getter\", [\"loaded_vy_registry\", \"loaded_sol_registry\"], indirect=True\n)\ndef test_pm_get_package(registry_getter, w3, monkeypatch):\n registry, _, _ = registry_getter\n w3.pm.registry = registry\n monkeypatch.setenv(\n \"ETHPM_IPFS_BACKEND_CLASS\", \"ethpm.backends.ipfs.DummyIPFSBackend\"\n )\n w3.pm.deploy_and_set_registry()\n w3.pm.release_package(\n \"owned\", \"1.0.0\", \"ipfs://QmbeVyFLSuEUxiXKwSsEjef6icpdTdA4kGG9BcrJXKNKUW\"\n )\n pkg = w3.pm.get_package(\"owned\", \"1.0.0\")\n assert isinstance(pkg, Package)\n assert pkg.name == \"owned\"\n","sub_path":"tests/core/pm-module/test_registry_integration.py","file_name":"test_registry_integration.py","file_ext":"py","file_size_in_byte":7044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"592182922","text":"meal = float(input(\"What is your meal amount: \"))\ntip = int(input(\"Enter tip %: \"))\ntax = .10\nprint(\"\\n\")\ntip_amt = meal * tip/100\ntax_amt = meal * tax\ntotal = meal + tip_amt + tax_amt\nprint(f\"\\nThe total meal was ${meal:.2f} and your tip was ${tip:.2f}\")\nprint(f\"The total with tax is ${total:.2f}.\\n\")\n\nnumber_of_people = (input(\"How many people are splitting the bill?: \"))\nprint(\"\\n\")\n","sub_path":"Tanya_Pierce/tip_calculator.py","file_name":"tip_calculator.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"366957895","text":"import sys\nimport io\nimport urllib.request as u_req\nfrom urllib.parse import urlencode\n\nsys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8');\nsys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8');\n\nurl1 = \"http://www.encar.com\";\n\nAPI = \"https://www.mois.go.kr/gpms/view/jsp/rss/rss.jsp\"\n\nvalue ={\n 'ctxCd': '1012'\n}\nprint('before',value);\nparams = urlencode(value);\nprint('after',params);\n\nurl = API + \"?\" + params\nprint(\"URL: \"+ url);\n\nreqData = u_req.urlopen(url).read().decode('utf-8');\nprint(\"출력 \",reqData);\n","sub_path":"download2_3_3.py","file_name":"download2_3_3.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"156845399","text":"import sensor\nimport GpsController\nimport socket\nfrom subprocess import Popen\n\n# add logging support\nimport logging\nmod_log = logging.getLogger('airpi.serial_gps')\n\nlocns = {\n \"MOB\" : \"Mobile\",\n \"RED\" : \"Node-Red\",\n \"TA1\" : \"Taunton\",\n \"TS5\" : \"Middlesbrough\"\n}\n\nclass GPS(sensor.Sensor):\n requiredData = []\n optionalData = [\"setTime\"]\n gpsc = None\n\n def __init__(self, data):\n self.log = logging.getLogger('airpi.serial_gps')\n self.sensorName = \"MTK3339\"\n self.valType = \"Location\"\n self.locnName = locns[socket.gethostname().split(\"-\")[1]]\n self.setTime = data[\"setTime\"]\n\n # start polling the GPS data\n try:\n self.gpsc = GpsController.GpsController()\n # start the controller thread\n self.gpsc.start()\n except Exception as e:\n self.log.error(\"GPS __init__ Exception: {0}\".format(e))\n raise\n\n def getVal(self):\n gpsData = [self.gpsc.utc, self.gpsc.fix.latitude, self.gpsc.fix.longitude, self.gpsc.fix.altitude, self.gpsc.fix.speed, \"physical\"]\n\n # we're mobile and outside if locnName is \"Mobile\"\n if self.locnName == \"Mobile\":\n gpsData.extend([\"mobile\", \"outdoor\"])\n else:\n gpsData.extend([\"fixed\", \"indoor\"])\n\n self.log.debug(\"GPS data: {0}\".format(gpsData))\n return gpsData\n\n def stopController(self):\n print(\"Stopping GPS controller\")\n self.log.info(\"Stopping GPS controller: {0}\".format(self.gpsc.isAlive()))\n if self.gpsc.isAlive():\n self.gpsc.stopController()\n # wait for the thread to finish\n self.gpsc.join()\n\n def setClock(self):\n print(\"Setting Clock\")\n self.log.debug(\"Setting Clock: {0}\".format(self.setTime))\n if self.setTime:\n if self.gpsc.utc:\n self.log.debug(\"setClock: {0}\".format(self.gpsc.utc))\n gpstime = self.gpsc.utc[:10] + ' ' + self.gpsc.utc[11:19]\n self.log.info(\"Setting Clock to {0}\".format(gpstime))\n # set the time\n Popen('/bin/date -u --set=\"{0}\"'.format(gpstime), shell=True)\n","sub_path":"sensors/serial_gps.py","file_name":"serial_gps.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"586511532","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport json\nimport gspread\nfrom consolemsg import error, fail\n\nclass SheetFetcher():\n\n def __init__(self, documentName, credentialFilename):\n from oauth2client.service_account import ServiceAccountCredentials\n try:\n credentials = ServiceAccountCredentials.from_json_keyfile_name(\n credentialFilename,\n scopes=['https://spreadsheets.google.com/feeds',],\n )\n except Exception as e:\n fail(str(e))\n\n gc = gspread.authorize(credentials)\n try:\n self.doc = gc.open(documentName)\n except:\n error(\"No s'ha trobat el document, o no li has donat permisos a l'aplicacio\")\n error(\"Cal compartir el document '{}' amb el següent correu:\"\n .format(documentName,json_key['client_email']))\n error(str(e))\n sys.exit(-1)\n\n def _worksheet(self, selector):\n if type(selector) is int:\n return self.doc.get_worksheet(selector)\n\n for s in self.doc.worksheets():\n if selector == s.id: return s\n if selector == s.title: return s\n\n raise Exception(\"Worksheet '{}' not found\".format(selector))\n\n def get_range(self, worksheetsSelector, rangeName):\n worksheet = self._worksheet(worksheetsSelector)\n cells = worksheet.range(rangeName)\n width = cells[-1].col-cells[0].col +1\n height = cells[-1].row-cells[0].row +1\n return [\n [cell.value for cell in row]\n for row in zip( *(iter(cells),)*width)\n ]\n\n def get_fullsheet(self, worksheetsSelector):\n workSheet = self._worksheet(worksheetsSelector)\n return workSheet.get_all_values()\n","sub_path":"sheetfetcher.py","file_name":"sheetfetcher.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"414180963","text":"import unittest\r\nimport re\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.common.exceptions import TimeoutException\r\nimport os.path\r\nfrom os import path\r\n\r\nlogin_url='https://qa-sandbox.apps.htec.rs/login'\r\nemail_identifier=\"//*[@id='root']/div/div[2]/div/div/div/div/form/div[1]/input\"\r\npass_identifier=\"//*[@id='root']/div/div[2]/div/div/div/div/form/div[2]/input\"\r\nbtn_identifier=\"/html/body/div/div/div[2]/div/div/div/div/form/button\"\r\nsandbox_identifier='//*[@id=\"root\"]/div/nav/div/a/b'\r\nCaseLink_identifier='//*[@id=\"root\"]/div/div[2]/div/div/div[2]/div[2]/div'\r\nCaseList_identifier = \"div[class='list-group mt-5']>a\"\r\nCaseTitle_identifier='//*[@id=\"root\"]/div/div[2]/div/div/div/form/div[1]/input'\r\nCaseDescription_identifier='//*[@id=\"root\"]/div/div[2]/div/div/div/form/div[2]/textarea'\r\nCaseExpected_identifier='//*[@id=\"root\"]/div/div[2]/div/div/div/form/div[3]/input'\r\nCaseStep1_identifier='//*[@id=\"stepId\"]'\r\nDelete_identifier='//*[@id=\"root\"]/div/div[2]/div/div/div/form/span[2]/button'\r\nConfirm_identifier='//*[@id=\"root\"]/div/div[2]/div/div/div/form/span[2]/div/div[2]/p/span[2]/button'\r\nCaseCreate_identifier='//*[@id=\"root\"]/div/div[2]/div/a[2]'\r\nsubmit_identifier='//*[@id=\"root\"]/div/div[2]/div/div/div/form/button'\r\nautomated_identifier='/html/body/div/div/div[2]/div/div/div/form/div[4]/div/div/label'\r\n\r\nclass TestCaseInfo:\r\n \r\n def __init__(self,l='',t='',d='',e='',s=''):\r\n self.link=l\r\n self.title=t\r\n self.description=d\r\n self.expected=e\r\n self.step1=s\r\n\r\n def caseID(self):\r\n return self.link[-4:]\r\n \r\n def describe(self, putin):\r\n if putin is None:\r\n self.description=''\r\n else:\r\n self.description=putin\r\n \r\n def export(self):\r\n FileName=self.caseID()+'.tst'\r\n file = open(FileName,\"w+\")\r\n file.write(self.link+'\"\\n')\r\n file.write(self.title+'\"\\n')\r\n file.write(self.description+'\"\\n')\r\n file.write(self.expected+'\"\\n')\r\n file.write(self.step1+'\"\\n')\r\n file.close()\r\n\r\nclass FirefoxTest(unittest.TestCase):\r\n\r\n def setUp(self):\r\n self.browser = webdriver.Firefox()\r\n self.browser.get(login_url)\r\n self.browser.find_element_by_xpath(email_identifier).send_keys('irinelko@gmail.com')\r\n self.browser.find_element_by_xpath(pass_identifier).send_keys('knedlica')\r\n self.browser.find_element_by_xpath(btn_identifier).submit()\r\n waitcondition = WebDriverWait(self.browser, 20).until(EC.presence_of_element_located((By.XPATH, CaseLink_identifier)))\r\n \r\n def deleteTest(self):\r\n self.browser.find_element_by_xpath(Delete_identifier).click()\r\n waitcondition = WebDriverWait(self.browser, 20).until(EC.presence_of_element_located((By.XPATH, Confirm_identifier)))\r\n self.browser.find_element_by_xpath(Confirm_identifier).click()\r\n\r\n def test_LoadTests(self):\r\n files = [f for f in os.listdir('.') if os.path.isfile(f)]\r\n self.browser.find_element_by_xpath(CaseLink_identifier).click()\r\n for f in files:\r\n if f.endswith('.tst'):\r\n waitcondition = WebDriverWait(self.browser, 20).until(EC.presence_of_element_located((By.XPATH, CaseCreate_identifier)))\r\n self.browser.find_element_by_xpath(CaseCreate_identifier).click()\r\n file = open(f,\"r\")\r\n link=file.readline()\r\n self.browser.find_element_by_xpath(CaseTitle_identifier).send_keys(file.readline())\r\n self.browser.find_element_by_xpath(CaseDescription_identifier).send_keys(file.readline())\r\n self.browser.find_element_by_xpath(CaseExpected_identifier).send_keys(file.readline())\r\n self.browser.find_element_by_xpath(CaseStep1_identifier).send_keys(file.readline())\r\n if file.readline().rstrip()=='true':\r\n self.browser.find_element_by_xpath(automated_identifier).click()\r\n self.browser.find_element_by_xpath(submit_identifier).click()\r\n file.close()\r\n\r\n def test_EditTests(self):\r\n self.browser.find_element_by_xpath(CaseLink_identifier).click() \r\n waitcondition = WebDriverWait(self.browser, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, CaseList_identifier)))\r\n CaseList=self.browser.find_elements_by_css_selector(CaseList_identifier)\r\n CaseLinks=[]\r\n\r\n for case in CaseList:\r\n CaseLink=case.get_attribute(\"href\")\r\n CaseLinks.append(CaseLink)\r\n for link in CaseLinks:\r\n self.browser.get(link)\r\n waitcondition = WebDriverWait(self.browser, 20).until(EC.presence_of_element_located((By.XPATH, CaseTitle_identifier)))\r\n self.browser.find_element_by_xpath(CaseTitle_identifier).send_keys(' edited')\r\n self.browser.find_element_by_xpath(CaseDescription_identifier).send_keys(' edited')\r\n self.browser.find_element_by_xpath(CaseExpected_identifier).send_keys(' edited')\r\n self.browser.find_element_by_xpath(CaseStep1_identifier).send_keys(' edited')\r\n StepContainer=self.browser.find_elements_by_xpath('//*[@id=\"root\"]/div/div[2]/div/div/div/form')\r\n for TestStep in StepContainer:\r\n print(TestStep.get_attribute(\"class\"))\r\n self.browser.find_element_by_xpath(submit_identifier).click()\r\n\r\n def test_DeleteEdited(self):\r\n self.browser.find_element_by_xpath(CaseLink_identifier).click() \r\n waitcondition = WebDriverWait(self.browser, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, CaseList_identifier)))\r\n CaseList=self.browser.find_elements_by_class_name(CaseList_identifier)\r\n CaseLinks=[]\r\n\r\n for case in CaseList:\r\n CaseLink=case.get_attribute(\"href\")\r\n CaseLinks.append(CaseLink)\r\n for link in CaseLinks:\r\n self.browser.get(link)\r\n waitcondition = WebDriverWait(self.browser, 20).until(EC.presence_of_element_located((By.XPATH, CaseTitle_identifier)))\r\n title=self.browser.find_element_by_xpath(CaseTitle_identifier).get_attribute(\"value\") \r\n if title[-6:]=='edited':\r\n self.deleteTest()\r\n\r\n def tearDown(self):\r\n self.browser.quit()\r\n\"\"\"\r\n def test_ExportCases(self):\r\n\r\n waitcondition = WebDriverWait(self.browser, 20).until(EC.presence_of_element_located((By.XPATH, CaseLink_identifier)))\r\n self.browser.find_element_by_xpath(CaseLink_identifier).click() \r\n waitcondition = WebDriverWait(self.browser, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, CaseList_identifier)))\r\n CaseList=self.browser.find_elements_by_css_selector(CaseList_identifier)\r\n CaseLinks=[]\r\n\r\n for case in CaseList:\r\n CaseLink=case.get_attribute(\"href\")\r\n CaseLinks.append(CaseLink)\r\n for link in CaseLinks:\r\n self.browser.get(link)\r\n Test=TestCaseInfo()\r\n waitcondition = WebDriverWait(self.browser, 20).until(EC.presence_of_element_located((By.XPATH, CaseTitle_identifier)))\r\n TitleOfCase=self.browser.find_element_by_xpath(CaseTitle_identifier).get_attribute(\"value\")\r\n DescriptionOfCase=self.browser.find_element_by_xpath(CaseDescription_identifier).text\r\n ExpectedOfCase=self.browser.find_element_by_xpath(CaseExpected_identifier).get_attribute(\"value\")\r\n StepOfCase=self.browser.find_element_by_xpath(CaseStep1_identifier).get_attribute(\"value\")\r\n print(TitleOfCase)\r\n Test.link=link\r\n Test.title=TitleOfCase\r\n Test.describe(DescriptionOfCase)\r\n Test.expected=ExpectedOfCase\r\n Test.step1=StepOfCase\r\n Test.export()\r\n self.deleteTest()\r\n\"\"\"\r\n\r\n \r\nif __name__ == \"__main__\":\r\n unittest.main()\r\n","sub_path":"QAtestAutomation.py","file_name":"QAtestAutomation.py","file_ext":"py","file_size_in_byte":8127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"24829361","text":"#!/usr/bin/env python\n\nfrom appy.pod.renderer import Renderer\nimport datetime\n\nhora = datetime.datetime.now()\ndef to_upper(s):\n return s.upper()\nrenderer = Renderer(\n 'ex_02.odt', \n globals(), \n 'out_02.odt'\n )\nrenderer.run()\n","sub_path":"procesa_fl/procesa_sse/appy/Manual/ex_02.py","file_name":"ex_02.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"173578558","text":"from astropy.io import fits\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport os\nfrom os import listdir\nimport pdb\n\ndef calculate_one_exposure(night,expid,sp_arr,sm_arr,cam_arr,preproc_dir=None,visual_check=False,full_region=False):\n\n n_sp=len(sp_arr)\n\n df_output = pd.DataFrame({'night':[], 'expid':[],'mjd':[],'flavor':[],'obstype':[],'camera':[],'rdnoise_preproc_a':[],'rdnoise_header_a':[],'rdnoise_preproc_b':[],'rdnoise_header_b':[],'rdnoise_preproc_c':[],'rdnoise_header_c':[],'rdnoise_preproc_d':[],'rdnoise_header_d':[],'median_flux_all':[],'median_flux_a':[],'median_flux_b':[],'median_flux_c':[],'median_flux_d':[]})\n\n for cam in cam_arr:\n rdnoise_region_a_arr=[]\n rdnoise_header_a_arr=[]\n rdnoise_region_b_arr=[]\n rdnoise_header_b_arr=[]\n rdnoise_region_c_arr=[]\n rdnoise_header_c_arr=[]\n rdnoise_region_d_arr=[]\n rdnoise_header_d_arr=[]\n for i in range(n_sp):\n camera=cam.lower()+sp_arr[i]\n #filename=preproc_dir+'/'+night+'/'+expid+'/preproc-'+cam+sp_arr[i]+'-'+expid+'.fits'\n filename=preproc_dir+'/'+night+'/'+expid+'/preproc-'+expid+'-'+cam+sp_arr[i]+'.fits'\n print('Processing ',camera)\n filename_raw='/global/cfs/cdirs/desi/spectro/data/'+night+'/'+expid+'/desi-'+expid+'.fits.fz'\n try:\n hdul=fits.open(filename)\n img_preproc=hdul['IMAGE'].data\n img_rdnoise=hdul['READNOISE'].data\n mjd=hdul[0].header['MJD-OBS']\n flavor=hdul[0].header['FLAVOR']\n header_raw=fits.getheader(filename_raw,1)\n obstype=header_raw['OBSTYPE']\n nx=len(img_preproc[0])\n ny=len(img_preproc)\n ### Select regions [y1:y2,x1:x2] ####\n if full_region:\n width=100\n x_off=0\n y1=0\n y2=int(ny/2)-1\n x1=0\n x2=width-1\n else:\n width=60\n x_off=10\n y1=250 #0\n y2=y1+500 #int(ny/2)-1\n x1=0+x_off\n x2=width-1+x_off\n region_a=img_preproc.copy()[y1:y2,x1:x2]\n rdnoise_a=np.median(img_rdnoise[y1:y2,x1:x2])\n # B\n if full_region:\n y1=0 \n y2=int(ny/2)-1\n x1=nx-width\n x2=nx-1\n else:\n y1=250 #\n y2=y1+500 #int(ny/2)-1\n x1=nx-width-x_off\n x2=nx-1-x_off\n region_b=img_preproc.copy()[y1:y2,x1:x2]\n rdnoise_b=np.median(img_rdnoise[y1:y2,x1:x2])\n # C\n if full_region:\n y1=int(ny/2)-1\n y2=ny-1\n x1=nx-width\n x2=nx-1\n else:\n y1=int(ny/2)-1+1250\n y2=y1+500#ny-1\n x1=nx-width-x_off\n x2=nx-1-x_off\n region_c=img_preproc.copy()[y1:y2,x1:x2]\n rdnoise_c=np.median(img_rdnoise[y1:y2,x1:x2])\n # D \n if full_region:\n y1=int(ny/2)-1\n y2=ny-1\n x1=0\n x2=width-1\n else:\n y1=int(ny/2)-1+1250\n y2=y1+500#ny-1\n x1=0+x_off\n x2=width-1+x_off \n region_d=img_preproc.copy()[y1:y2,x1:x2]\n rdnoise_d=np.median(img_rdnoise[y1:y2,x1:x2])\n\n std_a=(np.percentile(region_a,84)-np.percentile(region_a,16))/2.\n std_b=(np.percentile(region_b,84)-np.percentile(region_b,16))/2.\n std_c=(np.percentile(region_c,84)-np.percentile(region_c,16))/2.\n std_d=(np.percentile(region_d,84)-np.percentile(region_d,16))/2.\n median_flux_all=np.median(img_preproc)\n print(median_flux_all)\n median_flux_a=np.median(region_a)\n median_flux_b=np.median(region_b)\n median_flux_c=np.median(region_c)\n median_flux_d=np.median(region_d)\n\n if (visual_check):# and flavor.lower=='twilight'):\n plt.imshow(img_preproc,vmin=0,vmax=10)\n plt.colorbar()\n plt.show()\n thres=0\n nbin=25\n vmin=-5\n vmax=15\n xrange=(-15,20)\n if abs(rdnoise_a-std_a)>=thres or abs(rdnoise_b-std_b)>=thres or abs(rdnoise_c-std_c)>=thres or abs(rdnoise_d-std_d)>=thres:\n pdb.set_trace()\n plt.figure(figsize=(19,10))\n plt.subplot(2,4,1)\n plt.title(camera+' A header:'+str(rdnoise_a)[0:3]+' preproc:'+str(std_a)[0:3])\n plt.hist(np.array(region_a[0:500,:]).ravel(),nbin,range=xrange,alpha=0.5,color='red',label='[0:500]')\n plt.hist(np.array(region_a[500:1000,:]).ravel(),nbin,range=xrange,alpha=0.5,color='orange',label='[501:1000]')\n plt.hist(np.array(region_a[1001:1500,:]).ravel(),nbin,range=xrange,alpha=0.5,color='yellow',label='[1001:1500]')\n plt.hist(np.array(region_a[1501:,:]).ravel(),nbin,range=xrange,alpha=0.5,color='green',label='[1501:]')\n plt.legend(loc=0)\n plt.subplot(2,4,2)\n plt.title(camera+' B header:'+str(rdnoise_b)[0:3]+' preproc:'+str(std_b)[0:3])\n plt.hist(np.array(region_b[0:500,:]).ravel(),nbin,range=xrange,alpha=0.5,color='red')\n plt.hist(np.array(region_b[500:1000,:]).ravel(),nbin,range=xrange,alpha=0.5,color='orange')\n plt.hist(np.array(region_b[1001:1500,:]).ravel(),nbin,range=xrange,alpha=0.5,color='yellow')\n plt.hist(np.array(region_b[1501:,:]).ravel(),nbin,range=xrange,alpha=0.5,color='green')\n plt.subplot(2,4,3)\n plt.title(camera+' C header:'+str(rdnoise_c)[0:3]+' preproc:'+str(std_c)[0:3])\n plt.hist(np.array(region_c[0:500,:]).ravel(),nbin,range=xrange,alpha=0.5,color='red')\n plt.hist(np.array(region_c[500:1000,:]).ravel(),nbin,range=xrange,alpha=0.5,color='orange')\n plt.hist(np.array(region_c[1001:1500,:]).ravel(),nbin,range=xrange,alpha=0.5,color='yellow')\n plt.hist(np.array(region_c[1501:,:]).ravel(),nbin,range=xrange,alpha=0.5,color='green')\n plt.subplot(2,4,4)\n plt.title(camera+' D header:'+str(rdnoise_d)[0:3]+' preproc:'+str(std_d)[0:3])\n plt.hist(np.array(region_d[0:500,:]).ravel(),nbin,range=xrange,alpha=0.5,color='red')\n plt.hist(np.array(region_d[500:1000,:]).ravel(),nbin,range=xrange,alpha=0.5,color='orange')\n plt.hist(np.array(region_d[1001:1500,:]).ravel(),nbin,range=xrange,alpha=0.5,color='yellow')\n plt.hist(np.array(region_d[1501:,:]).ravel(),nbin,range=xrange,alpha=0.5,color='green')\n\n plt.subplot(2,4,5)\n plt.imshow(region_a,vmin=vmin,vmax=vmax)\n plt.title('A')\n plt.subplot(2,4,6)\n plt.imshow(region_b,vmin=vmin,vmax=vmax)\n plt.title('B')\n plt.subplot(2,4,7)\n plt.title('C')\n plt.imshow(region_c,vmin=vmin,vmax=vmax)\n plt.subplot(2,4,8)\n plt.title('D')\n plt.imshow(region_d,vmin=vmin,vmax=vmax)\n plt.show()\n\n d_this={'night':night, 'expid':expid,'mjd':mjd,'flavor':flavor,'obstype':obstype,'camera':camera,'rdnoise_preproc_a':std_a,'rdnoise_header_a':rdnoise_a,'rdnoise_preproc_b':std_b,'rdnoise_header_b':rdnoise_b,'rdnoise_preproc_c':std_c,'rdnoise_header_c':rdnoise_c,'rdnoise_preproc_d':std_d,'rdnoise_header_d':rdnoise_d,'median_flux_all':median_flux_all,'median_flux_a':median_flux_a,'median_flux_b':median_flux_b,'median_flux_c':median_flux_c,'median_flux_d':median_flux_d}\n df_output=df_output.append(d_this,ignore_index=True)\n except:\n print('Fail to process '+camera)\n\n return df_output\n\n\ndef calculate_one_night(night,preproc_dir=None,max=None):\n #print('{} Checking for new files on {}'.format(time.asctime(), night))\n expids=listdir(preproc_dir+'/'+str(night)+'/')\n expids.sort(reverse=True)\n sp_arr=['0', '1','2','3','4','5','6','7','8','9']\n sm_arr=['4','10','5','6','1','9','7','8','2','3']\n cam_arr=['b','r','z']\n\n df_output = pd.DataFrame({'night':[], 'expid':[],'mjd':[],'flavor':[],'obstype':[],'camera':[],'rdnoise_preproc_a':[],'rdnoise_header_a':[],'rdnoise_preproc_b':[],'rdnoise_header_b':[],'rdnoise_preproc_c':[],'rdnoise_header_c':[],'rdnoise_preproc_d':[],'rdnoise_header_d':[],'median_flux_all':[],'median_flux_a':[],'median_flux_b':[],'median_flux_c':[],'median_flux_d':[]})\n if not max:\n max=len(expids)\n elif max>len(expids):\n max=len(expids)\n for i in range(max):\n expid=expids[i]\n print(night,' ',expid)\n # Check the redux folder for reduced files\n df_expid=calculate_one_exposure(str(night),expid,sp_arr,sm_arr,cam_arr,preproc_dir=preproc_dir)\n df_output=df_output.append(df_expid)\n return df_output\n\n######################################\n####### Main code ####################\n######################################\n### Find all nights ###\n#######################\npreproc_dir=os.getenv('DESI_SPECTRO_REDUX')+'/daily/preproc/'\n#preproc_dir='//global/project/projectdirs/desi/users/zhangkai/redux_zeros/'\nnights=listdir(preproc_dir)\nnights=[int(x) for x in nights]\nnights.sort(reverse=True)\nread=True\nadd='all'\nnight_min=20200304\ndata_file='check_rdnoise_preproc_'+add+'.csv'\n\nif read:\n df_all_nights = pd.read_csv(data_file)\nelse:\n \n df_all_nights = pd.DataFrame({'night':[], 'expid':[],'mjd':[],'flavor':[],'obstype':[],'camera':[],'rdnoise_preproc_a':[],'rdnoise_header_a':[],'rdnoise_preproc_b':[],'rdnoise_header_b':[],'rdnoise_preproc_c':[],'rdnoise_header_c':[],'rdnoise_preproc_d':[],'rdnoise_header_d':[],'median_flux_all':[],'median_flux_a':[],'median_flux_b':[],'median_flux_c':[],'median_flux_d':[]})\n\n n_night=len(nights)\n for j in range(n_night):\n night=nights[j]\n df_night=calculate_one_night(night,preproc_dir=preproc_dir)\n df_all_nights=df_all_nights.append(df_night)\n cmd='rm '+data_file\n a=os.system(cmd)\n df_all_nights.to_csv(data_file,index=False)\n\n\nsp_arr=['0', '1','2','3','4','5','6','7','8','9']\nsm_arr=['4','10','5','6','1','9','7','8','2','3']\ncam_arr=['b','r','z']\n#obstype_arr=['zero']\nobstype_arr=['twilight','flat','arc','science']\n\nfrom matplotlib.backends.backend_pdf import PdfPages\nimport pdb;pdb.set_trace()\n\nwith PdfPages('check_rdnoise_preproc_1_'+add+'.pdf') as pdf:\n for obstype in obstype_arr:\n print(obstype)\n if True:\n for cam in cam_arr:\n plt.figure(figsize=(20,15))\n font = {'family' : 'normal',\n 'size' : 22}\n plt.rc('font', **font)\n for i in range(len(sp_arr)):\n sp=sp_arr[i]\n camera=cam+sp\n ind=np.where((df_all_nights['night']>=night_min) & (df_all_nights['camera'].str.lower()==camera) & (df_all_nights['obstype'].str.lower()==obstype))\n plt.subplot(3,4,i+1)\n x=df_all_nights.iloc[ind]['mjd']-int(min(df_all_nights.iloc[ind]['mjd']))\n plt.plot(x,df_all_nights.iloc[ind]['rdnoise_preproc_a'],'+',color='red',label='Amp A preproc')\n plt.plot(x,df_all_nights.iloc[ind]['rdnoise_preproc_b'],'+',color='yellow',label='Amp B preproc')\n plt.plot(x,df_all_nights.iloc[ind]['rdnoise_preproc_c'],'+',color='blue',label='Amp C preproc')\n plt.plot(x,df_all_nights.iloc[ind]['rdnoise_preproc_d'],'+',color='green',label='Amp D preproc')\n #plt.plot(x,df_all_nights.iloc[ind]['rdnoise_preproc_a'].tolist(),color='red')\n #plt.plot(x,df_all_nights.iloc[ind]['rdnoise_preproc_b'].tolist(),color='yellow')\n #plt.plot(x,df_all_nights.iloc[ind]['rdnoise_preproc_c'].tolist(),color='blue')\n #plt.plot(x,df_all_nights.iloc[ind]['rdnoise_preproc_d'].tolist(),color='green')\n plt.plot(x,df_all_nights.iloc[ind]['rdnoise_header_a'],'o',color='red',label='Amp A header')\n plt.plot(x,df_all_nights.iloc[ind]['rdnoise_header_b'],'o',color='yellow',label='Amp B header')\n plt.plot(x,df_all_nights.iloc[ind]['rdnoise_header_c'],'o',color='blue',label='Amp C header')\n plt.plot(x,df_all_nights.iloc[ind]['rdnoise_header_d'],'o',color='green',label='Amp D header')\n #plt.plot(x,df_all_nights.iloc[ind]['rdnoise_header_a'].tolist(),color='red')\n #plt.plot(x,df_all_nights.iloc[ind]['rdnoise_header_b'].tolist(),color='yellow')\n #plt.plot(x,df_all_nights.iloc[ind]['rdnoise_header_c'].tolist(),color='blue')\n #plt.plot(x,df_all_nights.iloc[ind]['rdnoise_header_d'].tolist(),color='green')\n plt.axis([0,max(x)+10,2,6])\n plt.title(camera+' '+obstype)\n if sp=='0':\n plt.legend(loc=0)\n if sp=='4':\n plt.ylabel('RDNOISE')\n if sp=='9':\n plt.xlabel('MJD-'+str(int(min(df_all_nights.iloc[ind]['mjd']))))\n pdf.savefig()\n plt.close()\n else:\n pass\n\nwith PdfPages('check_rdnoise_preproc_2_'+add+'.pdf') as pdf:\n for obstype in obstype_arr:\n print(obstype)\n if True:\n for cam in cam_arr:\n plt.figure(figsize=(20,15))\n font = {'family' : 'normal',\n 'size' : 22}\n plt.rc('font', **font)\n \n for i in range(len(sp_arr)):\n sp=sp_arr[i]\n camera=cam+sp\n ind=np.where((df_all_nights['night']>=night_min) & (df_all_nights['camera'].str.lower()==camera) & (df_all_nights['obstype'].str.lower()==obstype))\n plt.subplot(3,4,i+1)\n x=df_all_nights.iloc[ind]['mjd']-int(min(df_all_nights.iloc[ind]['mjd']))\n y=df_all_nights.iloc[ind]['rdnoise_preproc_a']-df_all_nights.iloc[ind]['rdnoise_header_a']\n plt.plot(x,y,'+',color='red',label='Amp A')\n #plt.plot(x,y,color='red')\n\n y=df_all_nights.iloc[ind]['rdnoise_preproc_b']-df_all_nights.iloc[ind]['rdnoise_header_b']\n plt.plot(x,y,'+',color='yellow',label='Amp B')\n #plt.plot(x,y,color='yellow')\n \n y=df_all_nights.iloc[ind]['rdnoise_preproc_c']-df_all_nights.iloc[ind]['rdnoise_header_c']\n plt.plot(x,y,'+',color='green',label='Amp C')\n #plt.plot(x,y,color='green')\n \n y=df_all_nights.iloc[ind]['rdnoise_preproc_d']-df_all_nights.iloc[ind]['rdnoise_header_d']\n plt.plot(x,y,'+',color='blue',label='Amp D')\n #plt.plot(x,y,color='blue')\n plt.axis([0,max(x)+10,-1,2])\n plt.plot([0,10000],[0,0],'--',color='black')\n plt.title(camera+' '+obstype)\n if sp=='0':\n plt.legend(loc=0)\n if sp=='4':\n plt.ylabel('RDNOISE(preproc-header')\n if sp=='9':\n plt.xlabel('MJD-'+str(int(min(df_all_nights.iloc[ind]['mjd']))))\n pdf.savefig()\n plt.close()\n\n\nwith PdfPages('check_rdnoise_preproc_3_'+add+'.pdf') as pdf:\n for obstype in obstype_arr:\n print(obstype)\n if True:\n\n for cam in cam_arr:\n plt.figure(figsize=(20,15))\n font = {'family' : 'normal',\n 'size' : 12}\n plt.rc('font', **font)\n\n for i in range(len(sp_arr)):\n sp=sp_arr[i]\n camera=cam+sp\n\n ind=np.where((df_all_nights['night']>=night_min) & (df_all_nights['camera'].str.lower()==camera) & (df_all_nights['obstype'].str.lower()==obstype))\n x=df_all_nights.iloc[ind]['rdnoise_header_a']\n y=df_all_nights.iloc[ind]['rdnoise_preproc_a']\n plt.subplot(3,4,i+1)\n plt.plot(x,y,'+',label='Amp A')\n x=df_all_nights.iloc[ind]['rdnoise_header_b']\n y=df_all_nights.iloc[ind]['rdnoise_preproc_b']\n plt.plot(x,y,'o',label='Amp B')\n x=df_all_nights.iloc[ind]['rdnoise_header_c']\n y=df_all_nights.iloc[ind]['rdnoise_preproc_c']\n plt.plot(x,y,'v',label='Amp C')\n x=df_all_nights.iloc[ind]['rdnoise_header_d']\n y=df_all_nights.iloc[ind]['rdnoise_preproc_d']\n plt.plot(x,y,'1',label='Amp D')\n plt.axis([1,6,1,6])\n plt.title(camera+' '+obstype)\n plt.xlabel('RDNOISE in header')\n plt.ylabel('RDNOISE measured')\n plt.plot([0,100],[0,100],color='black')\n plt.legend(loc=0)\n pdf.savefig()\n plt.close()\n\nwith PdfPages('check_rdnoise_preproc_4_'+add+'.pdf') as pdf:\n for cam in cam_arr:\n plt.figure(figsize=(20,15))\n font = {'family' : 'normal',\n 'size' : 12}\n plt.rc('font', **font)\n\n for i in range(len(sp_arr)):\n sp=sp_arr[i]\n camera=cam+sp\n\n ind=np.where((df_all_nights['night']>=night_min) & (df_all_nights['camera']==camera))\n x=df_all_nights.iloc[ind]['median_flux_all']\n y=df_all_nights.iloc[ind]['median_flux_a']\n plt.subplot(3,4,i+1)\n plt.plot(x,y,'+',label='Amp A')\n x=df_all_nights.iloc[ind]['median_flux_all']\n y=df_all_nights.iloc[ind]['median_flux_b']\n plt.plot(x,y,'o',label='Amp B')\n x=df_all_nights.iloc[ind]['median_flux_all']\n y=df_all_nights.iloc[ind]['median_flux_c']\n plt.plot(x,y,'v',label='Amp C')\n x=df_all_nights.iloc[ind]['median_flux_all']\n y=df_all_nights.iloc[ind]['median_flux_d']\n plt.plot(x,y,'1',label='Amp D')\n if (add==\"zero\"):\n plt.axis([0,5,0,5])\n plt.plot([0,5],[0,5],color='black')\n else:\n plt.axis([0,1100,0,20])\n plt.plot([0,1100],[0,20],color='black')\n\n plt.title(camera)\n plt.xlabel('Median Flux All Image')\n plt.ylabel('Median Flux regions')\n plt.legend(loc=0)\n pdf.savefig()\n plt.close()\n\nwith PdfPages('check_rdnoise_preproc_5_'+add+'.pdf') as pdf:\n for cam in cam_arr:\n plt.figure(figsize=(20,15))\n font = {'family' : 'normal',\n 'size' : 12}\n plt.rc('font', **font)\n\n for i in range(len(sp_arr)):\n sp=sp_arr[i]\n camera=cam+sp\n\n ind=np.where((df_all_nights['night']>=night_min) & (df_all_nights['camera']==camera))\n x=df_all_nights.iloc[ind]['median_flux_all']\n y=df_all_nights.iloc[ind]['rdnoise_preproc_a']-df_all_nights.iloc[ind]['rdnoise_header_a']\n plt.subplot(3,4,i+1)\n plt.plot(x,y,'+',label='Amp A')\n x=df_all_nights.iloc[ind]['median_flux_all']\n y=df_all_nights.iloc[ind]['rdnoise_preproc_a']-df_all_nights.iloc[ind]['rdnoise_header_a']\n plt.plot(x,y,'o',label='Amp B')\n x=df_all_nights.iloc[ind]['median_flux_all']\n y=df_all_nights.iloc[ind]['rdnoise_preproc_a']-df_all_nights.iloc[ind]['rdnoise_header_a']\n plt.plot(x,y,'v',label='Amp C')\n x=df_all_nights.iloc[ind]['median_flux_all']\n y=df_all_nights.iloc[ind]['rdnoise_preproc_a']-df_all_nights.iloc[ind]['rdnoise_header_a']\n plt.plot(x,y,'1',label='Amp D')\n plt.axis([0,1100,0,2])\n plt.title(camera)\n plt.xlabel('Median Flux All Image')\n plt.ylabel('RDNOISE Difference (preproc-overscan)')\n plt.plot([0,1100],[0,2],color='black')\n plt.legend(loc=0)\n pdf.savefig()\n plt.close()\n\n","sub_path":"sky/check_rdnoise_preproc.py","file_name":"check_rdnoise_preproc.py","file_ext":"py","file_size_in_byte":21251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"183977365","text":"from sklearn.feature_extraction.text import TfidfVectorizer\nfrom scipy.sparse import csr_matrix\nimport numpy as np\n\n\n\nwith open('/Users/yangchengran/Desktop/综合设计2/out.txt') as f3:\n res1 = f3.read()\n\noutfilename = \"/Users/yangchengran/Desktop/综合设计2/TF_IDF.txt\"\noutfilename_1 = \"/Users/yangchengran/Desktop/综合设计2/词向量.txt\"\n\noutputs = open(outfilename, 'w', encoding='UTF-8')\noutput_2=open(outfilename_1, 'w', encoding='UTF-8')\n\ncorpus = [res1]\nvector = TfidfVectorizer()\ntfidf = vector.fit_transform(corpus)\n\n#输出TF-IDF\nwordlist = vector.get_feature_names()#获取词袋模型中的所有词\n# tf-idf矩阵 元素a[i][j]表示j词在i类文本中的tf-idf权重\nweightlist = tfidf.toarray()\n#打印每类文本的tf-idf词语权重,第一个for遍历���有文本,第二个for便利某一类文本下的词语权重\nfor i in range(len(weightlist)):\n print(\"-------第\",i,\"段文本的词语tf-idf权重------\")\n for j in range(len(wordlist)):\n # print(wordlist[j],weightlist[i][j])\n outputs.write(str(wordlist[j])+\": \")\n outputs.write(str(weightlist[i][j])+\" \")\n if j%3==0:\n outputs.writelines(\"\\n\")\n\n#输出词向量\nfor k in range(len(tfidf.indices)):\n output_2.write(str(wordlist[k]) + \": \")\n output_2.writelines(str(tfidf.indices[k])+\" \")\n output_2.writelines(str(tfidf.data[k]) + '\\n')\n\n","sub_path":"代码/rest/向量化.py","file_name":"向量化.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"38365545","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /usr/lib/python2.6/site-packages/lbn/zenoss/brand.py\n# Compiled at: 2010-09-09 07:19:41\nfrom Acquisition import aq_base\nfrom packutils import addZenPackObjects\nZENPACKS = (\n ('ZenMaster', \"Master Zenoss for collecting stats from other remote Zenoss's\"),\n ('ZenSlave', 'Slave Zenoss for reporting stats to ZenMaster'),\n ('ZopeMonitor', 'Performance statistics of remote Zope instance'))\n\ndef addBranding(dmd, zenpack):\n \"\"\"\n Add LBN Manufacturer/Software into Zenoss\n \"\"\"\n manufacturers = dmd.Manufacturers\n if not getattr(aq_base(manufacturers), 'LBN', None):\n manufacturers.manage_addProduct['ZenModel'].manage_addManufacturer('LBN')\n manufacturers.LBN.manage_changeProperties(url='http://au.last-bastion.net', supportNumber='+61 2 8399 1271', address1='Unit 407, 181 Lawson Street', address2='Darlington', city='Sydney', state='NSW', country='Australia', zip='2008')\n lbn = manufacturers.LBN\n products = lbn.products\n for zpack in ZENPACKS:\n packname = 'ZenPacks.lbn.%s' % zpack[0]\n if not getattr(aq_base(products), packname, None):\n lbn.manage_addSoftware(prodName=packname)\n getattr(products, packname).manage_changeProperties(description=zpack[1])\n\n if not getattr(aq_base(products), 'BastionLinux', None):\n lbn.manage_addSoftware(prodName='BastionLinux', isOS=True)\n bl = products.BastionLinux\n bl.manage_changeProperties(description='Enterprise Zope/Plone/Zenoss Distro http://linux.last-bastion.net')\n addZenPackObjects(zenpack, (lbn,))\n return","sub_path":"pycfiles/lbn.zenoss-4.2.3.linux-x86_64.tar/brand.py","file_name":"brand.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"38059945","text":"import zipfile\nimport glob, os\nimport numpy as np\n\ndef is_float(string):\n \"\"\" True if given string is float else False\"\"\"\n try:\n return float(string)\n except ValueError:\n return False\n\nos.chdir(os.path.dirname(os.path.abspath(__file__)))\nfor file in glob.glob(\"*.zip\"):\n print(file)\n\nwith zipfile.ZipFile(file, \"r\") as zip_ref:\n zip_ref.extractall(file[:-4])\n\ndata = []\nfor datafile in glob.glob(file[:-4] + \"/*.DAT\"): \n print(datafile)\n with open(datafile, 'r') as f:\n d = f.readlines()\n for i in d:\n k = i.rstrip().split(\";\")\n #print(k)\n try:\n if k[15] and k[18] == \"RESIDENCE\":\n data.append([float(i) if is_float(i) else i for i in k]) \n except IndexError:\n pass\n\n \n\ndata = np.array(data, dtype='O')\nnp.set_printoptions(threshold=np.nan)\nprint(data)\nnp.savetxt(\"foo.csv\", data, delimiter=\",\", fmt=\"%s\")","sub_path":"Untitled-1.py","file_name":"Untitled-1.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"37965092","text":"\"\"\"\nAccess layer for interfacing with CHIANTI stored in HDF5\n\"\"\"\nimport os\n\nimport numpy as np\nimport h5py\ntry:\n import h5pyd\nexcept ImportError:\n pass\nimport astropy.units as u\nfrom astropy.table import QTable\nimport plasmapy.atomic\n\nimport fiasco\n\n__all__ = ['DataIndexer']\n\n\nclass DataIndexer(object):\n \"\"\"\n Data access layer for CHIANTI data\n \"\"\"\n \n def __new__(cls, *args):\n if fiasco.defaults['use_remote_data']:\n return DataIndexerRemote(\n fiasco.defaults['remote_domain'], fiasco.defaults['remote_endpoint'], args[1])\n else:\n return DataIndexerLocal(*args)\n\n @classmethod\n def create_indexer(cls, *args):\n if fiasco.defaults['use_remote_data']:\n return DataIndexerRemote.create_indexer(\n fiasco.defaults['remote_domain'], fiasco.defaults['remote_endpoint'], args[1])\n else:\n return DataIndexerLocal.create_indexer(*args)\n\n\nclass DataIndexerRemote(object):\n\n def __init__(self, domain, endpoint, top_level_path):\n self.domain = domain\n self.endpoint = endpoint\n self.top_level_path = top_level_path\n\n @classmethod\n def create_indexer(cls, domain, endpoint, top_level_path):\n \"\"\"\n Create an instance as long as the dataset exists\n \"\"\"\n with h5pyd.File(domain, 'r', endpoint=endpoint) as hf:\n path_is_valid = True if top_level_path in hf else False\n return cls(domain, endpoint, top_level_path) if path_is_valid else None\n\n @property\n def version(self):\n with h5pyd.File(self.domain, 'r', endpoint=self.endpoint) as hf:\n if 'chianti_version' in hf[self.top_level_path].attrs:\n version = hf[self.top_level_path].attrs['chianti_version']\n else:\n version = None\n return version\n \n @property\n def fields(self):\n with h5pyd.File(self.domain, 'r', endpoint=self.endpoint) as hf:\n fields = [k for k in hf[self.top_level_path]]\n return fields\n\n def as_table(self):\n qt = QTable()\n for field in self.fields:\n qt[field] = self[field]\n return qt\n \n def __contains__(self, key):\n with h5pyd.File(self.domain, 'r', endpoint=self.endpoint) as hf:\n key_in_grp = key in hf[self.top_level_path]\n return key_in_grp\n \n def __getitem__(self, key):\n \"\"\"\n NOTE: There seems to be a weird in bug in h5pyd where if a dataset\n is returned directly to a numpy array, the slicing/indexing fails. Thus,\n all of the gymnastics around returning datasets and casting to types appropriately.\n \"\"\"\n if type(key) is int:\n raise NotImplementedError('Iteration not supported.')\n with h5pyd.File(self.domain, 'r', endpoint=self.endpoint) as hf:\n if key not in self:\n return None\n ds = hf[self.top_level_path][key]\n if isinstance(ds, h5pyd.Group):\n data = DataIndexerRemote.create_indexer(self.domain, self.endpoint,\n '/'.join([self.top_level_path, key]))\n else:\n # Scalars cannot be sliced\n if not ds.shape:\n data = np.array(ds.value)\n else:\n data = ds[:]\n # Some things are just arrays\n if ds.attrs['unit'] == 'SKIP' or ds.dtype == 'object':\n data = data.astype(ds.dtype)\n else:\n data = u.Quantity(data, ds.attrs['unit'], dtype=ds.dtype)\n if '|S' in data.dtype.str:\n data = data.astype(str)\n return data\n \n def __repr__(self):\n with h5pyd.File(self.domain, 'r', endpoint=self.endpoint) as hf:\n grp = hf[self.top_level_path]\n var_names = [key for key in grp]\n footer = '' if 'footer' not in grp.attrs else grp.attrs['footer']\n \n name_strs = '\\n'.join(var_names)\n version = '' if self.version is None else f'-- v{self.version}'\n return f\"\"\"{self.top_level_path} {version}\n\nFields\n------\n{name_strs}\n\nFooter\n------\n{footer}\"\"\"\n\n\nclass DataIndexerLocal(object):\n \"\"\"\n Data access layer for each distinct CHIANTI dataset\n\n Acts as an interface layer between `Ion` and the CHIANTI data stored in the\n HDF5 database. All data that the user interacts with passes through this layer.\n\n .. warning:: This object is not meant to be instantiated directly by the user. Rather, instances\n are created by higher-level objects in order to provide access to the CHIANTI data.\n\n Parameters\n ----------\n hdf5_path : `str`\n top_level_path : `str`\n \"\"\"\n \n def __init__(self, hdf5_path, top_level_path):\n self.top_level_path = top_level_path\n self.hdf5_dbase_root = hdf5_path\n\n @classmethod\n def create_indexer(cls, hdf5_path, top_level_path):\n \"\"\"\n Create an instance as long as the dataset exists\n \"\"\"\n with h5py.File(hdf5_path, 'r') as hf:\n path_is_valid = True if top_level_path in hf else False\n return cls(hdf5_path, top_level_path) if path_is_valid else None\n\n @property\n def version(self):\n with h5py.File(self.hdf5_dbase_root, 'r') as hf:\n if 'chianti_version' in hf[self.top_level_path].attrs:\n version = hf[self.top_level_path].attrs['chianti_version']\n else:\n version = None\n return version\n \n @property\n def fields(self):\n with h5py.File(self.hdf5_dbase_root, 'r') as hf:\n fields = [k for k in hf[self.top_level_path]]\n return fields\n\n def as_table(self):\n qt = QTable()\n for field in self.fields:\n qt[field] = self[field]\n return qt\n \n def __contains__(self, key):\n with h5py.File(self.hdf5_dbase_root, 'r') as hf:\n key_in_grp = key in hf[self.top_level_path]\n return key_in_grp\n \n def __getitem__(self, key):\n if type(key) is int:\n raise NotImplementedError('Iteration not supported.')\n with h5py.File(self.hdf5_dbase_root, 'r') as hf:\n if key not in self:\n return None\n ds = hf[self.top_level_path][key]\n if isinstance(ds, h5py.Group):\n data = DataIndexer.create_indexer(self.hdf5_dbase_root,\n '/'.join([self.top_level_path, key]))\n else:\n if ds.attrs['unit'] == 'SKIP' or ds.dtype == 'object':\n data = np.array(ds, dtype=ds.dtype)\n else:\n data = u.Quantity(np.array(ds), ds.attrs['unit'], dtype=ds.dtype)\n if '|S' in data.dtype.str:\n data = data.astype(str)\n return data\n \n def __repr__(self):\n\n def ufilter(x):\n return ('' if 'unit' not in x.attrs or x.attrs['unit'] == 'SKIP'\n or x.attrs['unit'] == '' else '({})'.format(x.attrs['unit']))\n\n def dfilter(x):\n return '' if 'description' not in x.attrs else '{}'.format(x.attrs['description'])\n\n with h5py.File(self.hdf5_dbase_root, 'r') as hf:\n grp = hf[self.top_level_path]\n var_names = [(key, ufilter(grp[key]), dfilter(grp[key])) for key in grp]\n footer = '' if 'footer' not in grp.attrs else grp.attrs['footer']\n \n name_strs = '\\n'.join(['{} {} -- {}'.format(*v) for v in var_names])\n version = '' if self.version is None else f'-- v{self.version}'\n return f\"\"\"{self.top_level_path} {version}\n\nFields\n------\n{name_strs}\n\nFooter\n------\n{footer}\"\"\"\n","sub_path":"fiasco/datalayer.py","file_name":"datalayer.py","file_ext":"py","file_size_in_byte":7808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"612507358","text":"\"\"\"Encapsulates EV3Projects\"\"\"\n\nimport json\nimport os\nimport argparse\nimport collections\nfrom operator import methodcaller\nfrom ev3commit import Commit, Changeset\n\n\nclass EV3Project(object):\n @classmethod\n def newProject(cls, name, path, ev3data, who, host):\n if os.path.exists(path):\n return None\n newP = cls(name, path)\n newP.uploadCommit(ev3data, \"Initial Commit\", who, host)\n newP.save()\n return newP\n\n def save(self):\n data = {}\n data[\"head\"] = self.head\n data[\"failedMerges\"] = self.failedMerges\n data[\"tags\"] = self.tags\n data[\"name\"] = self.name\n with open(self.fullpath(\"project.json\"), \"w\") as project_file:\n json.dump(data, project_file)\n\n def addIgnoreComment(self, cid, comment):\n for fm in self.failedMerges:\n if \"{0}\".format(fm) == \"{0}\".format(cid):\n if not self.failedMerges[fm]:\n self.failedMerges[fm] = comment\n self.save()\n return \"\"\n else:\n # this should be impossible...\n return '{0} already had ignore comment'.format(cid)\n return '{0} not in failed merge list'.format(cid)\n\n def addTag(self, cid, description):\n clean = description.strip()\n if not clean:\n return 'tags must not be empty'\n for tag in self.tags:\n if tag == clean:\n return tag + ' already assigned'\n self.tags[description] = cid\n self.save()\n return ''\n\n def removeTag(self, description):\n clean = description.strip()\n for tag in self.tags:\n if tag == clean:\n del self.tags[tag]\n self.save()\n return ''\n return clean + ' not found'\n\n def fromTag(self, description):\n clean = description.strip()\n for tag in self.tags:\n if tag == clean:\n return self.getCommit(self.tags[tag])\n return None\n\n def listTags(self):\n return collections.OrderedDict(sorted(\n list(self.tags.items()), key=lambda t: t[1], reverse=True))\n\n def fullpath(self, filename):\n return os.path.join(self.path, filename)\n\n def __init__(self, name, path):\n self.name = name\n self.path = path\n self.failedMerges = {}\n self.tags = {}\n self.head = 1\n\n if not os.path.exists(self.path):\n os.makedirs(self.path)\n os.makedirs(self.fullpath('repo'))\n\n try:\n with open(self.fullpath(\"project.json\"), \"r\") as project_file:\n data = json.loads(project_file.read())\n self.head = data[\"head\"]\n self.failedMerges = data[\"failedMerges\"]\n if self.failedMerges is None:\n self.failedMerges = []\n try:\n self.tags = data[\"tags\"]\n except KeyError:\n self.tags = {}\n except IOError:\n pass\n\n def getCommit(self, cid):\n return Commit.from_id(self.path, cid)\n\n def getListOfCommits(self):\n commits = []\n cid = 1\n\n while os.path.isfile(Commit.file_from_id(self.path, cid)):\n commits.append(Commit.from_id(self.path, cid))\n cid = cid + 1\n return sorted(commits, key=methodcaller('time'), reverse=True)\n\n def findNextCommit(self):\n cid = 1\n while os.path.isfile(Commit.file_from_id(self.path, cid)):\n cid = cid + 1\n return str(cid)\n\n def from_id(self, cid):\n commit_id = cid\n if cid == \"head\":\n commit_id = self.head\n\n return Commit.from_id(self.path, commit_id)\n\n def download(self, cid):\n return self.from_id(cid).get_ev3_data(self.name)\n\n def graph(self, cid, showTest):\n return self.from_id(cid).graph(showTest)\n\n def change_head(self, cid):\n # Should this check to see if it is valid? I can't see a way through\n # the website that it can be wrong...\n self.head = cid\n self.save()\n\n def getDetails(self, cid):\n main_commit = Commit.from_id(self.path, cid)\n commits = self.getListOfCommits()\n fileDetails = {}\n for f in main_commit.files():\n # we want to go backwards and find the first instance of each file\n for commit in reversed(commits):\n if commit.getSHA(f) == main_commit.getSHA(f):\n fileDetails[f] = commit\n break\n return fileDetails\n\n def uploadCommit(self, ev3data, comment, who, host):\n cid = self.findNextCommit()\n commit = Commit.from_ev3file(\n self.path, cid, ev3data, comment, who, host, self.name)\n if cid == \"1\": # first one\n return cid\n\n head = Commit.from_id(self.path, self.head)\n cs = Changeset(commit, head)\n if not cs.different():\n commit.delete()\n return 0\n return cid\n\n def find_common_parent(self, commit1, commit2):\n parents1 = [\"{0}\".format(commit1.cid())]\n parents2 = [\"{0}\".format(commit2.cid())]\n\n while not set(parents1) & set(parents2):\n if commit1.parent():\n commit1 = Commit.from_id(self.path, commit1.parent())\n parents1.append(\"{0}\".format(commit1.cid()))\n if commit2.parent():\n commit2 = Commit.from_id(self.path, commit2.parent())\n parents2.append(\"{0}\".format(commit2.cid()))\n elif commit1.parent() == commit2.parent(): # in this case they are both 0\n parents1.append(\"0\")\n parents2.append(\"0\")\n return (set(parents1) & set(parents2)).pop()\n\n def find_possible_parent(self, commit):\n # Start with head and go backwards\n poss_id = int(self.head)\n\n while poss_id > 0:\n possParent = self.from_id(poss_id)\n if possParent.origParent() == commit.parent() and possParent.host() == commit.host():\n return possParent\n poss_id -= 1\n return None\n\n def remove_failed_merges(self, commit):\n while commit and commit.parent():\n foundList = []\n for fm in self.failedMerges:\n print(\"FM-{0},{1}\".format(fm, commit.cid()))\n if \"{0}\".format(fm) == \"{0}\".format(commit.cid()):\n print(\" wow\")\n foundList.append(fm)\n if foundList:\n for fm in foundList:\n self.failedMerges.pop(fm, None)\n commit = Commit.from_id(self.path, commit.parent())\n else:\n # Can return because if none were found, none will be found for parents either....\n return\n\n def try_merge(self, id_commit):\n errors_added = []\n errors_modified = []\n\n head_commit = Commit.from_id(self.path, self.head)\n # find common parent\n parent_cid = self.find_common_parent(head_commit, id_commit)\n\n parent_commit = Commit.from_id(self.path, parent_cid)\n changes_to_head = Changeset(parent_commit, head_commit)\n changes_to_commit = Changeset(parent_commit, id_commit)\n proposed_head_commit = head_commit\n\n for filename in changes_to_commit.newFiles():\n if (filename in changes_to_head.newFiles()) and (\n head_commit.getSHA(filename) != id_commit.getSHA(filename)):\n errors_added.append(filename)\n else:\n proposed_head_commit.files()[filename] = id_commit.files()[\n filename]\n for filename in changes_to_commit.modifiedFiles():\n if (filename in changes_to_head.modifiedFiles()) and (\n head_commit.getSHA(filename) != id_commit.getSHA(filename)):\n errors_modified.append(filename)\n else:\n proposed_head_commit.files()[filename] = id_commit.files()[\n filename]\n for filename in changes_to_commit.removedFiles():\n if filename not in changes_to_head.modifiedFiles():\n proposed_head_commit.remove_file(filename)\n\n return (proposed_head_commit, errors_added, errors_modified)\n\n def manual_merge(self, cid, commit_files, head_files):\n errors = []\n id_commit = Commit.from_id(self.path, cid)\n (proposed_head_commit, errors_added,\n errors_modified) = self.try_merge(id_commit)\n conflicts = errors_added + errors_modified\n for conflict in conflicts:\n if conflict in commit_files:\n proposed_head_commit.files()[conflict] = id_commit.files()[\n conflict]\n elif conflict in head_files:\n pass\n else:\n errors.append(conflict)\n if not errors:\n self.remove_failed_merges(id_commit)\n new_id = self.findNextCommit()\n new_commit = Commit.from_manual_merge(\n self.path, self.head, new_id, cid, proposed_head_commit.files())\n new_commit.save()\n self.head = new_id\n else:\n self.failedMerges[cid] = \"\"\n\n data = {}\n data[\"head\"] = self.head\n data[\"failedMerges\"] = self.failedMerges\n with open(self.fullpath(\"project.json\"), \"w\") as project_file:\n json.dump(data, project_file)\n\n return errors\n\n def merge(self, cid):\n errors = []\n if not self.head:\n self.head = cid\n else:\n id_commit = Commit.from_id(self.path, cid)\n if id_commit.parent() == self.head:\n self.head = cid\n else:\n (proposed_head_commit, errors_added,\n errors_modified) = self.try_merge(id_commit)\n for filename in errors_added:\n errors.append(\"{0} added in both\".format(filename))\n for filename in errors_modified:\n errors.append(\"{0} modified in both\".format(filename))\n\n if errors: # Attempt to fix by seeing if download was just forgotten\n possParent = self.find_possible_parent(id_commit)\n if possParent:\n id_commit.commitDetails[\"newParent\"] = possParent.cid()\n (new_proposed_head, new_add_errors,\n new_merge_errors) = self.try_merge(id_commit)\n if (not new_add_errors) and (not new_merge_errors):\n proposed_head_commit = new_proposed_head\n errors = []\n id_commit.save()\n else:\n id_commit.commitDetails[\"newParent\"] = \"\"\n print('Not possible parent',\n new_add_errors, new_merge_errors)\n\n if not errors:\n self.remove_failed_merges(id_commit)\n new_id = self.findNextCommit()\n new_commit = Commit.from_merge(\n self.path, self.head, new_id, cid, proposed_head_commit.files())\n cs = Changeset(new_commit, id_commit)\n if cs.different():\n new_commit.save()\n self.head = new_id\n else:\n # No need for merge commit\n self.head = cid\n else:\n self.failedMerges[cid] = \"\"\n data = {}\n data[\"head\"] = self.head\n data[\"failedMerges\"] = self.failedMerges\n with open(self.fullpath(\"project.json\"), \"w\") as project_file:\n json.dump(data, project_file)\n\n return errors\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(description=\"Test ev3project code\")\n parser.add_argument('file')\n parser.add_argument('-c', \"--comment\", help=\"comment for checkin\")\n args = parser.parse_args()\n\n commit_filename = args.file\n with open(commit_filename, 'r') as ev3File:\n ev3contents = ev3File.read()\n\n ev3P = EV3Project(\"test\", \"testDir\")\n commitId = ev3P.uploadCommit(\n ev3contents, \"comment\", \"author\", \"honeycrisp\")\n\n merge_errors = ev3P.merge(commitId)\n if merge_errors:\n print(merge_errors)\n else:\n print(\"Successful merge!\")\n\n with open(\"out.zip\", \"w\") as outfile:\n outfile.write(ev3P.download(ev3P.head))\n","sub_path":"ev3project.py","file_name":"ev3project.py","file_ext":"py","file_size_in_byte":12614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"45344125","text":"import statprof\nfrom dictionary import CrosswordSolver\n\nfrom time import time\nfrom random import choice, seed\nimport statprof\nimport pickle\n\ntry:\n with open(\"cross_word_solver.dmp\", 'rb') as fp:\n solver = pickle.load(fp)\nexcept:\n with open(\"words.txt\") as fp:\n words = set(line[:-1].lower() for line in fp)\n solver = CrosswordSolver()\n solver.updateWords(words)\n\ncharacters = [chr(_) for _ in range(ord('a'), ord('z') + 1)]\n\n# test = [\n# ['m', 'e', 'r'],\n# ['a', 'p', 'i'],\n# ['y', 'e', 'p']\n# ]\nsmin, smax = 400, 401\nstatprof.start()\nfor size in range(smin, smax):\n seed(time())\n test = [[choice(characters) for _ in range(size)] for _ in range(size)]\n\n for row in test:\n print(row)\n\n ans = solver.solve(test)\nstatprof.stop()\nstatprof.display()\n\nwith open(\"cross_word_solver.dmp\", 'wb') as fp:\n pickle.dump(solver, fp)\n","sub_path":"test_dictionary.py","file_name":"test_dictionary.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"278264248","text":"\n\nfrom xai.brain.wordbase.nouns._tonsil import _TONSIL\n\n#calss header\nclass _TONSILS(_TONSIL, ):\n\tdef __init__(self,): \n\t\t_TONSIL.__init__(self)\n\t\tself.name = \"TONSILS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"tonsil\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_tonsils.py","file_name":"_tonsils.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"406104393","text":"import os\nimport json\nimport time\nimport random\nimport datetime\nimport numpy as np\nfrom app.utils import *\nfrom app.models import *\nfrom app.serializers import *\nfrom django.db.models import Q, F\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.db.models.aggregates import Count, Sum, Max, Min, Avg\n\n# Create your views here.\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\n@csrf_exempt\ndef wincc(request):\n \"\"\" params = json.loads(str(request.body, 'utf8').replace('\\'', '\\\"'))[\n 'str'].split(',') \"\"\"\n\n params = str(request.body, 'utf8').split(',')\n\n workOrder = WorkOrder.objects.get(Q(number=params[1]))\n product = workOrder.product\n standard = ProductStandard.objects.get(Q(product=product))\n\n if 'start' in params[0]:\n if params[0].split('-')[1] == 'LP':\n product.number = params[2]\n product.save()\n workOrder.startTime = datetime.datetime.now()\n workOrder.status = CommonStatus.objects.get(name='加工中')\n if 'stop' in params[0]:\n if params[0].split('-')[1] == 'D':\n product.status = CommonStatus.objects.get(name='半成品')\n product.save()\n workOrder.endTime = datetime.datetime.now()\n workOrder.status = CommonStatus.objects.get(name='已完成')\n\n if params[0] == 'stop-%s' % Process.objects.filter(Q(route=WorkOrder.objects.get(number=params[1]).product.order.route)).last().number:\n product.status = CommonStatus.objects.get(name='已完成')\n product.save()\n order = product.order\n if order.products.all().filter(Q(status=None)).count() == 0:\n order.status = CommonStatus.objects.get(name='已完成')\n order.save()\n workOrder.save()\n\n if params[0] == 'check':\n if random.random() > 0.5:\n product.result = '合格'\n standard.result = '合格'\n standard.realValue = '合格'\n else:\n product.result = '不合格'\n standard.result = '不合格'\n standard.realValue = '不合格'\n product.save()\n standard.save()\n\n if params[0] == 'weight':\n standard.realValue = float(params[2])\n if np.abs(standard.realValue-float(standard.expectValue)) <= product.prodType.errorRange:\n standard.result = '合格'\n product.result = '合格'\n else:\n standard.result = '不合格'\n product.result = '不合格'\n standard.save()\n product.save()\n\n try:\n event = Event()\n event.workOrder = workOrder\n event.source = Process.objects.get(number=params[0].split(\n '-')[1], route=WorkOrder.objects.get(number=params[1]).product.order.route).name\n event.title = '%s%s' % (Process.objects.get(\n number=params[0].split('-')[1], route=WorkOrder.objects.get(number=params[1]).product.order.route).name, '开始' if params[0].split('-')[0] == 'start' else '结束')\n event.save()\n except Exception as e:\n print(e)\n\n return JsonResponse({'ok': 'ok'})\n\n\n@csrf_exempt\ndef selects(request):\n \"\"\" for pos in StorePosition.objects.filter(Q(store__storeType__name='原料库')):\n pos.status = '1'\n pos.save() \n\n for pos in StorePosition.objects.filter(Q(store__storeType__name='成品库')):\n pos.status = '2'\n pos.save() \"\"\"\n\n params = json.loads(request.body)\n selectList = {}\n if params['model'] == 'order' or params['model'] == 'productType':\n selectList = {\n 'line': list(map(lambda obj: obj.name, ProductLine.objects.all())),\n 'customer': list(map(lambda obj: obj.name, Customer.objects.all())),\n 'orderType': list(map(lambda obj: obj.name, OrderType.objects.all())),\n 'route': list(map(lambda obj: obj.name, ProcessRoute.objects.filter(~Q(processes__key=None)))),\n 'product': list(map(lambda obj: [obj.name, obj.orderType.name], ProductType.objects.filter(~Q(bom__contents__key=None)))),\n 'materials': list(map(lambda obj: {'name': obj['name'], 'size': obj['size']}, Material.objects.all().values('name', 'size').distinct()))\n }\n if params['model'] == 'bom':\n selectList = {\n 'materials': list(set(map(lambda obj: obj.name+'/'+obj.size, Material.objects.all()))),\n 'product': list(map(lambda obj: obj.name, ProductType.objects.filter(Q(bom=None)))),\n }\n if params['model'] == 'processRoute':\n selectList = {\n 'routeType': list(map(lambda obj: obj.name, OrderType.objects.all())),\n }\n if params['model'] == 'store':\n selectList = {\n 'direction': ['行优先', '列优先'],\n 'origin': ['左上起点', '左下起点'],\n 'workShop': list(map(lambda obj: obj.name, WorkShop.objects.all())),\n 'storeType': list(map(lambda obj: obj.name, StoreType.objects.all())),\n 'material': list(set(map(lambda obj: obj.name, Material.objects.all()))),\n 'productLine': list(map(lambda obj: obj.name, ProductLine.objects.all())),\n 'product': list(map(lambda obj: obj.name, ProductType.objects.filter(Q(orderType__name=params['order'])))),\n }\n if params['model'] == 'productLine':\n selectList = {\n 'workShop': list(map(lambda obj: obj.name, WorkShop.objects.all())),\n 'lineType': list(map(lambda obj: obj.name, OrderType.objects.all())),\n }\n if params['model'] == 'device':\n selectList = {\n 'deviceType': list(map(lambda obj: obj.name, DeviceType.objects.all())),\n }\n if params['model'] == 'document':\n selectList = {\n 'docType': list(map(lambda obj: [obj.name, obj.key], DocType.objects.all()))\n }\n if params['model'] == 'material' or params['model'] == 'tool':\n selectList = {\n 'store__name': list(map(lambda obj: obj.name, Store.objects.all())),\n }\n if params['model'] == 'user':\n selectList = {\n 'gender': ['男', '女'],\n 'role': list(map(lambda obj: obj.name, Role.objects.all())),\n 'department': list(map(lambda obj: obj.name, Organization.objects.filter(~Q(parent=None))))\n }\n return JsonResponse({'res': selectList})\n\n\n@csrf_exempt\ndef queryCharts(request):\n params = json.loads(request.body)\n year = datetime.datetime.now().year\n month = datetime.datetime.now().month\n day = datetime.datetime.now().day\n start = datetime.datetime.strptime(params['start'], '%Y/%m/%d')\n stop = datetime.datetime.strptime(\n params['stop'], '%Y/%m/%d')+datetime.timedelta(hours=24)\n data = Product.objects.filter(Q(order__orderType__name=params['order'])).values('batch').annotate(reals=Count('batch', filter=Q(\n workOrders__status__name='已完成')), expects=Count('batch'), good=Count('result', filter=Q(result='合格')), bad=Count('result', filter=Q(result='不合格')))\n\n goodRate = list(\n map(lambda obj: [dataX(obj['batch']), round(rateY(obj), 2)], data))\n\n categories = list(Product.objects.all().values_list(\n 'batch', flat=True).distinct())\n\n if Product.objects.all().count() == 0:\n start = '%s-%s-%s' % (str(year), str(month-1 if day <\n 14 else month), str(np.abs(day-15)))\n for day in np.arange(int(time.mktime(time.strptime(start, '%Y-%m-%d')))*1000, time.time()*1000, 24*60*60*1000):\n goodRate.append([day+8*60*60*1000, round(random.random(), 2)])\n categories.append(time.strftime(\n '%m-%d', time.localtime(day/1000)))\n\n progress = list(map(lambda obj: {'key': obj.key, 'number': obj.number[-4:], 'progress': round(obj.workOrders.all().filter(Q(status__name='已完成')).count(\n )/(obj.workOrders.all().count()), 2)}, Product.objects.filter(Q(workOrders__status__name='加工中') | Q(workOrders__status__name='等待中')).distinct()))\n\n if Product.objects.filter(Q(workOrders__status__name='加工中') | Q(workOrders__status__name='等待中')).count() == 0:\n for i in range(10):\n progress.append({'key': i, 'number': '产品%s' % (str(i+1)),\n 'progress': random.randint(0, 100)})\n\n rate = [\n {'name': '合格率', 'type': 'areaspline',\n 'color': 'rgb(190,147,255)', 'data': goodRate},\n ]\n\n target = Product.objects.filter(\n Q(batch__gte=datetime.datetime.now().date())).count()\n\n current = Product.objects.filter(\n Q(batch__gte=datetime.datetime.now().date(), status__name='入库')).count()\n\n good = Product.objects.filter(\n Q(batch__gte=datetime.datetime.now().date(), result='合格')).count()\n\n power = {'target': target if target != 0 else 100, 'current': current if current != 0 else 0, 'good': good if good != 0 else 0,\n 'series': [{'data': [{'y': current if current != 0 else 0, 'target': target if target != 0 else 100}]}]}\n\n return JsonResponse({'progress': progress, 'categories': categories, 'mateana': storeAna(params['order']), 'quality': qualityChart(params['order'], start, stop, all=True), 'goodRate': rate, 'power': power})\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"449658700","text":"\"\"\"\nCreates, queries, and deletes a usage report on the total number of requests for all services in a site,\nby machine specific calls rather than using the web adaptor.\n\nThis script is uniquely designed to access the ArcGIS Server servers (machines) in our iMAP 3.0 environment by their\nmachine name rather than going through the Web Adaptor. When we moved to ESRI's 10.6 environment the previous script\nfailed and we encountered errors related to tokens and client mismatching. A valid, working token, would be rejected\nrandomly and frequently. We first adapted using a while loop for handling failures. The loop caused repeated calls\nuntil a call when through and this is how we bypassed the issue. The issue appeared on multiple scripts so an overhaul\nwas performed and we abandoned calls to the web adaptor and instead hit the machiens by their direct path referencing\ntheir name rather than using the domain.\nContains AdminObject, FolderObject, MachineObject, ReportObject, ServiceObject, and NotJSONException classes.\nOriginal Design: JCahoon\nOverhaul Author: CJuice\nDate: 20180831\nRevised: This script is an overhaul of a previous script. The previous script used Python 2.7 and this script was\n designed with 3.7. The functionality and steps of the previous script were recreated herein but the code now uses\n the requests module and is consequently significantly different. This script was designed at ArcGIS Server 10.6\nRevised: 20180911, JC: Revised the create_master_url_list() function. Needed to skip the root 'services/' folder when\n inventorying services. Added a check for this root folder.\n\"\"\"\n\n\ndef main():\n \"\"\"\n Run the script if it is the primary call and not an import to another script.\n :return: None\n \"\"\"\n\n # IMPORTS\n import calendar\n import configparser\n import datetime\n import json\n import os\n import random\n import requests\n import uuid\n # NOTE: Believe urllib3 is included in requests module but to manage InsecureRequestWarning was also imported.\n # Without disabled warnings, every request would print a red warning. This is because we have chosen\n # 'verify=False' when making requests to secure services.\n import urllib3\n from urllib3.exceptions import InsecureRequestWarning\n urllib3.disable_warnings(InsecureRequestWarning)\n\n # VARIABLES\n _ROOT_PROJECT_PATH = os.path.dirname(__file__)\n CREDENTIALS_PATH = os.path.join(_ROOT_PROJECT_PATH, \"Docs/credentials.cfg\")\n config = configparser.ConfigParser()\n config.read(filenames=CREDENTIALS_PATH)\n\n # CSV_OUTPUT_FILE_PATH = r\"D:\\inetpub\\wwwroot\\DOIT\\StatusDashboard\\temp\\UsageStatistics.csv\" # PRODUCTION.\n # *********DOIT folder DNE on imap01d\n CSV_OUTPUT_FILE_PATH = f\"{_ROOT_PROJECT_PATH}/UsageStatistics.csv\" # TESTING\n PASSWORD = config[\"ags_server_credentials\"][\"password\"]\n SERVER_MACHINE_NAMES = {0: config['ags_prod_machine_names'][\"machine1\"],\n 1: config['ags_prod_machine_names'][\"machine2\"],\n 2: config['ags_prod_machine_names'][\"machine3\"],\n 3: config['ags_prod_machine_names'][\"machine4\"]}\n SERVER_PORT_SECURE = config['ags_prod_machine_names'][\"secureport\"]\n SERVER_ROOT_URL = \"https://{machine_name}.mdgov.maryland.gov:{port}\"\n USERNAME = config[\"ags_server_credentials\"][\"username\"]\n\n # CLASSES\n class AdminObject:\n \"\"\"\n The AdminObject class represents the needed functionality of ArcGIS Server admin access. Not all functionality\n is represented, only that which is relevant to the needed processes. There are portions of url's that are\n constants. These are made available to child classes that inherit AdminObject.\n \"\"\"\n\n ADMIN_SERVICES_ENDING = \"arcgis/admin/services\"\n GENERATE_TOKEN_ENDING = \"arcgis/admin/generateToken\"\n GEODATA_ROOT = \"https://geodata.md.gov/imap/rest/services\"\n REST_URL_ENDING = \"arcgis/rest/services\"\n\n def __init__(self, root_machine_url):\n \"\"\"\n Instantiate the AdminObject, setting the admin_services_url and the rest_url_machine_root attributes\n using the setter/getter mutator methods.\n\n :param root_machine_url: url specific to the machine being accessed in the requests. In bypassing the web\n adaptor and making machine specific calls this became necessary\n \"\"\"\n self.admin_services_url = root_machine_url\n self.rest_url_machine_root = root_machine_url\n\n @property\n def admin_services_url(self):\n return self.__admin_services_url\n\n @admin_services_url.setter\n def admin_services_url(self, value):\n self.__admin_services_url = f\"{value}/{AdminObject.ADMIN_SERVICES_ENDING}\"\n\n @property\n def rest_url_machine_root(self):\n return self.__rest_url_machine_root\n\n @rest_url_machine_root.setter\n def rest_url_machine_root(self, value):\n self.__rest_url_machine_root = f\"{value}/{AdminObject.REST_URL_ENDING}\"\n\n class FolderObject(AdminObject):\n \"\"\"\n The FolderObject class represents a service folder in the server services and inherits from AdminObject.\n\n This class overrides the __str__ builtin from AdminObject to provide meaningful printing of the object.\n Machine Name Path Example: 'https://gis-ags-imap02p.mdgov.maryland.gov:6443/arcgis/rest/services/Weather'\n \"\"\"\n\n def __init__(self, name, root_machine_url):\n \"\"\"\n Instantiate the FolderObject, first instantiating the inherited AdminObject using super(), and set\n attributes using the setter/getter mutator methods. Name is the name of the folder, folder_machine_url is\n the url to the folder using the machine path, folder_geodata_url is the url to the folder using the\n geodata.md.gov path, folder_short_services_url is the short/relative path for making calls for services when\n building usage report (doesn't reference the machine or geodata root portion of the url), and\n service_objects_list is a list intended for storing all ServiceObject objects for services within a folder.\n :param name: Name of the services folder\n :param root_machine_url: url for the machine, rather than the web adaptor path\n \"\"\"\n super().__init__(root_machine_url=root_machine_url) # Needs to be instantiated before folder_url\n self.name = name\n self.folder_geodata_url = name\n self.folder_machine_url = name\n self.folder_short_services_url = name\n # self.services_json = None # TODO: Used?\n self.service_objects_list = []\n\n @property\n def folder_geodata_url(self):\n return self.__folder_geodata_url\n\n @folder_geodata_url.setter\n def folder_geodata_url(self, value):\n self.__folder_geodata_url = f\"{AdminObject.GEODATA_ROOT}/{value}\"\n\n @property\n def folder_machine_url(self):\n return self.__folder_machine_url\n\n @folder_machine_url.setter\n def folder_machine_url(self, value):\n self.__folder_machine_url = f\"{self.rest_url_machine_root}/{value}\"\n\n @property\n def folder_short_services_url(self):\n return self.__folder_short_service_url\n\n @folder_short_services_url.setter\n def folder_short_services_url(self, value):\n self.__folder_short_service_url = f\"services/{value}\"\n\n def __str__(self):\n \"\"\"\n Override the __str__ builtin to control the appearance of the object print-out for readability.\n :return: string\n \"\"\"\n return f\"FOLDER: {self.name}-->\\n\\turl on machine = {self.folder_machine_url}\\n\\t\" \\\n f\"url on geodata = {self.folder_geodata_url}\"\n\n class MachineObject:\n \"\"\"\n The MachineObject class represents a server machine and stores properties and values.\n\n This class overrides the __str__ builtin to provide meaningful printing of the object.\n \"\"\"\n\n def __init__(self, machine_name, root_url, security_token, folder_names=None):\n \"\"\"\n Instantiate the machine object, setting the machine name, the root machine url, the token for accessing\n secure services, and the list for storing folder names.\n Machine name is name of the server machine and is necessary because the web adaptor is being bypassed\n and the servers are being hit directly using their machine name. The root url for the machine uses the\n machine name. The token is the key created by the server for accessing secure services. The folder names\n is a list of service folder names on the machine.\n :param machine_name: name of the server machine\n :param root_url: root url for machine\n :param security_token: the token generated by the machine for secure access\n :param folder_names: list of folders discovered during inspection of the services\n \"\"\"\n self.machine_name = machine_name\n self.root_url = root_url\n self.token = security_token\n self.folder_names_list = folder_names\n\n def __str__(self):\n \"\"\"\n Overriding the __str__ builtin to control the appearance of the object print-out for readability.\n :return: string\n \"\"\"\n return f\"MACHINE: {self.machine_name}-->\\n\\troot url = {self.root_url}\\n\\ttoken = {self.token}\\n\\t\" \\\n f\"folders list = {self.folder_names_list}\"\n\n class NotJSONException(Exception):\n \"\"\"\n Raise when the url for the request is malformed for our purposes and the server returns html, not json.\n\n Inherits from Exception class.\n \"\"\"\n\n def __init__(self):\n \"\"\"Instantiate the object and pass\"\"\"\n pass\n\n def __str__(self):\n \"\"\"Override the builtin __str__ method\"\"\"\n return \"Content is not in JSON format. CJuice\"\n\n class ReportObject(AdminObject):\n \"\"\"\n The ReportObject class is for service usage reports from ArcGIS Servers. Not all functionality\n is represented, only that which is relevant to the needed processes. There are portions of url's that are\n constants.\n Notes: 'add' is trigger for report creation, 'data' is trigger for querying, 'delete' is trigger for\n deleting report\n \"\"\"\n\n USAGE_REPORT_ENDING__CREATE = \"arcgis/admin/usagereports/add\"\n USAGE_REPORT_ENDING__QUERY = \"arcgis/admin/usagereports/{report_name}/data\"\n USAGE_REPORT_ENDING__DELETE = \"arcgis/admin/usagereports/{report_name}/delete\"\n\n def __init__(self, root_machine_url, master_urls_list, basic_request_json):\n \"\"\"\n Instantiate the ReportObject, first instantiating the inherited AdminObject using super(), and set\n attributes using the setter/getter mutator methods. Setting order preserves/honors dependencies. Sets a\n unique name for the report, the current time, the time span of the report query using the to and from\n attributes, the usage report urls for creating querying and deleting a report, the json definition for\n specific report content, and the packaged json object for passing to the server for usagereport generation.\n\n :param root_machine_url: root url for machine\n :param master_urls_list: list of master folder and service urls\n :param basic_request_json: json including token and format\n \"\"\"\n super().__init__(root_machine_url)\n self.report_name_id = uuid.uuid4().hex\n self.now_time = datetime.datetime.utcnow()\n self.to_time = ReportObject.datetime_to_timestamp_seconds(self.now_time) * 1000\n self.from_time = ReportObject.datetime_to_timestamp_seconds(self.now_time - datetime.timedelta(hours=48)) * 1000\n self.usage_reports_url__create = root_machine_url\n self.usage_reports_url__delete = root_machine_url\n self.usage_reports_url__query = root_machine_url\n self.report_url_create = None\n self.report_url_delete = None\n self.report_url_query = None\n self.master_urls_list = master_urls_list\n self.json_definition = None\n self.report_json_params = basic_request_json\n\n @staticmethod\n def datetime_to_timestamp_seconds(date_time_object):\n \"\"\"\n Take a date time object and returns the corresponding Unix timestamp value, assuming an epoch of 1970\n\n :param date_time_object: datetime object\n :return: seconds as integer\n \"\"\"\n return calendar.timegm(date_time_object.utctimetuple())\n\n @property\n def usage_reports_url__create(self):\n return self.__usage_reports_url__create\n\n @usage_reports_url__create.setter\n def usage_reports_url__create(self, value):\n self.__usage_reports_url__create = f\"{value}/{ReportObject.USAGE_REPORT_ENDING__CREATE}\"\n\n @property\n def usage_reports_url__delete(self):\n return self.__usage_reports_url__delete\n\n @usage_reports_url__delete.setter\n def usage_reports_url__delete(self, value):\n self.__usage_reports_url__delete = f\"{value}/{ReportObject.USAGE_REPORT_ENDING__DELETE}\"\n\n @property\n def usage_reports_url__query(self):\n return self.__usage_reports_url__query\n\n @usage_reports_url__query.setter\n def usage_reports_url__query(self, value):\n self.__usage_reports_url__query = f\"{value}/{ReportObject.USAGE_REPORT_ENDING__QUERY}\"\n\n @property\n def report_url_create(self):\n return self.__report_url_create\n\n @report_url_create.setter\n def report_url_create(self, value):\n create_url = self.usage_reports_url__create.format(report_name=self.report_name_id)\n self.__report_url_create = create_url\n\n @property\n def report_url_delete(self):\n return self.__report_url_delete\n\n @report_url_delete.setter\n def report_url_delete(self, value):\n delete_url = self.usage_reports_url__delete.format(report_name=self.report_name_id)\n self.__report_url_delete = delete_url\n\n @property\n def report_url_query(self):\n return self.__report_url_query\n\n @report_url_query.setter\n def report_url_query(self, value):\n query_url = self.usage_reports_url__query.format(report_name=self.report_name_id)\n self.__report_url_query = query_url\n\n @property\n def json_definition(self):\n return self.__json_definition\n\n @json_definition.setter\n def json_definition(self, value):\n \"\"\"\n Create usage report JSON definition. This json object goes into the json object submitted to the server. The\n object details indicate what is to be put into the report when it is built. 'resourceURIs' is a list of\n all service and folder urls per Jessie design and she may have borrowed the code from ESRI demo\n\n :param value:\n :return:\n \"\"\"\n\n self.__json_definition = {\"reportname\": self.report_name_id,\n \"since\": \"CUSTOM\",\n \"from\": int(self.from_time),\n \"to\": int(self.to_time),\n \"queries\": [\n {\"resourceURIs\": self.master_urls_list,\n \"metrics\": [\"RequestCount\"]}\n ],\n \"aggregationInterval\": 60,\n \"metadata\": {\"temp\": True,\n \"tempTimer\": 1454109613248}\n }\n\n @property\n def report_json_params(self):\n return self.__report_json_params\n\n @report_json_params.setter\n def report_json_params(self, value):\n \"\"\"\n NOTE: Proved absolutely essential for the usagereport value to be processed by json.dumps(). Received an\n error in response saying 'A JSONObject text must begin with '{' at character 1 of ...'\n :param value: json including the token and format\n :return:\n \"\"\"\n value.update({\"usagereport\": json.dumps(self.json_definition)})\n self.__report_json_params = value\n\n class ServiceObject(AdminObject):\n \"\"\"\n The ServiceObject class is for storing values related to an ArcGIS server service in a services folder and\n inherits from AdminObject.\n\n This class overrides the __str__ builtin to provide meaningful printing of the object.\n \"\"\"\n\n def __init__(self, folder, service_json, root_machine_url):\n \"\"\"\n Instantiate the ServiceObject class, first instantiating the inherited AdminObject using super(), and set\n attributes using the setter/getter mutator methods. Service name is the name of\n the service and the type is limited to ESRI types (eg. FeatureService)\n :param folder: name of the service folder\n :param service_json: json content of services key in response json\n :param root_machine_url: url for the machine, rather than the web adaptor path\n \"\"\"\n super().__init__(root_machine_url=root_machine_url)\n self.folder = folder\n self.service_name = service_json\n self.service_type = service_json\n self.service_short_services_url = None\n\n @property\n def service_name(self):\n return self.__service_name\n\n @service_name.setter\n def service_name(self, value):\n try:\n self.__service_name = value['name']\n except KeyError as ke:\n print(f\"KeyError: 'name' not found in services json for this service. {ke}\")\n exit()\n\n @property\n def service_type(self):\n return self.__service_type\n\n @service_type.setter\n def service_type(self, value):\n try:\n self.__service_type = value['type']\n except KeyError as ke:\n print(f\"KeyError: 'type' not found in services json for this service. {ke}\")\n exit()\n\n @property\n def service_short_services_url(self):\n return self.__service_short_services_url\n\n @service_short_services_url.setter\n def service_short_services_url(self, value):\n self.__service_short_services_url = f\"services/{self.service_name}.{self.service_type}\"\n\n def __str__(self):\n \"\"\"\n Overriding the __str__ builtin to control the appearance of the object print-out for readability.\n :return: string\n \"\"\"\n return f\"SERVICE: {self.service_name}-->\\n\\ttype = {self.service_type}\\n\\tfolder = {self.folder}\"\n\n # FUNCTIONS\n def create_params_for_request(token_action=None, json_payload=None, response_format=\"json\"):\n \"\"\"\n Create parameters to be submitted with the request.\n Various styles of requests are made and this function handles the variety and returns a dictionary\n :param token_action: route to be taken when creating the parameters\n :param json_payload: dictionary that will be added to basic json parameters\n :param response_format: type of response from requests, json and csv are two examples\n :return: dictionary of parameters\n \"\"\"\n if token_action is None and json_payload is None:\n values = {'f': response_format}\n elif token_action == \"getToken\":\n values = {'username': USERNAME, 'password': PASSWORD, 'client': 'requestip', 'f': response_format}\n elif token_action is not None and json_payload is not None:\n values = {'token': token_action, 'f': response_format}\n values.update(json_payload)\n else:\n values = {'token': token_action, 'f': response_format}\n return values\n\n def create_master_url_list(objects_list):\n \"\"\"\n Create a list of all urls using Folder objects and Service objects, stored in each Folder, and return the list.\n\n :param objects_list: list of Folder objects, containing Service objects\n :return: list of strings that represent urls\n \"\"\"\n master_list = []\n for obj_fold in objects_list:\n if obj_fold.folder_short_services_url == \"services/\":\n # Need to bypass the initial root folder so as not to get the whole 'services/' item, JC 20180911\n pass\n else:\n master_list.append(obj_fold.folder_short_services_url)\n for obj_serv in obj_fold.service_objects_list:\n master_list.append(obj_serv.service_short_services_url)\n return master_list\n\n def create_random_int(upper_integer):\n \"\"\"\n Create and return a random integer from 0 to one less than the upper range value.\n :param upper_integer: upper integer of range to be used\n :return: integer\n \"\"\"\n options = upper_integer - 1\n spot = random.randint(0, options)\n return spot\n\n def get_response(url, params):\n \"\"\"\n Submit a request with parameters to a url and return the response.\n\n :param url: url to which to make a request\n :param params: parameters to accompany the request\n :return: response from request\n \"\"\"\n # Protectionary action, to deal with mixed path characters between url syntax and os.path.join use of \"\\\"\n url = url.replace(\"\\\\\", \"/\")\n\n try:\n # Jessie discovered \"verify\" option and set to False to bypass the ssl issue\n response = requests.post(url=url, data=params, verify=False)\n except Exception as e:\n print(\"Error in response from requests: {}\".format(e))\n exit()\n else:\n result = None\n try:\n if \"html\" in response.headers[\"Content-Type\"]:\n raise NotJSONException\n elif \"text/csv\" in response.headers[\"Content-Type\"]:\n result = response\n elif \"application/json\" in response.headers[\"Content-Type\"]:\n result = response.json()\n except json.decoder.JSONDecodeError as jde:\n print(\"Error decoding response to json: {}\".format(jde))\n print(response)\n print(response.url)\n print(response.text)\n exit()\n except NotJSONException as NJE:\n print(f\"Response appears to be html, not json.\")\n print(response.url)\n print(response.headers)\n exit()\n return result\n\n def search_json_for_key(response_json, search_key):\n \"\"\"Search json for a key of interest and return the found value or exit on Key or Type Error.\"\"\"\n try:\n value = response_json[search_key]\n except KeyError as ke:\n print(\"KeyError: {}\".format(ke))\n exit()\n except TypeError as te:\n print(\"TypeError: {}\".format(te))\n print(response_json)\n exit()\n else:\n return value\n\n def write_response_to_csv(response, csv_path):\n \"\"\"Write content to a csv file.\"\"\"\n with open(csv_path, 'w') as csv_file_handler:\n for line in response.text:\n csv_file_handler.write(line)\n return\n\n # FUNCTIONALITY\n # Need a machine to which to make a request. Select at random from 4 total since we are bypassing web adaptor.\n machine = SERVER_MACHINE_NAMES[create_random_int(upper_integer=len(SERVER_MACHINE_NAMES))]\n\n # Need a token to make secure requests\n root_server_url = SERVER_ROOT_URL.format(machine_name=machine, port=SERVER_PORT_SECURE)\n generate_token_url = os.path.join(root_server_url, AdminObject.GENERATE_TOKEN_ENDING)\n token_params = create_params_for_request(token_action=\"getToken\")\n token_response = get_response(url=generate_token_url, params=token_params)\n token = search_json_for_key(response_json=token_response, search_key=\"token\")\n\n # Create a machine object for the selected ArcGIS Server machine. To store related values in object. Folders\n # variable assigned below\n machine_object = MachineObject(machine_name=machine,\n root_url=root_server_url,\n security_token=token)\n\n # Need to make a secure request for response as JSON to be able to access folders and services details\n basic_secure_params = create_params_for_request(token_action=machine_object.token)\n admin_object = AdminObject(root_machine_url=root_server_url)\n folders_request_response = get_response(url=admin_object.admin_services_url, params=basic_secure_params)\n\n # Need folder names list and to clean list; Remove System & Utilities, & append entry for root folder, per Jessie\n # NOTE: Noticed that Jessie also included 'GeoprocessingServices', but did not in statusdashboard script\n folder_names_raw = search_json_for_key(response_json=folders_request_response, search_key=\"folders\")\n remove_folders = [\"System\", \"Utilities\", \"GeoprocessingServices\"]\n folder_names_clean = list(set(folder_names_raw) - set(remove_folders))\n folder_names_clean.append(\"\")\n folder_names_clean.sort()\n\n # Assign the folder names list to the machine object variable.\n machine_object.folder_names_list = folder_names_clean\n print(machine_object)\n\n # Need a single list containing all folder url's AND all service url's from within all of those folders.\n # It is passed to the server and indicates the resourceURIs for which metrics will be built in the query process\n # Uses Folder objects to store folder urls and Service objects containing urls\n list_of_folder_objects = [FolderObject(name=folder_name, root_machine_url=machine_object.root_url) for folder_name\n in machine_object.folder_names_list]\n\n # For each folder, need a list of service objects for services in that folder\n for fold_obj in list_of_folder_objects:\n\n # Need a url to which to make a request to learn the services within\n services_request_response = get_response(url=fold_obj.folder_machine_url, params=basic_secure_params)\n services_json = search_json_for_key(response_json=services_request_response, search_key=\"services\")\n\n # Need to store the inventory of services that are within each folder\n for service in services_json:\n service_object = ServiceObject(folder=fold_obj.name,\n service_json=service,\n root_machine_url=machine_object.root_url)\n fold_obj.service_objects_list.append(service_object)\n\n master_url_list = create_master_url_list(list_of_folder_objects)\n\n # Need to create a new report object for use in generating report on server.\n report_object = ReportObject(root_machine_url=machine_object.root_url,\n master_urls_list=master_url_list,\n basic_request_json=basic_secure_params)\n\n # Report is created on the server. No response is needed. The variable isn't used afterward for that reason.\n print(\"Creating Report\")\n usage_report_params = create_params_for_request(token_action=machine_object.token,\n json_payload=report_object.report_json_params)\n get_response(url=report_object.report_url_create, params=usage_report_params)\n\n # Need to get the report contents using the query url\n # NOTE: Like the 'usagereports' dictionary it appears that any dictionary 'value' that is a dictionary must be\n # converted to a string first; using json.dumps()\n print(\"Querying Report\")\n post_data_query = {'filter': json.dumps({'machines': '*'})}\n report_query_params = create_params_for_request(token_action=machine_object.token,\n json_payload=post_data_query,\n response_format='csv')\n report_query_response = get_response(url=report_object.report_url_query, params=report_query_params)\n\n # Need to write the report content to csv file\n print(\"Writing CSV\")\n write_response_to_csv(response=report_query_response, csv_path=CSV_OUTPUT_FILE_PATH)\n\n # Need to delete the report from the server to reduce bloat\n print(\"Deleting Report\")\n get_response(url=report_object.report_url_delete, params=basic_secure_params)\n\n print(\"Complete!\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"CreateUsageReport_MOD.py","file_name":"CreateUsageReport_MOD.py","file_ext":"py","file_size_in_byte":29398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"133835416","text":"#########################################################################\n# Copyright 2011 Cloud Sidekick\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\nimport catoclient.catocommand\nfrom catoclient.param import Param\n\nclass GetTaskParameters(catoclient.catocommand.CatoCommand):\n\n Description = 'Gets a json formatted parameters template for a task.'\n API = 'get_task_parameters'\n Examples = '''\n_To get the parameters of the default version of a task and redirect to a file_\n\n cato-get-task-parameters -t \"mytask01\" > mytask01_params.json\n\n_To get the parameters of a specific version of a task_\n\n cato-get-task-parameters -t \"new example\" -v \"2.000\"\n\n_To get the most basic parameter template of a task, minus descriptions and defaults_\n\n cato-get-task-parameters -t \"new example\" -b\n'''\n Options = [Param(name='task', short_name='t', long_name='task',\n optional=False, ptype='string',\n doc='The ID or Name of a Task.'),\n Param(name='version', short_name='v', long_name='version',\n optional=True, ptype='string',\n doc='An optional specific Task Version. (Default if omitted.)'),\n Param(name='basic', short_name='b', long_name='basic',\n optional=True, ptype='boolean',\n doc='Get a basic template with no descriptive details or default values.')]\n \n\n def main(self):\n results = self.call_api(self.API, ['task', 'version', 'basic'])\n print(results)\n\n","sub_path":"catoclient/commands/gettaskparameters.py","file_name":"gettaskparameters.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"603076529","text":"from django.conf.urls import url\nfrom django.core.validators import EmailValidator\nfrom tastypie.http import HttpUnauthorized, HttpForbidden, HttpBadRequest\nfrom tastypie.resources import ModelResource\nfrom tastypie.utils import trailing_slash\n\nfrom SDA.resources import ResourceMeta\nfrom web_account.authentication import WebUserApiKeyAuthentication\nfrom web_account.models import User\n\n\nclass UserResource(ModelResource):\n\t'''Allow to login or logout a user from email only. On login create user if it does not exists.'''\n\tclass Meta(ResourceMeta):\n\t\tqueryset = User.objects.all()\n\t\tfields = []\n\t\tallowed_methods = ['get', 'post']\n\t\tresource_name = 'user'\n\t\tlist_allowed_methods = []\n\t\tdetail_allowed_methods = []\n\t\tauthentication = WebUserApiKeyAuthentication()\n\t\n\tdef prepend_urls(self):\n\t\treturn [\n\t\t\turl(r\"^(?P%s)/login%s$\" % (self._meta.resource_name, trailing_slash), self.wrap_view('login'), name=\"api_login\"),\n\t\t\turl(r'^(?P%s)/logout%s$' % (self._meta.resource_name, trailing_slash), self.wrap_view('logout'), name='api_logout'),\n\t\t]\n\t\n\tdef login(self, request, **kwargs):\n\t\tself.method_check(request, allowed=['post'])\n\t\t\n\t\t# Extract the email from the request data\n\t\tdata = self.deserialize(request, request.body)\n\t\temail = data.get('email', '')\n\t\t\n\t\t# Check that email is valid\n\t\ttry:\n\t\t\tEmailValidator()(email)\n\t\texcept Exception:\n\t\t\treturn self.create_response(request, 'Enter a valid email address.', HttpBadRequest)\n\t\t\n\t\t# We extract the name from the email\n\t\tname, _ = email.split('@', 1)\n\t\t\n\t\t# If the user does not exists we create it\n\t\tuser, created = User.objects.get_or_create(email = email, defaults = {'name' : name})\n\t\t\n\t\t# Check that user is active and login is successfull\n\t\tif user.is_active and user.do_login():\n\t\t\treturn self.create_response(request, {'name': user.name, 'api_key': user.api_key})\n\t\telse:\n\t\t\treturn self.create_response(request, 'Your account is disabled. Please contact the site administrators for help.', HttpForbidden)\n\t\n\tdef logout(self, request, **kwargs):\n\t\tself.method_check(request, allowed=['get'])\n\t\t# bad tastypie, is_authenticated returns None on success\n\t\tif self.is_authenticated(request) is None:\n\t\t\treturn self.create_response(request, {'success': True})\n\t\telse:\n\t\t\treturn self.create_response(request, {'success': False}, HttpUnauthorized)","sub_path":"web_account/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"586915198","text":"import pandas as pd\nlocation=\"Mll.csv\"\ne=pd.read_csv(location)\n\ne1= e.drop(e[(e.typeofaction!=\"cash-in\")].index)\ne1.to_csv('1.csv',index=False)\n\ne2= e.drop(e[(e.typeofaction!=\"transfer\")].index)\ne2.to_csv('2.csv',index=False)\n\nlocation1=\"1.csv\"\nlocation2=\"2.csv\"\n\ne3=pd.read_csv(location1)\ne4=pd.read_csv(location2)\n\nrel1=list(zip(e3.sourceid,e3.destinationid,e3.amountofmoney))\npp1=pd.DataFrame(data=rel1 , columns=['source','target','weight'])\npp1.to_csv('gephicsv1.csv',index=False)\n\nrel2=list(zip(e4.sourceid,e4.destinationid,e4.amountofmoney))\npp2=pd.DataFrame(data=rel2 , columns=['source','target','weight'])\npp2.to_csv('gephicsv2.csv',index=False)","sub_path":"deviation.py","file_name":"deviation.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"637926278","text":"\"\"\"People Counter.\"\"\"\n\"\"\"\n Copyright (c) 2018 Intel Corporation.\n Permission is hereby granted, free of charge, to any person obtaining\n a copy of this software and associated documentation files (the\n \"Software\"), to deal in the Software without restriction, including\n without limitation the rights to use, copy, modify, merge, publish,\n distribute, sublicense, and/or sell copies of the Software, and to\n permit person to whom the Software is furnished to do so, subject to\n the following conditions:\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\n\nimport os\nimport sys\nimport time\nimport socket\nimport json\nimport cv2\n\nimport logging as log\nimport paho.mqtt.client as mqtt\n\nfrom argparse import ArgumentParser\nfrom inference import Network\n\n# MQTT server environment variables\nHOSTNAME = socket.gethostname()\nIPADDRESS = socket.gethostbyname(HOSTNAME)\nMQTT_HOST = IPADDRESS\nMQTT_PORT = 3001\nMQTT_KEEPALIVE_INTERVAL = 60\n\n# Setup log file\nlog.basicConfig(filename='logfile.log', filemode='w', level=log.DEBUG)\n\n# Get correct video codec\nlog.info(\"Get correct video codec...\")\nif sys.platform == \"linux\" or sys.platform == \"linux2\":\n CODEC = 0x00000021\nelif sys.platform == \"darwin\":\n CODEC = cv2.VideoWriter_fourcc('M','J','P','G')\nelse:\n log.error(\"Unsupported OS.\")\n exit(1)\n\ndef build_argparser():\n \"\"\"\n Parse command line arguments.\n\n :return: command line arguments\n \"\"\"\n parser = ArgumentParser()\n parser.add_argument(\"-m\", \"--model\", required=True, type=str,\n help=\"Path to an xml file with a trained model.\")\n parser.add_argument(\"-i\", \"--input\", required=True, type=str,\n help=\"Path to image or video file\")\n parser.add_argument(\"-l\", \"--cpu_extension\", required=False, type=str,\n default=None,\n help=\"MKLDNN (CPU)-targeted custom layers.\"\n \"Absolute path to a shared library with the\"\n \"kernels impl.\")\n parser.add_argument(\"-d\", \"--device\", type=str, default=\"CPU\",\n help=\"Specify the target device to infer on: \"\n \"CPU, GPU, FPGA or MYRIAD is acceptable. Sample \"\n \"will look for a suitable plugin for device \"\n \"specified (CPU by default)\")\n parser.add_argument(\"-pt\", \"--prob_threshold\", type=float, default=0.5,\n help=\"Probability threshold for detections filtering\"\n \"(0.5 by default)\")\n return parser\n\ndef parse_output(frame, result, prob_threshold, w, h):\n '''\n Parse output.\n '''\n\n count = 0\n for obj in result[0][0]:\n if obj[2] > prob_threshold:\n xmin = int(obj[3] * w)\n ymin = int(obj[4] * h)\n xmax = int(obj[5] * w)\n ymax = int(obj[6] * h)\n cv2.rectangle(frame, (xmin, ymin), (xmax, ymax), (0, 255, 0), 1)\n count += 1\n return frame, count\n\ndef print_out_conf(result, frame):\n '''\n Print mean output confidence of people detected on frame.\n '''\n count = 0\n tot_confidence = 0\n mean_out_conf = 0\n \n for obj in result[0][0]:\n if obj[2] > 0:\n tot_confidence += obj[2]\n count += 1\n \n if count > 0:\n mean_out_conf = tot_confidence / count\n \n message = \"Output confidence: {:.1f}%\".format(mean_out_conf * 100)\n cv2.putText(frame, message, (20, 40),cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 255, 0), 1)\n return\n\ndef print_inf_time(time, frame):\n '''\n Print inference time on frame.\n '''\n message = \"Inference time: {:.1f}ms\".format(time * 1000)\n cv2.putText(frame, message, (20, 20),cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 255, 0), 1)\n return\n\ndef connect_mqtt():\n '''\n Connect to the MQTT client\n '''\n log.info(\"Connect to the MQTT client...\")\n client = mqtt.Client()\n client.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)\n\n return client\n\n\ndef infer_on_stream(args, client):\n \"\"\"\n Initialize the inference network, stream video to network,\n and output stats and video.\n\n :param args: Command line arguments parsed by `build_argparser()`\n :param client: MQTT client\n :return: None\n \"\"\"\n # Initialise the class\n infer_network = Network()\n # Set Probability threshold for detections\n prob_threshold = args.prob_threshold\n \n # Initialise counters\n current_count = 0\n last_count = 0\n debounced_count = 0\n debounced_last_count = 0\n total_count = 0\n\n # Load the model through `infer_network`\n infer_network.load_model(args.model, args.device, args.cpu_extension)\n net_input_shape = infer_network.get_input_shape()\n\n # Handle webcam, image or video \n log.info(\"Opening input stream...\")\n # Create a flag for single images\n image_flag = False\n # Check input\n if args.input == 'CAM':\n # The input is a webcam\n log.info(\"Webcam input.\")\n input_stream = 0\n elif os.path.isfile(args.input) == True:\n if args.input.endswith('.jpg') or args.input.endswith('.bmp'):\n # The input is a single image\n log.info(\"Single image input.\")\n image_flag = True\n else:\n # The input is a video\n log.info(\"Video input.\")\n input_stream = args.input\n else:\n # The input is not valid\n log.error(\"Specified input doesn't exist.\")\n exit(1) \n \n # Get and open video capture\n try:\n cap = cv2.VideoCapture(input_stream)\n cap.open(input_stream)\n log.info(\"Input correctly opened.\")\n except:\n log.error(\"Unable to open input.\")\n exit(1)\n \n # Grab the shape of the input \n width = int(cap.get(3))\n height = int(cap.get(4))\n\n # Initialize times\n start_ptime = 0.0\n start_debounce_time = 0.0\n \n log.info(\"Processing frames...\")\n \n # Process frames until the video ends, or process is exited\n while cap.isOpened():\n # Read the next frame\n flag, frame = cap.read()\n if not flag:\n break\n key_pressed = cv2.waitKey(60)\n\n # Pre-process the frame\n p_frame = cv2.resize(frame, (net_input_shape[3], net_input_shape[2]))\n p_frame = p_frame.transpose((2,0,1))\n p_frame = p_frame.reshape(1, *p_frame.shape)\n \n # Inference start time\n inf_start_t = time.time()\n \n # Perform inference on the frame\n infer_network.exec_net(0, p_frame)\n\n # Wait for the result\n if infer_network.wait(0) == 0:\n #Compute inference time\n inf_t = time.time() - inf_start_t\n \n # Get the results of the inference request\n result = infer_network.get_output(0)\n\n # Extract any desired stats from the results\n out_frame, current_count = parse_output(frame, result, args.prob_threshold, width, height)\n \n # \"Debounce\" mechanism\n if current_count != last_count:\n start_debounce_time = time.time()\n last_count = current_count\n if (time.time() - start_debounce_time) > 1.0:\n if current_count != debounced_count:\n debounced_count = current_count\n \n if debounced_count > debounced_last_count:\n start_ptime = time.time()\n total_count = total_count + debounced_count - debounced_last_count\n client.publish(\"person\", json.dumps({\"total\": total_count}))\n if debounced_count < debounced_last_count:\n pduration = time.time() - start_ptime \n client.publish(\"person/duration\", json.dumps({\"duration\": int(pduration)}))\n client.publish(\"person\", json.dumps({\"count\": debounced_count}))\n debounced_last_count = debounced_count\n \n # Print output confidence on frame\n print_out_conf(result, out_frame)\n \n # Print inference time on frame\n print_inf_time(inf_t, out_frame)\n\n if image_flag:\n # Write an output image if `single_image_mode`\n cv2.imwrite('out_image.jpg', out_frame)\n else:\n # Send the frame to the FFMPEG server\n sys.stdout.buffer.write(out_frame) \n sys.stdout.flush()\n \n \n # Break if escape key pressed\n if key_pressed == 27:\n break\n \n # Release the capture and destroy any OpenCV windows\n cap.release()\n cv2.destroyAllWindows()\n # Disconnect from MQTT\n client.disconnect()\n\ndef main():\n \"\"\"\n Load the network and parse the output.\n\n :return: None\n \"\"\"\n # Grab command line args\n args = build_argparser().parse_args()\n # Connect to the MQTT server\n client = connect_mqtt()\n # Perform inference on the input stream\n infer_on_stream(args, client)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"84919030","text":"#__autor__ = sunweiwei\n#date = 2018/3/4\n\nfrom mycrm.admin_base import BaseKingAdmin\n\nclass Adminsite(object):\n\n def __init__(self):\n self.enable_dict = {}\n\n def register(self,model_class,admin_class=None):#从register中取到数据库表和admin_class\n # print('.............',model_class,admin_class)\n app_name = model_class._meta.app_label #_meta取到app的名字\n model_name = model_class._meta.model_name#取到对应的表名\n # admin_name = admin_class._meta.app_label\n if not admin_class: #如果admin_class为空,执行默认的参数,有的换,执行填写的参数\n admin_class = BaseKingAdmin()\n else:\n admin_class = admin_class()\n\n admin_class.model = model_class#将model_class封装到admin_class中,后面用到\n # print(\"22222\",admin_class.model)\n if app_name not in self.enable_dict:\n # {app_name:\n # { model_name : admin_class }\n # } 格式\n self.enable_dict[app_name] = {}\n self.enable_dict[app_name][model_name] = admin_class\n\nsite = Adminsite()\n\n\n\n\n\n","sub_path":"N_CRM/mycrm/sites.py","file_name":"sites.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"591481962","text":"#coding=utf-8\n#__author__ = 'heshuai'\n#description=''' '''\n\nimport os\ncurrent_path = __file__\n\n\ndef get_parent_dir(path=current_path):\n if os.path.isdir(path):\n path = os.path.abspath(path)\n elif os.path.isfile(path):\n path = os.path.dirname(path)\n parent_path = os.path.dirname(path)\n return parent_path","sub_path":"miraScripts/mayaTools/lighting_tool/OF/lighting_UI/get_parent_dir.py","file_name":"get_parent_dir.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"366801671","text":"#Pythonで数独(AWS用)\n\ndef encode(grid):\n \"テキストから2次元配列のvaluesを作成する\"\n values = []\n digits = \"123456789\"\n chars = [c for c in grid if c in digits or c in '0.']\n assert len(chars) == 81\n grid_int = map(lambda x: int(x) if x != \".\" else 0, chars)\n\n count = 0\n row = []\n for i in grid_int:\n row.append(i)\n count += 1\n if count % 9 == 0: #行毎に分割\n values.append(row)\n row = []\n return values\n\ndef main(data):\n if solve(0, 0, data):\n #printtable(data)\n return data\n else:\n print (\"This problem is unsolvable\")\n\ndef solve(x, y, table):\n if x == 0 and y == 9:\n return True\n\n if table[y][x] == 0:\n for t in range(1, 10):\n table[y][x] = t\n if check(x, y, table):\n (nx, ny) = next(x, y)\n if solve(nx, ny, table):\n return True\n table[y][x] = 0\n return False\n else:\n (nx, ny) = next(x, y)\n if solve(nx, ny, table):\n return True\n\ndef next(x, y):\n x += 1\n if x > 8:\n x = 0\n y += 1\n return (x, y)\n\ndef check(x, y, table):\n return row(x, y, table) and column(x, y, table) and block(x, y, table)\n\ndef column(x, y, table):\n for yt in range(9):\n if yt != y:\n if table[y][x] == table[yt][x]:\n return False\n return True\n\ndef row(x, y, table):\n for xt in range(9):\n if xt != x:\n if table[y][x] == table[y][xt]:\n return False\n return True\n\ndef block(x, y, table):\n xbase = (x // 3) * 3\n ybase = (y // 3) * 3\n for yt in range(ybase, ybase + 3):\n for xt in range(xbase, xbase + 3):\n if xt != x and yt != y:\n if table[y][x] == table[yt][xt]:\n return False\n return True\n\ndef printtable(table):\n for y in range(9):\n for x in range(9):\n print (table[y][x])\n print (\"\")\n\ndef output(data):\n for i in range(9):\n for j in range (9):\n if data[i][j] == 0:\n print (\".\", end=\"\")\n else:\n print (data[i][j], end=\"\")\n\n if (j+1) % 3 == 0 and j < 8:\n print (\"|\", end=\"\")\n print(\"\")\n if (i+1) % 3 == 0 and i < 8:\n print (\"-----------\")\n print(\"\")\n\nif __name__ == \"__main__\":\n datafile = \"/home/ec2-user/environment/sudoku/data.txt\"\n datalinefile = \"/home/ec2-user/environment/sudoku/dataline.txt\"\n f = open(datalinefile)\n numbers = f.read()\n f.close\n values = encode(numbers)\n print(\"This is the problem!\")\n output(values)\n main(values)\n print(\"This is the answer!\")\n output(values)\n\n print(\"sucess!\")\n","sub_path":"awsNP.py","file_name":"awsNP.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"539834376","text":"# pip install opencv-contrib-python\n\nimport numpy as np\nimport cv2\nimport sys\nimport glob\n\ndef load_dict_uid():\n\tdict_uid = {}\n\tfds = [it.replace('data/', '') for it in glob.glob('data/*')]\n\tfds.sort()\n\tfor index, it in enumerate(fds):\n\t\tdict_uid[it] = index\n\t\n\treturn dict_uid\n\ndef load_data_samples(meta_file, dict_uid):\n\timages = []\n\tlabels = []\n\twith open(meta_file) as f:\n\t\tfor line in f:\n\t\t\tfilename, uid = line.strip().split('\\t')\n\t\t\timg = cv2.imread(filename) / 255\n\t\t\timg = np.reshape(img, (-1))\n\t\t\timages.append(img)\n\t\t\tlabels.append(dict_uid[uid])\n\n\treturn images, labels\n\ndef train(meta_file):\n\t# create uid dict\n\tdict_uid = load_dict_uid()\n\tprint(dict_uid)\n\n\t# load data samples\n\timages, labels = load_data_samples(meta_file, dict_uid)\n\n\t# create model --> train\n\trecognizer = cv2.face.EigenFaceRecognizer_create()\n\trecognizer.train(images, np.array(labels))\n\n\t# save model\n\trecognizer.save('model.yml')\n\t\ndef test(file_model, meta_file):\n\trecognizer = cv2.face.EigenFaceRecognizer_create()\n\trecognizer.read(file_model)\n\n\tdict_uid = load_dict_uid()\n\timages, labels = load_data_samples(meta_file, dict_uid)\n\tcount = 0\n\tfor i in range(len(images)):\n\t\tpre, score = recognizer.predict(images[i])\n\t\tcount += 1 if pre==labels[i] else 0 # <>? : \n\n\treturn count / len(labels)\n\n\tpass\n\nif __name__ == \"__main__\":\n\tif len(sys.argv) >= 2 and sys.argv[1] == 'train':\n\t\ttrain('train.txt')\n\tprint('train acc:', test('model.yml', 'train.txt'))\n\tprint('test acc:', test('model.yml', 'test.txt'))","sub_path":"face-recognition-opencv/train_test.py","file_name":"train_test.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"390996412","text":"# -*- coding: utf-8 -*-\n# @Time : 2020-04-25 01:16\n# @Author : icarusyu\n# @FileName: topo_case1.py.py\n# @Software: PyCharm\nimport tkinter as tk\nimport tkinter.font as tkFont\nfrom PIL import Image,ImageTk\n\n# 第1步,实例化object,建立窗口window\nroot = tk.Tk()\n\n# 第2步,给窗口的可视化起名字\nroot.title('动态网络拓扑')\n\n# 第3步,设定窗口的大小(长 * 宽)\nroot.geometry('600x400') # 这里的乘是小x\n\n# 第4步,在图形界面上创建 500 * 200 大小的画布并放置各种元素\ncanvas = tk.Canvas(root, bg='LightGrey', height=600, width=600)\n\n# 放置ap1,h1\nap = Image.open('ap.png')\nap = ap.resize((80,80), Image.ANTIALIAS)\nap = ImageTk.PhotoImage(ap)#在root实例化创建,否则会报错\nx1,y1 = 200, 250\ncanvas.create_image(x1, y1, anchor = 'n',image=ap) # 图片锚定点(n图片顶端的中间点位置)放在画布(250,0)坐标处\n# label\nname_p1 = tk.Label(root, fg='DarkSlateBlue', text='AP1', font=('Arial', 20)) # 相对位置\nname_p1.place(x=x1, y=y1 + 70, anchor='n')\nf = tkFont.Font(name_p1, name_p1.cget(\"font\"))\nf.configure(underline=True)\nname_p1.configure(font=f)\n\nlaptop = Image.open('laptop.png')\nlaptop = laptop.resize((80, 60), Image.ANTIALIAS)\nlaptop = ImageTk.PhotoImage(laptop) # 在root实例化创建,否则会报错\nx5, y5 = 200, 50\ncanvas.create_image(x5, y5, anchor = 'n',image=laptop) # 图片锚定点(n图片顶端的中间点位置)放在画布(250,0)坐标处\n# line\nline = canvas.create_line(x5, y5+50, x1, y1, fill = 'blue', dash=(10,10), width = 3) # 画直线\n# label\nname_p1 = tk.Label(root, fg='DarkSlateBlue', text='L1', font=('Arial', 20)) # 相对位置\nname_p1.place(x=x5, y=y5 + 70, anchor='n')\nf = tkFont.Font(name_p1, name_p1.cget(\"font\"))\nf.configure(underline=True)\nname_p1.configure(font=f)\n\ncanvas.pack()\n\n# 第7步,主窗口循环显示\nroot.mainloop()","sub_path":"gui/validation1.py","file_name":"validation1.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"118096914","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('task', '0002_auto_20150721_1700'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='task',\n name='client_task',\n field=models.BooleanField(default=False, verbose_name=b'\\xe6\\x98\\xaf\\xe5\\x90\\xa6\\xe6\\x98\\xaf\\xe5\\xae\\xa2\\xe6\\x88\\xb7\\xe7\\xab\\xaf\\xe4\\xbb\\xbb\\xe5\\x8a\\xa1'),\n ),\n migrations.AddField(\n model_name='task',\n name='success_rate',\n field=models.IntegerField(default=100, verbose_name=b'\\xe6\\x88\\x90\\xe5\\x8a\\x9f\\xe7\\x8e\\x87'),\n ),\n ]\n","sub_path":"apps/task/migrations/0003_auto_20150922_1502.py","file_name":"0003_auto_20150922_1502.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"18775254","text":"#!/usr/bin/env python3\nfrom nodes import Iterator\n\nquery = {\n 'PROJECTION': ['name','id'],\n 'SELECTION' : ['id', '>', '2'],\n 'FILESCAN' : ['people']\n}\n\nquery2 = {\n 'AGGREGATION': ['sum','age'],\n 'PROJECTION' : ['age'],\n 'SELECTION' : ['id', '>=', '0'],\n 'FILESCAN' : ['people']\n}\n\nquery3 = {\n 'AGGREGATION': ['average','age'],\n 'PROJECTION' : ['age'],\n 'SELECTION' : ['id', '>=', '0'],\n 'FILESCAN' : ['people']\n}\n\ndef execute_plan(plan):\n result = Iterator(plan).next()\n print('--- query ---')\n print('printing query :',plan)\n print('printing result:',result)\n return\n\ndef main(function, cmd=None):\n execute_plan(query)\n execute_plan(query2)\n execute_plan(query3)\n return\n\nif __name__ == '__main__':\n import argparse\n\n parser = argparse.ArgumentParser(description='Run some queries')\n parser.add_argument('-f','--function', help='Function ')\n parser.add_argument('-c','--command', help='Text to run ')\ndef repeat(repeats, input):\n repeats = int(repeats)\n return input * repeats\n\n\n@app.route('/users//') # for a route '/users/____/____', two parameters in the url get passed as username and id\ndef show_user_profile(username, id):\n print(username)\n print(id)\n return \"username: \" + username + \", id: \" + id\n\n\nif __name__==\"__main__\": # If __name__ is \"__main__\" we know we are running this file directly and not importing\n\n\n\n # it from a different module\n app.run(debug=True) # Run the app in debug mode.\n","sub_path":"helloFlask/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"134350670","text":"import hashlib\nimport json\nimport mmap\nimport pefile\nimport re\nimport struct\nimport time\nfrom pathlib import Path\n\n\ndef pos():\n return mm.tell()\n\n\ndef find_pattern(pattern, offset=0, adjust=0):\n if type(pattern) == str:\n return mm.seek(mm.find(bytes.fromhex(pattern), offset) + adjust)\n elif type(pattern) == bytes:\n return mm.seek(re.search(pattern, mm[offset:]).start() + offset + adjust)\n\n\ndef find_pattern_backwards(pattern, start=0, adjust=0):\n pattern = pattern.replace(\" \", \"\")\n pattern_len = len(pattern) // 2\n while mm.read(pattern_len) != bytes.fromhex(pattern):\n mm.seek(pos() - pattern_len - 1)\n if adjust != 0:\n mm.seek(pos() + adjust)\n\n\ndef patch(title, on, toggle_in_game=False, tooltip=None):\n offset = pos()\n on = on.replace(\" \", \"\") if type(on) == str else on.hex()\n off = mm.read(len(on) // 2).hex()\n\n if title not in game[\"data\"]:\n game[\"data\"][title] = {}\n game[\"data\"][title][\"tooltip\"] = tooltip\n game[\"data\"][title][\"toggle_in_game\"] = toggle_in_game\n game[\"data\"][title][\"type\"] = \"default\"\n game[\"data\"][title][\"patches\"] = []\n\n hack = {}\n hack[\"offset\"] = f\"0x{offset:X}\"\n hack[\"rva\"] = f\"0x{pe.get_rva_from_offset(offset):X}\"\n hack[\"off\"] = off.upper()\n hack[\"on\"] = on.upper()\n game[\"data\"][title][\"patches\"].append(hack)\n\n\ndef patch_union(\n title, name, on, toggle_in_game=False, tooltip=None, patch_type=\"union\", adjust=0\n):\n offset = pos() + adjust\n if patch_type != \"number\":\n on = on.replace(\" \", \"\").upper() if type(on) == str else on.hex().upper()\n\n if title not in game[\"data\"]:\n game[\"data\"][title] = {}\n game[\"data\"][title][\"tooltip\"] = tooltip\n game[\"data\"][title][\"toggle_in_game\"] = toggle_in_game\n game[\"data\"][title][\"type\"] = patch_type\n game[\"data\"][title][\"patches\"] = {}\n game[\"data\"][title][\"patches\"][\"offset\"] = f\"0x{offset:X}\"\n game[\"data\"][title][\"patches\"][\"rva\"] = f\"0x{pe.get_rva_from_offset(offset):X}\"\n\n game[\"data\"][title][\"patches\"][name] = on\n\n\nstart_time = time.time()\ngame = None\n\nfor dll in Path(\".\").glob(\"popn22*.dll\"):\n\n with open(dll, \"r+b\") as infile:\n mm = mmap.mmap(infile.fileno(), length=0, access=mmap.ACCESS_READ)\n pe = pefile.PE(dll, fast_load=True)\n h = infile.read()\n\n game = {}\n game[\"info\"] = {}\n game[\"info\"][\"title\"] = \"pop'n music\"\n game[\"info\"][\"version\"] = None\n game[\"info\"][\"datecode\"] = dll.stem[6:].strip(\"-\")\n game[\"info\"][\"file\"] = \"popn22.dll\"\n game[\"info\"][\"md5\"] = hashlib.md5(h).hexdigest()\n game[\"info\"][\"sha1\"] = hashlib.sha1(h).hexdigest()\n game[\"data\"] = {}\n\n title = \"E: Drive Fix\"\n find_pattern(\"65 3A 2F\", 0x200000)\n patch(title, \"64 65 76\", tooltip=\"Fix crash caused by no E: drive\")\n\n title = \"HDMI Audio Fix\"\n find_pattern(\"10 85 C0 75 96\", 0x100000, 1)\n patch(title, \"90\" * 4)\n\n title = \"Prevent Windows volume change on boot\"\n find_pattern(\"10 89 44 24 14 8B C6\", 0x100000)\n find_pattern_backwards(\"83 EC\", pos(), -2)\n patch(title, \"C3\", tooltip=\"If your volume gets forced to max, turn this on\")\n\n title = \"Boot to Event Mode\"\n find_pattern(\n \"8B 00 C3 CC CC CC CC CC CC CC CC CC CC CC CC CC C7 40 04 00 00 00 00\",\n 0x80000,\n )\n patch(title, \"31 C0 40 C3\")\n\n title = \"Remove Timer\"\n find_pattern(\"00 0F 85 65 05 00 00\", 0x90000, 1)\n patch(title, \"90 E9\")\n\n title = \"Skip Menu and Long Note Tutorials\"\n find_pattern(\"00 84 C0 74 3A E8\", 0x20000, 3)\n patch(title, \"EB\")\n find_pattern_backwards(\"75 5E\", pos(), -2)\n patch(title, \"EB\")\n find_pattern(\"5F 5E 66 83 F8 01 75\", 0x70000, 6)\n patch(title, \"EB\")\n\n title = \"Unlock All Songs\"\n find_pattern(\"FF FF A9 06 00 00 68 74\", 0x90000, 7)\n patch(title, \"EB\")\n find_pattern_backwards(\"74 13\", pos(), -2)\n patch(title, \"90 90\")\n\n title = \"Unlock EX Charts\"\n ex = []\n mm.seek(0x200000)\n while True:\n find_pattern(\"80 00 00 03\", pos(), 1)\n if int(pos() - 2) > 0x200000:\n mm.seek(pos() - 1)\n patch(title, \"00\")\n else:\n break\n mm.seek(0x200000)\n while True:\n find_pattern(\"80 00 00 07\", pos(), 1)\n if int(pos() - 2) > 0x200000:\n mm.seek(pos() - 1)\n patch(title, \"00\")\n else:\n break\n\n find_pattern(\"83 38 00 75 22\", 0x90000, 3)\n if pos() > 0x1000:\n title = \"Unlock Deco Parts\"\n patch(title, \"90 90\")\n\n title = \"Unlock Characters\"\n find_pattern(\"01 00 00 74 0E 8B FA E8\", 0x90000, 3)\n patch(title, \"EB\")\n\n title = \"Premium Free\"\n find_pattern(\"CC FE 46 0E 80 BE\", 0x90000, 1)\n patch(title, \"90 90 90\", tooltip=\"Score buffer never resets, use offline\")\n find_pattern(\"75\", pos())\n patch(title, \"EB\")\n find_pattern(\"77 3E\", pos())\n patch(title, \"EB 07\")\n\n title = \"Autoplay\"\n find_pattern(\"84 C0 0F 84 08 01 00 00\", 0x90000, 2)\n patch(title, \"90\" * 6)\n find_pattern(\"74 53\", pos())\n patch(title, \"90 90\")\n\n title = \"Replace COLOR CHECK test menu with debug CHARA VIEWER\"\n find_pattern(str.encode(\"COLOR CHECK\").hex(), 0x190000)\n patch(\n title,\n str.encode(\"CHARA VIEWER\\x00\"),\n tooltip=\"Press service button to exit\",\n )\n find_pattern(\"33 C0 68 A4 06\", 0x10000)\n find_pattern_backwards(\"CC CC\", pos())\n chara = pe.get_rva_from_offset(pos())\n find_pattern(\"00 00 00 00 68 AC 00 00 00 E8\", 0x20000, 5)\n patch(title, \"B0 34 0C\")\n find_pattern(\"50 E8\", pos(), 2)\n here = pe.get_rva_from_offset(pos())\n patch(title, struct.pack(\"\", dll.stem + \".json\")\n\nif Path(\"json_to_bemanipatcher.py\").is_file() and game:\n from json_to_bemanipatcher import json_to_bemanipatcher\n\n json_to_bemanipatcher(\"popn22\", \"popn\")\n\nif game:\n end_time = time.time()\n print(\"Elapsed time:\", end_time - start_time)\n print()\n","sub_path":"docs/find_popn_offsets.py","file_name":"find_popn_offsets.py","file_ext":"py","file_size_in_byte":7136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"267488767","text":"file = open(\"Urls.txt\",\"r\")\nline = file.readlines()\nList=[]\na=0\nfor i in line:\n\tb=i[30:]\n\tif (i!=\"Excptnthrn\" and b[0:9]!=\"User_talk\" and b[0:14]!=\"Wikipedia_talk\" and b[0:4]!=\"Talk\"):\n\t\ta=a+1\n\t\ttemp=i[30:]\n\t\tList.append(temp)\n\t\tprint(temp, end=\"\")","sub_path":"ControversialWikiPages/urltocode.py","file_name":"urltocode.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"454159748","text":"from __future__ import absolute_import , unicode_literals\nimport platform\nimport os\nfrom celery import Celery\n\nif platform.system() == 'Windows':\n os.environ.setdefault('FORKED_BY_MULTIPROCESSING','1')\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'forum_backend_project.settings')\n\napp = Celery('forum_backend')\n\napp.config_from_object('django.conf:settings',namespace='CELERY')\n\napp.autodiscover_tasks()\n\n\napp.conf.update(\n timezone = 'Asia/Shanghai'\n)\n\n@app.task(bind=True)\ndef debug_task(self):\n print('Request: {0!r}'.format(self.request))\n","sub_path":"forum_backend/forum_backend_project/celery.py","file_name":"celery.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"57951372","text":"import re\nprint(\"do you want to write a line or want to link a file\")\nans=input(\"type 1 for writting and 2 for linking: \")\nif ans==\"1\":\n strn=input(\"type your line :\\n\")\n regx=input(\"type your expression :\")\n matches=re.findall(regx,strn)\n print(matches)\nelse:\n fname=input(\"Enter a file name\")\n regx=input(\"Enter an expression\")\n fhand=open(fname)\n for line in fhand:\n line=line.rstrip()\n matches=re.findall(regx,line)\n if len(matches)>0:\n print(matches)\n print(\"line: \",line)\n","sub_path":"ptut/src/jay/ja.py","file_name":"ja.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"31741916","text":"from lib.mytypes import ListOfPoints\nfrom lib.geometric_tool_lab import *\nfrom lib.util import *\nfrom lib.getrand import *\nfrom pprint import pprint\nimport operator\n\n\ndef merge_convex_hulls(left_convex_hull: list[Point], right_convex_hull: list[Point]) -> list[Point]:\n \"\"\" Łączenie dwóch rozdzielnych otoczek. Otoczki muszą być zadane w formie wierzchołków podanych w kolejności przeciwnej do \n ruchu wskazówek zegara. Ponadto left_convex_hull powinno być lewą otoczką, a right_convex_hull prawą. \"\"\"\n\n left_ch_size = len(left_convex_hull)\n right_ch_size = len(right_convex_hull)\n\n\n # znajdujemy prawy skrajny punkt lewej otoczki \n left_ch_rightmost_idx = index_of_max(left_convex_hull, cmp_idx=0)\n right_ch_leftmost_idx = index_of_min(right_convex_hull, cmp_idx=0)\n\n \n left = left_convex_hull[left_ch_rightmost_idx]\n right = right_convex_hull[right_ch_leftmost_idx]\n left_idx = left_ch_rightmost_idx\n right_idx = right_ch_leftmost_idx\n \n\n # górna styczna\n while orientation(left, right, right_convex_hull[(right_idx - 1) % right_ch_size]) != -1 or orientation(right, left, left_convex_hull[(left_idx + 1) % left_ch_size]) != 1:\n\n # podnosimy punkt na prawej otoczce\n while orientation(left, right, right_convex_hull[(right_idx - 1) % right_ch_size]) != -1:\n right_idx = (right_idx - 1) % right_ch_size\n right = right_convex_hull[right_idx]\n\n # podnosimy punkt na lewej otoczce\n while orientation(right, left, left_convex_hull[(left_idx + 1) % left_ch_size]) != 1:\n left_idx = (left_idx + 1) % left_ch_size\n left = left_convex_hull[left_idx]\n \n \n upper_tangent_left_idx = left_idx\n upper_tangent_right_idx = right_idx\n \n \n # dolna styczna\n left = left_convex_hull[left_ch_rightmost_idx]\n right = right_convex_hull[right_ch_leftmost_idx]\n left_idx = left_ch_rightmost_idx\n right_idx = right_ch_leftmost_idx\n \n while orientation(left, right, right_convex_hull[(right_idx + 1) % right_ch_size]) != 1 or orientation(right, left, left_convex_hull[(left_idx - 1) % left_ch_size]) != -1:\n \n # opuszczamy punkt na prawej otoczce\n while orientation(left, right, right_convex_hull[(right_idx + 1) % right_ch_size]) != 1:\n right_idx = (right_idx + 1) % right_ch_size\n right = right_convex_hull[right_idx]\n\n # opuszczamy punkt na lewej otoczce\n while orientation(right, left, left_convex_hull[(left_idx - 1) % left_ch_size]) != -1:\n left_idx = (left_idx - 1) % left_ch_size\n left = left_convex_hull[left_idx]\n \n \n lower_tangent_left_idx = left_idx\n lower_tangent_right_idx = right_idx\n \n \n merged_convex_hull = [ ]\n\n while upper_tangent_left_idx != ((lower_tangent_left_idx + 1) % left_ch_size):\n merged_convex_hull.append(left_convex_hull[upper_tangent_left_idx])\n upper_tangent_left_idx = (upper_tangent_left_idx + 1) % left_ch_size\n \n while lower_tangent_right_idx != ((upper_tangent_right_idx + 1) % right_ch_size):\n merged_convex_hull.append(right_convex_hull[lower_tangent_right_idx])\n lower_tangent_right_idx = (lower_tangent_right_idx + 1) % right_ch_size \n \n return merged_convex_hull \n\n\n\n\ndef divide_conq(point2_set: list[Point]) -> Union[list[Point], None]:\n if len(point2_set) <= 2: return point2_set\n \n left_convex_hull = divide_conq(point2_set[ : len(point2_set) // 2])\n right_convex_hull = divide_conq(point2_set[len(point2_set) // 2 : ])\n \n return merge_convex_hulls(left_convex_hull, right_convex_hull)\n\n\n\n\ndef main():\n random_points = rand_point2_set(10, 0, 10).tolist()\n\n pprint(random_points)\n\n print(\"--\" * 10)\n\n convex_hull = divide_conq(random_points)\n \n \n pprint(convex_hull)\n \n \nif __name__ == \"__main__\":\n main()","sub_path":"convexhull/divide_conq.py","file_name":"divide_conq.py","file_ext":"py","file_size_in_byte":3951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"330682420","text":"#!/home/xlin/miniconda3/bin/python\n# -*- coding: utf-8 -*-\n \nimport logging\nimport os.path\nimport sys\nimport multiprocessing\nimport random\nfrom nltk.corpus import stopwords\n \nimport numpy as np\nfrom gensim.corpora import WikiCorpus\nfrom gensim.models import Word2Vec\nfrom gensim.models.word2vec import LineSentence\nfrom gensim.models.keyedvectors import KeyedVectors\nfrom scipy import spatial\nimport scipy\nimport scipy.stats\n\nfrom numpy import dot\nfrom numpy.linalg import norm\n\nfrom sklearn.manifold import TSNE\nimport matplotlib.pyplot as plt\n\nif __name__ == '__main__':\n \n # check and process input arguments\n if len(sys.argv) < 2:\n print(globals()['__doc__'] % locals())\n sys.exit(1)\n \n dict = {}\n inFile = open(sys.argv[1], 'r')\n counter = 0\n for aLine in inFile:\n aLine = aLine.strip('\\n')\n lineToken = aLine.split(',')\n for ii in range(2):\n aWord = lineToken[ii].strip()\n if (aWord not in dict):\n dict[aWord] = counter\n counter = counter + 1\n inFile.close()\n\n winLen = 10\n corpusSize = 0\n corpusFile = open(sys.argv[2], 'r')\n MImatrix = np.zeros((counter, counter))\n for aLine in corpusFile:\n aLine = aLine.strip('\\n')\n lineToken = aLine.split(' ')\n lenOfLine = len(lineToken)\n for ii in range(lenOfLine):\n lineToken[ii] = lineToken[ii].strip()\n corpusSize = corpusSize + lenOfLine\n idx = 0\n for aToken in lineToken:\n if aToken in dict:\n row = dict[aToken]\n beginIdx = idx - winLen\n if (beginIdx < 0):\n beginidx = 0\n endIdx = idx + winLen + 1\n if (endIdx > lenOfLine):\n endIdx = lenOfLine\n beginIdx = 0\n endIdx = lenOfLine\n testToken = lineToken[beginIdx:endIdx]\n for oneWord in testToken:\n if (oneWord in dict):\n col = dict[oneWord]\n MImatrix[row, col] = MImatrix[row, col] + 1\n idx = idx + 1\n corpusFile.close()\n\n inFile = open(sys.argv[1], 'r')\n outFile = open(sys.argv[3], 'w')\n for aLine in inFile:\n aLine = aLine.strip('\\n')\n lineToken = aLine.split(',')\n idx1 = dict[lineToken[0].strip()]\n idx2 = dict[lineToken[1].strip()]\n pA = 1.0*MImatrix[idx1][idx1]/corpusSize\n pB = 1.0*MImatrix[idx2][idx2]/corpusSize\n pAB = 1.0*MImatrix[idx1][idx2]/corpusSize\n #print(\"%.6e, %.6e, %.6e\" % (pA, pB, pAB))\n PMI = np.log10(pAB/pA/pB)/np.log10(2.0)\n outFile.write(\"%s, %.2e, %.2e, %.2e, %.2e\\n\" % (aLine, pA, pB, pAB, PMI))\n \n inFile.close()\n outFile.close()\n","sub_path":"word2vec/calculateMI.py","file_name":"calculateMI.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"174695160","text":"import tkinter as tk\nfrom python_files import Constants as C\n\n\nclass NewPassPopup(object):\n def __init__(self, master):\n self.top = tk.Toplevel(master)\n self.top.geometry(\"300x100\")\n self.shirt_number = 0\n shirt_number_label = tk.Label(self.top, text=\"Shirt number\")\n vcmd = (master.register(self.validate),\n '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')\n self.shirt_number_entry = tk.Entry(self.top, validate='key', validatecommand=vcmd)\n add_button = tk.Button(self.top, text='Add pass',\n command=lambda: self.cleanup())\n\n received_label = tk.Label(self.top, text=\"Received or Missed:\")\n upper_label = tk.Label(self.top, text=\"Upper or Lower:\")\n self.received = tk.StringVar()\n self.received.set(\"R\")\n self.upper = tk.StringVar()\n self.upper.set(\"U\")\n received_rb = tk.Radiobutton(self.top, text=\"Received\", variable=self.received, value=\"R\")\n miss_rb = tk.Radiobutton(self.top, text=\"Missed\", variable=self.received, value=\"M\")\n upper_rb = tk.Radiobutton(self.top, text=\"Upper\", variable=self.upper, value=\"U\")\n lower_rb = tk.Radiobutton(self.top, text=\"Lower\", variable=self.upper, value=\"L\")\n self.shirt_number_entry.bind('', lambda x: self.received.set(\"R\"))\n self.shirt_number_entry.bind('', lambda x: self.received.set(\"M\"))\n self.shirt_number_entry.bind('', lambda x: self.upper.set(\"U\"))\n self.shirt_number_entry.bind('', lambda x: self.upper.set(\"L\"))\n self.shirt_number_entry.focus_set()\n self.top.bind('', self.cleanup)\n\n shirt_number_label.grid(row=0, column=0)\n self.shirt_number_entry.grid(row=0, column=1, columnspan=2)\n received_label.grid(row=1, column=0)\n received_rb.grid(row=1, column=1)\n miss_rb.grid(row=1, column=2)\n upper_label.grid(row=2, column=0)\n upper_rb.grid(row=2, column=1)\n lower_rb.grid(row=2, column=2)\n add_button.grid(row=3, column=1, pady=C.NORMAL_PADDING)\n self.top.columnconfigure(0, weight=1)\n self.top.columnconfigure(1, weight=1)\n self.top.columnconfigure(2, weight=1)\n\n def cleanup(self, event=None):\n self.shirt_number = self.shirt_number_entry.get()\n self.top.destroy()\n\n def validate(self, action, index, value_if_allowed,\n prior_value, text, validation_type, trigger_type, widget_name):\n if text in '0123456789':\n try:\n float(value_if_allowed)\n return True\n except ValueError:\n return False\n else:\n return False\n","sub_path":"python_files/NewPassPage.py","file_name":"NewPassPage.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"429456415","text":"# 278-First_Bad_Version_EASY.py\n\n# https://leetcode.com/problems/first-bad-version/\n\n# You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.\n\n# Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.\n\n# You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.\n\n# Example:\n\n# Given n = 5, and version = 4 is the first bad version.\n\n# call isBadVersion(3) -> false\n# call isBadVersion(5) -> true\n# call isBadVersion(4) -> true\n\n# Then 4 is the first bad version.\n\n# The isBadVersion API is already defined for you.\n# @param version, an integer\n# @return a bool\n# def isBadVersion(version):\n\nclass Solution:\n def firstBadVersion(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n\n # implement using binary search\n # start with full search space (1, n)\n # check midpoint\n # if midpoint is bad, then set mid as latest bad\n # then move right to mid and check the next section\n # if mid is not bad then move left to mid\n # finally if our pointers overlap return the first_bad\n\n left = 1\n right = n\n first_bad = n\n\n while left <= right:\n curr_version = left + (right - left) // 2\n curr_version_is_bad = isBadVersion(curr_version)\n if curr_version_is_bad:\n right = curr_version - 1\n if curr_version < first_bad:\n first_bad = curr_version\n if not curr_version_is_bad:\n left = curr_version + 1\n\n return first_bad\n\n\n # Example\n# n = 1000\n# v = 100\n# left = 1; right = 1000\n# curr_version = 1 + (1000 - 1) // 2 = 500\n# curr_version_is_bad == True\n# right = 500 - 1 = 499; left = 1\n# first_bad = 500\n\n# curr_version = 1 + (499 - 1) // 2 = 250\n# curr_version_is_bad == True\n# right = 250 - 1 = 249; left = 1\n# first_bad = 250\n\n# curr_version = 1 + (249 - 1) // 2 = 125\n# curr_version_is_bad == True\n# right = 125 - 1 = 124; left = 1\n# first_bad = 125\n\n# curr_version = 1 + (124 - 1) // 2 = 62\n# curr_version_is_bad == False\n# right = 124; left = 63\n\n# curr_version = 63 + (124 - 63) // 2 = 93\n# curr_version_is_bad == False\n# right = 124; left = 94\n\n# curr_version = 94 + (124 - 94) // 2 = 109\n# curr_version_is_bad == True\n# right = 108; left = 94\n# first_bad = 109\n\n# curr_version = 94 + (108 - 94) // 2 = 101\n# curr_version_is_bad == True\n# right = 100; left = 94\n# first_bad = 101\n\n# curr_version = 94 + (100 - 94) // 2 = 97\n# curr_version_is_bad == False\n# right = 100; left = 97 + 1 = 98\n\n# curr_version = left + (right - left) // 2\n# curr_version = 98 + (100 - 98) // 2 = 99\n# curr_version_is_bad == False\n# right = 100; left = 99 + 1 = 100\n# first_bad = 101\n# BREAK\n# return first_bad == 101 WRONG\n\n # If we don't break but change to while left <= right\n\n# curr_version = left + (right - left) // 2\n# curr_version = 100 + (100 - 100) // 2 = 100\n# curr_version_is_bad == True\n# right = 100 - 1 = 99; left = 100\n# first_bad = 100\n\n # alternative:\n # if we change to check if left == right then check\n # left == right == mid if bad and return it if lower\n # than first_bad?\n\n # curr_version = left + (right - left) // 2\n # curr_version = left + (right - left) // 2 = ?\n # curr_version_is_bad == ?\n # right = ?; left = ?\n # first_bad = ?","sub_path":"leetcode/278-First_Bad_Version_EASY.py","file_name":"278-First_Bad_Version_EASY.py","file_ext":"py","file_size_in_byte":4108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"606283022","text":"#!/usr/bin/python\n# 2014 Wells Riley\n# 2017 Justin Ramos\n\nimport argparse\nimport pigpio\nimport time\nimport thread\n\nparser = argparse.ArgumentParser(description='Strike dat gong.')\nparser.add_argument('--pin', help='Servo GPIO pin; default 4', nargs='?',type=int, default=4)\nparser.add_argument('--left', help='PWM left position; default 500', nargs='?',type=int, default=500)\nparser.add_argument('--right', help='PWM right position; default 2500', nargs='?',type=int, default=2500)\nparser.add_argument('--freq', help='PWM frequency in Hz; default 50', nargs='?',type=int, default=50)\nparser.add_argument('--range', help='PWM frequency range; default 20000', nargs='?',type=int, default=20000)\nparser.add_argument('--step', help='PWM step width; default 100', nargs='?',type=int, default=100)\nparser.add_argument('--intensity', metavar='1-11', help='Step multiplier; default 1', nargs='?',type=int, default=1)\n\nargs = parser.parse_args()\n\nPIN = int(args.pin)\nLEFT = int(args.left)\nRIGHT = int(args.right)\nCENTER = int(LEFT + ((RIGHT - LEFT)/2))\nPWM_FREQ = int(args.freq)\nPWM_RANGE = int(args.range)\nPWM_STEP = int(args.step * args.intensity)\n\npigpio = pigpio.pi()\n\ndef init_servo():\n pigpio.set_PWM_frequency(PIN, PWM_FREQ)\n pigpio.set_PWM_range(PIN, PWM_RANGE)\n move_servo(CENTER)\n\ndef move_servo(duty_cycle_us=0):\n pigpio.set_servo_pulsewidth(PIN, duty_cycle_us)\n\ndef spin_servo_cw_from(start, end):\n for duty_cycle_us in range(start, end+PWM_STEP, PWM_STEP):\n move_servo(duty_cycle_us)\n\ndef spin_servo_ccw_from(start, end):\n for duty_cycle_us in range(start, end-PWM_STEP, -PWM_STEP):\n move_servo(duty_cycle_us)\n\ndef stop_servo():\n move_servo(CENTER)\n pigpio.set_servo_pulsewidth(PIN, 0)\n\ndef gong():\n spin_servo_ccw_from(CENTER, LEFT)\n time.sleep(0.1)\n spin_servo_cw_from(LEFT, CENTER)\n time.sleep(0.1)\n\ntry:\n init_servo()\n gong()\n stop_servo()\nfinally:\n pigpio.stop()\n","sub_path":"gong.py","file_name":"gong.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"307936769","text":"from flask import (\n abort,\n g,\n render_template,\n request,\n session,\n)\nimport time\nimport uuid\n\nfrom app import app, api\nfrom .item import recent_items\n\n@app.context_processor\ndef template_context():\n if request.path.startswith('/ajax/pub'):\n return {}\n elif request.path.startswith('/ajax/user'):\n return {\n 'csrf_token': generate_csrf_token,\n 'user': g.user,\n }\n\n return {\n 'app': app,\n 'csrf_token': generate_csrf_token,\n 'recent': recent_items(),\n 'request': request,\n 'stats': api('/trade/stats'),\n 'user': g.user,\n }\n\ncontexts = {\n ('570', '2'): 'dota',\n ('730', '2'): 'csgo',\n ('753', '1'): 'games',\n ('753', '6'): 'misc',\n}\ncontext_names = {\n 'dota': 'Dota 2',\n 'csgo': 'CS:GO',\n 'games': 'Games',\n 'misc': 'Misc. Steam Items',\n}\nrcontexts = {v: k for k, v in contexts.items()}\n\ndef set_context(apt=None, name=None):\n context = contexts.get(apt, name)\n if context:\n g.context = context\n g.app = apt or rcontexts.get(context)\n g.app_name = context_names[context]\n\n@app.before_request\ndef setup_globals():\n g.app = None\n g.context = None\n g.steam_app = None\n g.set_context = set_context\n\n rpath = request.path.lstrip('/').split('/', 1)[0]\n if rpath in contexts.values():\n g.context = rpath\n g.app = rcontexts[rpath]\n g.app_name = context_names[rpath]\n\n@app.before_request\ndef csrf_protect():\n if request.method == \"POST\":\n csrf = session.get('csrf', {})\n token = request.form.get('_csrf_token')\n expired = time.time() - 15 * 60\n if not csrf.get(token, 0) > expired:\n csrf.pop(token, None)\n abort(400)\n\ndef generate_csrf_token():\n if not 'csrf' in session:\n session['csrf'] = {}\n\n acceptable = time.time() - 5 * 60\n expired = time.time() - 20 * 60\n for token, timeout in session['csrf'].copy().items():\n if timeout < expired:\n del session['csrf'][token]\n session.modified = True\n elif timeout > acceptable:\n break\n else:\n token = str(uuid.uuid4())\n session['csrf'][token] = time.time()\n session.modified = True\n return token\n\n@app.route('/')\ndef slash():\n return render_template('index.html')\n","sub_path":"src/website/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"271102407","text":"\"\"\"\nScript to obtain the sentiment score for each tweet of the user timeline of a sample of users at a specific location\nAuthor: Thyago Mota\nDate: 09/11/16\n\"\"\"\n\nimport subprocess, string, calendar\nfrom pymongo import MongoClient\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\n\n# global parameters\nlocation = 'New York'\ntz = -5\nSentiStrength = ['java', '-jar', '/users/meotm01/dev/java/SentiStrength/SentiStrengthCom.jar', 'sentidata', '/users/meotm01/dev/java/SentiStrength/SentStrength_Data_December2015English/', 'scale', 'text']\nmax_itt = 3600 # seconds or 1 hour\n\ndef main():\n try:\n \"\"\"MongoDB connection\"\"\"\n client = MongoClient('hydrogen')\n print('Connected to MongoDB!')\n db = client.elusa\n print('Connected to elusa DB!')\n\n for user in db.sample_users.find({'location': 'New York'}):\n #user = db.sample_users.find_one({'location': location, 'screen_name': 'wittlesteph_'})\n #print(user)\n timeline = []\n print('Getting sentiment scores for', user['screen_name'], '...')\n for tweet in user['tweets']:\n #if not tweet['retweet']:\n # continue\n # TODO: optimize this later...\n text = ''\n for c in tweet['text']:\n if c in string.printable:\n text += c\n # end TODO!\n # convert create_at field with format: Wed May 25 14:19:00 +0000 2016\n dt = datetime.strptime(tweet['created_at'], '%a %b %d %H:%M:%S %z %Y')\n timestamp = calendar.timegm(dt.timetuple())\n proc = subprocess.Popen(SentiStrength + [text], stdout = subprocess.PIPE)\n output = proc.stdout.read()\n data = output.strip()\n data = output.split()\n sentiment = int(data[-1])\n # print(sentiment, timestamp, text)\n #print(timestamp, sentiment, sep = ',')\n if not tweet['retweet']:\n timeline = [[timestamp, sentiment, False]] + timeline\n else:\n timeline = [[timestamp, sentiment, True]] + timeline\n x_tweet = []\n y_tweet = []\n x_retweet = []\n y_retweet = []\n #print(timeline)\n for timestamp, sentiment, retweet in timeline:\n # it's a retweet\n if retweet:\n # ignore retweet if it's the 1st post in the group\n if len(x_tweet) == 0:\n continue\n # keep retweet if it's close to the previous post or retweet\n if timestamp - x_tweet[-1] <= max_itt or (len(x_retweet) > 0 and timestamp - x_retweet[-1] <= 0):\n x_retweet.append(timestamp)\n y_retweet.append(sentiment)\n # plot the group if its size is significant\n else:\n if len(x_tweet) > 10:\n plt.figure()\n plt.hold(True)\n plt.plot(x_tweet, y_tweet, '-k')\n if len(x_retweet) > 0:\n plt.scatter(x_retweet, y_retweet)\n plt.title(user['screen_name'])\n plt.xlabel('timestamp')\n plt.ylabel('sentiment')\n plt.grid(True)\n plt.show()\n # start all over again (ignore the retweet because it will be the 1st in the next group anyway)\n x_tweet = []\n y_tweet = []\n x_retweet = []\n y_retweet = []\n # it's a post\n else:\n # 1st post in the group\n if len(x_tweet) == 0:\n x_tweet.append(timestamp)\n y_tweet.append(sentiment)\n # keet post if it's close to the previous post or retweet\n elif timestamp - x_tweet[-1] <= max_itt or (len(x_retweet) > 0 and timestamp - x_retweet[-1] <= 0):\n x_tweet.append(timestamp)\n y_tweet.append(sentiment)\n # plot the group if its size is significant\n else:\n if len(x_tweet) > 10:\n plt.figure()\n plt.hold(True)\n plt.plot(x_tweet, y_tweet, '-k')\n if len(x_retweet) > 0:\n plt.scatter(x_retweet, y_retweet)\n plt.title(user['screen_name'])\n plt.xlabel('timestamp')\n plt.ylabel('sentiment')\n plt.grid(True)\n plt.show()\n # start all over again (keeping the current tweet)\n x_tweet = [timestamp]\n y_tweet = [sentiment]\n x_retweet = []\n y_retweet = []\n # you might need to print the last group if it's significant\n if len(x_tweet) > 10:\n plt.figure()\n plt.hold(True)\n plt.plot(x_tweet, y_tweet, '-k')\n if len(x_retweet) > 0:\n plt.scatter(x_retweet, y_retweet)\n plt.title(user['screen_name'])\n plt.xlabel('timestamp')\n plt.ylabel('sentiment')\n plt.grid(True)\n plt.show()\n\n except Exception as ex:\n print('Error:', ex)\n finally:\n client.close()\n print('bye!')\n\n'''\n proc = subprocess.Popen(['java', '-jar', '/users/meotm01/dev/java/SentiStrength/SentiStrengthCom.jar', 'sentidata', '/users/meotm01/dev/java/SentiStrength/SentStrength_Data_December2015English/', 'scale', 'text', 'i love you'], stdout = subprocess.PIPE)\n output = proc.stdout.read()\n data = output.strip()\n data = output.split()\n #print(data)\n print(int(data[-1]))\n'''\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/sample_users_sentiment.py","file_name":"sample_users_sentiment.py","file_ext":"py","file_size_in_byte":6300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"597899120","text":"import cv2\r\n\r\n\r\ndef CM1():\r\n capture = cv2.VideoCapture(0)\r\n\r\n face_cascade = cv2.CascadeClassifier('lbpcascade_frontalface.xml')\r\n\r\n eye_glass = cv2.CascadeClassifier('haarcascade_eye_tree_eyeglasses.xml')\r\n\r\n while True:\r\n\r\n ret, frame = capture.read()\r\n\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n\r\n faces = face_cascade.detectMultiScale(gray)\r\n\r\n for (x, y, w, h) in faces:\r\n\r\n font = cv2.FONT_HERSHEY_COMPLEX\r\n\r\n cv2.putText(frame, '', (x + w, y + h), font, 1, (250, 250, 250), 2, cv2.LINE_AA)\r\n\r\n cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)\r\n\r\n roi_gray = gray[y:y + h, x:x + w]\r\n\r\n roi_color = frame[y:y + h, x:x + w]\r\n\r\n eye_g = eye_glass.detectMultiScale(roi_gray)\r\n\r\n for (ex, ey, ew, eh) in eye_g:\r\n cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)\r\n\r\n cv2.imshow('frame', frame)\r\n\r\n if cv2.waitKey(1) & 0xff == ord('q'):\r\n break\r\n\r\n capture.release()\r\n\r\n cv2.destroyAllWindows()\r\n\r\n","sub_path":"camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"293335131","text":"import astra\nimport numpy as np\nimport tomosipo as ts\nfrom .utils import up_tuple\n\n\ndef fdk(reconstruction_geometry):\n \"\"\"Do an FDK reconstruction of the given geometry.\n\n Expects a single volume dataset and a single projection dataset to\n be associated with the geometry.\n\n :param reconstruction_geometry: `ReconstructionGeometry`\n A reconstruction geometry with a single projection dataset and\n a single volume dataset.\n :returns: None\n :rtype: NoneType\n\n \"\"\"\n r = reconstruction_geometry\n\n if len(r.projection_data) > 1:\n raise ValueError(\n \"ReconstructionGeometry has more than one projection dataset. Expected one.\"\n )\n if len(r.volume_data) > 1:\n raise ValueError(\n \"ReconstructionGeometry has more than one volume dataset. Expected one.\"\n )\n\n projector = r.astra_projector\n v = r.astra_vol_data[0]\n p = r.astra_proj_data[0]\n\n astra.experimental.accumulate_FDK(projector, v, p)\n\n\nclass ReconstructionGeometry(object):\n \"\"\"ReconstructionGeometry handles reconstruction parameters and object lifetimes\n\n \"\"\"\n\n def __init__(self, *data, detector_supersampling=1, voxel_supersampling=1):\n \"\"\"Create a new reconstruction object\n\n :param *data: `Data` objects\n Data to use for forward and back projection. At least one\n data object relating to a VolumeGeometry and at least one\n data object relating to a projection geometry is required.\n :param detector_supersampling: `int`\n For the forward projection, DetectorSuperSampling^2 rays\n will be used. This should only be used if your detector\n pixels are larger than the voxels in the reconstruction\n volume. (default: 1)\n :param voxel_supersampling: `int`\n For the backward projection, VoxelSuperSampling^3 rays\n will be used. This should only be used if your voxels in\n the reconstruction volume are larger than the detector\n pixels. (default: 1)\n :returns:\n :rtype:\n\n \"\"\"\n self.projection_data = []\n self.astra_proj_data = []\n self.volume_data = []\n self.astra_vol_data = []\n\n self.voxel_supersampling = voxel_supersampling\n self.detector_supersampling = detector_supersampling\n\n for d in data:\n try:\n if d.is_projection():\n self.projection_data.append(d)\n self.astra_proj_data.append(d.to_astra())\n elif d.is_volume():\n self.volume_data.append(d)\n self.astra_vol_data.append(d.to_astra())\n except AttributeError:\n raise ValueError(\n f\"Given object with class {d.__class__}; expected: `VolumeGeometry` or `ProjectionGeometry`\"\n )\n\n if len(self.projection_data) < 1:\n raise ValueError(\n \"ReconstructionGeometry requires at least one projection dataset\"\n )\n if len(self.volume_data) < 1:\n raise ValueError(\n \"ReconstructionGeometry requires at least one volume dataset\"\n )\n\n # Set astra projector\n self.astra_projector = self.__astra_projector()\n\n def __astra_projector(self):\n assert len(self.projection_data) > 0\n assert len(self.volume_data) > 0\n\n return astra.create_projector(\n \"cuda3d\",\n self.projection_data[0].geometry.to_astra(),\n self.volume_data[0].geometry.to_astra(),\n options={\n \"VoxelSuperSampling\": self.voxel_supersampling,\n \"DetectorSuperSampling\": self.detector_supersampling,\n },\n )\n\n def forward(self):\n astra.experimental.do_composite_FP(\n self.astra_projector, self.astra_vol_data, self.astra_proj_data\n )\n\n def backward(self):\n astra.experimental.do_composite_BP(\n self.astra_projector, self.astra_vol_data, self.astra_proj_data\n )\n","sub_path":"tomosipo/ReconstructionGeometry.py","file_name":"ReconstructionGeometry.py","file_ext":"py","file_size_in_byte":4094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"250999239","text":"import json\nfrom operator import attrgetter, itemgetter\nimport os\nimport re\nfrom collections import defaultdict\nimport sys\nimport inspect\nfrom typing import Optional, Tuple\n\nfrom flask import current_app, render_template, render_template_string, jsonify\nfrom jinja2.exceptions import TemplateAssertionError\n\ntry:\n # Jinja2 < 3.1 (Flask <= 2.0 and python 3.6)\n # https://jinja.palletsprojects.com/en/3.0.x/api/#jinja2.evalcontextfilter\n from jinja2 import evalcontextfilter as pass_eval_context\nexcept ImportError:\n # Jinja2 < 3.1 (Flask >= 2.0 and python <= 3.7)\n from jinja2 import pass_eval_context\n\ntry:\n # Jinja2 < 3.1 (Flask <= 2.0 and python 3.6)\n from jinja2 import Markup\nexcept ImportError:\n # Jinja2 < 3.1 (Flask >= 2.0 and python <= 3.7)\n from jinja2.utils import markupsafe\n Markup = markupsafe.Markup\n\ntry:\n from flask.globals import _cv_app\nexcept ImportError:\n _cv_app = None\n try:\n from flask import _app_ctx_stack as stack\n except ImportError:\n from flask import _request_ctx_stack as stack\n\n\nif sys.version < '3':\n get_function_code = attrgetter('func_code')\nelse:\n get_function_code = attrgetter('__code__')\n\n\ndef custom_jsonify(*args,\n indent: Optional[int] = None,\n separators: Optional[Tuple] = (',', ':'),\n **kwargs):\n response = jsonify(*args, **kwargs)\n json_data = json.loads(response.data.decode('utf-8'))\n json_string = json.dumps(json_data,\n indent=indent,\n separators=separators)\n response.data = json_string.encode('utf-8')\n return response\n\n\ndef get_decorator_frame_info(frame) -> dict:\n \"\"\"\n The way that the line number of a decorator is detected changed across\n python versions:\n - python <= 3.8:\n stack()[1].lineno points to the line above the decorated function\n => points to the closest decorator, not necessarily the one that did the\n call to stack()\n - python 3.9 and 3.10:\n stack()[1].lineno points to the line of the decorated function\n - python 3.11:\n stack()[1].lineno points to the exact line of the decorator that did the\n call to stack()\n\n Example:\n\n 1 |def call_stack_and_get_lineno():\n 2 |\n 3 | def decorator(func):\n 4 | calling_frame = stack()[1]\n 5 | print(calling_frame.lineno)\n 6 | return func\n 7 |\n 8 | return decorator\n 9 |\n 10 |\n 11 |@decorator1\n 12 |@call_stack_and_get_lineno\n 13 |@decorator2\n 14 |def func():\n 15 | pass\n\n - python <= 3.8: will print line 13\n - python 3.9 and 3.10: will print line 14 (desired behaviour)\n - python 3.11: will print line 12\n\n We adjust the found line number with some offset (by reading the python\n source file) if required.\n \"\"\"\n line_number = frame.lineno\n try:\n with open(frame.filename, 'r') as python_file:\n python_lines = python_file.readlines()\n # current line + next ones\n context_lines = python_lines[line_number - 1:]\n except (OSError, FileNotFoundError):\n print(\"You're probably using flask_selfdoc with compiled python code \"\n \"- prefer uncompiled source files to extract correct filenames \"\n \"and line numbers.\")\n # not 100% correct solution, won't work for multiline decorator\n # or if there are decorators between @autodoc.doc() and the endpoint\n # function\n context_lines = frame.code_context\n\n # if the detected line number doesn't point to a function definition,\n # we iterate until we find one.\n for line in context_lines:\n if not line.strip().startswith('def '):\n line_number += 1\n else:\n break\n\n return {\n 'filename': frame.filename,\n 'line': line_number,\n }\n\n\nclass Autodoc(object):\n\n def __init__(self, app=None):\n self.app = app\n self.func_groups = defaultdict(set)\n self.func_props = defaultdict()\n self.immutable_props = ['rule', 'endpoint']\n self.default_props = [\n 'methods', 'docstring',\n 'args', 'defaults', 'location'] + self.immutable_props\n self.func_locations = defaultdict(dict)\n if app is not None:\n self.init_app(app)\n\n def init_app(self, app):\n if hasattr(app, 'teardown_appcontext'):\n app.teardown_appcontext(self.teardown)\n else:\n app.teardown_request(self.teardown)\n self.add_custom_template_filters(app)\n\n def teardown(self, exception):\n if _cv_app is not None:\n ctx = _cv_app.get(None) # noqa: F841\n else:\n ctx = stack.top # noqa: F841\n\n def add_custom_template_filters(self, app):\n \"\"\"Add custom filters to jinja2 templating engine\"\"\"\n self.add_custom_nl2br_filters(app)\n\n def add_custom_nl2br_filters(self, app):\n \"\"\"Add a custom filter nl2br to jinja2\n Replaces all newline to
\n \"\"\"\n _paragraph_re = re.compile(r'(?:\\r\\n|\\r|\\n){3,}')\n\n @app.template_filter()\n @pass_eval_context\n def nl2br(eval_ctx, value):\n result = '\\n\\n'.join('%s' % p.replace('\\n', Markup('
\\n'))\n for p in _paragraph_re.split(value))\n return result\n\n def doc(self, groups=None, set_location=True, **properties):\n \"\"\"Add flask route to autodoc for automatic documentation\n\n Any route decorated with this method will be added to the list of\n routes to be documented by the generate() or html() methods.\n\n By default, the route is added to the 'all' group.\n By specifying group or groups argument, the route can be added to one\n or multiple other groups as well, besides the 'all' group.\n\n If set_location is True, the location of the function will be stored.\n NOTE: this assumes that the decorator is placed just before the\n function (in the normal way).\n\n Custom parameters may also be passed in beyond groups, if they are\n named something not already in the dict descibed in the docstring for\n the generate() function, they will be added to the route's properties,\n which can be accessed from the template.\n\n If a parameter is passed in with a name that is already in the dict, but\n not of a reserved name, the passed parameter overrides that dict value.\n \"\"\"\n def decorator(f):\n # Get previous group list (if any)\n if f in self.func_groups:\n groupset = self.func_groups[f]\n else:\n groupset = set()\n\n # Set group[s]\n if type(groups) is list:\n groupset.update(groups)\n elif type(groups) is str:\n groupset.add(groups)\n groupset.add('all')\n self.func_groups[f] = groupset\n self.func_props[f] = properties\n\n # Set location\n if set_location:\n caller_frame = inspect.stack()[1]\n self.func_locations[f] = get_decorator_frame_info(caller_frame)\n\n return f\n return decorator\n\n def generate(self, groups='all', sort=None):\n \"\"\"Return a list of dict describing the routes specified by the\n doc() method\n\n Each dict contains:\n - methods: the set of allowed methods (ie ['GET', 'POST'])\n - rule: relative url (ie '/user/')\n - endpoint: function name (ie 'show_user')\n - docstring: docstring of the function\n - args: function arguments\n - defaults: defaults values for the arguments\n\n By specifying the group or groups arguments, only routes belonging to\n those groups will be returned.\n\n Routes are sorted alphabetically based on the rule.\n \"\"\"\n groups_to_generate = list()\n if type(groups) is list:\n groups_to_generate = groups\n elif type(groups) is str:\n groups_to_generate.append(groups)\n\n links = []\n for rule in current_app.url_map.iter_rules():\n\n if rule.endpoint == 'static':\n continue\n\n func = current_app.view_functions[rule.endpoint]\n arguments = sorted(list(rule.arguments)) if rule.arguments else ['None']\n func_groups = self.func_groups[func]\n func_props = self.func_props[func] if func in self.func_props \\\n else {}\n location = self.func_locations.get(func, None)\n\n if func_groups.intersection(groups_to_generate):\n props = dict(\n methods=sorted(list(rule.methods)),\n rule=\"%s\" % rule,\n endpoint=rule.endpoint,\n docstring=func.__doc__.strip(' ') if func.__doc__ else None,\n args=arguments,\n defaults=rule.defaults or dict(),\n location=location,\n )\n for p in func_props:\n if p not in self.immutable_props:\n props[p] = func_props[p]\n links.append(props)\n if sort == \"lexical\":\n sort = sort_lexically\n if sort:\n return sort(links)\n else:\n return sorted(links, key=itemgetter('rule'))\n\n def html(self, groups='all', template=None, **context):\n \"\"\"Return an html string of the routes specified by the doc() method\n\n A template can be specified. A list of routes is available under the\n 'autodoc' value (refer to the documentation for the generate() for a\n description of available values). If no template is specified, a\n default template is used.\n\n By specifying the group or groups arguments, only routes belonging to\n those groups will be returned.\n \"\"\"\n context['autodoc'] = context['autodoc'] if 'autodoc' in context \\\n else self.generate(groups=groups)\n context['defaults'] = context['defaults'] if 'defaults' in context \\\n else self.default_props\n if template:\n return render_template(template, **context)\n else:\n filename = os.path.join(\n os.path.dirname(__file__),\n 'templates',\n 'autodoc_default.html'\n )\n with open(filename) as file:\n content = file.read()\n with current_app.app_context():\n try:\n return render_template_string(content, **context)\n except TemplateAssertionError:\n raise RuntimeError(\n \"Autodoc was not initialized with the Flask app.\")\n\n def json(self,\n groups='all',\n indent: Optional[int] = None,\n separators: Optional[Tuple] = (',', ':')):\n \"\"\"Return a json object with documentation for all the routes specified\n by the doc() method.\n\n By specifiying the groups argument, only routes belonging to those groups\n will be returned.\n \"\"\"\n autodoc = self.generate(groups=groups)\n\n def endpoint_info(doc):\n args = sorted(doc['args'])\n if args == ['None']:\n args = []\n return {\n \"args\": [(arg, doc['defaults'].get(arg, None)) for arg in args],\n \"docstring\": doc['docstring'],\n \"methods\": doc['methods'],\n \"rule\": doc['rule']\n }\n data = {\n 'endpoints':\n [endpoint_info(doc) for doc in autodoc]\n }\n return custom_jsonify(data, indent=indent, separators=separators)\n\n\ndef sort_lexically(links):\n def parts(endpoint):\n rule = endpoint['rule']\n return rule.split(\"/\")\n\n return sorted(links, key=parts)\n\n\nSelfdoc = Autodoc\n","sub_path":"flask_selfdoc/autodoc.py","file_name":"autodoc.py","file_ext":"py","file_size_in_byte":11999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"428714126","text":"# -*- coding: utf-8 -*-\n\"\"\"This module supplies some smart utilities\"\"\"\n\nimport logging\nimport pyo\nimport math\n\ndef mapToRange(inVal, rangeIn=[0,1], rangeOut=None, scale=\"lin\", resolution=\"float\"):\n \"\"\"\n Map a value (inVal) from a range to another range\n\n Params:\n\n inVal : numberfloat\n input value\n\n rangeIn : list\n min and max values expected in input\n\n rangeOut : list\n min and max value expected in output\n if rangeOut[0] > rangeOut[1] the scale will be reversed accordingly\n\n scale : str\n scaling mode between rangeIn and rangeOut\n 'lin' - linear\n 'log' - logarithmic\n 'exp' - exponential\n\n resolution : str\n output number resolution\n 'float' - default\n 'int' - value will be rounded and parsed as an integer\n \"\"\"\n\n rangeInMin = min(rangeIn[0],\n rangeIn[1])\n rangeInMax = max(rangeIn[0],\n rangeIn[1])\n outVal = float(max(rangeInMin,\n min(inVal,\n rangeInMax)))\n\n if rangeOut is not None:\n rangeOutMin = min(rangeOut[0],\n rangeOut[1])\n rangeOutMax = max(rangeOut[0],\n rangeOut[1])\n if scale == 'log':\n outVal = math.log10(\n (\n (outVal - rangeIn[0]) / (rangeIn[1] - rangeIn[0])\n ) * 9 + 1\n ) * (rangeOut[1] - rangeOut[0]) + rangeOut[0]\n elif scale == 'exp':\n outVal = (\n math.pow(10,\n (\n (outVal - rangeIn[0]) / (rangeIn[1] - rangeIn[0])\n )\n ) / 9 - 1 / 9\n ) * (rangeOut[1] - rangeOut[0]) + rangeOut[0]\n elif scale == 'lin':\n outVal = (\n (outVal - rangeIn[0]) / (rangeIn[1] - rangeIn[0])\n ) * (rangeOut[1] - rangeOut[0]) + rangeOut[0]\n\n outVal = max(rangeOutMin, min(outVal, rangeOutMax))\n\n if resolution == 'int': outVal = int(round(outVal))\n return outVal\n\n\ndef mapArgs(method):\n \"\"\"\n Decorator function : filter a method's argument by applying mapToRange\n Retrieve the arguments from self.maps, which must be a dictionnary of the\n following form :\n self.maps = {\n \"methodToDecorate\": {rangeIn:[0,1], rangeOut:[0,127], scale:\"lin\", resolution=\"float\"},\n # etc\n }\n\n\n Usage:\n\n @mapArgs\n self.methodToDdecorate(self, value):\n ...\n \"\"\"\n def setter(self, IN):\n arguments = self.maps[method.__name__]\n OUT = mapToRange(IN, **arguments)\n logging.debug(\"From '%s' mapping '%s' to '%s'\" % (method.__name__, IN, OUT) )\n return method(self, OUT)\n\n return setter\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"37896365","text":"# Jichen Dai 08 Oct 2019\n# I pledge my honor that I have abided by the Stevens Honor System\n# This structure of this program referenced https://github.com/qiyunlu/SIT.CS520.bus_operation_simulation\nimport random\nimport math\n\n# parameters\nstationNum = 15\nbusNum = 5\ndriveTime = float(5*60) # 5 minute\nmeanArrivalRate = float(12) #lambda = 5 person/minute\nboardingTime = float(2) # seconds\nsimulatingTime = float(8*60*60) # seconds\noutputTime = float(30*60) #output the state of bus per hour\napplyStrategy = 1\n\n\nclass Simulation:\n def __init__(self):\n print(\"applyStrategy =\" + str(applyStrategy))\n self.startTime = float(0) #start time\n self.currentTime = self.startTime\n self.stopTime = float(-1) #stopTime is used to keep the distances between buses. while someone is boarding, implement stopTime = currentTime and all other buses should stop and wait.\n\n self.output = open(\"Output.txt\", 'a') #the file to store the program's detail output\n self.monitorOutput =open(\"monitorOutput.txt\", 'a') # the firl to store perodical Buses states\n\n self.eventQueue = []\n self.buses = []\n self.stations = []\n self.records = [] # records of every station\n\n ######################## Initialization ####################################3\n # initialize Bus array\n for i in range(busNum):\n self.buses.append(Bus(i, -1, -1, -1, -1))\n # initialize station array\n for i in range(stationNum):\n self.stations.append(Station(i, 1, 0))\n # initialize record array\n for i in range(stationNum):\n self.records.append(Record())\n self.records[i].totalPeople = 0\n self.records[i].totalArrival = 0\n self.records[i].maxQueue = 0\n self.records[i].minQueue = int(simulatingTime /meanArrivalRate) # minimal waiting list (initialized to be a relatively large)\n\n # generate one person event for each stop\n for i in range(stationNum):\n self.eventQueue.append(Event(0, self.startTime, -1, i))\n\n # generate 5 arrival event that distribute qeually in a circle\n distance = int(stationNum / busNum)\n for i in range(busNum):\n stationName = i*distance % stationNum\n self.eventQueue.append(Event(1, self.startTime, i, stationName))\n #update bus state\n self.buses[i].nextStop = stationName\n self.buses[i].nextArrivalTime = self.startTime\n # generate a monitor to eventQueue\n self.eventQueue.append(Event(3, self.startTime+outputTime, -1, -1))\n\n # sort eventQueue in the end of initialization\n self.sortQueue()\n\n\n\n\n ########################### start simulating ##############################\n while (self.currentTime < simulatingTime):\n event = self.eventQueue.pop(0)\n self.currentTime = event.startTime\n\n # identify type of the event\n if(event.eventType == 0): # event:person\n # update station's state\n self.stations[event.stationName].peopleNum += 1\n # write event 0 in output.txt\n self.printE0(event, self.output)\n self.stations[event.stationName].peopleArriveTime() #calculate arrival time of next person\n # generate event: person\n self.eventQueue.append(Event(0, self.currentTime + self.stations[event.stationName].peopleArrivalTime, -1, event.stationName))\n self.eventQueue = self.sortQueue()\n\n elif(event.eventType == 1): # event:arrival\n # update bus's state\n self.buses[event.busName].busState = 1\n self.buses[event.busName].nextArrivalTime = self.currentTime\n # write event 1 in output.txt\n self.printE1(event, self.output)\n # update station's state\n self.records[event.stationName].totalPeople += self.stations[event.stationName].peopleNum\n self.records[event.stationName].totalArrival += 1\n if(self.records[event.stationName].maxQueue < self.stations[event.stationName].peopleNum):\n self.records[event.stationName].maxQueue = self.stations[event.stationName].peopleNum\n if(self.records[event.stationName].minQueue > self.stations[event.stationName].peopleNum):\n self.records[event.stationName].minQueue = self.stations[event.stationName].peopleNum\n\n # if there is no people,go to next station\n if(self.stations[event.stationName].peopleNum == 0):\n # print event 1 in output.txt\n self.printE10(event, self.output)\n nextStationName = (event.stationName + 1)%stationNum\n self.eventQueue.append(Event(1, self.currentTime+driveTime, event.busName, nextStationName))\n self.eventQueue = self.sortQueue()\n # update bus's state\n self.buses[event.busName].lastStop = event.stationName\n self.buses[event.busName].nextStop = nextStationName\n self.buses[event.busName].nextArrivalTime = self.currentTime + driveTime\n self.buses[event.busName].busState = 0\n else: # create boarder event\n self.eventQueue.append(Event(2, self.currentTime, event.busName, event.stationName))\n self.eventQueue = self.sortQueue()\n\n elif(event.eventType == 2): # event:boarder\n # update bus's state\n self.buses[event.busName].busState = 1\n self.buses[event.busName].nextArrivalTime = self.currentTime\n\n # if all people boardered, bus go to the next station\n if(self.stations[event.stationName].peopleNum == 0):\n # print event 2 in output.txt\n self.printE20(event, self.output)\n\n nextStationName = (event.stationName + 1) % stationNum\n addedTime = self.currentTime\n\n if(applyStrategy == 1):\n if(self.stopTime == self.currentTime):\n addedTime += boardingTime\n\n self.eventQueue.append(Event(1, addedTime + driveTime, event.busName, nextStationName))\n self.eventQueue = self.sortQueue()\n\n # update bus's state\n self.buses[event.busName].lastStop = event.stationName\n self.buses[event.busName].nextStop = nextStationName\n self.buses[event.busName].nextArrivalTime = addedTime + driveTime\n self.buses[event.busName].busState = 0\n else: #people are boarding\n self.stations[event.stationName].peopleNum -= 1\n\n if(applyStrategy == 1):\n if (self.stopTime != self.currentTime):\n self.stopDrive()\n self.stopTime = self.currentTime\n\n # print event 2 in output.txt\n self.printE21(event, self.output)\n\n self.eventQueue.append(Event(2, self.currentTime + boardingTime, event.busName, event.stationName))\n self.eventQueue = self.sortQueue()\n\n elif(event.eventType == 3): # event:minitor, it is used to output bus's and station's state periodically\n #code: output\n self.print_periodical_bus_state(self.monitorOutput)\n self.eventQueue.append(Event(3, self.currentTime + outputTime, -1, -1))\n self.eventQueue = self.sortQueue()\n\n ######################## simulating finished ##############################\n self.printRecord(self.output)\n\n\n\n\n\n # after occurance of a event, sort eventQueue by startTime, if starTtime is the same, order by eventType.\n def sortQueue(self):\n Queues = self.eventQueue\n for i in range(len(self.eventQueue)-1):\n flag = 0\n for j in range(len(self.eventQueue)-1):\n if(self.eventQueue[j].startTime > self.eventQueue[j+1].startTime):\n self.eventQueue[j], self.eventQueue[j+1] = self.eventQueue[j+1], self.eventQueue[j]\n flag = 1\n elif(self.eventQueue[j].startTime == self.eventQueue[j+1].startTime):\n if(self.eventQueue[j].eventType > self.eventQueue[j+1].eventType):\n self.eventQueue[j], self.eventQueue[j + 1] = self.eventQueue[j + 1], self.eventQueue[j]\n flag = 1\n if(flag == 0): # finish sort if there is no order change in eventQueue\n break\n return Queues\n\n #### strategy to keep distances between buses: All buses will stop if someone is boarding\n def stopDrive(self):\n # every bus's arrival time will delay 2 seconds if a person is boarding.\n for event in self.eventQueue:\n if(event.eventType == 1):\n event.startTime += boardingTime\n self.sortQueue()\n # revise buses' arrival time after stoping\n for event in self.eventQueue:\n if(event.eventType == 1):\n self.buses[event.busName].nextArrivalTime = event.startTime\n\n # print every station's record after simulation.\n def printRecord(self, file):\n file.write(\"\\n==================== Simulation completed! ============================\" + \"\\n\\n\")\n for i in range(stationNum):\n file.write(\"Station No.\" + str(i) + \"\\n\" )\n # keep one decimal\n average = int((self.records[i].totalPeople / self.records[i].totalArrival * 10)) / 10\n file.write(\"The average size of a waiting queue is: \" + str(average) + \"\\n\" )\n file.write(\"The maximum size of a waiting queue is: \" + str(self.records[i].maxQueue) + \"\\n\")\n file.write(\"The minimum size of a waiting queue is: \" + str(self.records[i].minQueue) + \"\\n\")\n file.write(\" \\n\")\n\n # translate \"seconds\" into the format of \"day hour:minute:second\"\n def timeFormatting(self, seconds):\n # calculate seconds\n second = int(seconds % 60)\n seconds = int(seconds / 60)\n # calculate munites\n minute = seconds % 60\n seconds = int(seconds / 60)\n # calculate hours\n hour = seconds % 24\n seconds = int(seconds / 60)\n # calculate days\n day = int(seconds)\n return \"Time: \" + str(hour) + \":\" + str(minute).zfill(2) + \":\" + str(second).zfill(2) + \" day \" + str(day)\n\n # print event 0\n def printE0(self, event, file):\n file.write( self.timeFormatting(self.currentTime) + \"\\n\")\n file.write(\"One person comes to N0.\" + str(event.stationName) + \" station.\\n\")\n file.write(\"Now there are \" + str(self.stations[event.stationName].peopleNum) + \" people at this station.\\n\")\n file.write(\" \" + \"\\n\")\n\n # print event 1 when station isn't empty\n def printE1(self, event, file):\n file.write(self.timeFormatting(self.currentTime) + \"\\n\")\n file.write(\"N0.\" + str(event.busName) + \" bus arrives No.\" + str(event.stationName) + \" station.\\n\")\n file.write(\" \\n\")\n\n # print event 1 when the station is empty\n def printE10(self, event, file):\n file.write(self.timeFormatting(self.currentTime) + \"\\n\")\n file.write(\"No people at No.\" + str(event.stationName) + \" station.\" + \"\\n\")\n file.write(\"No.\" + str(event.busName) + \" bus leaves.\" + \"\\n\")\n file.write(\" \" + \"\\n\")\n\n # print event2 when all people boarded\n def printE20(self, event, file):\n file.write(self.timeFormatting(self.currentTime) + \"\\n\")\n file.write(\"All people at No.\" + str(event.stationName) + \" station boarded No.\" + str(event.busName) + \" bus.\" + \"\\n\")\n file.write(\"No.\" + str(event.busName) + \" bus leaves.\" + \"\\n\")\n file.write(\" \" + \"\\n\")\n\n # print event2 when someone is boarding\n def printE21(self, event, file):\n file.write(self.timeFormatting(self.currentTime) + \"\\n\")\n file.write(\"One person is boarding No.\" + str(event.busName) + \" bus at No.\" + str(event.stationName) + \" station.\" + \"\\n\")\n file.write(\"There ar still \" + str(self.stations[event.stationName].peopleNum) + \" people at this station\" + \"\\n\")\n file.write(\" \" + \"\\n\")\n\n # print periodical buses states\n def print_periodical_bus_state(self, file):\n file.write(\"\\n====================== Periodical states of buses =====================\\n\\n\")\n file.write(\"Time : \" + self.timeFormatting(self.currentTime)+ \"\\n\")\n for bus in self.buses:\n file.write(\"No.\" + str(bus.busName) + \" bus\\n\")\n if(bus.busState == 0): # bus is driving\n file.write(\"Bus is driving from No.\"+ str(bus.lastStop) + \" station to No.\" + str(bus.nextStop) + \" station.\\n\")\n file.write(\"Bus will arrive next station after \" + str(bus.nextArrivalTime-self.currentTime) + \" seconds.\\n\")\n else: # bus is in station\n file.write(\"Bus is stop at No.\" + str(bus.nextStop) + \" station.\\n\")\n file.write(\"people is boarding\\n\")\n file.write(\"------------------------------------------------------------------------\\n\")\n file.write(\"====================== Station =========================\\n\")\n for i in range(stationNum):\n file.write(\"No.\" + str(i) + \" station\\n\")\n average = int((self.records[i].totalPeople / self.records[i].totalArrival * 10)) / 10\n file.write(\"The average size of a waiting queue is: \" + str(average) + \"\\n\")\n file.write(\"The maximum size of a waiting queue: \" + str(self.records[i].maxQueue) + \"\\n\")\n file.write(\"The minimum size of a waiting queue: \" + str(self.records[i].minQueue) + \"\\n\")\n file.write(\"------------------------------------------------------------------------\\n\")\n file.write(\"============================================================================\\n\\n\")\n\n # draw the road\n file.write(\"Station \")\n for i in range(stationNum):\n file.write(str(i).zfill(3) + \"-----\")\n file.write(\"000\\n\")\n # people at every station\n file.write(\"Peoele \")\n for i in range(stationNum):\n file.write(str(self.stations[i].peopleNum).zfill(3) + \" \")\n file.write(str(self.stations[0].peopleNum).zfill(3) + \"\\n\\n\")\n # print buses situation\n for i in range(busNum):\n file.write(\"Bus \" + str(i).zfill(3) + \" \")\n if(self.buses[i].busState == 0):\n for j in range(stationNum):\n if(j == self.buses[i].lastStop):\n file.write(\" | ==> \")\n else:\n file.write(\" | \")\n file.write(\" | \\n\")\n else:\n for j in range(stationNum):\n if (j == self.buses[i].lastStop):\n file.write(\"STP \")\n else:\n file.write(\" | \")\n file.write(\" | \\n\")\n\n####################### define Bus, Station, event #########################\nclass Bus:\n def __init__(self, busName, lastStop, nextStop, nextArrivalTime, busStation):\n self.busName = busName\n self.lastStop = lastStop\n self.nextStop = nextStop\n self.nextArrivalTime = nextArrivalTime # the time bus arrives last stop\n self.busState = busStation # 0 means bus is on the way, 1 means bus is in the station\n\n\nclass Station:\n def __init__(self, stationName, peopleNum, peopleArrivalTime):\n self.stationName = stationName # name of station( an integer from 0 to 14 )\n self.peopleNum = peopleNum # number of people\n self.peopleArrivalTime = peopleArrivalTime # arrival time for next people\n self.seed = random.randint(500,1500)\n\n def peopleArriveTime(self):\n self.peopleArrivalTime = int(-1 * meanArrivalRate * math.log((self.seed + 1) / 65536))\n self.seed = (25173 * self.seed - 13849) % 65536\n\n\nclass Event:\n def __init__(self, eventType, startTime, busName, stationName):\n # eventType = 0 : a person arrives at a bus station\n # eventType = 1 : a bus arrives at a bus station\n # eventType = 2 : a person boards the bus\n # eventType = 3 : monitor event, output the running state after a period of time\n self.eventType = eventType\n self.startTime = startTime # when a event occurs\n self.busName = busName\n self.stationName = stationName\n\n# record of a station\nclass Record:\n def __init__(self):\n self.totalPeople = 0 # total arrival people\n self.totalArrival = 0 # total number of buses' arrival times\n self.maxQueue = 0 # maximal waiting queue\n self.minQueue = 0 # minimal waiting queue\n\n\n\nif __name__ == \"__main__\":\n Simulation()","sub_path":"BusSimulation/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":17228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"20312313","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n'''\r\nCreated on 2014-9-17\r\n\r\n@author: Rich\r\n'''\r\nimport logging,os\r\nDEBUG,INFO,WARN=logging.INFO,logging.DEBUG,logging.INFO\r\n'''\r\nset config LOG_PATH and APP_NAME(Default logfile prefix)\r\n'''\r\nBASIC_LOG_PATH=\"log\"\r\nAPP_NAME=\"ayi\"\r\n\r\n'''\r\nExtend config-info\r\ne.g.\r\n{\r\n\"new1\": {\"file\":\"new1\",\"level\":DEBUG},\r\n\"new2\": {\"file\":\"new2\",\"level\":DEBUG},\r\n:\r\n:\r\n}\r\n'''\r\nEXTEND_CONFIG={\r\n \"WWW\": {\"file\":\"www\",\"level\":DEBUG},\r\n }\r\n\r\n\r\n\r\nfrom logging.handlers import TimedRotatingFileHandler\r\nfrom logging import StreamHandler,Logger as _Logger\r\n\r\n\r\n\r\nBASIC_LOG_PATH=\"{0}{1}{2}\".format(os.getcwd(),os.sep,BASIC_LOG_PATH)\r\n\r\n\r\n\r\nLOG_CONFIG={\"default\": {\"file\":APP_NAME,\"level\":DEBUG}}\r\n\r\nLOG_CONFIG.update(EXTEND_CONFIG)\r\n\r\nclass Logger(_Logger):\r\n DEBUG,INFO,WARN=logging.INFO,logging.DEBUG,logging.INFO\r\n @classmethod\r\n def __init_logger__(cls):\r\n if not hasattr(cls,\"__inited__\"):\r\n cls.__inited__=True\r\n \r\n if not os.path.exists(BASIC_LOG_PATH):\r\n os.mkdir(BASIC_LOG_PATH)\r\n \r\n for k,d in LOG_CONFIG.items():\r\n cls.regist(k,d)\r\n @classmethod\r\n def regist(cls,key,config):\r\n '''\r\n Usesage:\r\n key:str\r\n config:dict,e.g. {\"file\":\"PLUGIN\",\"level\":logging.INFO}\r\n '''\r\n if not hasattr(cls,\"logger\"):\r\n cls.logger={} \r\n if not cls.logger.has_key(key):\r\n cls.logger[key]=Logger(config[\"file\"],level=config[\"level\"])\r\n return cls.get(key)\r\n @classmethod\r\n def get(cls,name=\"default\"):\r\n cls.__init_logger__()\r\n if not cls.logger.has_key(name):\r\n name=\"default\"\r\n return cls.logger[name]\r\n @classmethod\r\n def Warn(cls,name=\"default\",message=\"\",*args,**kwargs):\r\n cls.get(name).warn(message,*args,**kwargs)\r\n @classmethod\r\n def Error(cls,name=\"default\",message=\"\",*args,**kwargs):\r\n cls.get(name).error(message,*args,**kwargs)\r\n @classmethod\r\n def Info(cls,name=\"default\",message=\"\",*args,**kwargs):\r\n cls.get(name).info(message,*args,**kwargs)\r\n @classmethod\r\n def Debug(cls,name=\"default\",message=\"\",*args,**kwargs):\r\n cls.get(name).debug(message,*args,**kwargs) \r\n @classmethod\r\n def Exception(cls,name=\"default\",message=\"\",*args,**kwargs):\r\n cls.get(name).exception(message,*args,**kwargs)\r\n \r\n def __init__(self,filename,level=logging.INFO):\r\n _Logger.__init__(self,filename,level)\r\n formatter=logging.Formatter('%(name)-12s %(asctime)s level-%(levelname)-8s thread-%(thread)-8d \\n%(message)s\\n--end--')\r\n \r\n fileTimeHandler = TimedRotatingFileHandler(\"{0}{1}{2}\".format(BASIC_LOG_PATH ,os.sep, filename), \"H\", 1, 10,encoding=\"utf-8\")\r\n fileTimeHandler.suffix = \"%Y%m%d%H.log\" \r\n fileTimeHandler.setFormatter(formatter)\r\n fileTimeHandler.setLevel(level)\r\n self.addHandler(fileTimeHandler)\r\n \r\n console=StreamHandler()\r\n console.setLevel(level)\r\n console.setFormatter(formatter)\r\n self.addHandler(console)\r\n \r\n self.handler=fileTimeHandler \r\n @property\r\n def Loghandler(self):\r\n return self.handler\r\n def __del__(self):\r\n self.removeHandler(self.handler)\r\n \r\n\r\nLogger.__init_logger__()\r\n\r\n\r\n ","sub_path":"WEB-APP/common/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":3412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"94802586","text":"import ebonite\nfrom ebonite.build.provider.ml_model import MLModelProvider\nfrom ebonite.build.runner.base import LocalTargetHost\nfrom ebonite.build.runner.simple_docker import DockerImage, DockerServiceInstance, SimpleDockerRunner\nfrom ebonite.core.objects import core\nfrom ebonite.runtime.server import Server\nfrom ebonite.utils.importing import module_importable\n\n\ndef build_model_docker(image_name: str, model: 'core.Model', server: Server = None,\n image_tag='latest', force_overwrite=False, **kwargs):\n \"\"\"\n Builds docker image from Model instance\n\n :param image_name: docker image name to create\n :param model: model to create image\n :param server: server instance to wrap model\n :param image_tag: docker image tag\n :param force_overwrite: force overwrite image if it exists\n :param kwargs: same as in DockerBuilder.__init__\n \"\"\"\n if server is None:\n from ebonite.ext.flask import FlaskServer\n server = FlaskServer()\n\n if not module_importable('docker'):\n raise RuntimeError(\"Can't build docker container: docker module is not installed. Install it \"\n \"with 'pip install docker'\")\n\n from ebonite.build.builder.docker_builder import DockerBuilder, is_docker_running\n\n if not is_docker_running():\n raise RuntimeError(\"Docker is unavailable\")\n\n provider = MLModelProvider(model, server)\n builder = DockerBuilder(provider, image_name, image_tag, force_overwrite, **kwargs)\n builder.build()\n\n\ndef run_docker_img(container_name: str, image_name: str, port_mapping=None, detach=False):\n if port_mapping is None:\n port_mapping = {9000: 9000}\n runner = SimpleDockerRunner()\n service = DockerServiceInstance(container_name, DockerImage(image_name), LocalTargetHost(), port_mapping)\n runner.run(service, detach=detach)\n\n\ndef create_service_from_model(model_name: str, model_object, model_input, *,\n project_name: str = 'default_project', task_name: str = 'default_project',\n service_name: str = None, run_service: bool = False):\n \"\"\"\n This function does full default Ebonite's pipeline.\n Creates model, pushes it, wraps with a server, builds the docker image and runs it (if needed).\n\n :param model_name: model name to create.\n :param model_object: object containing model.\n :param model_input: model input.\n :param project_name: project name.\n :param task_name: task name.\n :param service_name: service name. Use model_name if not provided.\n :param run_service: run wrapped model with docker container if provided.\n \"\"\"\n service_name = service_name or model_name\n ebnt = ebonite.Ebonite.inmemory()\n\n t = ebnt.get_or_create_task(project_name, task_name)\n model = t.create_and_push_model(model_object, model_input, model_name)\n\n build_model_docker(service_name, model)\n\n if run_service:\n run_docker_img(service_name, service_name, detach=True)\n","sub_path":"src/ebonite/build/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"45539973","text":"import tensorflow as tf\n\n\nv1 = tf.Variable(0,dtype=tf.float32) #定义一个变量计算滑动平均,这个变量的初始值为0。注意这里手动指定了变量的类型为tf.float32,因为需要计算滑动平均的变量比必须是实数型。\nstep = tf.Variable(0,trainable=False)# 这里step变量模拟神经网络中迭代的轮数,可以用于动态控制衰减率。\n\n# 定义一个滑动平均的类(class).初始化时给定了衰减率(0.99)和控制衰减率的变量step。\nema = tf.train.ExponentialMovingAverage(0.99,step)\n\n# 定义一个更新变量滑动平均的操作。这里需要给定一个列表,每次执行这个操作时这个列表的变量都会更新。\nmaintain_averages_op = ema.apply([v1])\n\n\nwith tf.Session() as sess:\n #初始化所有变量\n init_op = tf.global_variables_initializer()\n sess.run(init_op)\n\n #通过ema.average(v1)获取滑动平均之后变量的取值。在初始化之后变量v1的值和v1的滑动平均都为0.\n print(sess.run([v1,ema.average(v1)]))\n\n #更新变量v1的值到5\n sess.run(tf.assign(v1,5))\n #更新v1的滑动平均值。衰减率为min{0.99,(1+step)/(10+step) = 0.1} = 0.1,所以v1的滑动平均会被更新为0.1*0+0.9*5= 4.5\n sess.run(maintain_averages_op)\n print(sess.run([v1,ema.average(v1)]))\n\n\n # 更新step的值为10000\n sess.run(tf.assign(step,10000))\n # 更新v1的值为10.\n sess.run(tf.assign(v1,10))\n # 更新v1的滑动平均值。衰减率为min{0.99,(1+step)/(10+step)约等于0.999} = 0.99,所以v1的滑动平均会被更新为0.99*4.5 + 0.01*10 = 4.555\n sess.run(maintain_averages_op)\n print(sess.run([v1,ema.average(v1)]))\n\n sess.run(maintain_averages_op)\n print(sess.run([v1,ema.average(v1)]))","sub_path":"part4_Deep_Network/滑动平均模型/ExponentialMovingAverage_1.py","file_name":"ExponentialMovingAverage_1.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"144091864","text":"import nltk\nimport sys\nimport re\nimport json\nimport networkx as nx\nimport pickle\n\nG = nx.MultiDiGraph() \nH = nx.MultiDiGraph() \ndef main():\n lmtzr = nltk.stem.wordnet.WordNetLemmatizer()\n \n f = file (sys.argv[1])\n G = pickle.load(f)\n f.close()\n\n for u,v,data in G.edges_iter (data=True):\n if G.has_edge(u,v) and G.has_edge(v,u):\n H.add_edge(u,v,attr_dict=data)\n\n f = file (\"at_recip_multidigraph.pkl\", \"w\")\n pickle.dump(H,f)\n f.close ()\n\nif __name__ == \"__main__\":\n main()\n\n \n \n\n","sub_path":"make_at_recip_multidigraph.py","file_name":"make_at_recip_multidigraph.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"483775154","text":"\r\n#Calcular o número máximo de pedaços possível, com um único corte horizontal\r\n\r\n#Entrada de dados\r\nalturas = [] #Criar uma lista de tuplas (com as alturas dos retângulos e suas respectivas posições)\r\nN = int(input('Inserir o número de retângulos: ')) #Receber o número de retângulos\r\nh = [int(i) for i in input().split()] #Receber as alturas\r\nfor i in range(len(h)): \r\n alturas.append((h[i],i+1)) #Adicionar as tuplas, a partir das alturas e suas posições\r\nalturas.sort() #Ordenar a lista de tuplas, pelas alturas, começando pela menor altura\r\n\r\n\r\n#Criar um marcador para identificar os retângulos já verificados com \"0\"\r\nmark = [1 for i in range(N+2)] #\"1\" representa os ainda não verificados\r\nmark[0] = 0 #Marcar com 0 a primeira posição para representar a borda inicial\r\nmark[N+1] = 0 #Marcar com 0 a última posição para representar a borda final\r\n\r\n#Contar a quantidade de pedaços\r\n#A partir da ideia da diferença entre alturas dos retângulos\r\npieces_max = 2 #Quantidade máxima de pedaços(resultado global)\r\npieces_cur = 2 #Quantidade máxima de pedaços(índice corrente)\r\n #Quantidade máxima de pedaços é a partir de 2 \r\nfor i in alturas:\r\n h, index = i #Para acessar os índices h (altura) e index (posição) das tuplas\r\n pieces_max = max(pieces_max, pieces_cur) #Quantidade de cortes é o maior valor entre o valor acumulado e o valor corrente\r\n mark[index] = 0 #Marcar o retângulo a ser verificado com \"0\"\r\n if mark[index-1]==1 and mark[index+1]==1: #Quando o retângulo verificado for menor que o anterior e o posterior\r\n pieces_cur+=1 #Somar um pedaço\r\n if mark[index-1]==0 and mark[index+1]==0: #Quando o retângulo verificado for maior que o anterior e o posterior\r\n pieces_cur-=1 #Subtrair um pedaço\r\n\r\n#Imprimir a quantidade máxima de pedaços\r\nprint(pieces_max)\r\n","sub_path":"cortanto_o_papel.py","file_name":"cortanto_o_papel.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"250297764","text":"# encoding: utf-8\nimport os\n\nfrom gaeautils.bundle import bundle\nfrom gaeautils.workflow import Workflow\n\n\nclass genotype(Workflow):\n \"\"\" genotype \"\"\"\n\n INIT = bundle(genotype=bundle())\n INIT.genotype.program = \"GaeaGenotyper.jar\"\n INIT.genotype.parameter = \"-genotype_likelihoods_model BOTH -stand_call_conf 30.0 -stand_emit_conf 10.0 -dbsnp file:///ifs4/ISDC_BD/GaeaProject/resource/dbsnp_135.hg19.modify.vcf\"\n\n def run(self, impl, dependList):\n impl.log.info(\"step: genotype!\")\n inputInfo = self.results[dependList[0]].output\n result = bundle(output=bundle(),script=bundle())\n \n #extend program path\n self.genotype.program = self.expath('genotype.program')\n \n if not self.option.multiSample:\n if self.genotype.parameter.find('-noMultiSampleCall') != -1:\n impl.log.warning(\"Pipeline is in single sample mode, disable -noMultiSampleCall. (deleted)\")\n self.genotype.parameter = self.genotype.parameter.replace('-noMultiSampleCall','')\n \n if self.file.get(\"regionVariation\"):\n self.genotype.parameter += \" -intervals file://%s \" % self.file.regionVariation\n elif self.file.get(\"region\"):\n self.genotype.parameter += \" -intervals file://%s \" % self.file.region\n \n #global param\n ParamDict = self.file.copy()\n ParamDict.update({\n \"PROGRAM\": \"%s jar %s\" % (self.hadoop.bin, self.genotype.program),\n \"REF\": \"file://%s\" % self.ref.normal.gaeaIndex,\n \"REDUCERNUM\":self.hadoop.reducer_num\n })\n \n #script template \n fs_cmd = self.fs_cmd\n cmd = []\n cmd.append(\"%s ${INPUT}/_*\" % fs_cmd.delete )\n cmd.append(\"%s ${OUTDIR}\" % fs_cmd.delete )\n cmd.append(\"${PROGRAM} -input ${INPUT} -out ${OUTDIR} -ref ${REF} -reduceNum ${REDUCERNUM} %s\" %self.genotype.parameter )\n \n JobParamList = []\n for sampleName in inputInfo:\n scriptsdir = impl.mkdir(self.gaeaScriptsDir,sampleName)\n hdfs_outputPath = os.path.join(self.option.dirHDFS,sampleName,'genotype_output')\n result.output[sampleName] = hdfs_outputPath\n \n #global param\n JobParamList.append({\n \"SAMPLE\" : sampleName,\n \"SCRDIR\" : scriptsdir,\n \"INPUT\": inputInfo[sampleName],\n \"OUTDIR\": hdfs_outputPath\n })\n \n \n #write script\n scriptPath = \\\n impl.write_scripts(\n name = 'genotype',\n commands=cmd,\n JobParamList=JobParamList,\n paramDict=ParamDict)\n \n #result\n result.script.update(scriptPath) \n return result\n \n","sub_path":"workflow/H_genotype.py","file_name":"H_genotype.py","file_ext":"py","file_size_in_byte":2886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"30058806","text":"import subprocess, os, sys, argparse\n\n\ndef run(n_hids, lrs, mcs, n_epochs, output_dir):\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n for n_hid in n_hids:\n for lr in lrs:\n for mc in mcs:\n output = os.path.join(\\\n output_dir, \n (\"n_hid_{}_lr_{}_nag_{}_mb_ReL.npz\").format(n_hid, lr, mc))\n cmd = ['python', 'back_propagation_v6.py', \n '-hu', str(n_hid), \n '-l', str(lr), \n '-m', str(mc), \n '-e', str(n_epochs), \n '-i', output,\n '-o', output]\n print(*cmd)\n with subprocess.Popen(cmd) as p:\n try:\n p.wait(timeout=None)\n except KeyboardInterrupt:\n sys.exit(0)\n\nif __name__==\"__main__\":\n # Parse command line arguments\n parser = argparse.ArgumentParser(\\\n description='Run backpropagation for the given hyperparameters.')\n parser.add_argument('-hu', '--hidden_units', type=int, nargs='+', \n default=[10, 20, 30], help='The numbers of hidden units')\n parser.add_argument('-l', '--learning_rates', type=float, nargs='+', \n default=[0.1, 0.3, 0.6], help='Learning rates')\n parser.add_argument('-e', '--epochs', type=int, \n default=50, help='The number of maximum epoch')\n parser.add_argument('-m', '--momentum_coefficients', type=float, nargs='+',\n default=[0.3, 0.6, 0.9], help='Momentum coefficients')\n #parser.add_argument('-b', '--batches', type=int, default=10,\n # help='The number of mini-batches')\n parser.add_argument('-o', '--output-dir', type=str, \n default=\"./result\")\n parser.add_argument('-p', '--parameter-sets', type=float, nargs=3, action='append',\n help='The set of parameters (n_hid, lr, mc)')\n args = parser.parse_args()\n\n if args.parameter_sets:\n for p_set in args.parameter_sets:\n run(n_hids = [int(p_set[0])], \n lrs = [p_set[1]], \n mcs = [p_set[2]], \n n_epochs = args.epochs, \n output_dir = args.output_dir)\n else:\n run(n_hids = args.hidden_units, \n lrs = args.learning_rates, \n mcs = args.momentum_coefficients, \n n_epochs = args.epochs, \n output_dir = args.output_dir)\n","sub_path":"1.basic/ver_6/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"157454233","text":"\"\"\"\nq2-final.py: for sub-challenge 2\n\"\"\"\nimport sklearn.ensemble\nimport pandas\nimport step00\n\nif __name__ == \"__main__\":\n # clinical_data\n clinical_data = pandas.read_csv(\"/data/clinical_data.csv\")\n clinical_data.set_index(\"patientID\", inplace=True)\n clinical_data[\"ECOGPS\"] = list(map(lambda x: float(x) if step00.can_convert_to_float(x) else None, list(clinical_data[\"ECOGPS\"])))\n clinical_data[\"TMB\"] = list(map(lambda x: float(x) if step00.can_convert_to_float(x) else None, list(clinical_data[\"TMB\"])))\n clinical_data.columns = list(map(lambda x: \"Clinical_\" + x, list(clinical_data.columns)))\n clinical_data.sort_index(axis=\"index\", inplace=True)\n\n data_list = [clinical_data]\n for i, f in enumerate([\"/data/GRCh37ERCC_ensembl75_isoforms_tpm.csv\"]):\n tmp_data = pandas.read_csv(f)\n tmp_data.set_index(list(tmp_data.columns)[0], inplace=True)\n tmp_data = tmp_data.T\n tmp_data.columns = list(map(lambda x: str(i) + \"_\" + x, list(tmp_data.columns)))\n tmp_data.sort_index(axis=\"index\", inplace=True)\n data_list.append(tmp_data)\n\n given_data = pandas.concat(data_list, axis=\"columns\", join=\"inner\", verify_integrity=True)\n given_data = given_data.select_dtypes(exclude=\"object\")\n\n selected_columns = step00.read_pickle(\"/Output/Step11/OS.RF.tar.gz\")[\"columns\"]\n total = len(selected_columns)\n\n test_data = pandas.DataFrame()\n for i, gene in enumerate(selected_columns):\n print(i, total, gene)\n test_data[gene] = given_data[list(filter(lambda x: x.endswith(gene), list(given_data.columns)))].sum(axis=1)\n test_data.info()\n\n regressor: sklearn.ensemble.RandomForestRegressor = step00.read_pickle(\"/Output/Step11/OS.RF.tar.gz\")[\"regressor\"]\n\n answer_data = pandas.DataFrame()\n answer_data[\"patientID\"] = list(test_data.index)\n answer_data[\"prediction\"] = regressor.predict(test_data)\n answer_data.to_csv(\"/output/predictions.csv\", index=False)\n","sub_path":"jwlee230/Program/Python/q2-final.py","file_name":"q2-final.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"282986917","text":"import threading, time\nimport wave\nimport numpy as np\nfrom ctypes import *\n\nC_lib = CDLL(\"./C_lib.so\")\nclass fm_tx(threading.Thread):\n def __init__(self,tx_q,params,raw_data):\n threading.Thread.__init__(self)\n self.txq = tx_q\n self.params = params\n self.raw_data = raw_data\n\n def run(self):\n #set the buffer size\n frame_duration = 20e-3\n sample_rate = self.params[2]\n file_sample_num = self.params[3]*self.params[0]\n sdr_rate = 1.92e6\n osr = int(sdr_rate/sample_rate)\n\n frame_len = sample_rate * frame_duration\n frame_num = np.int16(file_sample_num/frame_len)\n frame_len = int(frame_len)\n\n #allocate space for data\n interp_output_len = frame_len*osr\n fp_real_buf = (c_short*interp_output_len)()\n fp_imag_buf = (c_short*interp_output_len)()\n\n #modulation\n Kf=3.1\n fc=0\n cum_data = np.cumsum(self.raw_data) / float(sample_rate)\n t = np.linspace(0,file_sample_num-1,file_sample_num)\n interp_t = np.linspace(0,frame_len-1,frame_len*osr)\n mod_data = np.cos(Kf*cum_data+2*np.pi*t*fc)+1j*np.sin(Kf*cum_data+2*np.pi*t*fc)\n\n #fix point, move eleven bits to the left and turn into int16\n fp_mod_data_real = np.int16(mod_data.real*2048)\n fp_mod_data_imag = np.int16(mod_data.imag*2048)\n\n #put each frame into buffer\n for frm_idx in range(frame_num):\n start_time = time.time()\n fp_buf = (c_short*(interp_output_len*2))()\n \n #interpolation \n fp_real_buf[:] = np.interp(interp_t,t[:frame_len],fp_mod_data_real[frm_idx*frame_len:(frm_idx+1)*frame_len]).astype(np.int16)\n fp_imag_buf[:] = np.interp(interp_t,t[:frame_len],fp_mod_data_imag[frm_idx*frame_len:(frm_idx+1)*frame_len]).astype(np.int16)\n\n #combine real and image to one\n of_combiner = C_lib.CSM_data_combiner(fp_real_buf,fp_imag_buf,fp_buf,interp_output_len)\n self.txq.put(fp_buf)\n end_time = time.time()\n \n## print 'tx frame time is ', end_time - start_time\n","sub_path":"FM/FM_python (copy)/fm_tx.py","file_name":"fm_tx.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"127280421","text":"from classes import *\nfrom util import *\n\nimport httplib, json\n\napikey = '6117a56225f311c3'\n\nname = 'weather underground'\ndef init(cache):\n\tcache.currmod = __name__\n\tcache.hookcmd('WEATHER', 0, weather, 1, helpweather, reqchan=False)\n\tcache.hookcmd('W', 0, weather, 1, helpw, reqchan=False)\ndef deinit(cache, reloading=False):\n\tcache.currmod = __name__\n\tcache.unhookcmd('WEATHER')\n\tcache.unhookcmd('W')\n\ndef weather(nick, target, params, bot, cache):\n\tlocation = params.strip().replace(' ', '_')\n\tconn = httplib.HTTPConnection(\"api.wunderground.com\")\n\tconn.request(\"GET\", \"/api/%s/conditions/q/%s.json\" % (apikey, location))\n\tres = conn.getresponse()\n\tif res.status == 200:\n\t\tdata = res.read()\n\t\twz = json.loads(data)\n\t\tif 'current_observation' in wz:\n\t\t\twz = wz['current_observation']\n\t\t\tbuf = \"Weather for %s, %s: %s - Feels like: %s - Conditions: %s - Humidity: %s. %s\" % (wz['display_location']['full'], wz['display_location']['country_iso3166'], wz['temperature_string'], wz['feelslike_string'], wz['weather'], wz['relative_humidity'], wz['observation_time'])\n\t\t\tbot.msg(target, buf)\n\t\t\treturn\n\tbot.msg(target, \"Error retrieving weather.\")\n\ndef helpweather():\n\treturn ['WEATHER ', 'Gets weather data from Weather Underground']\ndef helpw():\n\treturn ['W ', 'Alias for WEATHER.']\n","sub_path":"modules/autoload/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"527150408","text":"import os\nos.environ.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings')\n\nimport django\ndjango.setup()\n\nimport random\nfrom firstapp.models import Topic,WebPage,AccessRecord\nfrom faker import Faker\n\nfakegen= Faker()\ntopics_name=['Social','Gaming','WebSite','News']\n\ndef addTopic():\n t=Topic.objects.get_or_create(topic_name=random.choice(topics_name))[0]\n t.save()\n return t\n\ndef populate(N=5):\n for entry in range(N):\n top=addTopic()\n\n fakeName=fakegen.company()\n fakeUrl=fakegen.url()\n fakeDate=fakegen.date()\n\n webpg=WebPage.objects.get_or_create(topic=top, name=fakeName,url=fakeUrl)[0]\n accessRec=AccessRecord.objects.get_or_create(name=webpg,date=fakeDate)\n\nif __name__=='__main__':\n print('Populating !')\n populate(50)\n print('Population Complete!!')\n","sub_path":"first_project/populate_firstapp.py","file_name":"populate_firstapp.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"616330300","text":"import tkinter as tk\n\nfrom src.longest_common_substring_finder import LongestCommonSubstringFinder\nfrom src.longest_palindrome_finder import LongestPalindromeFinder\nfrom src.longest_repetitive_substring_finder import \\\n LongestRepetitiveSubstringFinder\nfrom src.pattern_finder import PatternFinder\n\n\nclass Application(tk.Frame):\n def __init__(self, master=None):\n super().__init__(master)\n\n self.pf_btn = tk.Button(master=self, text='Pattern Finder',\n command=self.toggle_pf)\n self.pf_btn.grid(row=0, column=0, sticky='nsew')\n\n self.lrsf_btn = tk.Button(master=self, text='Longest Repetitive Substring Finder',\n command=self.toggle_lrsf)\n self.lrsf_btn.grid(row=1, column=0, sticky='nsew')\n\n self.lcsf_btn = tk.Button(master=self, text='Longest Common Substring Finder',\n command=self.toggle_lcsf)\n self.lcsf_btn.grid(row=2, column=0, sticky='nsew')\n\n self.lpf_btn = tk.Button(master=self, text='Longest Palindrome Finder',\n command=self.toggle_lpf)\n self.lpf_btn.grid(row=3, column=0, sticky='nsew')\n\n self.active_frame = tk.Frame()\n self.active_frame.grid(row=0, column=1, rowspan=4, sticky='nsew')\n\n self.pf = PatternFinder(self)\n self.lrsf = LongestRepetitiveSubstringFinder(self)\n self.lcsf = LongestCommonSubstringFinder(self)\n self.lpf = LongestPalindromeFinder(self)\n\n for i in range(2):\n self.grid_columnconfigure(i, weight=1)\n\n for i in range(4):\n self.grid_rowconfigure(i, weight=1)\n\n tk.Grid.columnconfigure(master, 0, weight=1)\n tk.Grid.rowconfigure(master, 0, weight=1)\n\n self.grid(column=0, row=0, sticky='nsew')\n\n def _activate_buttons(self):\n self.pf_btn.configure(state='normal')\n self.lrsf_btn.configure(state='normal')\n self.lcsf_btn.configure(state='normal')\n self.lpf_btn.configure(state='normal')\n\n def toggle_pf(self):\n self._activate_buttons()\n self.pf_btn.configure(state='disabled')\n\n self.active_frame.grid_remove()\n self.active_frame = self.pf\n self.active_frame.grid(row=0, column=1, rowspan=4, sticky='nsew')\n\n def toggle_lrsf(self):\n self._activate_buttons()\n self.lrsf_btn.configure(state='disabled')\n\n self.active_frame.grid_remove()\n self.active_frame = self.lrsf\n self.active_frame.grid(row=0, column=1, rowspan=4, sticky='nsew')\n\n def toggle_lcsf(self):\n self._activate_buttons()\n self.lcsf_btn.configure(state='disabled')\n\n self.active_frame.grid_remove()\n self.active_frame = self.lcsf\n self.active_frame.grid(row=0, column=1, rowspan=4, sticky='nsew')\n\n def toggle_lpf(self):\n self._activate_buttons()\n self.lpf_btn.configure(state='disabled')\n\n self.active_frame.grid_remove()\n self.active_frame = self.lpf\n self.active_frame.grid(row=0, column=1, rowspan=4, sticky='nsew')\n\n\nroot = tk.Tk()\nroot.resizable(False, False)\napp = Application(master=root)\napp.mainloop()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"315003493","text":"# ATENÇÃO: Você pode customizar o módulo alterando o valor abaixo.\nINTERATIVIDADE = 0\n# ATENÇÃO: Você pode customizar o módulo alterando o valor acima\n\"\"\"\n---------------------------------------------------------------------\nSe INTERATIVIDADE = 0 (Não interativo), nenhum diálogo será exibido\nna tela e você poderá acompanhar somente as mensagens exibidas pelo\nmundo, como 'Você caiu em um Poço!' ou 'Você matou o Wumpus!'\n---------------------------------------------------------------------\nSe INTERATIVIDADE = 1, os diálogos acerca da representação do mundo\nda personagem serão exibidos na tela, assim você poderá acompanhar\ncada passo do protagonista. Além disso, você usará a tecla 'Enter'\npara avançar para o próximo passo.\n---------------------------------------------------------------------\nSe INTERATIVIDADE = 2 (Interativo), os diálogos serão exibidos\nnormalmente e você poderá decidir as ações da personagem.\n---------------------------------------------------------------------\nObservação: Os diálogos acerca do mundo e do mundo compartilhado\nestão dividios por um ponto (.)\n---------------------------------------------------------------------\n\"\"\"\n\n# Variaveis globais (do módulo) que o mundo acessa para passar informações para a personagem.\n\nglobal nFlechas\n\"\"\"\nNúmero de flechas que a personagem possui. Serve apenas para\nconsulta da personagem, pois o mundo mantém uma cópia \"segura\" dessa\ninformação (não tente inventar flechas...).\n\"\"\"\n\nglobal mundoCompartilhado\n\"\"\"\nEsse é um espaço onde a personagem tem acesso à representação do\nmundo de uma outra personagem. Essa informação pode ser usada como a\npersonagem quiser (por exemplo, transferindo o conteúdo para o seu\npróprio \"mundo\", ou mantendo uma lista dos vários mundos\ncompartilhados com outras personagens).\n\"\"\"\n\n\n# Outras variáveis globais do módulo personagemNUSP\n\nglobal N\n\"\"\" Dimensão do mundo.\n\"\"\"\n\nglobal mundo\n\"\"\"\nRepresenta o conhecimento da personagem em relação ao Mundo de\nWumpus. Essa é uma matriz de NxN onde a personagem toma notas de suas\npercepções ao longo do caminho que percorre, indicando os muros, as\nsalas livres e as salas percorridas, bem como a proximidade de perigos\n(poços e Wumpus). A geometria do mundo é a de um toro (aquela figura\nque parece um donut!) onde existem sempre 4 salas vizinhas à posição\n[i][j]: em sentido horário e a partir da (nossa) direita essas seriam:\n[i][(j+1)%N], [(i+1)%N][j], [i][(j-1)%N] e [(i-1)%N][j]. Cada entrada\nmundo[i][j] é uma lista de anotações/rótulos correspondentes às\ninformações encontradas ou deduzidas pela personagem sobre o conteúdo\nda sala (i,j).\n\"\"\"\n\nglobal posicao\n\"\"\"\nRepresenta a posição relativa da personagem no mundo. Cada\npersonagem começa em uma posição aleatória (e desconhecida por ela,\npois não possui GPS ou equivalente) do Mundo \"real\" de Wumpus, e por\nisso precisa usar um sistema de coordenadas pessoal para se orientar.\nPor convenção, sua posição inicial é representada como [0,0] (canto\nsuperior esquerdo) nesse sistema. Como o mundo não tem bordas, podemos\nusar sempre os i=0,...,N-1 e j=0,...,N-1, que percorrem todas as salas\npossíveis do Mundo de Wumpus, usando o operador módulo (%) para\ncorrigir a posição quando um passo nos levar a uma sala de índice <0\nou >=N.\n\"\"\"\n\nglobal orientacao\n\"\"\"\nJuntamente com a posição relativa, permite à personagem manter o\nhistórico das salas visitadas. Essa orientação é independente da\norientação \"real\" que o mundo usa para coordenar a ação de todas as\npersonagens. Por convenção, todas as personagens indicam sua orientação\ninicial como \"para baixo\" ou \"sul\", correspondente à direção [1,0]\n(direção do eixo vertical).\n\"\"\"\n\nglobal rotas\n\"\"\"\nRepresenta o conjunto de todas as possiveis rotas para posições livres\nque a personagem pode tomar à fim de percorrer o mundo de Wumpus mantendo-se\nviva. Cada vez que a personagem passa por uma localização com posições\nadjacentes livres, é incluído na lista de rotas estas posições para que a\npersonagem possa explorá-las em um futuro breve.\n\"\"\"\n\nglobal rotaatual\n\"\"\"\nA 'rota atual' faz referência ao atual caminho definido pela personagem.\nEm geral, esta é a primeira rota definida na variável rotas, que engendra\ntodas as posições que a personagem ainda pretende visitar.\n\"\"\"\n\nglobal comandos\n\"\"\"\nEsta variável representa a fila de comandos que a personagem precisa\ntomar à fim de chegar ao ponto indicado. Para cada ponto previamente\nadicionado na lista de rotas (e, portanto, para cada casa livre\nconhecida), cria-se a lista de comandos que a personagem irá seguir\nà fim de alcançar uma casa livre.\n\"\"\"\n\nglobal pInformacao\n\"\"\"\nEstá variável é um valor inteiro e só é ativada quando a personagem\ndetecta algum outro personagem na mesma posição. Nesta ocasião, esta\nvariável, 'Pedir Informação' é ativada, fazendo com que a personagem\ncompartilhe informações na próxima ação.\nQuando pInformacao = 0, a personagem não percebe ninguem para\ncompartilhar; quando pInformacao = 1, a personagem percebeu alguém e\nirá compartilhar na próxima ação; quando pInformacao = 2, a personagem\njá compartilhou informação e agora irá atualizar seu mundo.\n\"\"\"\n\ndef inicializa(tamanho):\n \"\"\" Função de inicialização da personagem (recebe o tamanho do mundo).\n Usa as variáveis globais (do módulo) para representar seu\n conhecimento do mundo, sua posição e sua orientação relativas\n ao início da simulação. Você pode criar e inicializar outras\n variáveis aqui (por exemplo, a lista de salas livres e não\n visitadas).\n \"\"\"\n\n # Declara as variáveis globais que serão acessadas\n global N, mundo, posicao, orientacao, rotas, rotaatual, comandos, pInformacao\n # Guarda o tamanho do mundo\n N = tamanho\n # Cria a matriz NxN com a representação do mundo conhecido\n mundo = []\n for i in range(N) : \n linha = []\n for j in range(N) : \n linha.append([]) # começa com listas vazias\n mundo.append(linha)\n # Posição e orientação iniciais da personagem (sempre serão [0,0] e [1,0]).\n posicao = [0,0]\n orientacao = [1,0]\n # As rotas e os comandos disponíveis no início são sempre nulos.\n rotas = []\n comandos = []\n # A personagem inicia o jogo sem rota predeterminada.\n rotaatual = [0,0]\n # A personagem também não pensa em solicitar informações.\n pInformacao = 0\n # Marca a posição inicial como Visitada e Livre. Podemos fazer isso mesmo\n # que esta posição seja, por exemplo, um poço; neste caso, a personagem\n # perde antes de começar a jogar. Só há jogo, portanto, quando a primeira\n # posição é livre.\n mundo[0][0] = ['L']\n\n\ndef marcar(evento):\n \"\"\" Esta função é utilizada para marcar algum evento, como 'L', 'P'\n ou 'W' nas casas adjacentes ao personagem. Não serão feitas marcações\n caso as posições já estejam rotuladas com 'L' ou 'M'.\n \"\"\"\n \n # Declara as variáveis globais que serão acessadas.\n global N, mundo, posicao\n # Guarda a posição atual na variável 'pos'.\n pos = posicao\n # A variável i assume o valor, respectivamente, das posições ao norte,\n # ao sul, à oeste e à leste da atual posição da personagem.\n for i in [[(pos[0]-1)%N,pos[1]],[(pos[0]+1)%N,pos[1]],[pos[0],(pos[1]-1)%N],[pos[0],(pos[1]+1)%N]]:\n # Se a posição não estiver rotulada com 'L' ou 'M', marca-a com\n # o evento determinado.\n if not 'L' in mundo[i[0]][i[1]] and not 'M' in mundo[i[0]][i[1]] and not evento in mundo[i[0]][i[1]]:\n # Desmarca a possibilidade de Poço caso esteja sendo\n # marcado posição Livre.\n if evento == 'L' and 'P?' in mundo[i[0]][i[1]]:\n mundo[i[0]][i[1]].remove('P?')\n # Desmarca a possibilidade de Wumpus caso esteja sendo\n # marcado posição Livre.\n if evento == 'L' and 'W?' in mundo[i[0]][i[1]]:\n mundo[i[0]][i[1]].remove('W?')\n # Verifica, antes de marcar um evento, se já não existe uma\n # certeza de Poço ou Wumpus naquela região.\n if not (evento == 'P?' and 'P' in mundo[i[0]][i[1]]) and not (evento == 'W?' and 'W' in mundo[i[0]][i[1]]):\n # Marca na posição o evento determinado.\n mundo[i[0]][i[1]].append(evento)\n\n\ndef marcarduplo():\n \"\"\" Esta função é utilizada somente para marcar a possibilidade de\n existir simultaneamente um Poço e um Wumpus na região.\n \"\"\"\n \n # Declara as variáveis globais que serão acessadas.\n global N, mundo, posicao\n # Guarda a posição atual na variável 'pos'.\n pos = posicao\n # Similar à função 'marcar', i assume o norte, o sul, o oeste e o leste.\n for i in [[(pos[0]-1)%N,pos[1]],[(pos[0]+1)%N,pos[1]],[pos[0],(pos[1]-1)%N],[pos[0],(pos[1]+1)%N]]:\n # Se a posição não estiver rotulada com nenhum valor já conhecido,\n # como 'L', 'M', 'P?', 'P', 'W? e 'W', podemos marcar a posição\n # com os valores simultâneos de Poço e Wumpus.\n if not 'L' in mundo[i[0]][i[1]] and not 'M' in mundo[i[0]][i[1]] and not 'P' in mundo[i[0]][i[1]] and not 'P?' in mundo[i[0]][i[1]] and not 'W' in mundo[i[0]][i[1]] and not 'W?' in mundo[i[0]][i[1]]:\n mundo[i[0]][i[1]].append('P?')\n mundo[i[0]][i[1]].append('W?')\n\n\ndef contagem():\n \"\"\" Esta função tem como objetivo contar o número de casas livres\n ou rotuladas com 'M' ao redor da posição atual da personagem. Se\n existir apenas uma única posição não-livre (ou 'M') adjacente, a\n função retorna esta posição; do contrário, esta função retorna o\n número de casas adjacentes livres.\n \"\"\"\n\n # Declara as variáveis globais que serão acessadas.\n global N, mundo, posicao\n # Inicializa as variáveis especificas no tratamento da função.\n contador, perigo = 0, 0\n # Guarda a posição atual na variável 'pos'.\n pos = posicao\n # Similar à função 'marcar', i assume o norte, o sul, o oeste e o leste.\n for i in [[(pos[0]-1)%N,pos[1]],[(pos[0]+1)%N,pos[1]],[pos[0],(pos[1]-1)%N],[pos[0],(pos[1]+1)%N]]:\n # Verifica para cada uma das posições assimiladas se elas estão livres\n # (ou rotuladas com 'M'). \n if 'L' in mundo[i[0]][i[1]] or 'M' in mundo[i[0]][i[1]]:\n contador += 1\n else:\n perigo = i\n # Se há 3 casas adjacentes livres, há uma única casa adjacente não-livre;\n # neste caso, a função retorna a posição desta casa. Se há um número\n # diferente de casas livres, a função retorna este valor.\n if contador == 3:\n return perigo\n else:\n return contador\n\n\ndef pathfinder(ponto):\n \"\"\" Esta função é responsável por encontrar um caminho seguro\n do ponto em que a personagem se encontra no momento até o\n ponto desejado (possivelmente uma casa livre e ainda não visitada)\n \"\"\"\n\n # Declara as variáveis globais que serão acessadas.\n global N, mundo, posicao, orientacao, comandos\n\n # Limpa os comandos, caso ainda haja algum na fila.\n comandos = []\n\n # Declara as variáveis utilizadas nesta função.\n posatual = [posicao[0], posicao[1]] # Posição\n oriatual = [orientacao[0], orientacao[1]] # Orientação\n representacao = [] # Matriz de representação do mundo\n encontrei = True # Variável qualquer para laço\n k = 2 # Contador qualquer para laço\n\n # Cria uma matriz NxN (do tamanho do mundo) que representa este\n # universo a partir de valores inteiros.\n for i in range(N) : \n representacao.append([])\n for j in range(N) : \n representacao[i].append(0) # começa com listas nulas\n\n # Atribui o valor '-2' para todas as posições na matriz representação\n # que apresenta alguma ameaça (por exemplo: P, P?, W, W?) ou ainda é\n # desconhecida (não tem rótulo algum).\n for i in range(N):\n for j in range(N):\n if not 'L' in mundo[i][j]:\n representacao[i][j] = -2\n\n # Atribui o valor '1' para a posição em que dejesamos chegar.\n representacao[ponto[0]][ponto[1]] = 1\n\n # O seguinte laço realiza, para cada k, uma varredura completa da\n # matriz de representação e atribui o valor k para posições com\n # regiões adjacentes valendo k-1. Dessa forma, cada casa passa\n # a significar o número de passos necessários para se atingir a\n # posição pretendida.\n while encontrei:\n encontrei = False\n for i in range(N):\n for j in range(N):\n # verifica se o valor ainda não foi atribuido e se\n # as casas adjacentes valem k-1.\n if representacao[i][j] == 0 and (representacao[(i-1)%N][j] == k -1 or representacao[(i+1)%N][j] == k -1 or representacao[i][(j-1)%N] == k -1 or representacao[i][(j+1)%N] == k -1):\n representacao[i][j] = k\n encontrei = True\n k += 1\n\n # O seguinte laço executa as atribuições elaboradas no percurso\n # definido anteriormente e adiciona as futuras ações à lista\n # de comandos.\n kpersonagem = representacao[posatual[0]][posatual[1]]\n while kpersonagem > 1:\n # Calcula qual é a posição à frente da personagem\n frente = [(posatual[0] + oriatual[0])%N, (posatual[1] + oriatual[1])%N]\n # Verifica se a posição à frente da personagem é a casa correta\n # para realizar o movimento predefinido pela rota.\n if representacao[frente[0]][frente[1]] == kpersonagem -1:\n posatual[0], posatual[1] = frente[0], frente[1]\n comandos.append('A')\n else:\n # Calcula qual é a posição atrás da personagem\n atras = [(posatual[0] - oriatual[0])%N, (posatual[1] - oriatual[1])%N]\n # Verifica se a posição atrás da personagem é a casa correta\n # para realizar o movimento predefinido pela rota.\n if representacao[atras[0]][atras[1]] == kpersonagem -1:\n posatual[0], posatual[1] = atras[0], atras[1]\n oriatual[0], oriatual[1] = -oriatual[0], -oriatual[1]\n comandos += ['E','E','A']\n else:\n # Calcula qual é a posição à esquerda da personagem\n a, b = oriatual[0], oriatual[1]\n if a == 0:\n b = -b\n a, b = b, a\n aesquerda = [(posatual[0] + a)%N, (posatual[1] + b)%N]\n # Verifica se a posição à esquerda da personagem é a casa correta\n # para realizar o movimento predefinido pela rota.\n if representacao[aesquerda[0]][aesquerda[1]] == kpersonagem -1:\n posatual[0], posatual[1] = aesquerda[0], aesquerda[1]\n oriatual[0], oriatual[1] = a, b\n comandos += ['E', 'A']\n else:\n # Calcula qual é a posição à direita da personagem\n a, b = oriatual[0], oriatual[1]\n if b == 0:\n a = -a\n a, b = b, a\n adireita = [(posatual[0] + a)%N, (posatual[1] + b)%N]\n # Verifica se a posição à direita da personagem é a casa correta\n # para realizar o movimento predefinido pela rota.\n if representacao[adireita[0]][adireita[1]] == kpersonagem -1:\n posatual[0], posatual[1] = adireita[0], adireita[1]\n oriatual[0], oriatual[1] = a, b\n comandos += ['D', 'A']\n else:\n # Se nenhuma das quatro posições (à frente, atras,\n # à direita e à esquerda) funcionou corretamente\n # na execução deste código, há algo errado.\n raise Exception('Erro na função Pathfinder!')\n # Realiza a subtração para manter a coerência do laço\n kpersonagem -= 1\n\n\ndef compartilhar():\n \"\"\"\n Esta função tem por objetivo inserir as informações que foram\n compartilhadas com a personagem na sua representação do mundo.\n Para isso, percorremos todo o mundo compartilhado e comparamos\n com as informações que a nossa personagem possui.\n \"\"\"\n\n # Declara as variáveis globais que serão acessadas.\n global N, mundo, mundoCompartilhado\n\n # O seguinte laço percorre todos os elementos do mundo e do\n # mundoCompartilhado, fazendo algumas comparações. Em geral,\n # vamos adicionar elementos à nossa representação se a posição\n # estiver vazia ou se há possibilidade de existir algum perigo\n for i in range(N):\n for j in range(N):\n if not 'V' in mundo[i][j]:\n # Adiciona-se local 'L' ao mundo.\n if mundoCompartilhado[i][j] == ['L']:\n mundo[i][j] = ['L']\n # Adiciona-se 'P' ao mundo.\n if mundoCompartilhado[i][j] == ['P']:\n mundo[i][j] = ['P']\n # Adiciona-se 'W' ao mundo.\n if mundoCompartilhado[i][j] == ['W']:\n mundo[i][j] = ['W']\n\n # Aqui, é importante fazer uma varredura das posições para ver se é\n # possível encontrar novas casas livres a partir das informações que\n # a personagem recebeu.\n for i in range(N):\n for j in range(N):\n if not [i,j] == rotaatual and not [i,j] in rotas and mundo[i][j] == ['L']:\n rotas.append([i,j])\n\n\ndef planejar(percepcao):\n \"\"\" Nessa função a personagem deve atualizar seu conhecimento\n do mundo usando sua percepção da sala atual. Através desse\n parâmetro a personagem recebe (do mundo) todas as informações\n sensoriais associadas à sala atual, bem como o feedback de\n sua última ação.\n Essa percepção é uma lista de strings que podem valer:\n \"F\" = fedor do Wumpus em alguma sala adjacente,\n \"B\" = brisa de um poço em sala adjacente, \n \"I\" para impacto com uma parede,\n \"U\" para o urro do Wumpus agonizante e\n \"Nome\" quando uma outra personagem é encontrada.\n \"\"\"\n\n # Declara as variáveis globais que serão acessadas\n global mundo, posicao, orientacao, nFlechas, mundoCompartilhado, pInformacao\n\n # Define as variáveis de posição e orientação.\n pos, ori = posicao, orientacao\n\n # Define a variável 'tamanho da percepção', utilizada na\n # verificação de possíveis aliados.\n tampercepcao = len(percepcao)\n\n # Se a personagem recebeu um impacto, é necessário corrigir\n # a posição relativa e marcar a proxima posição com 'M'.\n # Isto deve ser feito antes de tudo para evitar que o código\n # seja rodado com a posição não corrigida!\n if 'I' in percepcao:\n tampercepcao -= 1 # Um item percebido é o 'I'\n pos[0] = (pos[0]-ori[0])%len(mundo)\n pos[1] = (pos[1]-ori[1])%len(mundo)\n mundo[(pos[0]+ori[0])%len(mundo)][(pos[1]+ori[1])%len(mundo)] = ['V', 'M']\n\n # Se a personagem acabou de compartilhar informações, é o momento certo\n # para ela adicionar estas novidades à sua representação do mundo.\n if pInformacao == 2:\n pInformacao = 0 # Zera a variável para permitir novos compartilhamentos.\n compartilhar()\n\n # Se a personagem está em uma posição rotulada como ameaça e\n # está jogando (ou seja, viva), podemos concluir que a casa\n # está livre.\n if 'P?' in mundo[pos[0]][pos[1]] or 'W?' in mundo[pos[0]][pos[1]]:\n mundo[pos[0]][pos[1]] = ['V', 'L']\n\n # Insere o rótulo 'V' (Visitado) na posição atual.\n if not 'V' in mundo[pos[0]][pos[1]]:\n mundo[pos[0]][pos[1]].insert(0, 'V')\n\n # Gerenciamento de ameaças.\n if not 'B' in percepcao and not 'F' in percepcao:\n # Se não há brisa nem fedor próximo, posso concluir que as\n # casas adjacentes estão livres.\n marcar('L')\n elif 'B' in percepcao and not 'F' in percepcao:\n tampercepcao -= 1 # Outro item percebido é a 'B'\n # Se a personagem esta sentindo uma brisa, é necessário marcar\n # a possibilidade de um poço nas casas adjacentes.\n i = contagem()\n # Se a contagem retornar um valor inteiro, significa que há\n # mais de uma casa adjacente não-livre; marcaremos, então, estas\n # posições. Se a contagem retornar uma posição, significa que\n # esta é a única casa não-livre adjacente ao personagem,\n # podemos concluir certamente que existe um poço ('P')\n # nesta região.\n if type(i) == int:\n marcar('P?')\n else:\n mundo[i[0]][i[1]] = ['P']\n elif not 'B' in percepcao and 'F' in percepcao:\n tampercepcao -= 1 # Outro item percebido é o 'F'\n # Se a personagem esta sentindo um fedor, é necessário marcar\n # a possibilidade de um Wumpus nas casas adjacentes!\n i = contagem()\n # Aqui, ocorre um tratamento similar ao dado para a marcação\n # das posições de Poço.\n if type(i) == int:\n marcar('W?')\n else:\n mundo[i[0]][i[1]] = ['W']\n else:\n tampercepcao -= 2 # Outros itens percebidos são a 'B' e o 'F'\n # Se a personagem está sentindo simultaneamente um fedor e uma\n # brisa, é necessário utilizar as duas marcações ao mesmo\n # tempo para não sobrescrever outras regiões.\n # Obs: Como sabemos que existem pelo menos dois perigos ao lado,\n # não é necessário realizar a contagem para averiguar certezas\n # de Poço ou Wumpus.\n marcarduplo()\n \n # Se a personagem ouvir um urro, significa que não há mais perigo\n # à frente, isto é, a posição pode ser marcada como 'L'\n if 'U' in percepcao:\n tampercepcao -= 1 # Outro item percebido é o 'U'\n mundo[(pos[0]+ori[0])%len(mundo)][(pos[1]+ori[1])%len(mundo)] = ['L']\n\n # Se a personagem notar algo além de 'I','B','F' e 'U' na lista de\n # percepções, significa que há mais algum personagem. A variável é\n # ativada para que a nossa personagem compartilhe informações na\n # próxima ação.\n if tampercepcao > 0:\n pInformacao = 1\n\n # ################### I N T E R A T I V I D A D E #####################\n if INTERATIVIDADE == 1 or INTERATIVIDADE == 2:\n print(\"Percepção recebida pela personagem:\", percepcao)\n \n # mostra na tela (para o usuário) o mundo conhecido pela personagem\n # e o mundo compartilhado (quando disponível)\n print(\"Mundo conhecido pela personagem:\")\n for i in range(len(mundo)):\n for j in range(len(mundo[0])):\n if pos==[i,j]:\n print(\"X\",end=\"\")\n if ori==[0,-1]:\n print(\"<\",end=\"\")\n if ori==[0,1]:\n print(\">\",end=\"\")\n if ori==[1,0]:\n print(\"v\",end=\"\")\n if ori==[-1,0]:\n print(\"^\",end=\"\")\n print(\"\".join(mundo[i][j]),end=\"\\t.\")\n print(\"\".join(mundoCompartilhado[i][j]),end=\"\\t| \")\n print(\"\\n\"+\"-\"*(16*len(mundo)+1))\n # #####################################################################\n\n\ndef agir():\n \"\"\" Nessa função a personagem deve usar seu conhecimento\n do mundo para decidir e tentar executar (devolver) uma ação.\n Possíveis ações (valores de retorno da função) são\n \"A\"=Andar, \"D\"=girarDireita, \"E\"=girarEsquerda,\n \"T\"=aTirar e \"C\"=Compartilhar.\n \"\"\"\n # Declara as variáveis globais que serão acessadas\n global mundo, posicao, orientacao, nFlechas, mundoCompartilhado, rotas, rotaatual, comandos, pInformacao\n\n # Define as variáveis de posição e orientação.\n pos, ori = posicao, orientacao\n\n # Definição das posições adjacentes ao local atual da\n # personagem. Isto será utilizado para montar a estratégia.\n norte = [(pos[0]-1)%N,pos[1]]\n sul = [(pos[0]+1)%N,pos[1]]\n oeste = [pos[0],(pos[1]-1)%N]\n leste = [pos[0],(pos[1]+1)%N]\n\n # Aqui, adicionamos às rotas as casas livres (Obs: isso não inclui\n # casas livres e visitadas). Em outras palavras, marcamos todas as\n # casas livres para visitar em alguma ocasião futura.\n for i in [sul, norte, oeste, leste]:\n # Verificamos se a posição desejada esta rotulada como livre.\n if not i == rotaatual and not i in rotas and mundo[i[0]][i[1]] == ['L']:\n rotas.append(i)\n\n # Aqui, verificamos se o terrível Wumpus foi detectado em alguma posição\n # adjacente à personagem. Em teoria, a personagem deve eliminar o Wumpus\n # na maior parte dos jogos, já que, em algum momento, a personagem irá\n # traçar uma rota para uma posição vizinha (e ainda não visitada) do\n # Wumpus e, neste momento, detectá-lo.\n for i in [sul, norte, oeste, leste]:\n if mundo[i[0]][i[1]] == ['W']:\n # Neste momento, o Wumpus foi detectado. A partir daqui, pedimos\n # ajuda para a função pathfinder para traçar uma rota (basicamente\n # em se tratando das rotações da personagem) e trocamos a ultima\n # ação (ir em direção ao Wumpus) por atirar.\n rotaatual = i\n pathfinder(rotaatual)\n comandos.pop()\n if nFlechas > 0:\n comandos.append('T')\n \n # Este código é o cerne da estratégia tomada pelo computador durante\n # o jogo. Vamos sempre manter uma lista (rotas) atualizada com as\n # posições de todas as casas livres e ainda não visitadas. A partir\n # desta lista, vamos elaborar uma lista de comandos que permitirá\n # a personagem ir até as casas livres e ainda não visitadas.\n if pInformacao == 1:\n # Se a condição for verificada, a personagem deve imediatamente\n # compartilhar informações\n pInformacao = 2\n acao = 'C'\n elif len(comandos) == 0:\n while len(rotas) > 0:\n # Confirma se a primeira posição na lista de rotas\n # está marcada apenas como 'L'. É importante realizar\n # este procedimento porque a personagem pode visitar\n # esta posição durante alguma rota anterior.\n if mundo[rotas[0][0]][rotas[0][1]] == ['L']:\n # Caso a primeira rota seja adequada, chamamos a função\n # pathfinder para encontrar o melhor caminho da personagem\n # até o ponto desejado\n rotaatual = rotas.pop(0)\n pathfinder(rotaatual)\n break\n else:\n # Se a primeira rota não for adequada, vamos removê-la\n rotas.pop(0)\n if len(comandos) == 0:\n # Se não há rotas nem comandos disponíveis, a personagem\n # começa a girar esperando possivelmente encontrar alguem\n # para trocar informações.\n acao = 'E'\n else:\n acao = comandos.pop(0)\n else:\n acao = comandos.pop(0)\n\n\n # ################### I N T E R A T I V I D A D E #####################\n if INTERATIVIDADE == 1:\n dialog = input('Aperte Enter para continuar...')\n if INTERATIVIDADE == 2:\n acao = input(\"Digite a ação desejada (A/D/E/T/C): \")\n # #####################################################################\n\n\n # Atualiza as posições relativas à personagem com base na ação\n # decidida anteriormente. Caso a personagem sofra um impacto de\n # um muro, a posição será corrigida na função 'planejar'\n if acao == 'A':\n # Movimento para frente\n pos[0] = (pos[0]+ori[0])%len(mundo)\n pos[1] = (pos[1]+ori[1])%len(mundo)\n if acao == 'E':\n # Movimento para a esquerda\n if ori[0]==0:\n ori[1] = -ori[1]\n ori[0],ori[1] = ori[1],ori[0]\n if acao == 'D':\n # Movimento para a direita\n if ori[1]==0:\n ori[0] = -ori[0]\n ori[0],ori[1] = ori[1],ori[0]\n\n # Verificação e retorno da ação.\n assert acao in [\"A\",\"D\",\"E\",\"T\",\"C\"]\n return acao\n","sub_path":"MAC110/EP3/personagens/personagem_43.py","file_name":"personagem_43.py","file_ext":"py","file_size_in_byte":28425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"97657703","text":"import requests\nfrom bs4 import BeautifulSoup\n\n\ndef urlToBS(url):\n res = requests.get(url)\n return BeautifulSoup(res.text, \"html.parser\")\n\n\ndef getHeadAndTailInOrigin(div):\n a = div.find_all(\"a\")\n li = []\n for word in a:\n if '-' in word.text:\n li.append(word.text)\n\n return li # 접두 접미어 리스트로 출력\n\n\ndef getOrigin(word):\n base_url = \"http://www.dictionary.com/browse/\" + word\n bs = urlToBS(base_url)\n\n result = []\n for i in bs.find_all(\"section\"):\n if i.find(\"section\") is None and i.find(\"span\", {\"id\": \"wordOrigin\"}) is not None:\n result.append(i)\n\n ht = []\n origin = []\n for section in result:\n div = section.find(\"div\")\n ht.extend(getHeadAndTailInOrigin(div))\n origin.append(div.text) # 실제 기원 문장으로 출력\n return [ht, origin] # [[접두접미],[실제 기원들]]\n\n\ndef getMeansInDiv(div, word_class):\n if div.find(\"h3\", {\"class\": \"dic_tit6\"}) is not None:\n title = div.find(\"h3\", {\"class\": \"dic_tit6\"}).find(\"span\").text\n else:\n title = \"\"\n means = []\n dts = div.find(\"dl\").find_all(\"dt\")\n\n for dt in dts:\n span = dt.find(\"em\").find(\"span\", {\"class\": \"fnt_k06\"})\n if span is not None:\n means.append(span.text)\n word_class[title] = means\n\n\ndef getWordClasses(word):\n base_url = \"http://endic.naver.com\"\n bs = urlToBS(base_url + \"/search.nhn?sLn=kr&query=\" + word)\n\n try:\n query = bs.find(\"div\", {\"id\": \"wrap\"}) \\\n .find(\"div\", {\"id\": \"container\"}) \\\n .find(\"div\", {\"id\": \"content\"}) \\\n .find(\"div\", {\"class\": \"word_num\"}) \\\n .find(\"dl\", {\"class\": \"list_e2\"}) \\\n .find(\"dt\", {\"class\": \"first\"}) \\\n .find(\"span\", {\"class\": \"fnt_e30\"}) \\\n .find(\"a\")[\"href\"]\n except:\n print(\"cannot find result\")\n return # 예외 처리\n\n bs = urlToBS(base_url + query)\n divs = bs.find(\"div\", {\"id\": \"wrap\"}) \\\n .find(\"div\", {\"id\": \"container\"}) \\\n .find(\"div\", {\"id\": \"content\"}) \\\n .find(\"div\", {\"id\": \"zoom_content\"}) \\\n .find_all(\"div\", {\"class\": \"box_wrap1\"})\n word_class = {}\n for div in divs:\n getMeansInDiv(div, word_class)\n\n return [word_class, getExample(bs)]\n\n\n# word 페이지의 bs\ndef getExample(bs):\n examples = []\n divs = bs.find(\"div\", {\"id\": \"wrap\"}) \\\n .find(\"div\", {\"id\": \"container\"}) \\\n .find(\"div\", {\"id\": \"content\"}) \\\n .find(\"div\", {\"id\": \"zoom_content\"}) \\\n .find_all(\"div\", {\"class\": \"box_wrap20\"})\n for div in divs:\n div = div.find(\"h3\", {\"class\": \"dic_tit2\"})\n if div is None:\n continue\n ul = div.parent.find(\"ul\").find_all(\"li\", {\"class\", \"utb\"}, False)\n\n for li in ul[:3]: # 세개만\n sentence = li.find(\"div\", {\"class\", \"lineheight18 mar_top01\"}) \\\n .find(\"span\", {\"class\", \"fnt_e09 _ttsText\"}).text.strip()\n index = li.find(\"div\", {\"class\", \"lineheight18 mar_top01\"}) \\\n .find(\"span\", {\"class\", \"fnt_e09 _ttsText\"}).find_all(\"i\")\n for i in range(len(index)):\n if index[i].find(\"b\") is not None:\n index = i\n break\n mean = li.find(\"div\", {\"class\", \"mar_top1\"}).text.strip()\n examples.append([sentence, mean, index])\n\n return examples\n\n# print(getOrigin(\"prior\"))\nprint(getWordClasses(\"take\"))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"52521532","text":"class SvenReplacer:\n\n def Patchnote_replace(text):\n string = text\n string = string.replace('_', ' ')\n string = string.replace('Attribute', ' ')\n string = string.replace('special', ' ')\n string = string.replace('Ability10', 'TalentTree Level 10')\n string = string.replace('Ability11', 'TalentTree Level 10')\n string = string.replace('Ability12', 'TalentTree Level 15')\n string = string.replace('Ability13', 'TalentTree Level 15')\n string = string.replace('Ability14', 'TalentTree Level 20')\n string = string.replace('Ability15', 'TalentTree Level 20')\n string = string.replace('Ability16', 'TalentTree Level 25')\n string = string.replace('Ability17', 'TalentTree Level 25')\n string = string.replace('Status', '')\n return string\n \n#testkrams\n \n# text = '''Changes For Bloodseeker:\n# AttackDamageMin was change from 29 to 33\n# AttackDamageMax was change from 35 to 39\n# Changes For Crystal Maiden:\n# MovementSpeed was change from 280 to 275\n# Changes For Zeus:\n# MovementSpeed was change from 295 to 300\n# Changes For Venomancer:\n# AttributeAgilityGain was change from 2.600000 to 2.800000\n# Changes For Viper:\n# Ability12 was change from special_bonus_strength_10 to special_bonus_strength_15\n# Changes For Shadow Demon:\n# Ability10 was change from special_bonus_strength_6 to special_bonus_strength_10\n# Ability11 was change from special_bonus_movement_speed_10 to special_bonus_movement_speed_20\n# Ability13 was change from special_bonus_spell_amplify_6 to special_bonus_spell_amplify_8\n# Ability14 was change from special_bonus_magic_resistance_10 to special_bonus_magic_resistance_15\n# Changes For Treant Protector:\n# MovementSpeed was change from 290 to 280\n# Changes For Skywrath Mage:\n# Ability14 was change from special_bonus_movement_speed_20 to special_bonus_movement_speed_40\n# Ability15 was change from special_bonus_magic_resistance_15 to special_bonus_magic_resistance_20\n# Changes For Ember Spirit:\n# Ability10 was change from special_bonus_spell_amplify_10 to special_bonus_spell_amplify_8\n# Ability11 was change from special_bonus_attack_damage_25 to special_bonus_attack_damage_30\n# Changes For Monkey King:\n# Ability11 was change from special_bonus_armor_5 to special_bonus_evasion_10\n# StatusHealthRegen was change from 0.750000 to 1.50000'''\n#\n# ausgabe = SvenReplacer.Patchnote_replace(text)\n# print(ausgabe)\n","sub_path":"SvenReplacer.py","file_name":"SvenReplacer.py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"11753335","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n#cangye@hotmail.com\r\n\"\"\"\r\n字典学习\r\n\"\"\"\r\nprint(__doc__)\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib as mpl\r\nimport numpy as np\r\nfrom sklearn.decomposition import DictionaryLearning\r\nmpl.style.use('fivethirtyeight')\r\nfrom sklearn.datasets import make_circles\r\n\r\nnp.random.seed(0)\r\n\r\nX, y = make_circles(n_samples=400, factor=.3, noise=.05)\r\n\r\npca = DictionaryLearning(n_components=2)\r\nX_pca = pca.fit_transform(X)\r\n\r\nfig = plt.figure()\r\nax = fig.add_subplot(211)\r\nax.scatter(X[:, 0], X[:, 1], c=y)\r\nax.axis(\"equal\")\r\nax = fig.add_subplot(212)\r\nax.scatter(X_pca[:, 0], X_pca[:, 1], c=y)\r\n\r\nax.axis(\"equal\")\r\nplt.show()","sub_path":"1.27_courses/DimensionalityReduction/DictionaryLearning.py","file_name":"DictionaryLearning.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"486515113","text":"# import pandas to read csv file\nimport pandas as pd \n\n# import Path to deal with paths\nfrom pathlib import Path\n\n\n\n\n\n# import the file by taking the input of user\n# input will be the path of csv file\n\ndef importingCsv():\n\n # get the path of file\n pathOfFile = Path(input('Kindly input the path of csv file: '))\n\n \n # pathOfFile = Path('/Users/Test/Documents/fire_points.csv')\n\n # read the file into pandas dataframe\n\n csvData = pd.read_csv(pathOfFile)\n\n\n #output the dataframe\n return csvData\n\n# print(importingCsv())\n\n# take the dataframe output by the method\n\nfirePointData = importingCsv()\n# print (firePointData)\n\n# print headers of data frame\n\ncoloumnInFirePointData = firePointData.columns\nprint(coloumnInFirePointData)\n\n# get the input of level\nselectedLevel = input ('Enter a heading:')\n\n# create an empty list which will contain the unique values from the said \nunique_list = []\n# print(firePointData['Range'])\n\n# getting a list from a column of a dataframe\nrawlist = firePointData[selectedLevel].to_list()\n#remove extra space\nlist1=[]\nfor i in rawlist:\n list1.append(i.rstrip())\n# print(list1)\n\n# getting all unique values\n\nfor any in list1: \n# check if exists in unique_list or not \n if any not in unique_list: \n unique_list.append(any) \n\n#initialising null dictionary\nfreq_result={}\n#traversing all elements of intrested_level\nfor i in unique_list:\n freq_result[i] = list1.count(i)\n\n# importing csv to write csv file output\nimport csv\n\n\n# trying to set the path of frequency file save location\nsaveLocationOfFireFrequency = Path(input('Where do you want to save the frequency output and name the file also with .csv extension'))\n\nprint(freq_result)\nw = csv.writer(open(saveLocationOfFireFrequency, 'w') )\nfor key, val in freq_result.items():\n w.writerow([key,val])\n\n\n# now we have the frequency values\n# we can move to importing the shape file and changing\n# the attribute table and enter the values of fire frequency\n\n# import geopandas to read the csv file\n\nimport geopandas as gpd \nimport matplotlib.pyplot as plt \n\n#get the path of shpaefile\n\n# fp = path of the shape file in which you want to enter the frequency data\n\nfp = Path(input('enter the path of shapefile'))\n\n# read the file using geopandas\n\ndata = gpd.read_file(fp)\n\n# command to acess active geoseries gdf.geometry.name\n# To change which column is the active geometry column, use the GeoDataFrame.set_geometry() method.\n# adding new field\ndata[\"fire_f\"]= 0\n\n# \n# plt.show()\n\n\n# we can use both the dictionary we outputed or we can call back\n# the frequecy output file and use the two coloumns as list and \n# use those list.\n\n# first we are going to try and use the diciotnary\n# the dicitonary that contains the values is freq_result{}\n\n# input doesn't work. error is that the dataframe has no such metho\n# fieldOfFire = input('name of field whose fire_f attributes are being changed: ')\n\nfor value in freq_result.keys():\n\n # this code will give us the index of the rows which have the string \n index_c = data[data.Beat_Name.str.match(value,case = False)].index.tolist()\n\n # now we want to set the fire values of the indices\n for j in index_c:\n data._set_value(j,'fire_f',freq_result[value])\n\n# now we try to test weather it worked or not\nprint(data.head())\n\n# writing to new shape file\n\n# writing to a file\n# data.to_file(\"Path where you want to save the shape file\")\n\n# ask user where he want to save the file\nsaveFileLocation = Path(input('Enter the path where you want to save the modified shape file'))\n\n# writing to that path\ndata.to_file(saveFileLocation)\n\n\n# method didnt work earlier becauase of an space at the end.\n# to remove thhis space i will have to use srtip method at appropriate place.\n# the space is coing from the input fire point csv file\n\n\n# now we will plot the map\n# to plot we have to import matplotlib. we have already done that\n\nfilePathOfModifiedShapeFile = saveFileLocation\n\ndataOfFire = gpd.read_file(filePathOfModifiedShapeFile)\n\nbeatFireMap = dataOfFire.plot(column = 'fire_f', cmap='OrRd', categorical= True, legend=True)\n\n#setting title\nbeatFireMap.set_title('Beat Fire Map')\n# plt.show()\n# set axis off\nbeatFireMap.set_axis_off()\n\n# for annotating with names of beats\ndataOfFire.apply(lambda x:beatFireMap.annotate(s=x.Beat_Name,xy=x.geometry.centroid.coords[0],ha='center'),axis=1)\n\n# showing the file\n# plt.show()\n\n# saving the file\n# enter the path where you want to save the file\nplt.savefig('/Users/Test/Documents/beatmap.png')\n\n\n\n# https://jakevdp.github.io/PythonDataScienceHandbook/04.00-introduction-to-matplotlib.html\n\n# http://darribas.org/gds15/content/labs/lab_03.html\n\n\n","sub_path":"GeopandasScript/single_beat.py","file_name":"single_beat.py","file_ext":"py","file_size_in_byte":4660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"266721740","text":"\"\"\"\n// Time Complexity : O(nlogn)\n// Space Complexity : O(1)\n// Did this code successfully run on Leetcode : Yes\n// Any problem you faced while coding this : No\n\n// Your code here along with comments explaining your approach\nAlgorithm Explanation\nSince we want to maximize the minimum of pair of elements, we need to bring\nthem in order and then just keep the minimum from each pair linearly till the end\n- Sort the array\n- Sum the numbers at the even position(taking min of the pair)\n- return sum\n\"\"\"\n\nclass Solution:\n def arrayPairSum(self, nums: List[int]) -> int:\n nums.sort()\n N = len(nums)\n k = N // 2\n results = []\n i = 0\n ans = sum([t if not i % 2 else 0 for i,t in enumerate(nums)])\n return ans","sub_path":"array_partition1.py","file_name":"array_partition1.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"168352450","text":"import copy\nimport os\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom IPython.display import clear_output\ntry:\n from sklearn.model_selection import train_test_split\nexcept ImportError:\n from sklearn.cross_validation import train_test_split\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2, f_classif, mutual_info_classif\n\n# libact classes\nfrom libact.base.dataset import Dataset, import_libsvm_sparse\nfrom sklearn.linear_model import LogisticRegression\nfrom libact.models import *\nfrom libact.query_strategies import *\nfrom libact.labelers import IdealLabeler\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import f1_score\nfrom sklearn.linear_model import LogisticRegression as ls\nfrom sklearn.metrics import roc_auc_score\nimport pandas as pd\nimport numpy as np\nimport libact\nfrom libact.models import SVM\nfrom libact.query_strategies import QUIRE, UncertaintySampling, RandomSampling, ActiveLearningByLearning, HintSVM\nimport warnings\nfrom sklearn.cluster import KMeans\nimport random\nwarnings.filterwarnings(\"ignore\")\n\n\ndef prepare_ytrain_foract(y_train, samp):\n \"\"\"\n Used to prepare training dataset of target variables\n \"\"\"\n i = 0\n yy_train=pd.DataFrame(y_train)\n model_y_train=[]\n while (i Feature Selection\n # select features with feature selection\n X_train_feature=[i[0] for i in trn_dss.get_labeled_entries()]\n y_train_feature=[i[1] for i in trn_dss.get_labeled_entries()]\n col_index, features_f=feature_selection(X_train_feature, y_train_feature, all_cols, f_class=True)\n \n features_ls.append(features_f)\n \n # update the X_train dataset and y_train with the current selection of variables\n X_train_updated=[i[0][col_index] for i in trn_dss.data]\n y_train_updated=[i[1] for i in trn_dss.data]\n trn_dss_updated=Dataset(X_train_updated, y_train_updated)\n \n # update X_test \n X_test_feature=[i[col_index] for i in X_test] \n \n if(type_=='random'):\n qs = RandomSampling(trn_dss_updated, method=method_, model=model)\n model1=model\n elif(type_=='unc'):\n qs=UncertaintySampling(trn_dss_updated, method=method_, model=model)\n model1=model\n elif(type_=='qbc'):\n qs = QueryByCommittee(trn_dss_updated, models=model)\n model1=method_\n elif(type_=='dens'):\n qs = DWUS(trn_dss_updated, model=model)\n model1=model\n \n for i in range(0,part1):\n # ask id only asks for particular id, not all, everytime\n ask_id=qs.make_query()\n asks.append(ask_id)\n # lbl label returns the label of a given sample\n lb = y_train[ask_id]\n lbls.append(lb)\n # update updates the unlabeled sample with queried sample\n trn_dss.update(ask_id, lb)\n trn_dss_updated.update(ask_id, lb)\n \n label_holder.append(lbls)\n asked_id.append(asks)\n \n # trains only on the labeled examples and chosen values\n model1.train(trn_dss_updated)\n # predict it \n pred_y=model1.predict(X_test_feature)\n \n # save the results\n f1score.append(f1_score(y_test, pred_y))\n tn.append(confusion_matrix(y_test,pred_y)[0][0])\n fp.append(confusion_matrix(y_test,pred_y)[0][1])\n fn.append(confusion_matrix(y_test,pred_y)[1][0])\n tp.append(confusion_matrix(y_test,pred_y)[1][1])\n \n # score returns the mean accuracy of the results\n #E_in = np.append(E_in, 1 - model.score(trn_dss)) #train\n #E_out = np.append(E_out, 1 - model.score(tst_ds)) #test\n\n k=trn_dss_updated.len_labeled()\n print(k)\n print(quota)\n print('iteration:', iter_)\n print(len(f1score))\n print('train dataset labeled:', trn_dss.len_labeled())\n print('train dataset shape:',trn_dss.format_sklearn()[0].shape)\n print('train dataset sum:',trn_dss.format_sklearn()[1].sum())\n print('Current f1 score:',f1_score(y_test, pred_y))\n print('Current progress:',np.round(k/quota*100,2),'%')\n print('Chosen_features:',features_f)\n \n # number of iterations\n iter_=iter_+1\n \n q= [i for i in range(k_beg,quota,part)]\n iter_=[i for i in range(0,len(f1score))]\n\n \n if (save==True):\n #q= [i for i in range(k_beg,quota,part)]\n #iter_=[i for i in range(0,len(f1score))]\n saved_file=pd.DataFrame({'iter':iter_,'quota':q, 'f1_score':f1score,'tn': tn, 'fp':fp, 'fn': fn, 'tp':tp, 'id_index':asked_id,'label':label_holder, 'features':features_ls})\n saved_file.to_csv(save_name)\n \n \n \n return q, iter_, f1score, tn, fp,fn, tp, k, trn_dss.data, label_holder, asked_id, features_ls\n\n\n\ndef run_faster(trn_dss, tst_ds, y_train, model, qs, X_test, y_test, save_name, save, part=20):\n \"\"\"\n Batch active learning algorithm\n \"\"\"\n # the main active learning algorithm\n E_in, E_out = [], []\n f1score =[]\n label_holder, asked_id = [], []\n tn, fp, fn, tp =[], [], [], []\n \n k= trn_dss.len_labeled()\n k_beg= trn_dss.len_labeled()\n \n quota = len(trn_dss.data)\n iter_ = 0\n while (k>\nimport ssl\nssl._create_default_https_context = ssl._create_unverified_context\n#ssl_ignore--<<\n\n#twitterAPIの利用-->>\n##アクセスTokenなど接続情報の指定-->>\nconsumer_key = \"XXXXXXXXXXXXXXXXXXXXXXXXXX\"\nconsumer_secret = \"XXXXXXXXXXXXXXXXXXXXXXXXXX\"\naccess_token = \"XXXXXXXXXXXXXXXXXXXXXXXXXX\"\naccess_secret = \"XXXXXXXXXXXXXXXXXXXXXXXXXX\"\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_secret)\napi = tweepy.API(auth)\nf = open('sinceId.txt')\nfile_id = f.readline()\nf.close()\n\n#Microsoft Cognitive ComputerVisionAPIの利用-->>\n##接続情報の指定-->>\nimage_url = ''\nheaders = {\n 'Content-Type': 'application/json',\n 'Ocp-Apim-Subscription-Key': 'XXXXXXXXXXXXXXXXXXXXXXXXXX',\n}\nparams = urllib.urlencode({\n 'visualFeatures': 'Description',\n})\n\n#GoogleTranslateAPIの利用-->>\n##接続情報の指定-->>\ngct_head = 'https://www.googleapis.com/language/translate/v2?key='\ngct_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXX'\ngct_mid = '&target=ja&q='\ngct_url = gct_head + gct_key + gct_mid\n\n#body-->>\nconn = httplib.HTTPSConnection('api.projectoxford.ai')\n#sinceIdファイルのID以降のIDを持つ自分へのリプライツイートを指定\nstatus = api.mentions_timeline(since_id=file_id)\ntry:\n if status[0]._json['id_str'] != '':\n f = open('sinceIdBef.txt','w')\n f.write(file_id)\n f.close()\n f = open('sinceId.txt','w')\n f.write(status[0]._json['id_str'])\n f.close()\nexcept IndexError:\n pass\nfor index in range(len(status)):\n body = \"\"\n try:\n #リプライツイートの画像の有無を確認\n image_url = status[index]._json['entities']['media'][0]['media_url']\n print('img_url' + str(index) + ' >> ' + image_url)\n body = \"\"\"{'url': '%s'}\"\"\" % (image_url)\n except KeyError:\n print(\"microsoft computer vision api KeyError\")\n continue\n #リプライの送信元ユーザのユーザー名を格納\n scrn_name = status[index]._json[u'user'][u'screen_name']\n conn.request(\"POST\", \"/vision/v1.0/analyze?%s\" % params, body, headers)\n cv_res = conn.getresponse()\n cv_res_data = cv_res.read()\n cv_res_json = json.loads(cv_res_data)\n try:\n cv_res_txt = cv_res_json[u'description'][u'captions'][0][u'text']\n except KeyError:\n print(\"google translation api KeyError\")\n continue\n gct_req_url = gct_url + cv_res_txt\n gct_res = requests.post(gct_req_url)\n print(gct_req_url)\n gct_res_txt = gct_res.json()[u'data'][u'translations'][0][u'translatedText']\n #リプライの返信先を指定\n rep_txt = '@' + scrn_name + ' ' + gct_res_txt\n rep_id = status[index]._json['id_str']\n api.update_status(status=rep_txt, in_reply_to_status_id=rep_id)\n# print(gct_res_txt)\nconn.close()\n#body--<<\n","sub_path":"image2text.py","file_name":"image2text.py","file_ext":"py","file_size_in_byte":3177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"457382200","text":"#!/usr/bin/env python\n\n# read a stream from a local host\nfrom pyspark.sql.functions import explode, split\nimport pyspark\n\nimport logging\nlogging.basicConfig(level=logging.WARNING)\nlogger = logging.getLogger('ai.applecare')\nlogger.setLevel(logging.DEBUG)\n\nlogger.debug('setup spark')\nspark = (pyspark.sql.SparkSession\n .builder\n .appName('ch2 read stram')\n .getOrCreate())\n\n# spark.sparkContext.setLogLevel('INFO')\n\ndf = spark.range(0, 10000, 1, 8)\nprint(f'>>>>> df.rdd.getNumPartitions(): {df.rdd.getNumPartitions()}')\n\n\nimport numpy as np\n\nprint(np.arange(0, 30, 3))\n","sub_path":"lrn-spark/notebooks/ch1-lrn-spark-rand-nums-to-partitions.py","file_name":"ch1-lrn-spark-rand-nums-to-partitions.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"251884009","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\n# William Dimitrios Paraschas (paraschas@gmail.com)\n\n\nimport signal\nimport sys\nimport time\n\n\ndef sigint_handler(signal, frame):\n \"\"\"\n \"\"\"\n print()\n print(\"Interrupted with CTRL-C, exiting...\")\n\n sys.exit()\n\n\ndef perpetual():\n \"\"\"\n \"\"\"\n while True:\n print(\"Running, press CTRL-C to verify graceful termination.\")\n time.sleep(1)\n\n\ndef handle_interupts_with_sigint_handler():\n \"\"\"\n \"\"\"\n # terminate gracefully on CTRL-C\n signal.signal(signal.SIGINT, sigint_handler)\n\n perpetual()\n\n\ndef handle_interupts_with_exception_handler():\n \"\"\"\n \"\"\"\n try:\n perpetual()\n except KeyboardInterrupt:\n print()\n print(\"Interrupted with CTRL-C, exiting...\")\n sys.exit()\n\n\nif __name__ == \"__main__\":\n # handle_interupts_with_sigint_handler()\n handle_interupts_with_exception_handler()\n","sub_path":"terminate_gracefully_on_CTRL-C.py","file_name":"terminate_gracefully_on_CTRL-C.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"304910863","text":"# -*- coding: utf-8 -*-\nfrom django.contrib.auth.models import User\nfrom mock import patch, Mock\nfrom django.test import TestCase\n\nclass EventTestBase(TestCase):\n def setUp(self):\n # self.patch_redis = patch('redis.Redis')\n # self.mock_redis = self.patch_redis.start()\n\n self.patch_get_current_request = patch('django_request_local.middleware.RequestLocal.get_current_request')\n self.mock_get_current_request = self.patch_get_current_request.start()\n remote_user = 'http://authhost/user/testuser'\n self.mock_request = Mock()\n self.mock_request.COOKIES = {\n 'remote_user': remote_user\n }\n self.mock_request.user = User.objects.create_user('event_user', '', 'event_user')\n self.mock_get_current_request.return_value = self.mock_request\n\n self.patch_send_task = patch('celery.execute.send_task')\n self.mock_send_task = self.patch_send_task.start()\n\n def tearDown(self):\n # self.patch_redis.stop()\n self.patch_get_current_request.stop()\n self.patch_send_task.stop()","sub_path":"event/tests/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"548549221","text":"import numpy as np\r\nimport tempfile\r\nfrom shutil import copy\r\nimport pandas as pd\r\nimport subprocess\r\nimport shutil\r\nimport multiprocessing.pool as mpp\r\nimport scipy.spatial.distance as ssd\r\n\r\n\r\ndef run_comparisons(pair_id, metric_id):\r\n \"\"\"This function runs through all required steps to compare a pair of maps (see Approach step 2-9)\"\"\"\r\n global map1_id, map2_id\r\n #map selection is different based on metric type\r\n if metric_id in single_comparison:\r\n map1 = map_list[pair_id][0]\r\n map2 = map_list[pair_id][1] \r\n if metric_id in multi_comparison:\r\n map1 = map_pairs[pair_id][0]\r\n map2 = map_pairs[pair_id][1]\r\n # Stores map number of each mLap for later use in processing\r\n map1_id, map2_id = map_id(map1, map2)\r\n name1 = 'map' + str(map1_id)\r\n name2 = 'map' + str(map2_id)\r\n if metric_id == 'kappa':\r\n with tempfile.TemporaryDirectory() as tempdir:\r\n # Generate and copy all requires files to the temp folder\r\n copy_files(tempdir, map1_id, map2_id, metric_id)\r\n #call command prompt\r\n cslpath = tempdir + '/base_csl.csl'\r\n logpath = tempdir + '/log.log'\r\n outputpath = tempdir\r\n call_cmd(mckdir=mckdir, csl=cslpath, log=logpath, outputdir=tempdir)\r\n #extract value from output file\r\n comparison = tempdir + '\\kappa.sts'\r\n kappa = extract_stats(comparison, metric_id)\r\n return name1, name2, kappa\r\n elif metric_id == 'kfuzzy':\r\n with tempfile.TemporaryDirectory() as tempdir:\r\n # Generate and copy all requires files to the temp folder\r\n copy_files(tempdir, map1_id, map2_id, metric_id)\r\n #call command prompt\r\n cslpath = tempdir + '/kfuzzy.csl'\r\n logpath = tempdir + '/log.log'\r\n outputpath = tempdir\r\n call_cmd(mckdir=mckdir, csl=cslpath, log=logpath, outputdir=tempdir)\r\n #extract value from output file\r\n comparison = tempdir + '\\kfuzzy.sts'\r\n kfuzzy = extract_stats(comparison, metric_id)\r\n return name1, name2, kfuzzy\r\n elif metric_id == 'simp':\r\n with tempfile.TemporaryDirectory() as tempdir:\r\n # Generate and copy all requires files to the temp folder\r\n copy_files(tempdir, map1_id, map2_id, metric_id)\r\n #call command prompt\r\n cslpath = tempdir + '/base_csl.csl'\r\n logpath = tempdir + '/log.log'\r\n outputpath = tempdir\r\n call_cmd(mckdir=mckdir, csl=cslpath, log=logpath, outputdir=tempdir)\r\n #extract value from output file\r\n comparison = tempdir + '\\\\simpson.sts'\r\n sim1, sim2 = extract_stats(comparison, metric_id)\r\n return name1, name2, sim1, sim2 \r\n elif metric_id == 'shan':\r\n with tempfile.TemporaryDirectory() as tempdir:\r\n # Generate and copy all requires files to the temp folder\r\n copy_files(tempdir, map1_id, map2_id, metric_id)\r\n #call command prompt\r\n cslpath = tempdir + '/base_csl.csl'\r\n logpath = tempdir + '/log.log'\r\n outputpath = tempdir\r\n call_cmd(mckdir=mckdir, csl=cslpath, log=logpath, outputdir=tempdir)\r\n #extract value from output file\r\n comparison = tempdir + '\\\\shannon.sts'\r\n shan1, shan2 = extract_stats(comparison, metric_id)\r\n return name1, name2, shan1, shan2 \r\n else:\r\n return 'invalid metric id'\r\n \r\ndef copy_files(path, map_nr1, map_nr2, metric_id):\r\n \"\"\"This function takes a filepath and a pair of maps then copies the maps and other required files to the specified filepath\"\"\"\r\n #Convert maps\r\n map1name = 'map' + str(map_nr1) + '.asc'\r\n map2name = 'map' + str(map_nr2) + '.asc'\r\n map1 = ascfolder + map1name\r\n map2 = ascfolder + map2name\r\n copy(map1, path) \r\n copy(map2, path)\r\n #Copy mask files\r\n copy(maskfile, path) \r\n copy(masklandfile, path)\r\n #Generate and copy csl file for comparison\r\n if metric_id == 'kappa':\r\n csl_kappa(path=path, map_nr1=map_nr1, map_nr2=map_nr2)\r\n elif metric_id == 'kfuzzy':\r\n csl_kfuzzy(path=path, map_nr1=map_nr1, map_nr2=map_nr2)\r\n elif metric_id == 'simp':\r\n csl_simpson(path=path, map_nr1=map_nr1, map_nr2=map_nr2)\r\n elif metric_id == 'shan':\r\n csl_shannon(path=path, map_nr1=map_nr1, map_nr2=map_nr2)\r\n #Copy log file\r\n gen_log(path, map_nr1, map_nr2)\r\n #Copy legends folder\r\n dst = path + '/Legends'\r\n shutil.copytree(src,dst)\r\n \r\ndef extract_stats(sts, sts_id):\r\n \"\"\"This function reads the output file generated by MCK and extracts the necessary stats based on the metric send\"\"\"\r\n if sts_id == 'kappa':\r\n with open(sts, 'r') as file:\r\n for l, line in enumerate(file):\r\n if l == 3:\r\n # Extract kappa\r\n loc2 = line.find(' kappa=\"')\r\n loc_start2 = loc2 + len(' kappa=\"')\r\n loc_end2 = line.find('\"', loc_start2)\r\n kappa = float(line[loc_start2:loc_end2])\r\n return kappa\r\n elif sts_id == 'kfuzzy':\r\n with open(sts, 'r') as file:\r\n for l, line in enumerate(file):\r\n if l == 3:\r\n # Extract fuzzy kappa\r\n loc2 = line.find('fuzzy_kappa=\"')\r\n loc_start2 = loc2 + len('fuzzy_kappa=\"')\r\n loc_end2 = line.find('\"', loc_start2)\r\n kfuzzy = float(line[loc_start2:loc_end2])\r\n return kfuzzy\r\n elif sts_id == 'simp':\r\n with open(sts, 'r') as file:\r\n for l, line in enumerate(file):\r\n if l == 3:\r\n #Find first value\r\n loc = line.find('overall_first=\"')\r\n loc_start = loc + len('overall_first=\"')\r\n loc_end = line.find('\"', loc_start)\r\n sim1 = float(line[loc_start:loc_end])\r\n #Find second value\r\n loc2= line.find('overall_second=\"')\r\n loc_start2= loc2 + len('overall_second=\"')\r\n loc_end2= line.find('\"', loc_start2)\r\n sim2 = float(line[loc_start2:loc_end2])\r\n return sim1, sim2\r\n elif sts_id == 'shan':\r\n with open(sts, 'r') as file:\r\n for l, line in enumerate(file):\r\n if l == 3:\r\n #Find first value\r\n loc = line.find('overall_first=\"')\r\n loc_start = loc + len('overall_first=\"')\r\n loc_end = line.find('\"', loc_start)\r\n shan1 = float(line[loc_start:loc_end])\r\n #Find second value\r\n loc2= line.find('overall_second=\"')\r\n loc_start2= loc2 + len('overall_second=\"')\r\n loc_end2= line.find('\"', loc_start2)\r\n shan2 = float(line[loc_start2:loc_end2])\r\n return shan1, shan2\r\n \r\n else:\r\n return 'Incorrect stats id'\r\n \r\ndef map_id(map1, map2):\r\n \"\"\"This function returns the map number for 2 provided maps based on the path of the maps\"\"\"\r\n map1_start = map1.find('_') + 1\r\n map1_end = map1.find('.')\r\n map1_id = int(map1[map1_start:map1_end])\r\n \r\n map2_start = map2.find('_') + 1\r\n map2_end = map2.find('.')\r\n map2_id = int(map2[map2_start:map2_end])\r\n return map1_id, map2_id\r\n \r\ndef csl_kappa(path, map_nr1, map_nr2):\r\n \"\"\"This function copies a base csl file to the provided directory then rewrites it to run the desired kappa comparison\"\"\"\r\n file_dir = path + '\\\\base_csl.csl'\r\n copy(base_csl, path)\r\n with open(file_dir, 'w+') as file:\r\n file.truncate(0)\r\n file.write('\\n')\r\n map1 = path + '\\map' + str(map_nr1) + '.asc'\r\n map2 = path + '\\map' + str(map_nr2) + '.asc'\r\n mask = path + '\\mask.asc'\r\n file.writelines(['\\n\\t' \\\r\n ,'\\n\\t\\t' \\\r\n , '\\n\\t\\t' \\\r\n ,'\\n\\t\\t\\t' \\\r\n ,'\\n\\t\\t\\t\\t' \\\r\n ,'\\n\\t\\t\\t\\t' \\\r\n ,'\\n\\t\\t\\t' \\\r\n ,'\\n\\t\\t' \\\r\n ,'\\n\\t\\n'])\r\n file.write('')\r\n \r\ndef csl_kfuzzy(path, map_nr1, map_nr2):\r\n \"\"\"This function copies a base csl file to the provided directory then rewrites it to run the desired fuzzy kappa comparison\"\"\"\r\n map1 = path + '\\\\map' + str(map_nr1) + '.asc'\r\n map2 = path + '\\\\map' + str(map_nr2) + '.asc'\r\n mask = path + '\\mask.asc' \r\n copy(base_kfuzzy, path)\r\n \r\n file_dir = path + \"\\kfuzzy.csl\" \r\n \r\n #Read data\r\n with open(file_dir, 'r') as file:\r\n data = file.readlines()\r\n #Change Data \r\n line3= '\\t\\n'\r\n line909 = '\\n'\r\n data[3] = line3\r\n data[909] = line909\r\n #Write new data in\r\n with open(file_dir, 'w') as file:\r\n file.writelines(data)\r\n \r\ndef csl_simpson(path, map_nr1, map_nr2):\r\n \"\"\"This function copies a base csl file to the provided directory then rewrites it to run the desired simpson's comparison\"\"\"\r\n file_dir = path + '\\\\base_csl.csl'\r\n copy(base_csl, path)\r\n with open(file_dir, 'w+') as file:\r\n file.truncate(0)\r\n file.write('\\n')\r\n map1 = path + '\\map' + str(map_nr1) + '.asc'\r\n map2 = path + '\\map' + str(map_nr2) + '.asc'\r\n mask = path + '\\mask.asc'\r\n file.writelines(['\\n\\t' \\\r\n ,'\\n\\t\\t'\\\r\n , '\\n\\t\\t\\t' \\\r\n ,'\\n\\t\\t' \\\r\n , '\\n\\t\\t' \\\r\n ,'\\n\\t\\t\\t\\t' \\\r\n ,'\\n\\t\\t\\t\\t\\t' \\\r\n ,'\\n\\t\\t\\t\\t\\t' \\\r\n ,'\\n\\t\\t\\t' \\\r\n ,'\\n\\t\\t' \\\r\n ,'\\n\\t\\n'])\r\n file.write('') \r\n\r\ndef csl_shannon(path, map_nr1, map_nr2):\r\n \"\"\"This function copies a base csl file to the provided directory then rewrites it to run the desired simpson's comparison\"\"\"\r\n file_dir = path + '\\\\base_csl.csl'\r\n copy(base_csl, path)\r\n with open(file_dir, 'w+') as file:\r\n file.truncate(0)\r\n file.write('\\n')\r\n map1 = path + '\\map' + str(map_nr1) + '.asc'\r\n map2 = path + '\\map' + str(map_nr2) + '.asc'\r\n mask = path + '\\mask.asc'\r\n file.writelines(['\\n\\t' \\\r\n ,'\\n\\t\\t'\\\r\n , '\\n\\t\\t\\t' \\\r\n ,'\\n\\t\\t' \\\r\n , '\\n\\t\\t' \\\r\n ,'\\n\\t\\t\\t\\t' \\\r\n ,'\\n\\t\\t\\t\\t\\t' \\\r\n ,'\\n\\t\\t\\t\\t\\t' \\\r\n ,'\\n\\t\\t\\t' \\\r\n ,'\\n\\t\\t' \\\r\n ,'\\n\\t\\n'])\r\n file.write('') \r\n \r\ndef gen_log(path, map_nr1, map_nr2):\r\n \"\"\"This function copies a base log file to the provided directory then rewrites it with desired changes\"\"\"\r\n copy(log_path, path)\r\n file_dir = path + '/log.log'\r\n line3 = 'maps=' + path + '\\map' + str(map_nr1) + '.asc'\r\n line4 = 'maps=' + path + '\\map' + str(map_nr2) + '.asc'\r\n #Read data\r\n with open(file_dir, 'r') as file:\r\n data = file.readlines()\r\n #Change Data \r\n data[3] = line3 + '\\n'\r\n data[4] = line4\r\n #Write new data in\r\n with open(file_dir, 'w') as file:\r\n file.writelines(data) \r\n \r\ndef call_cmd(mckdir, csl, log, outputdir):\r\n \"\"\"\"\"\"\r\n cmd= [mckdir, 'CMD', '/RunComparisonSet', csl, log, outputdir]\r\n subprocess.run(cmd, check=True, shell=True)\r\n\r\ndef single_df(maps, stats, metric):\r\n \"\"\"This function takes the output from the run comparisons function for single map comparison metrics and returns the distance matrix\"\"\"\r\n #create base df to form basis for distance matrix\r\n df = pd.DataFrame(index=maps)\r\n df[metric] = stats\r\n #calculate euclidean distance between all values then change to matrix form\r\n matrix = ssd.squareform(ssd.pdist(df))\r\n df_clean = pd.DataFrame(matrix, index=maps, columns=maps)\r\n \r\n # save values to disk\r\n csv_val = csv_dir + metric + '_values.csv'\r\n df_vals = pd.DataFrame(index=map_set)\r\n df_vals[metric] = stats\r\n df_vals.to_csv(csv_val)\r\n #save df to disk\r\n csv_name = csv_dir + metric + '_df.csv'\r\n df_clean.to_csv(csv_name, index=False)\r\n\r\ndef multi_df(map1, map2, stats, metric):\r\n \"\"\"This function takes the output from the run comparisons function for multi map comparison metrics and returns the distance matrix\"\"\"\r\n #Create two dataframes with swapped map columns\r\n df = pd.DataFrame()\r\n df['map1'] = [x for x in map1]\r\n df['map2'] = [x for x in map2]\r\n df[metric] = stats\r\n df2 = df\r\n df2 = df2[[ 'map2', 'map1', metric]]\r\n df2.columns = ['map1', 'map2', metric] \r\n df_concat = pd.concat([df, df2])\r\n df_pivot = df_concat.pivot(index='map2', columns='map1', values=metric) \r\n ## clean up the presentation\r\n #Remove unecessary labeling\r\n index = df_pivot.index.union(df_pivot.columns)\r\n df_clean = df_pivot.reindex(index=index, columns=index)\r\n #reindex to correct numerical order\r\n ordered = df_clean.index.to_series().str.rsplit('p').str[-1].astype(int).sort_values()\r\n df_clean = df_clean.reindex(index=ordered.index, columns=ordered.index).fillna(1).round(decimals=3) \r\n #save df to disk\r\n csv_name = csv_dir + metric + '_df.csv'\r\n df_clean.to_csv(csv_name, index=False)\r\n\r\ndef istarmap(self, func, iterable, chunksize=1):\r\n \"\"\"starmap-version of imap\r\n \"\"\"\r\n if self._state != mpp.RUN:\r\n raise ValueError(\"Pool not running\")\r\n\r\n if chunksize < 1:\r\n raise ValueError(\r\n \"Chunksize must be 1+, not {0:n}\".format(\r\n chunksize))\r\n\r\n task_batches = mpp.Pool._get_tasks(func, iterable, chunksize)\r\n result = mpp.IMapIterator(self._cache)\r\n self._taskqueue.put(\r\n (\r\n self._guarded_task_generation(result._job,\r\n mpp.starmapstar,\r\n task_batches),\r\n result._set_length\r\n ))\r\n return (item for chunk in result for item in chunk)\r\nmpp.Pool.istarmap = istarmap\r\n\r\n#### SETUP VARIABLES ####\r\n## ABSOLUTE PATH ##\r\n# changing this variable to where the main folder with all files is is the only path adjustment that is necessary\r\nabs_dir = 'C:/LUMOS/clusterfiles/'\r\n# Name of the csv files generated by landusescanner that contain map data\r\nlus_outputname = \"map500exp_\"\r\next = '.csv'\r\n#copy files source\r\nsrc = abs_dir + 'Legends'\r\n# Location of required files for MCK Comparisons\r\nascfolder = abs_dir + 'ascmaps/'\r\ncsvfolder = abs_dir + 'csvmaps/'\r\nmaskfile = abs_dir + 'mask.asc'\r\nmasklandfile = abs_dir + 'maskland.msk'\r\nbase_csl = abs_dir + 'base_csl.csl'\r\n#fuzzy kappa has its own base csl due to its different structure\r\nbase_kfuzzy = abs_dir + 'kfuzzy.csl'\r\nlog_path = abs_dir + 'log.log'\r\nmckdir = abs_dir + 'Map_Comparison_Kit/MCK.exe'\r\n# max map comparisons to run\r\nnr_maps = 10\r\n#directory where the dataframes containing output are stored\r\ncsv_dir = abs_dir + 'Output_DFs/'\r\n\r\nmap_set = ['map' + str(i) for i in range(nr_maps)]\r\n\r\n# Generate list containing a set of maps based on setup variables\r\nmaps = []\r\nmaps.extend([csvfolder + lus_outputname + str(x) + ext for x in np.arange(0, nr_maps)])\r\n\r\n# Generate list containing all possible map comparisons\r\nmap_pairs=[]\r\nfor i in range(len(maps)):\r\n for j in range(len(maps)):\r\n if i < j:\r\n map1 = maps[i]\r\n map2 = maps[j]\r\n map_pairs.append((map1,map2))\r\n\r\n# Generate list of map inputs for metrics that have a single map statistic\r\nmap_list= []\r\nfor i in np.arange(0, len(maps), 2):\r\n try:\r\n map1 = maps[i]\r\n map2 = maps[i + 1]\r\n map_list.append((map1,map2))\r\n except IndexError:\r\n # If there is only one map left send it in with itself\r\n map1 = maps[i]\r\n map2 = maps[i]\r\n map_list.append((map1,map2)) \r\n \r\n# Lists used in run_comparison to check comparison type\r\nsingle_comparison = ['pland', 'tca', 'shan', 'simp']\r\nmulti_comparison = ['kappa', 'kfuzzy', 'alloc', 'quant', 'td', 'oa', 'prop']\r\n\r\n#Variables that store number of iteration for single and multi map comparisons\r\nsingle_its = len(map_list)\r\nmulti_its = len(map_pairs)","sub_path":"dependencies/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":19250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"634109970","text":"\"\"\"\n528\n\"\"\"\nimport random\nimport bisect\nclass Solution:\n\n def __init__(self, w):\n \"\"\"\n :type w: List[int]\n \"\"\"\n self.w = w\n self.arr = [w[0]]\n for n in w[1:]:\n self.arr.append(self.arr[-1]+n)\n\n def pickIndex(self):\n \"\"\"\n :rtype: int\n \"\"\"\n rnd = random.random()*self.arr[-1]\n i = bisect.bisect_left(self.arr, rnd)\n return i\n \n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(w)\n# param_1 = obj.pickIndex()","sub_path":"current_session/python/528_redo2.py","file_name":"528_redo2.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"485433644","text":" # ------------------------------------------------------------------------------\r\n# BSD 2-Clause License\r\n#\r\n# Copyright (c) 2019-2020, Thomas Larsson\r\n# All rights reserved.\r\n#\r\n# Redistribution and use in source and binary forms, with or without\r\n# modification, are permitted provided that the following conditions are met:\r\n#\r\n# 1. Redistributions of source code must retain the above copyright notice, this\r\n# list of conditions and the following disclaimer.\r\n#\r\n# 2. Redistributions in binary form must reproduce the above copyright notice,\r\n# this list of conditions and the following disclaimer in the documentation\r\n# and/or other materials provided with the distribution.\r\n#\r\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\r\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\r\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\r\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\r\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\r\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n# ------------------------------------------------------------------------------\r\n\r\nimport bpy, os, mathutils, math, time\r\nfrom bpy_extras.io_utils import ImportHelper\r\nfrom math import sin, cos\r\nfrom mathutils import *\r\nfrom bpy.props import *\r\n\r\nfrom .utils import *\r\nfrom .source import Source\r\nfrom .target import Target\r\nfrom .simplify import TimeScaler\r\n\r\nclass BvhFile:\r\n filename_ext = \".bvh\"\r\n filter_glob : StringProperty(default=\"*.bvh\", options={'HIDDEN'})\r\n filepath : StringProperty(name=\"File Path\", description=\"Filepath used for importing the BVH file\", maxlen=1024, default=\"\")\r\n\r\n\r\nclass MultiFile(ImportHelper):\r\n files : CollectionProperty(\r\n name = \"File Path\",\r\n type = bpy.types.OperatorFileListElement)\r\n\r\n directory : StringProperty(\r\n subtype='DIR_PATH')\r\n\r\n def getFilePaths(self):\r\n if self.files:\r\n filepaths = []\r\n for file_elem in self.files:\r\n filepath = os.path.join(self.directory, file_elem.name)\r\n filepaths.append(filepath)\r\n return filepaths\r\n else:\r\n return [self.filepath]\r\n\r\n###################################################################################\r\n# BVH importer.\r\n# The importer that comes with Blender had memory leaks which led to instability.\r\n# It also creates a weird skeleton from CMU data, with hands theat start at the wrist\r\n# and ends at the elbow.\r\n#\r\n\r\n#\r\n# class CNode:\r\n#\r\n\r\nclass CNode:\r\n def __init__(self, words, parent):\r\n name = words[1]\r\n for word in words[2:]:\r\n name += ' '+word\r\n\r\n self.name = name\r\n self.parent = parent\r\n self.children = []\r\n self.head = Vector((0,0,0))\r\n self.offset = Vector((0,0,0))\r\n if parent:\r\n parent.children.append(self)\r\n self.channels = []\r\n self.matrix = None\r\n self.inverse = None\r\n return\r\n\r\n def __repr__(self):\r\n return \"CNode %s\" % (self.name)\r\n\r\n def display(self, pad):\r\n vec = self.offset\r\n if vec.length < Epsilon:\r\n c = '*'\r\n else:\r\n c = ' '\r\n print(\"%s%s%10s (%8.3f %8.3f %8.3f)\" % (c, pad, self.name, vec[0], vec[1], vec[2]))\r\n for child in self.children:\r\n child.display(pad+\" \")\r\n return\r\n\r\n\r\n def build(self, amt, orig, parent):\r\n self.head = orig + self.offset\r\n if not self.children:\r\n return self.head\r\n\r\n zero = (self.offset.length < Epsilon)\r\n eb = amt.edit_bones.new(self.name)\r\n if parent:\r\n eb.parent = parent\r\n eb.head = self.head\r\n tails = Vector((0,0,0))\r\n for child in self.children:\r\n tails += child.build(amt, self.head, eb)\r\n tail = tails/len(self.children)\r\n if (tail-self.head).length == 0:\r\n print(\"Zero-length bone: %s\" % eb.name)\r\n vec = self.head - parent.head\r\n tail = self.head + vec*0.1\r\n eb.tail = tail\r\n (loc, rot, scale) = eb.matrix.decompose()\r\n self.matrix = rot.to_matrix()\r\n self.inverse = self.matrix.copy()\r\n self.inverse.invert()\r\n if zero:\r\n return eb.tail\r\n else:\r\n return eb.head\r\n\r\n#\r\n# readBvhFile(context, filepath, scn, scan):\r\n# Custom importer\r\n#\r\n\r\nLocation = 1\r\nRotation = 2\r\nHierarchy = 1\r\nMotion = 2\r\nFrames = 3\r\n\r\nEpsilon = 1e-5\r\n\r\nclass FrameRange:\r\n startFrame : IntProperty(\r\n name = \"Start Frame\",\r\n description = \"Starting frame for the animation\",\r\n default = 1)\r\n\r\n endFrame : IntProperty(\r\n name = \"Last Frame\",\r\n description = \"Last frame for the animation\",\r\n default = 250)\r\n\r\n def draw(self, context):\r\n self.layout.prop(self, \"startFrame\")\r\n self.layout.prop(self, \"endFrame\")\r\n\r\n\r\nclass BvhLoader(FrameRange):\r\n scale : FloatProperty(\r\n name=\"Scale\",\r\n description=\"Scale the BVH by this value\",\r\n min=0.0001, max=1000000.0,\r\n soft_min=0.001, soft_max=100.0,\r\n precision = 3,\r\n default=1.0)\r\n\r\n x : EnumProperty(\r\n items = [(x,x,x) for x in [\"0\", \"90\", \"180\", \"270\"]],\r\n name = \"X\",\r\n description = \"X Euler Angle\",\r\n default = \"90\")\r\n\r\n y : EnumProperty(\r\n items = [(y,y,y) for y in [\"0\", \"90\", \"180\", \"270\"]],\r\n name = \"Y\",\r\n description = \"Y Euler Angle\",\r\n default = \"0\")\r\n\r\n z : EnumProperty(\r\n items = [(z,z,z) for z in [\"0\", \"90\", \"180\", \"270\"]],\r\n name = \"Z\",\r\n description = \"Z Euler Angle\",\r\n default = \"0\")\r\n\r\n ssFactor : IntProperty(\r\n name=\"Subsample Factor\",\r\n description=\"Sample only every n:th frame\",\r\n min=1, default=1)\r\n\r\n useDefaultSS : BoolProperty(\r\n name=\"Use default subsample\",\r\n description = \"Subsample based on difference in frame rates between BVH file and Blender\",\r\n default=True)\r\n\r\n def draw(self, context):\r\n FrameRange.draw(self, context)\r\n self.layout.separator()\r\n self.layout.label(text=\"Source Rig Orientation:\")\r\n row = self.layout.row()\r\n row.label(text=\"X:\")\r\n row.prop(self, \"x\", expand=True)\r\n row = self.layout.row()\r\n row.label(text=\"Y:\")\r\n row.prop(self, \"y\", expand=True)\r\n row = self.layout.row()\r\n row.label(text=\"Z:\")\r\n row.prop(self, \"z\", expand=True)\r\n self.layout.separator()\r\n self.layout.prop(self, \"useDefaultSS\")\r\n if not self.useDefaultSS:\r\n self.layout.prop(self, \"ssFactor\")\r\n self.layout.separator()\r\n\r\n\r\n def readBvhFile(self, context, filepath, scn, scan):\r\n frameno = 1\r\n euler = Euler((int(self.x)*D, int(self.y)*D, int(self.z)*D))\r\n flipMatrix = euler.to_matrix()\r\n ssFactor = self.ssFactor\r\n\r\n fileName = os.path.realpath(os.path.expanduser(filepath))\r\n (shortName, ext) = os.path.splitext(fileName)\r\n if ext.lower() != \".bvh\":\r\n raise MocapError(\"Not a bvh file: \" + fileName)\r\n startProgress( \"Loading BVH file \"+ fileName )\r\n\r\n time1 = time.perf_counter()\r\n level = 0\r\n nErrors = 0\r\n coll = context.scene.collection\r\n rig = None\r\n\r\n fp = open(fileName, \"rU\")\r\n print( \"Reading skeleton\" )\r\n lineNo = 0\r\n for line in fp:\r\n words= line.split()\r\n lineNo += 1\r\n if len(words) == 0:\r\n continue\r\n key = words[0].upper()\r\n if key == 'HIERARCHY':\r\n status = Hierarchy\r\n ended = False\r\n elif key == 'MOTION':\r\n if level != 0:\r\n raise MocapError(\"Tokenizer out of kilter %d\" % level)\r\n if scan:\r\n return root\r\n amt = bpy.data.armatures.new(\"BvhAmt\")\r\n rig = bpy.data.objects.new(\"BvhRig\", amt)\r\n coll.objects.link(rig)\r\n setActiveObject(context, rig)\r\n updateScene()\r\n bpy.ops.object.mode_set(mode='EDIT')\r\n bpy.ops.object.mode_set(mode='EDIT')\r\n root.build(amt, Vector((0,0,0)), None)\r\n #root.display('')\r\n bpy.ops.object.mode_set(mode='OBJECT')\r\n status = Motion\r\n print(\"Reading motion\")\r\n elif status == Hierarchy:\r\n if key == 'ROOT':\r\n node = CNode(words, None)\r\n root = node\r\n nodes = [root]\r\n elif key == 'JOINT':\r\n node = CNode(words, node)\r\n nodes.append(node)\r\n ended = False\r\n elif key == 'OFFSET':\r\n (x,y,z) = (float(words[1]), float(words[2]), float(words[3]))\r\n node.offset = self.scale * flipMatrix @ Vector((x,y,z))\r\n elif key == 'END':\r\n node = CNode(words, node)\r\n ended = True\r\n elif key == 'CHANNELS':\r\n oldmode = None\r\n for word in words[2:]:\r\n (index, mode, sign) = channelYup(word)\r\n if mode != oldmode:\r\n indices = []\r\n node.channels.append((mode, indices))\r\n oldmode = mode\r\n indices.append((index, sign))\r\n elif key == '{':\r\n level += 1\r\n elif key == '}':\r\n if not ended:\r\n node = CNode([\"End\", \"Site\"], node)\r\n node.offset = self.scale * flipMatrix @ Vector((0,1,0))\r\n node = node.parent\r\n ended = True\r\n level -= 1\r\n node = node.parent\r\n else:\r\n raise MocapError(\"Did not expect %s\" % words[0])\r\n elif status == Motion:\r\n if key == 'FRAMES:':\r\n nFrames = int(words[1])\r\n elif key == 'FRAME' and words[1].upper() == 'TIME:':\r\n frameTime = float(words[2])\r\n frameFactor = int(1.0/(scn.render.fps*frameTime) + 0.49)\r\n if self.useDefaultSS:\r\n ssFactor = frameFactor if frameFactor > 0 else 1\r\n self.startFrame *= ssFactor\r\n self.endFrame *= ssFactor\r\n status = Frames\r\n frame = 0\r\n frameno = 1\r\n\r\n bpy.ops.object.mode_set(mode='POSE')\r\n pbones = rig.pose.bones\r\n for pb in pbones:\r\n pb.rotation_mode = 'QUATERNION'\r\n elif status == Frames:\r\n if (frame >= self.startFrame and\r\n frame <= self.endFrame and\r\n frame % ssFactor == 0 and\r\n frame < nFrames):\r\n self.addFrame(words, frameno, nodes, pbones, flipMatrix)\r\n showProgress(frameno, frame, nFrames, step=200)\r\n frameno += 1\r\n frame += 1\r\n\r\n fp.close()\r\n if not rig:\r\n raise MocapError(\"Bvh file \\n%s\\n is corrupt: No rig defined\" % filepath)\r\n setInterpolation(rig)\r\n time2 = time.perf_counter()\r\n endProgress(\"Bvh file %s loaded in %.3f s\" % (filepath, time2-time1))\r\n if frameno == 1:\r\n print(\"Warning: No frames in range %d -- %d.\" % (self.startFrame, self.endFrame))\r\n renameBvhRig(rig, filepath)\r\n rig.McpIsSourceRig = True\r\n return rig\r\n\r\n\r\n def addFrame(self, words, frame, nodes, pbones, flipMatrix):\r\n m = 0\r\n first = True\r\n flipInv = flipMatrix.inverted()\r\n for node in nodes:\r\n bname = node.name\r\n if bname not in pbones.keys():\r\n for (mode, indices) in node.channels:\r\n m += len(indices)\r\n else:\r\n pb = pbones[bname]\r\n for (mode, indices) in node.channels:\r\n if mode == Location:\r\n vec = Vector((0,0,0))\r\n for (index, sign) in indices:\r\n vec[index] = sign*float(words[m])\r\n m += 1\r\n if first:\r\n pb.location = node.inverse @ (self.scale * flipMatrix @ vec) - node.head\r\n pb.keyframe_insert('location', frame=frame, group=bname)\r\n first = False\r\n elif mode == Rotation:\r\n mats = []\r\n for (axis, sign) in indices:\r\n angle = sign*float(words[m])*D\r\n mats.append(Matrix.Rotation(angle, 3, axis))\r\n m += 1\r\n mat = (node.inverse @ flipMatrix) @ mats[0] @ mats[1] @ mats[2] @ (flipInv @ node.matrix)\r\n insertRotation(pb, mat, frame)\r\n\r\n#\r\n# channelYup(word):\r\n# channelZup(word):\r\n#\r\n\r\ndef channelYup(word):\r\n if word == 'Xrotation':\r\n return ('X', Rotation, +1)\r\n elif word == 'Yrotation':\r\n return ('Y', Rotation, +1)\r\n elif word == 'Zrotation':\r\n return ('Z', Rotation, +1)\r\n elif word == 'Xposition':\r\n return (0, Location, +1)\r\n elif word == 'Yposition':\r\n return (1, Location, +1)\r\n elif word == 'Zposition':\r\n return (2, Location, +1)\r\n\r\ndef channelZup(word):\r\n if word == 'Xrotation':\r\n return ('X', Rotation, +1)\r\n elif word == 'Yrotation':\r\n return ('Z', Rotation, +1)\r\n elif word == 'Zrotation':\r\n return ('Y', Rotation, -1)\r\n elif word == 'Xposition':\r\n return (0, Location, +1)\r\n elif word == 'Yposition':\r\n return (2, Location, +1)\r\n elif word == 'Zposition':\r\n return (1, Location, -1)\r\n\r\n#\r\n# end BVH importer\r\n#\r\n###################################################################################\r\n\r\n\r\n###################################################################################\r\n\r\n#\r\n# class CEditBone():\r\n#\r\n\r\nclass CEditBone():\r\n def __init__(self, bone):\r\n self.name = bone.name\r\n self.head = bone.head.copy()\r\n self.tail = bone.tail.copy()\r\n self.roll = bone.roll\r\n if bone.parent:\r\n self.parent = bone.parent.name\r\n else:\r\n self.parent = None\r\n if self.parent:\r\n self.use_connect = bone.use_connect\r\n else:\r\n self.use_connect = False\r\n #self.matrix = bone.matrix.copy().rotation_part()\r\n (loc, rot, scale) = bone.matrix.decompose()\r\n self.matrix = rot.to_matrix()\r\n self.inverse = self.matrix.copy()\r\n self.inverse.invert()\r\n\r\n def __repr__(self):\r\n return (\"%s p %s\\n h %s\\n t %s\\n\" % (self.name, self.parent, self.head, self.tail))\r\n\r\n#\r\n# renameBones(srcRig, context):\r\n#\r\n\r\ndef renameBones(srcRig, context):\r\n from .source import getSourceBoneName\r\n\r\n srcBones = []\r\n trgBones = {}\r\n\r\n setActiveObject(context, srcRig)\r\n bpy.ops.object.mode_set(mode='EDIT')\r\n bpy.ops.object.mode_set(mode='EDIT')\r\n #print(\"Ren\", bpy.context.object, srcRig.mode)\r\n ebones = srcRig.data.edit_bones\r\n for bone in ebones:\r\n srcBones.append( CEditBone(bone) )\r\n\r\n setbones = []\r\n adata = srcRig.animation_data\r\n if adata is None:\r\n action = None\r\n else:\r\n action = adata.action\r\n for srcBone in srcBones:\r\n srcName = srcBone.name\r\n trgName = getSourceBoneName(srcName)\r\n if isinstance(trgName, tuple):\r\n print(\"BUG. Target name is tuple:\", trgName)\r\n trgName = trgName[0]\r\n eb = ebones[srcName]\r\n if trgName:\r\n if action and srcName in action.groups.keys():\r\n grp = action.groups[srcName]\r\n grp.name = trgName\r\n eb.name = trgName\r\n trgBones[trgName] = CEditBone(eb)\r\n setbones.append((eb, trgName))\r\n else:\r\n eb.name = '_' + srcName\r\n\r\n for (eb, name) in setbones:\r\n eb.name = name\r\n #createExtraBones(ebones, trgBones)\r\n bpy.ops.object.mode_set(mode='OBJECT')\r\n\r\n#\r\n# renameBvhRig(srcRig, filepath):\r\n#\r\n\r\ndef renameBvhRig(srcRig, filepath):\r\n base = os.path.basename(filepath)\r\n (filename, ext) = os.path.splitext(base)\r\n print(\"File\", filename, len(filename))\r\n if len(filename) > 12:\r\n words = filename.split('_')\r\n if len(words) == 1:\r\n words = filename.split('-')\r\n name = 'Y_'\r\n if len(words) > 1:\r\n words = words[1:]\r\n for word in words:\r\n name += word\r\n else:\r\n name = 'Y_' + filename\r\n print(\"Name\", name)\r\n\r\n srcRig.name = name\r\n adata = srcRig.animation_data\r\n if adata:\r\n adata.action.name = name\r\n return\r\n\r\n#\r\n# deleteSourceRig(context, rig, prefix):\r\n#\r\n\r\ndef deleteSourceRig(context, rig, prefix):\r\n ob = context.object\r\n setActiveObject(context, rig)\r\n bpy.ops.object.mode_set(mode='OBJECT')\r\n setActiveObject(context, ob)\r\n deleteObject(context, rig)\r\n if bpy.data.actions:\r\n for act in bpy.data.actions:\r\n if act.name[0:2] == prefix:\r\n act.use_fake_user = False\r\n if act.users == 0:\r\n bpy.data.actions.remove(act)\r\n\r\n\r\ndef deleteObject(context, ob):\r\n if context.object:\r\n bpy.ops.object.mode_set(mode='OBJECT')\r\n bpy.ops.object.select_all(action='DESELECT')\r\n ob.select_set(True)\r\n for coll in bpy.data.collections:\r\n if ob in coll.objects.values():\r\n coll.objects.unlink(ob)\r\n bpy.ops.object.delete(use_global=False)\r\n del ob\r\n\r\n#----------------------------------------------------------\r\n# Renamer\r\n#----------------------------------------------------------\r\n\r\nclass BvhRenamer(Source, Target):\r\n useAutoScale : BoolProperty(\r\n name=\"Auto Scale\",\r\n description=\"Rescale skeleton to match target\",\r\n default=True)\r\n\r\n def draw(self, context):\r\n self.layout.prop(context.scene, \"McpIncludeFingers\")\r\n self.layout.separator()\r\n Source.draw(self, context)\r\n Target.draw(self, context)\r\n self.layout.prop(self, \"useAutoScale\")\r\n if not self.useAutoScale:\r\n self.layout.prop(self, \"scale\")\r\n self.layout.separator()\r\n\r\n\r\n def rescaleRig(self, trgRig, srcRig):\r\n if not self.useAutoScale:\r\n return\r\n upleg1 = getTrgBone(\"thigh.L\", trgRig)\r\n upleg2 = getTrgBone(\"thigh_twist.L\", trgRig)\r\n if upleg2:\r\n trgScale = upleg1.length + upleg2.length\r\n else:\r\n trgScale = upleg1.length\r\n srcScale = srcRig.data.bones[\"thigh.L\"].length\r\n scale = trgScale/srcScale\r\n print(\"Rescale %s with factor %f\" % (srcRig.name, scale))\r\n self.scale = scale\r\n\r\n bpy.ops.object.mode_set(mode='EDIT')\r\n ebones = srcRig.data.edit_bones\r\n for eb in ebones:\r\n oldlen = eb.length\r\n eb.head *= scale\r\n eb.tail *= scale\r\n bpy.ops.object.mode_set(mode='OBJECT')\r\n adata = srcRig.animation_data\r\n if adata is None:\r\n return\r\n for fcu in adata.action.fcurves:\r\n words = fcu.data_path.split('.')\r\n if words[-1] == 'location':\r\n for kp in fcu.keyframe_points:\r\n kp.co[1] *= scale\r\n\r\n\r\n def renameAndRescaleBvh(self, context, srcRig, trgRig):\r\n if srcRig.McpRenamed:\r\n raise MocapError(\"%s already renamed and rescaled.\" % srcRig.name)\r\n\r\n from .t_pose import putInTPose\r\n\r\n scn = context.scene\r\n scn.frame_current = 0\r\n setActiveObject(context, srcRig)\r\n #(srcRig, srcBones, action) = renameBvhRig(rig, filepath)\r\n self.findTarget(context, trgRig)\r\n self.findSource(context, srcRig)\r\n renameBones(srcRig, context)\r\n putInTPose(srcRig, scn.McpSourceTPose, context)\r\n setInterpolation(srcRig)\r\n self.rescaleRig(trgRig, srcRig)\r\n srcRig.McpRenamed = True\r\n\r\n#----------------------------------------------------------\r\n# Object Problems\r\n#----------------------------------------------------------\r\n\r\ndef checkObjectProblems(context):\r\n problems = \"\"\r\n epsilon = 1e-2\r\n rig = context.object\r\n\r\n eu = rig.rotation_euler\r\n if abs(eu.x) + abs(eu.y) + abs(eu.z) > epsilon:\r\n problems += \"object rotation\\n\"\r\n\r\n vec = rig.scale - Vector((1,1,1))\r\n if vec.length > epsilon:\r\n problems += \"object scaling\\n\"\r\n\r\n if problems:\r\n msg = (\"BVH Retargeter cannot use this rig because it has:\\n\" +\r\n problems +\r\n \"Apply object transformations before using BVH Retargeter\")\r\n raise MocapError(msg)\r\n\r\n########################################################################\r\n#\r\n# class MCP_OT_LoadBvh(BvhOperator, MultiFile, BvhFile):\r\n#\r\n\r\nclass MCP_OT_LoadBvh(HideOperator, MultiFile, BvhFile, BvhLoader):\r\n bl_idname = \"mcp.load_bvh\"\r\n bl_label = \"Load BVH File\"\r\n bl_description = \"Load an armature from a bvh file\"\r\n bl_options = {'UNDO'}\r\n\r\n def draw(self, context):\r\n self.layout.prop(self, \"scale\")\r\n BvhLoader.draw(self, context)\r\n\r\n def run(self, context):\r\n for filepath in self.getFilePaths():\r\n rig = self.readBvhFile(context, filepath, context.scene, False)\r\n bpy.ops.object.mode_set(mode='OBJECT')\r\n rig.select_set(True)\r\n context.view_layer.objects.active = rig\r\n print(\"BVH file(s) loaded\")\r\n\r\n def invoke(self, context, event):\r\n context.window_manager.fileselect_add(self)\r\n return {'RUNNING_MODAL'}\r\n\r\n#\r\n# class MCP_OT_RenameActiveToSelected(BvhOperator):\r\n#\r\n\r\nclass MCP_OT_RenameActiveToSelected(BvhPropsOperator, IsArmature, TimeScaler, BvhRenamer):\r\n bl_idname = \"mcp.rename_active_to_selected\"\r\n bl_label = \"Rename Selected From Active\"\r\n bl_description = \"Rename bones of selected (source) armatures and scale it to fit the active (target) armature\"\r\n bl_options = {'UNDO'}\r\n\r\n def draw(self, context):\r\n BvhRenamer.draw(self, context)\r\n TimeScaler.draw(self, context)\r\n\r\n def run(self, context):\r\n scn = context.scene\r\n trgRig = context.object\r\n for srcRig in context.selected_objects:\r\n if srcRig != trgRig and srcRig.type == 'ARMATURE':\r\n self.renameAndRescaleBvh(context, srcRig, trgRig)\r\n if self.useTimeScale:\r\n self.timescaleFCurves(srcRig)\r\n bpy.ops.object.mode_set(mode='OBJECT')\r\n print(\"%s renamed\" % srcRig.name)\r\n context.view_layer.objects.active = trgRig\r\n\r\n def invoke(self, context, event):\r\n from .retarget import ensureInited\r\n ensureInited(context.scene)\r\n return BvhPropsOperator.invoke(self, context, event)\r\n\r\n#\r\n# class MCP_OT_LoadAndRenameBvh(HideOperator, ImportHelper, BvhFile):\r\n#\r\n\r\nclass MCP_OT_LoadAndRenameBvh(HideOperator, IsArmature, ImportHelper, BvhFile, BvhLoader, BvhRenamer, TimeScaler):\r\n bl_idname = \"mcp.load_and_rename_bvh\"\r\n bl_label = \"Load And Rename BVH File\"\r\n bl_description = \"Load armature from bvh file and rename bones\"\r\n bl_options = {'UNDO'}\r\n\r\n def draw(self, context):\r\n BvhLoader.draw(self, context)\r\n BvhRenamer.draw(self, context)\r\n TimeScaler.draw(self, context)\r\n\r\n def prequel(self, context):\r\n from .retarget import changeTargetData\r\n return changeTargetData(context.object, context.scene)\r\n\r\n def run(self, context):\r\n checkObjectProblems(context)\r\n scn = context.scene\r\n trgRig = context.object\r\n srcRig = self.readBvhFile(context, self.properties.filepath, scn, False)\r\n self.renameAndRescaleBvh(context, srcRig, trgRig)\r\n if self.useTimeScale:\r\n self.timescaleFCurves(srcRig)\r\n bpy.ops.object.mode_set(mode='OBJECT')\r\n srcRig.select_set(True)\r\n trgRig.select_set(True)\r\n context.view_layer.objects.active = trgRig\r\n print(\"%s loaded and renamed\" % srcRig.name)\r\n\r\n def sequel(self, context, data):\r\n from .retarget import restoreTargetData\r\n restoreTargetData(data)\r\n\r\n#----------------------------------------------------------\r\n# Initialize\r\n#----------------------------------------------------------\r\n\r\nclasses = [\r\n MCP_OT_LoadBvh,\r\n MCP_OT_RenameActiveToSelected,\r\n MCP_OT_LoadAndRenameBvh,\r\n]\r\n\r\ndef initialize():\r\n\r\n bpy.types.Object.McpRenamed = BoolProperty(default = False)\r\n\r\n for cls in classes:\r\n bpy.utils.register_class(cls)\r\n\r\n\r\ndef uninitialize():\r\n for cls in classes:\r\n bpy.utils.unregister_class(cls)\r\n","sub_path":"makehuman/mh_ws/src/retarget_bvh/load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":25728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"337620069","text":"catic = True\nwhile catic:\n enter = input(\"请输入一个数字,输入quit退出计算: \")\n enter1 = input(\"请再输入一个数字,输入quit退出计算: \")\n # while enter or enter1 != \"quit\" :\n sum = int(enter) + int(enter1)\n # print(\"这两个数字的和是: %d\" %sum)\n report = input(\"是否继续参与计算,如果是输入Yes,否则输入No :\")\n if report == \"No\":\n catic = False\n print(\"这两个数字的和是: %s + %s =%s \" % (enter, enter1, sum))\n","sub_path":"day_4_while.py","file_name":"day_4_while.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"638445758","text":"import json\nimport logging\nfrom os.path import abspath, dirname, join, exists\n\nroot_path = abspath(join(dirname(__file__)))\n\nlogger = logging.getLogger(__name__)\n\nclass ColorProfileEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, ColorProfile):\n return obj.to_encodable()\n return json.JSONEncoder.default(self, obj)\n\nclass Range:\n\n def __init__(self, min, max):\n self.min = min\n self.max = max\n\n\nclass ColorProfile:\n\n def __init__(self, camera_mode):\n\n self.camera_mode = camera_mode\n\n self.red = Range(0,255)\n self.green = Range(0,255)\n self.blue = Range(0,255)\n\n self.hsl_hue = Range(0,255)\n self.hsl_sat = Range(0,255)\n self.hsl_lum = Range(0,255)\n\n self.hsv_hue = Range(0,255)\n self.hsv_sat = Range(0,255)\n self.hsv_val = Range(0,255)\n\n\n camera_mode_filepath = join(root_path, 'color_profile_%s.json' % camera_mode)\n\n if exists(camera_mode_filepath):\n logger.info(\"loading from %s\" % camera_mode_filepath)\n with open(camera_mode_filepath, mode=\"rb\" ) as f:\n profile = json.loads(f.read())\n self.update(profile)\n\n def update(self, profile):\n\n color_profile = self\n\n color_profile.red.min = int(profile['rgb']['r']['min'])\n color_profile.red.max = int(profile['rgb']['r']['max'])\n\n color_profile.green.min = int(profile['rgb']['g']['min'])\n color_profile.green.max = int(profile['rgb']['g']['max'])\n\n color_profile.blue.min = int(profile['rgb']['b']['min'])\n color_profile.blue.max = int(profile['rgb']['b']['max'])\n\n color_profile.hsv_hue.min = int(profile['hsv']['h']['min'])\n color_profile.hsv_hue.max = int(profile['hsv']['h']['max'])\n\n color_profile.hsv_sat.min = int(profile['hsv']['s']['min'])\n color_profile.hsv_sat.max = int(profile['hsv']['s']['max'])\n\n color_profile.hsv_val.min = int(profile['hsv']['v']['min'])\n color_profile.hsv_val.max = int(profile['hsv']['v']['max'])\n\n color_profile.hsl_hue.min = int(profile['hsl']['h']['min'])\n color_profile.hsl_hue.max = int(profile['hsl']['h']['max'])\n\n color_profile.hsl_sat.min = int(profile['hsl']['s']['min'])\n color_profile.hsl_sat.max = int(profile['hsl']['s']['max'])\n\n color_profile.hsl_lum.min = int(profile['hsl']['l']['min'])\n color_profile.hsl_lum.max = int(profile['hsl']['l']['max'])\n\n\n def to_encodable(self):\n rgb = dict(\n r=dict(min=self.red.min,\n max=self.red.max),\n b=dict(min=self.blue.min,\n max=self.blue.max),\n g=dict(min=self.green.min,\n max=self.green.max)\n )\n\n hsl = dict(\n h=dict(min=self.hsl_hue.min,\n max=self.hsl_hue.max),\n s=dict(min=self.hsl_sat.min,\n max=self.hsl_sat.max),\n l=dict(min=self.hsl_lum.min,\n max=self.hsl_lum.max)\n )\n\n hsv = dict(\n h=dict(min=self.hsv_hue.min,\n max=self.hsv_hue.max),\n s=dict(min=self.hsv_sat.min,\n max=self.hsv_sat.max),\n v=dict(min=self.hsv_val.min,\n max=self.hsv_val.max)\n )\n\n return dict(camera_mode=self.camera_mode,\n rgb=rgb,\n hsv=hsv,\n hsl=hsl)\n","sub_path":"profiles/color_profile.py","file_name":"color_profile.py","file_ext":"py","file_size_in_byte":3174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"284676869","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('smskeeper', '0100_message_body'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='message',\n name='natty_result_pkl',\n field=models.TextField(null=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"peanut/smskeeper/migrations/0101_message_natty_result_pkl.py","file_name":"0101_message_natty_result_pkl.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"124055357","text":"\nimport os\nimport logging\n\n\n\n\nclass Config(object):\n\n target_project_id = os.getenv(\"TARGET_PROJECT_ID\")\n\n # Any resource with the following label will be ignored.... I think.\n exclude_key = \"terminator\"\n exclude_value = \"DontTouchMeBro\"\n\n # Path to the service account that does the work\n sa_path = os.getenv(\"SA_PATH\", './sa_json')\n\n # Keep this set to true until you are certain you are ready to run for realz\n\n dry_run = False if os.getenv(\"DRY_RUN\", \"True\").lower() == \"false\" else True\n\n\n # List of services to run on. Set to allservices to run against all.\n target_services = [x.strip() for x in os.getenv(\"TARGET_SERVICES\", \"\").split(\",\")]\n\n def destructive(self, func):\n def wrapper(*args):\n if not self.dry_run:\n func(*args)\n else:\n logging.warning(\"CONFIG: DryRun set to True which prevents destructive actions\")\n return wrapper\n","sub_path":"eraser/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"190241844","text":"import json\r\nfrom urllib.parse import urlencode\r\nimport requests\r\nfrom requests import Response\r\nimport datetime as dt\r\nfrom datetime import datetime\r\nimport pandas as pd\r\nimport time\r\n\r\n\r\ndef post_rest(url, body, headers, print_log=True, encode_require=False):\r\n if print_log:\r\n print(\"POST REQUEST - url={}, body={}\".format(url, body))\r\n if encode_require:\r\n response: Response = requests.post(url, data=urlencode(body), headers=headers)\r\n else:\r\n response: Response = requests.post(url, json=body, headers=headers)\r\n if response.status_code != 200:\r\n print(response.text)\r\n content = None\r\n else:\r\n try:\r\n content = response.json()\r\n except BaseException as e:\r\n print(response.text)\r\n content = None\r\n raise e\r\n if print_log:\r\n print(\"{} - POST RESPONSE - url={}, data={}\".format(response.status_code, url, content))\r\n return content\r\n\r\n\r\nstrategy_id = \"10\"\r\nbuy_sell = \"BUY\"\r\ncode_list = [\"DGW\", \"HAX\", 'NKG', 'PET', 'SHI', 'SMC', 'TDG']\r\n# code = \"AMD\"\r\nfor code in code_list:\r\n data_sent = {\"strategyId\": strategy_id, \"sellBuyType\": buy_sell, \"code\": code}\r\n\r\n import_response = post_rest(url='http://172.31.32.110/signals', body=data_sent, headers={})\r\n time.sleep(5)\r\n print(\"DONE : {}\".format(code))\r\n","sub_path":"send_signals_equity.py","file_name":"send_signals_equity.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"34432093","text":"import os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\nimport sys\nimport tensorflow as tf\nimport tensorflow.contrib\nfrom tensorflow.contrib.layers import fully_connected\nimport numpy as np\nfrom DataFunctions import splitData\n\n\nfilestem = sys.argv[1]\nnum_test = float(sys.argv[2])\n\n\nprint(\"--POS TAGGER 3 HIDDEN LAYERS, 250 TRAINING STEPS--\")\n\n#import array of word vectors from text file\nfeatures = np.load(filestem + \"_X.npy\")\n#import array of one-hot POS labels from text file\nlabels = np.load(filestem + \"_Y.npy\")\n\n#print the shape of each numpy array\nprint(\"FEATURES ARRAY SHAPE: \")\nprint(features.shape)\nprint(\"LABELS ARRAY SHAPE\")\nprint(labels.shape)\n\n#make sure the size of the instances and labels is the same\nassert features.shape[0] == labels.shape[0]\n\nfeatures_train, features_test = splitData(num_test, features)[0], splitData(num_test, features)[1]\n\nlabels_train, labels_test = splitData(num_test, labels)[0], splitData(num_test, labels)[1]\n\nnum_inputs = features.shape[1]\nnum_labels = labels.shape[1]\nnum_hidden = int(num_inputs/10)\nnum_hidden_total = num_hidden + 150\n\nprint(\"FIRST HIDDEN LAYER WILL HAVE\", num_hidden, \"UNITS\")\n\nprint(\"REMAINING HIDDEN LAYERS WILL HAVE 50 UNITS\")\n\n#X and Y are Tensorflow placeholders for the input and correct label values in the Neural Net model\nX = tf.placeholder(tf.float32, shape=[None, num_inputs], name=\"inputs\")\nY = tf.placeholder(tf.float32, shape=[None, num_labels], name=\"labels\")\n\n#Create weight and bias vectors for the model\nwith tf.name_scope(\"dnn\"):\n hidden1 = fully_connected(X, num_hidden, scope=\"hidden1\")\n hidden2 = fully_connected(hidden1, 50, scope=\"hidden2\")\n hidden3 = fully_connected(hidden2, 50, scope=\"hidden3\")\n output = fully_connected(hidden3, num_labels, scope=\"outputs\", activation_fn=None)\n\n#use Tensorflow's cross entropy as a loss function (recommended by Tensorflow)\ncross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=Y, logits=output))\n\n#training will be done through gradient descent minimizing cross entropy\ntrain_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n\n#initiate Tensorflow session\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n\n for i in range(250):\n train_step.run(feed_dict={X: features_train, Y: labels_train})\n\n correct_prediction = tf.equal(tf.argmax(Y,1), tf.argmax(output,1))\n\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n #print the accuracy when the model is used on the test dataset\n print(\"Test Set Accuracy: \", accuracy.eval(feed_dict={X: features_test, Y: labels_test}))","sub_path":"FinalProject/Scikit-Tensorflow/TensorPOSDeep.py","file_name":"TensorPOSDeep.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"469525494","text":"# mean human length, optimal length, old MAG attributes\nimport json, math\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MaxNLocator\nimport numpy as np\nfrom rushhour import json_to_ins, constuct_mag\nfrom scipy import stats\n\nlen_file = '/Users/chloe/Documents/RushHour/data/paths.json'\nins_file = '/Users/chloe/Documents/RushHour/data/data_adopted/'\n# sorted according to optimal length\nall_instances = ['prb8786', 'prb11647', 'prb21272', 'prb13171', 'prb1707', 'prb23259', 'prb10206', 'prb2834', 'prb28111', 'prb32795', 'prb26567', 'prb14047', 'prb14651', 'prb32695', 'prb29232', 'prb15290', 'prb12604', 'prb20059', 'prb9718', 'prb29414', 'prb22436', 'prb62015', 'prb38526', 'prb3217', 'prb34092', 'prb12715', 'prb54081', 'prb717', 'prb31907', 'prb42959', 'prb79230', 'prb14898', 'prb62222', 'prb68910', 'prb33509', 'prb46224', 'prb47495', 'prb29585', 'prb38725', 'prb33117', 'prb20888', 'prb55384', 'prb6671', 'prb343', 'prb68514', 'prb29600', 'prb23404', 'prb19279', 'prb3203', 'prb65535', 'prb14485', 'prb34551', 'prb72800', 'prb44171', 'prb1267', 'prb29027', 'prb24406', 'prb58853', 'prb24227', 'prb45893', 'prb25861', 'prb15595', 'prb54506', 'prb48146', 'prb78361', 'prb25604', 'prb46639', 'prb46580', 'prb10166', 'prb57223']\nout_dir = '/Users/chloe/Documents/RushHour/figures/len_MAG_old_scatter.png'\nout_dir_1 = '/Users/chloe/Documents/RushHour/figures/MAGold_vs_len_scatter.png'\ncorr_out_dir = '/Users/chloe/Documents/RushHour/data/len_MAG_old_corr.npy'\np_out_dir = '/Users/chloe/Documents/RushHour/data/len_MAG_old_p.npy'\ndata = []\nmag_node_dict = {}\nmag_edge_dict = {}\nhumanlen_dict = {}\nmean_dict = {}\noptimal_dict = {}\nall_human_len = []\ny_human_err = []\n\n# preprocess human & optimal len dict\nfor i in range(len(all_instances)):\n\thumanlen_dict[all_instances[i] + '_count'] = 0\n\thumanlen_dict[all_instances[i]+ '_len'] = 0\n\tall_human_len.append([])\n\tmean_dict[all_instances[i]] = 0\n\toptimal_dict[all_instances[i]] = 0\nwith open(len_file) as f:\n\tfor line in f:\n\t\tdata.append(json.loads(line))\nfor i in range(0, len(data)): # iterate through every subject trial\n\tline = data[i]\n\tinstance = line['instance']\n\tcomplete = line['complete']\n\thuman_len = int(line['human_length'])\n\topt_len = int(line['optimal_length'])\n\tif complete == 'False':\n\t\tcontinue\n\telse:\n\t\thumanlen_dict[instance + '_count'] += 1\n\t\thumanlen_dict[instance + '_len'] = humanlen_dict[instance + '_len'] + human_len\n\t\tins_index = all_instances.index(instance)\n\t\tall_human_len[ins_index].append(human_len)\n\t\toptimal_dict[instance] = opt_len\nfor i in range(len(all_instances)): # calculate mean human len and std\n\tif humanlen_dict[all_instances[i] + '_count'] == 0:\n\t\tmean_dict[all_instances[i]] = 0\n\t\tcontinue\n\telse:\n\t\tmean_dict[all_instances[i]] = humanlen_dict[all_instances[i] + '_len'] / humanlen_dict[all_instances[i] + '_count']\n\ty_human_err.append(np.std(all_human_len[i]) / math.sqrt(humanlen_dict[all_instances[i] + '_count']))\n\tprint(all_human_len[i])\n\t#if np.std(all_human_len[i]) > 40:\n\t#\tprint(np.std(all_human_len[i]))\n\n# process mag attributes\nfor i in range(len(all_instances)):\n\tcur_ins = all_instances[i]\n\tins_dir = ins_file + all_instances[i] + '.json'\n\tcur_ins_obj = json_to_ins(ins_dir)\n\tcur_mag, cur_nodes = constuct_mag(cur_ins_obj)\n\tnum_nodes = len(cur_nodes)\n\tnum_edges = sum([len(nd) for nd in cur_mag.values()])\n\tmag_node_dict[cur_ins] = num_nodes\n\tmag_edge_dict[cur_ins] = num_edges\n# print special results\n# print('now print interesting results\\n')\n# for i in range(len(all_instances)):\n# \tins = all_instances[i]\n# \tm = mean_dict[ins]\n# \topt = optimal_dict[ins]\n# \tn_nodes = mag_node_dict[ins]\n# \tn_edge = mag_edge_dict[ins]\n# \tif m >= opt * 3:\n# \t\tprint(ins + ' optimal = ' + str(opt) + ', human = ' + str(m) + ', #nodes = ' + str(n_nodes) + ', #edge = ' + str(n_edge))\n\n# generate value lists\ny_human = []\ny_opt = []\ny_nodes = []\ny_edges = []\nfor i in range(len(all_instances)):\n\ty_human.append(mean_dict[all_instances[i]])\n\ty_opt.append(optimal_dict[all_instances[i]])\n\ty_nodes.append(mag_node_dict[all_instances[i]])\n\ty_edges.append(mag_edge_dict[all_instances[i]])\n\n# generate figure\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.bar(np.arange(len(all_instances)), y_human, alpha=0.9, color='orange', label='human')\nax.errorbar(np.arange(len(all_instances)), y_human, yerr=y_human_err, alpha=0.5, c='red', fmt='none')\nax.bar(np.arange(len(all_instances)), y_opt, alpha=0.65, color='green', label='optimal')\nax.set_xticklabels([])\nax.yaxis.set_major_locator(MaxNLocator(20))\nax.grid(axis = 'y', alpha = 0.3)\nax.set_facecolor('0.98')\nax.set_xlabel('Puzzles')\nax.set_ylabel('#moves, #nodes, #edge')\nscatter1 = plt.scatter(np.arange(len(all_instances)), y_nodes, s=5, color='blue', label='#nodes')\nscatter2 = plt.scatter(np.arange(len(all_instances)), y_edges, s=5, color='red', label='#edges')\nscatter1.set_zorder(2)\nscatter2.set_zorder(2)\n# plt.plot(np.arange(len(all_instances)), y_nodes, color='blue', label='#nodes')\n# plt.plot(np.arange(len(all_instances)), y_edges, color='red', label='#edges')\nplt.title('Human Length, Optimal Length, #old MAG Nodes, #old MAG Edges')\nplt.legend(loc='upper left')\n#plt.show()\nplt.savefig(out_dir)\nplt.close()\n\n\n# plot nodes vs len, edges vs len\nfig, axarr = plt.subplots(2,2)\naxarr[0,0].scatter(y_nodes, y_human, color='orange')\n# axarr[0,0].set_xlabel('#nodes')\naxarr[0,0].set_ylabel('human_len')\naxarr[1,0].scatter(y_nodes, y_opt, color='green')\naxarr[1,0].set_xlabel('#nodes')\naxarr[1,0].set_ylabel('opt_len')\naxarr[0,1].scatter(y_edges, y_human, alpha=0.8, color='red')\n# axarr[0,1].set_xlabel('#edges')\n# axarr[0,1].set_ylabel('human_len')\naxarr[1,1].scatter(y_edges, y_opt, alpha=0.8, color='blue')\naxarr[1,1].set_xlabel('#edges')\n# axarr[1,1].set_ylabel('opt_len')\naxarr[0,0].set_title('new MAG #nodes vs len, #edges vs len', loc='left')\n#plt.show()\nplt.savefig(out_dir_1)\nplt.close()\n\n\n# calculate pearson correlation and p-value\ncorr_list = []\np_list = []\ncorr, p = stats.spearmanr(y_human, np.array(y_nodes)+np.array(y_edges))\ncorr_list.append(corr)\np_list.append(p)\nprint(\"SP-corr human_len & #nodes+#edges: %s, P-value is %s\\n\" % (str(format(corr, '.6f')), str(format(p, '.6f'))))\ncorr, p = stats.spearmanr(y_opt, np.array(y_nodes)+np.array(y_edges))\ncorr_list.append(corr)\np_list.append(p)\nprint(\"SP-corr opt_len & #nodes+#edges: %s, P-value is %s\\n\" % (str(format(corr, '.6f')), str(format(p, '.6f'))))\ncorr, p = stats.spearmanr(y_human, y_nodes)\ncorr_list.append(corr)\np_list.append(p)\nprint(\"SP-corr human_len & #nodes: %s, P-value is %s\\n\" % (str(format(corr, '.6f')), str(format(p, '.6f'))))\ncorr, p = stats.spearmanr(y_human, y_edges)\ncorr_list.append(corr)\np_list.append(p)\nprint(\"SP-corr human_len & #edges: %s, P-value is %s\\n\" % (str(format(corr, '.6f')), str(format(p, '.6f'))))\ncorr, p = stats.spearmanr(y_opt, y_nodes)\ncorr_list.append(corr)\np_list.append(p)\nprint(\"SP-corr opt_len & #nodes: %s, P-value is %s\\n\" % (str(format(corr, '.6f')), str(format(p, '.6f'))))\ncorr, p = stats.spearmanr(y_opt, y_edges)\ncorr_list.append(corr)\np_list.append(p)\nprint(\"SP-corr opt_len & #edges: %s, P-value is %s\\n\" % (str(format(corr, '.6f')), str(format(p, '.6f'))))\nnp.save(corr_out_dir, corr_list)\nnp.save(p_out_dir, p_list)\n\n'''\nresults: \n\nP-corr human_len & #nodes+#edges: 0.342881, P-value is 0.003664\n\nP-corr opt_len & #nodes+#edges: 0.298504, P-value is 0.012073\n\nP-corr human_len & #nodes: 0.298775, P-value is 0.011992\n\nP-corr human_len & #edges: 0.353791, P-value is 0.002660\n\nP-corr opt_len & #nodes: 0.263168, P-value is 0.027727\n\nP-corr opt_len & #edges: 0.306560, P-value is 0.009847\n\nSP-corr human_len & #nodes+#edges: 0.362871, P-value is 0.002020\n\nSP-corr opt_len & #nodes+#edges: 0.296653, P-value is 0.012642\n\nSP-corr human_len & #nodes: 0.338189, P-value is 0.004191\n\nSP-corr human_len & #edges: 0.368244, P-value is 0.001710\n\nSP-corr opt_len & #nodes: 0.268502, P-value is 0.024612\n\nSP-corr opt_len & #edges: 0.304543, P-value is 0.010368\n\n'''\n\n\n","sub_path":"scripts/len_MAG_old.py","file_name":"len_MAG_old.py","file_ext":"py","file_size_in_byte":7943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"52158346","text":"import socket\nimport time\nimport threading\n\n\ndef printer(lock):\n global connected_to\n global connected\n while True:\n time.sleep(0.3)\n try:\n with lock:\n in_data = client.recv(1024).decode().split('|')\n if not in_data[0]:\n continue\n if in_data[0] == 'disconnected_from_user':\n client.send(bytes('|{}'.format(connected_to), 'UTF-8'))\n continue\n if in_data and in_data[1].isdigit():\n connected_to = in_data[1]\n connected = True\n print(in_data[0])\n except Exception as e:\n print(e)\n\n\nSERVER = \"127.0.0.1\"\nPORT = 8080\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nuserName = input('Your name: ')\nuserType = 'driver'\ncarBrand = input('Car brand: ') or ''\ncarModel = input('Car model: ') or ''\ncarPlate = input('Car plate: ') or ''\nlat = input('Latitude: ')\nlon = input('Longitude: ')\n\nclient.connect((SERVER, PORT))\nclient.sendall(bytes('{}|{}|{}|{}|{}|{}|{}'.format(\n userType, userName,\n carBrand, carModel, carPlate,\n lat, lon\n), 'UTF-8'))\n\nconnected_to = ''\nconnected = False\n\nlock = threading.Lock()\np = threading.Thread(target=printer, args=(lock,), daemon=True)\np.start()\n\nwhile True:\n out_data = input()\n client.sendall(bytes('{}|{}'.format(out_data, connected_to), 'UTF-8'))\n if out_data == 'exit':\n break\nclient.close()\n","sub_path":"Client/driver_client.py","file_name":"driver_client.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"130029162","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n readme = fh.read()\n\nsetuptools.setup(\n name = \"alphaorm\",\n version = \"0.0.111\",\n author = \"Claret Nnamocha\",\n author_email = \"devclareo@gmail.com\",\n description = \"A nice database orm written in python\",\n long_description = readme,\n long_description_content_type = \"text/markdown\",\n url = \"https://github.com/alpha-orm/python-alpha-orm\",\n packages = setuptools.find_packages(),\n keywords = ['database', 'orm', 'db', 'database-orm'],\n classifiers = [\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n python_requires = '>=3.6'\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"364088329","text":"\"\"\"\nCreated on Tue Aug 12 15:56:00 2020\n\n@author: jan-philippfranken\n\"\"\"\n###############################################################################\n########################### Tree Regrower ###################################\n###############################################################################\n\n####################### General imports #######################################\nimport random as rd\nimport copy\nimport pandas as pd\n\n####################### Custom imports ########################################\nfrom recode_rule_to_list import rule_translator\n\n\nclass tree_regrower(rule_translator):\n '''this fellow does some regrowing to a given tree'''\n def __init__self(self):\n self.__init__self(self)\n\n def regrow_tree(self, t, prod, replacements,non_terminal_list = ['S','A','C','B']):\n '''this function regrows a tree based on an input tree and returns sufficient information for growing new sub tree'''\n # first getting all information from initial tree\n productions = copy.deepcopy(prod)\n t_rule = t['rule'] # initial rule\n t_prec = t['prec']\n # t_prec = pd.read_csv('test.csv')\n t_prod = t_prec['from']\n t_bv = t['bv'] # initial bound variables\n # t_bv = ['x1']\n t_prime_bv = t_bv.copy() # new bound variables (might be changed later)\n t_list = self.string_to_list(t_rule) # transforming rule into list of list\n # t_list = ['Z.forall', ['lambda', 'x1', ':', 'Z.not_operator', ['Z.not_operator', ['Z.or_operator', ['Z.and_operator', ['Z.or_operator', ['Z.not_operator', ['Z.not_operator', ['Z.equal', ['x1', 'green', 'colour']]], 'Z.not_operator', ['Z.equal', ['x1', 'green', 'colour']]], 'Z.equal', ['x1', 'blue', 'colour']], 'Z.not_operator', ['Z.equal', ['x1', 'blue', 'colour']]]]], 'X']]\n ind_nested = self.get_inds(t_list) # gettinng elements and all nested indexes\n # print(ind_nested)\n # print(t_list)\n\n # then sampling new node and replacements\n t_prod_inds = list(range(0, len(t_prod)))\n nt_inds = [index for index,prod in zip(t_prod_inds,t_prod) if prod in non_terminal_list]\n nt_ind = rd.choice(nt_inds) # selecting random nonterminal index from which tree will be regrown\n # nt_ind = 5/\n # nt_in/d = 4\n nt = t_prod[nt_ind]\n\n# # print(nt_ind)\n# # print('indaabove')\n\n if len(t_bv) == 1:\n productions[nt] = ['Z.equal(x1, D)', 'K(x1, E)']\n\n\n p_ind = rd.choice(list(range(0, len(productions[nt]))))\n # p_ind = 0\n# # print(p_ind)\n# # print('pindabove')\n new_p = productions[nt][p_ind]\n new_prod_prob = 1/len(productions[nt])\n cut = 0 # default variable that might change to 1 if nt is \"S\" (since then more needs to be removed from t_prec, see below)\n\n # now checking which nt was selected and reacting accordinngly\n if nt == \"B\" or nt == \"C\":\n b_inds = [index for index,prod in zip(t_prod_inds,t_prod) if prod in [nt]] # getting indexes for B only\n n_b_select = b_inds.index(nt_ind) # getting the exact B (ie which one from many has been chosen if many are available)\n # now use the above to get the index of the selected be from the lists including all features\n all_inds = list(range(0, len(ind_nested)))\n b_inds = [index for index,prod in zip(all_inds,ind_nested) if prod in replacements[nt]]\n spec_ind = ind_nested[b_inds[n_b_select]+1]\n spec_ind_plus = spec_ind.copy()\n spec_ind_plus[len(spec_ind_plus)-1] += 1\n\n\n # ensures that no nonsense comparisons can be made\n bound_vars = list(range(1, len(t_prime_bv)+1))\n for ch in [\"N\", \"O\"]:\n if ch in new_p:\n rand_ind = bound_vars.index(rd.choice(bound_vars))\n new_p = new_p.replace(ch, str(bound_vars[rand_ind]))\n if len(t_bv) >= 2:\n del(bound_vars[rand_ind])\n\n\n # now transforming the indeces for the deeplist into strings to then replace items in the deeplist\n spec_ind_l = [str([ind]) for ind in spec_ind]\n spec_ind_plus_l = [str([ind]) for ind in spec_ind_plus]\n spec_ind_s = ''.join(spec_ind_l)\n spec_ind_plus_s = ''.join(spec_ind_plus_l)\n t_prime_list = copy.deepcopy(t_list)\n\n # replacing part of list with new part and removing the part immediately following the initial part\n exec('t_prime_list' + spec_ind_s + '=' + 'new_p')\n del_in_prec = eval('t_prime_list' + spec_ind_plus_s) # quickly getinng the items that need to be deleted\n exec('del(t_prime_list' + spec_ind_plus_s + ')')\n\n # finally we need to get t_prime rule and create t_prime prec\n t_prec_to = list(t_prec['to'])\n t_prec_from = list(t_prec['from'])\n t_prime_rule = self.list_to_string(t_prime_list)\n t_prime_prec = t_prec\n t_prime_prec.at[nt_ind, 'from'] = nt\n t_prime_prec.at[nt_ind, 'to'] = new_p\n t_prime_prec.at[nt_ind, 'toix'] = float(p_ind)\n t_prime_prec.at[nt_ind, 'li'] = new_prod_prob\n# # print(t_prime_prec['to'])\n # some items from t_prime_prec need to be deleted (those that were only used in the initial t_prec); might be nested list\n del_in_prec = self.get_list(del_in_prec)\n del_in_prec_2 = [str(i) if isinstance(i, int) else \"'\" + i + \"'\" if isinstance(i, str) and '.' not in i else i for i in del_in_prec]\n del_in_prec = del_in_prec + del_in_prec_2\n prec_inds = list(range(0, len(t_prec['to'])))\n\n # need to apply some operations to t_prec_to first\n to_ind = 0\n for to in t_prec_to:\n for ch in [\"(\"]:\n if isinstance(to, str):\n if ch in to:\n cut = to.index(ch)\n to = to[:cut]\n to_ind += 1\n\n # now we can identify which elements need ot be dropped\n drop_inds = [i for i,to in zip(prec_inds,t_prec_to) if to in del_in_prec and i > nt_ind]\n drop_inds_new = []\n for i in drop_inds:\n if t_prec_from[i] != \"M\":\n drop_inds_new.append(i)\n\n# # print(t_prec_to)\n # if isinstance(t_prime_prec['to'][nt_ind +1], str):\n # if t_prime_prec['to'][nt_ind +1][0] == \"Z\":\n # if t_prime_prec['to'][nt_ind +2] not in productions[\"G\"] or t_prime_prec['to'][nt_ind +2] not in productions[\"I\"]:\n # drop_inds.append(nt_ind+1)\n\n drop_inds_new = list(set(drop_inds_new)) # getting rid of duplicates\n# # print(drop_inds_new)\n\n if nt == \"C\" or \"B\":\n t_prime_prec = t_prime_prec.drop(drop_inds_new)\n\n # elif nt == \"B\":\n # t_prime_prec = t_prime_prec.loc[:nt_ind:]\n\n\n return {\"t_prime_rule\": t_prime_rule, \"t_prime_bv\": t_prime_bv, \"t_prime_prec\": t_prime_prec, \"nt_ind\": nt_ind, \"nt\": nt}\n\n\n # this is a bit hacky since it does something to the number of bound variables\n elif nt == 'A':\n t_prime_list = t_list\n if nt_ind == 5:\n for ch in [\"S\"]:\n if ch in new_p:\n new_p = new_p.replace(ch, \"B\")\n t_prime_list[1][4][4][3] = new_p\n del(t_prime_list[1][4][4][4])\n elif nt_ind == 3:\n t_prime_bv = t_prime_bv[:2]\n t_prime_list[1][4][3] = new_p\n del(t_prime_list[1][4][4])\n elif nt_ind == 1:\n t_prime_bv = t_prime_bv[:1]\n t_prime_list[1][3] = new_p\n# # # print('hi')\n del(t_prime_list[1][4])\n\n # also for S but simpler\n elif nt == 'S':\n # cut=1\n t_prime_list = t_list\n sum_s = sum([1 for a in t_prod if a in [\"S\"]])\n if nt_ind == 4:\n t_prime_bv = t_prime_bv[:3]\n for ch in [\"A\"]:\n if ch in new_p:\n new_p = new_p.replace(ch, \"B\")\n for ch in [\"N\"]:\n if ch in new_p:\n new_p = new_p.replace(ch, \"3\")\n t_prime_list[1][4][3] = new_p\n del(t_prime_list[1][4][4])\n elif nt_ind == 2:\n t_prime_bv = t_prime_bv[:2]\n for ch in [\"N\"]:\n if ch in new_p:\n new_p = new_p.replace(ch, \"2\")\n t_prime_list[1][3] = new_p\n del(t_prime_list[1][4])\n elif nt_ind == 0:\n t_prime_prec = pd.DataFrame({\"from\": [], \"to\": [], \"toix\": [], \"li\": []})\n t_prime_rule = \"S\"\n t_prime_bv = []\n t_prime_list[0] = \"S\"\n del(t_prime_list[1])\n return {\"t_prime_rule\": t_prime_rule, \"t_prime_bv\": t_prime_bv, \"t_prime_prec\": t_prime_prec, \"nt_ind\": nt_ind, \"nt\": nt}\n\n\n t_prime_rule = self.list_to_string(t_prime_list)\n t_prime_prec = copy.deepcopy(t_prec)\n t_prime_prec.at[nt_ind, 'from'] = nt\n t_prime_prec.at[nt_ind, 'to'] = new_p\n t_prime_prec.at[nt_ind, 'toix'] = float(p_ind)\n t_prime_prec.at[nt_ind, 'li'] = new_prod_prob\n\n if nt == \"S\" or nt == \"A\":\n t_prime_rule = self.list_to_string(t_prime_list)\n t_prime_prec = t_prime_prec.loc[:nt_ind-cut:]\n return {\"t_prime_rule\": t_prime_rule, \"t_prime_bv\": t_prime_bv, \"t_prime_prec\": t_prime_prec, \"nt_ind\": nt_ind, \"nt\": nt}\n\n\n return {\"t_prime_rule\": t_prime_rule, \"t_prime_bv\": t_prime_bv, \"t_prime_prec\": t_prime_prec, \"t_prime_list\": t_prime_list}\n\n","sub_path":"model/create_plots/tree_regrower.py","file_name":"tree_regrower.py","file_ext":"py","file_size_in_byte":9968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"498055625","text":"# ======================================================================================================================\n# monte_carlo_run.py\n# Jeff Bennett, jab6ft@virginia.edu\n#\n# This script provides an example of using Temoatools to build and run Monte Carlo simluations using Temoa models.\n# The approach remains from the baselines example to build models from two .xlsx files. The first\n# provides all possible system and technology data (named data.xlsx in the example). The second specifies scenarios\n# that make use of specified combinations of technology data (named Scenarios.xlsx in the example).\n#\n# Required inputs (lines 106-116)\n# temoa_path - path to Temoa directory that contains temoa_model/\n# project_path - path to directory that contains this file (expects a subdirectory within named data)\n# modelInputs_XLSX_list - list that contains the *.xlsx file with model data (within data subdirectory)\n# scenarioInputs - identifies which technologies are used for each scenario (within data subdirectory)\n# scenarioNames_list - names of each scenario to perform a monte carlo simulation with (named within ScenarioInputs)\n# sensitivityInputs - identifies which parameters to vary in monte carlo study\n# sensitivityMultiplier - percent perturbation for each sensitivity variable\n# ncpus - number of cores to use, -1 for all, -2 for all but one, replace with int(os.getenv('NUM_PROCS')) for cluster\n# solver - leave as '' to use system default, other options include 'cplex', 'gurobi'\n# n_cases - number of simulations to run\n#\n# Outputs (paths are all relative to project_path)\n# data/data.db - universal database that contains input data in a .sqlite database\n# configs/config_*.txt - a separate configuration file for each Temoa run\n# databases/*.dat - a separate .sqlite database for each Temoa run\n# databases/*.sqlite - a separate .sqlite database for each Temoa run\n# ======================================================================================================================\nimport os\nfrom joblib import Parallel, delayed, parallel_backend\nimport pandas as pd\nimport temoatools as tt\n\n\n# =======================================================\n# Function to evaluate a single model\n# =======================================================\ndef evaluateMonteCarlo(modelInputs, scenarioXLSX, scenarioName, combined_name, monte_carlo_case, temoa_path,\n project_path, solver,\n cases, caseNum):\n # Unique filename\n model_filename = combined_name + '_' + monte_carlo_case + '_' + scenarioName + '_' + str(caseNum)\n\n # Prepare monte carlo inputs\n cols = ['type', 'variable', 'tech', caseNum]\n MCinputs = cases.loc[:, cols]\n MCinputs = MCinputs.rename(columns={caseNum: 'value'})\n\n # Build Model\n tt.build(modelInputs, scenarioXLSX, scenarioName, model_filename, MCinputs=MCinputs, path=project_path,\n mc_type='values')\n\n # Run Model\n error = tt.run(model_filename, saveEXCEL=False, temoa_path=temoa_path, debug=True, solver=solver)\n\n # Analyze Model (w/ default monte carlo analysis function)\n if not error:\n folder = os.path.join(project_path, 'databases')\n db = model_filename + '.sqlite'\n results = tt.analyze_db(folder, db, scenario=scenarioName, iteration=caseNum, switch='tech', tod_analysis=True,\n debug=False)\n\n # store uncertain variables and their values\n for i in range(len(MCinputs)):\n mc_var = MCinputs.loc[i, 'tech'] + '-' + MCinputs.loc[i, 'variable']\n results.loc[:, mc_var] = MCinputs.loc[i, 'value']\n else:\n results = pd.Dataframe()\n\n return results\n\n\nif __name__ == '__main__':\n\n # =======================================================\n # Model Inputs\n # =======================================================\n temoa_path = os.path.abspath('../../../temoa-energysystem')\n project_path = os.getcwd()\n monte_carlo_inputs = 'monte_carlo_inputs.xlsx'\n monte_carlo_cases = ['lowBio', 'highBio'] # each case corresponds with a list in scenarioNames\n scenarioInputs = 'scenarios_emerging_tech.xlsx'\n scenarioNames = ['woEmerg_wFossil', 'woEmerg_woFossil',\n 'wEmerg_wFossil', 'wEmerg_woFossil']\n\n n_baseline = 1\n n_uncertainty = 100\n n_iterations = [n_baseline, n_baseline,\n n_uncertainty, n_uncertainty]\n\n modelInputs_primary = 'data_va_noEmissionLimit.xlsx'\n modelInputs_secondary = ['data_emerging_tech.xlsx', 'data_H2_VFB.xlsx']\n\n emission_inputs = ['emissionLimit_decarb_2050.xlsx']\n emission_names = ['2050']\n\n ncpus = 1 # default, unless otherwise specified in sbatch script\n solver = '' # leave blank to let temoa decide which solver to use of those installed\n\n # =======================================================\n # begin script\n # =======================================================\n try:\n ncpus = int(os.getenv('NUM_PROCS')) # try to use variable defined in sbatch script\n except:\n ncpus = ncpus # otherwise default to this number of cores\n\n # =======================================================\n # Create directories - best completed before using multiprocessing\n # =======================================================\n mc_dir = 'monte_carlo'\n tt.create_dir(project_path=project_path, optional_dir=mc_dir)\n\n # =======================================================\n # iterate through emission_inputs\n # =======================================================\n for emission_input, emission_name in zip(emission_inputs, emission_names):\n # naming convention\n combined_name = emission_name\n combined_file = combined_name + '.xlsx'\n\n # files\n files = [emission_input]\n for modelInput in modelInputs_secondary:\n if len(modelInput) > 0:\n files.append(modelInput)\n\n # combine files\n tt.combine(project_path=project_path, primary=modelInputs_primary,\n data_files=files,\n output=combined_file)\n\n # =======================================================\n # Move modelInputs_XLSX to database\n # =======================================================\n modelInputs = tt.move_data_to_db(combined_file, path=project_path)\n\n # ====================================\n # Perform Simulations\n # ====================================\n\n for monte_carlo_case in monte_carlo_cases:\n for scenarioName, iterations in zip(scenarioNames, n_iterations):\n # Create monte carlo cases\n os.chdir(os.path.join(project_path, 'data'))\n cases = tt.createMonteCarloCases_distributions(monte_carlo_inputs, monte_carlo_case, iterations)\n os.chdir(project_path)\n\n # Save cases\n os.chdir(os.path.join(project_path, mc_dir))\n cases.to_csv('MonteCarloInputs_' + monte_carlo_case + '_' + scenarioName + '_' + combined_name + '.csv',\n index=False)\n os.chdir(project_path)\n\n # Perform simulations in parallel\n with parallel_backend('multiprocessing', n_jobs=ncpus):\n outputs = Parallel(n_jobs=ncpus, verbose=5)(\n delayed(evaluateMonteCarlo)(modelInputs, scenarioInputs, scenarioName, combined_name,\n monte_carlo_case, temoa_path,\n project_path,\n solver, cases, caseNum) for caseNum in range(iterations))\n\n # Save results to a csv\n os.chdir(os.path.join(project_path, mc_dir))\n df = pd.DataFrame()\n for output in outputs:\n df = df.append(output, ignore_index=True)\n df.to_csv('MonteCarloResults_' + monte_carlo_case + '_' + scenarioName + '_' + combined_name + '.csv')\n os.chdir(project_path)\n","sub_path":"projects/va_emerging_tech/jbennett_dissertation/vet_run_monte_carlo.py","file_name":"vet_run_monte_carlo.py","file_ext":"py","file_size_in_byte":8156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"196263097","text":"from datetime import datetime\n\n# All case types have reports from year 1960 up until the current year.\nstart_year = 1960\nend_year = datetime.today().year\n\n# This is the base url to retrieve files.\nbase_url = \"https://oeaaa.faa.gov/oeaaa/external/ExternalCaseDownloadServlet?emaNelif=\"\n\n# These are the directory paths to where the CSV files will be saved.\nbase_path = \"./data\"\non_air_support_path = f\"{base_path}/on_air_support\"\noff_air_support_path = f\"{base_path}/off_air_support\"\non_off_air_support_frequencies_path = f\"{base_path}/on_off_air_support_frequencies\"\n\n# Cases' are use to get reports by case_type, year, region, and download_type.\ncases = (\n # On Airport Cases:\n {\n \"case_type\": \"OnAirport\",\n \"region\": [\"AAL\", \"ACE\", \"AEA\", \"AGL\", \"ANE\", \"ANM\", \"ASO\", \"ASW\", \"AWP\"],\n \"download_type\": \"List.gzip\",\n \"path\": on_air_support_path\n },\n # Off Airport Cases:\n {\n \"case_type\": \"OffAirport\",\n \"region\": [\"AAL\", \"ACE\", \"AEA\", \"AGL\", \"ANE\", \"ANM\", \"ASO\", \"ASW\", \"AWP\", \"WTE\", \"WTW\"],\n \"download_type\": \"List.gzip\",\n \"path\": off_air_support_path\n },\n # On Airport Cases' Frequencies:\n {\n \"case_type\": \"OnAirport\",\n \"region\": [\"AAL\", \"ACE\", \"AEA\", \"AGL\", \"ANE\", \"ANM\", \"ASO\", \"ASW\", \"AWP\"],\n \"download_type\": \"FList.gzip\",\n \"path\": on_off_air_support_frequencies_path\n },\n # Off Airport Cases' Frequencies:\n {\n \"case_type\": \"OffAirport\",\n \"region\": [\"AAL\", \"ACE\", \"AEA\", \"AGL\", \"ANE\", \"ANM\", \"ASO\", \"ASW\", \"AWP\", \"WTE\", \"WTW\"],\n \"download_type\": \"FList.gzip\",\n \"path\": on_off_air_support_frequencies_path\n }\n)\n","sub_path":"src/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"91007671","text":"# this program will print a user specified amount\n# of random numbers to the random_numbers.txt file\n\n# import the random module\nimport random\n\n# state the variables used\nnum_of_rand = 0\nrandom_num = 0\n\n# state the constants\nRAND_MAX = 500\n\ndef main():\n # create variable for user input\n num_of_rand = int( input( \"Enter amount of random numbers: \" ) )\n\n # open the file\n infile = open( 'random_numbers.txt', 'w' )\n\n # randomize number, writes to file as number var\n # gets too num_of_rand iterations\n for number in range( 1, num_of_rand+1 ):\n random_num = random.randint( 1, RAND_MAX ) \n infile.write( str( random_num ) + '\\n' )\n\n # close the file\n infile.close()\n print( \"Saved in the random_numbers.txt file.\" ) \n\n# call the main function\nmain()\n","sub_path":"rand_file_writer.py","file_name":"rand_file_writer.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"432988980","text":"import numpy as np\nimport clify\nimport argparse\n\nfrom config import rl_config as config\n\nfrom dps.env import ga_no_modules, ga_no_classifiers, ga_no_transformations\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--ablation\", default=\"no_modules\", choices=\"no_modules no_classifiers no_transformations\".split())\nparser.add_argument(\"--search\", action=\"store_true\")\nargs, _ = parser.parse_known_args()\n\nif args.ablation == 'no_modules':\n config.update(ga_no_modules.config_delta)\n\nelif args.ablation == 'no_classifiers':\n config.update(ga_no_classifiers.config_delta)\n\nelif args.ablation == 'no_transformations':\n config.update(ga_no_transformations.config_delta)\n\nelse:\n raise Exception(\"NotImplemented\")\n\nconfig.update(ablations=args.ablation, reductions=\"sum\")\n\n\nif args.search:\n config.n_train = 2**10\n grid = dict(lr_schedule=[1e-3, 1e-4, 1e-5], value_weight=[0, 1])\nelse:\n grid = dict(n_train=2**np.arange(6, 18, 2))\n\n\nfrom dps.hyper import build_and_submit, default_host_pool\nclify.wrap_function(build_and_submit)(\n config=config, distributions=grid, n_param_settings=None, host_pool=default_host_pool)\n","sub_path":"scripts/iclr_2018/rl_ablations.py","file_name":"rl_ablations.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"599793993","text":"import speed_dreams as sd\n\ndef initMemory():\n print(\"Init Memory\")\n Memory = sd.CSharedMemory()\n Memory.setSyncMode(True)\n return Memory\n\n\nMemory = initMemory()\n\n# Publish the values on SHM\nMemory.Data.Control.Steering = 0.0\nMemory.Data.Control.Accelerating = 0.0\n# Abnormal situation\nMemory.Data.Control.Breaking = 3.0\nprint(\"Create Abnormal Situation\")\n\n# Notify the wrapper about it\nMemory.indicateReady()\n\n# Read Again anc check right value is there\nimport time\n\nwhile True:\n time.sleep(0.1)\n # Maintain the abnormal situation\n Memory.Data.Control.Breaking = 3.0\n Memory.indicateReady()\n\n","sub_path":"src/deepdrive/test-driver-2.py","file_name":"test-driver-2.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"207739965","text":"####################\n#\n# Author: silentcat\n# Date: 2018-07-09\n# Description: Draws the grid\n# using Tkinter.\n#\n####################\n\nimport tkinter\nimport grid\nimport distances\n\ndef draw_grid(maze, dists=None):\n\n grid_str = '+' + '---+' * maze.columns + '\\n' # Creates the top +---+---+--...+ (... is the number of '---+' that correspond to the columns).\n for row in maze.cells:\n top = '|' # Set the extreme western border as '|'.\n bottom = '+' # Set the corner of the bottom border.\n for cell in row: # For each cell in the row, \n eastern = ' ' if cell and cell.east and cell.linked(cell.east) else '|' # Open up the passage to the eastern cell if linked.\n southern = ' ' if cell and cell.south and cell.linked(cell.south) else '---' # Open up the passage to the southern cell if linked.\n if dists == None: # If no distances structure is provided.\n top += ' ' + eastern # Set a space in the middle.\n else:\n if cell:\n top += ' ' + str(dists[cell]) + ' ' + eastern # Set the distance from the root in the middle.\n\n bottom += southern + '+' # Add the southern border and the last corner.\n\n grid_str += top + '\\n' + bottom + '\\n' # Add the top and then the bottom.\n\n return grid_str\n\ndef draw_background(w, x, y, cell, dists, cell_size=40):\n if cell in dists.distances:\n dist = dists.distances[cell]\n max_val = dists.max_dist(dists.maze)[1]\n intensity = float(max_val - dist) / float(max_val)\n\n dark = int(255 * intensity)\n bright = int(128 + (127 * intensity))\n\n dark_str = str(hex(dark))[2:].zfill(2)\n bright_str = str(hex(bright))[2:].zfill(2)\n\n hex_str = '#' + dark_str + bright_str + dark_str\n w.create_rectangle(x, y, x + cell_size, y + cell_size, fill=hex_str, width=0)\n\ndef draw_links(w, x, y, cell, cell_size=40):\n link_count = len(cell.links)\n fill_str = ''\n if link_count == 0:\n fill_str = 'red'\n if link_count == 1:\n fill_str = 'green'\n if link_count == 2:\n fill_str = 'blue'\n if link_count == 3:\n fill_str = 'gray'\n if link_count == 4:\n fill_str = 'black'\n w.create_rectangle(x, y, x + cell_size, y + cell_size, fill=fill_str, width=0)\n\ndef draw_g(g, cell_size=40, dists=None, links=False):\n \n img = tkinter.Tk()\n img_width = 100 * g.columns\n img_height = 100 * g.rows\n w = tkinter.Canvas(img, width=img_width, height=img_height)\n x = img_width / 4\n y = img_height / 4\n for row in g.cells:\n for cell in row:\n if cell and dists:\n draw_background(w, x, y, cell, dists, cell_size)\n if cell and links:\n draw_links(w, x, y, cell, cell_size)\n if cell and (cell.north == None or cell.linked(cell.north) == False):\n w.create_line(x, y, x + cell_size, y, width=3)\n if cell and (cell.west == None or cell.linked(cell.west) == False):\n w.create_line(x, y, x, y + cell_size, width=3)\n if cell and (cell.east == None or cell.linked(cell.east) == False):\n w.create_line(x + cell_size, y, x + cell_size, y + cell_size, width=3)\n if cell and (cell.south == None or cell.linked(cell.south) == False):\n w.create_line(x, y + cell_size, x + cell_size, y + cell_size, width=3)\n \n x += cell_size\n x -= (cell_size * g.columns)\n y += cell_size\n \n w.pack()\n img.mainloop()\n\n","sub_path":"python/draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":3565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"291328995","text":"from django.http import HttpRequest, JsonResponse\nfrom CustomAuth.models import User\n\n\ndef jwt(function):\n \"\"\"\n :param function: The view function that call with a url that client request\n :return: if user has jwt authentication and is not anonymous call function,\n else response 403\n \"\"\"\n\n def wrap(request: HttpRequest, *args, **kwargs):\n user: User = request.user\n is_jwt_authentication = request.headers.__contains__('jwt-authentication')\n if not user.is_anonymous and is_jwt_authentication:\n return function(request, *args, *kwargs)\n else:\n context = {\n 'error': 'jwt authentication is required'\n }\n return JsonResponse(context, status=403)\n\n return wrap\n","sub_path":"decorators/jwt.py","file_name":"jwt.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"396239512","text":"import sys\n#sys.path.append('/home/dhvanan/IISc/WORK/SchedulingWrapper')\nimport operator\nimport random\nram_allocation_ratio = 1\n\n\ndef RandomFit_Core(hosts,req):\n\t'''\n\tinput: hosts list with each host as a dictionary\n req dict: {vm-default:[{},{}],vm-custom:[{},{}]}\n\n\toutput: VM:Host Mapping\n\t'''\n\tmapping=[]\n\thost_list ={}\n\thosts_dict={}\n\n\n\tinstance_count=0\n\tfor vm_type in req:\n\t\tmapping_dict = {}\n\t\tfor request in req[vm_type]:\n\t\t\tcore_req = request['cores']\n\t\t\thost = hosts[random.randint(0,len(hosts)-1)]\n\t\t\tif(host['free_vcpus']>=core_req):\n\t\t\t\thost['free_vcpus']-=core_req\n\t\t\t\tmapping_dict[request['name']] = host['host']\n\t\tmapping.append(mapping_dict)\n\treturn mapping\n\n\n#r = {\"vm-default\":[{\"name\" : \"VM1\",\"ram\":1},{\"name\" : \"VM2\",\"ram\":1},{\"name\" : \"VM3\",\"ram\":1},{\"name\" : \"VM4\",\"ram\":2},{\"name\" : \"VM5\",\"ram\":4},{\"name\" : \"VM6\",\"ram\":4},{\"name\" : \"VM7\",\"ram\":1}]}\n#h = [{'host':'host1','free_ram':6},{'host':'host2','free_ram':7}]\n#res = FirstFit_Ram(h,r)\n#print res\n","sub_path":"Scheduler/algorithms/randomfit_core.py","file_name":"randomfit_core.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"174404589","text":"from app import schemas\nfrom app.api import get_genres\nfrom app.config import get_settings\nfrom app.db import crud\nfrom app.db import database\nfrom app.db import models\nfrom app.db.search import client\nfrom sqlalchemy.exc import IntegrityError\nfrom tqdm import tqdm\n\n\ndef dump_media_to_db(media: models.Media) -> None:\n \"\"\"Turns Media-model into a Media-schemas, and adds to Media table\"\"\"\n\n formatted_media = schemas.Media(\n id=media.get(\"id\"),\n title=media.get(\"title\"),\n original_title=media.get(\"original_title\"),\n overview=media.get(\"overview\"),\n release_date=media.get(\"release_date\"),\n genres=media.get(\"genres\"),\n poster_path=media.get(\"poster_path\"),\n popularity=media.get('popularity')\n )\n try:\n db = database.SessionLocal()\n db_media = crud.get_media_by_id(db=db, media_id=formatted_media.id)\n if not db_media:\n crud.create_media(db=db, media=formatted_media)\n except IntegrityError: # Still a bit unsure why this only happens sometimes\n pass\n finally:\n db.close()\n\n\ndef dump_genres_to_db() -> None:\n \"\"\"Turns a dict of genres into Genre-schemas, and feeds them to crud create\n \"\"\"\n # TODO: connection should probably be done in a safer way\n db = database.SessionLocal()\n genres = get_genres()\n\n for key in genres:\n formatted_genre = schemas.Genre(\n id=key,\n name=genres[key],\n value=genres[key],\n )\n\n db_genre = crud.get_genre_by_id(db=db, genre_id=key)\n if not db_genre:\n crud.create_genre(db=db, genre=formatted_genre)\n db.close()\n\n\ndef format_genres() -> None:\n \"\"\"Finds any genre name containing ampersand (&), formats the name to work with the\n TMDb query, and calls crud update\n \"\"\"\n db = database.SessionLocal()\n genres = crud.get_all_genres(db=db)\n\n formatted_genres = [\n schemas.Genre(\n id=genre.id,\n name=str(genre.name).replace(' & ', '%20%26%20'),\n value=genre.name\n )\n for genre in genres if ' & ' in genre.name\n ]\n\n for genre in formatted_genres:\n crud.update_genre_name(db, genre)\n\n\ndef init_meilisearch_indexing():\n \"\"\"MeiliSearch indexing from Postgres DB\n \"\"\"\n supported_country_codes = get_settings().supported_country_codes\n\n db = database.SessionLocal()\n try:\n media_list = crud.get_all_media(db=db)\n\n for country_code in supported_country_codes:\n media_list_as_dict = [\n schemas.Media(\n id=media.id,\n title=media.title,\n original_title=media.original_title,\n overview=media.overview,\n release_date=media.release_date,\n genres=media.genres,\n poster_path=media.poster_path,\n popularity=media.popularity,\n specific_provider_names=[\n provider.get(country_code).get('provider_name')\n for provider in media.providers\n if provider.get(country_code)\n ],\n specific_providers=[\n provider.get(country_code)\n for provider in media.providers\n if provider.get(country_code)\n ]\n ).dict()\n for media in media_list\n ]\n client.index(f'media_{country_code}').add_documents(media_list_as_dict)\n\n extract_unique_providers_to_txt(media_list, country_code)\n\n print(\n f'Meilisearch indexing {len(supported_country_codes)} x '\n f'{len(media_list)} elements'\n )\n\n except Exception as e:\n print(f'Error in database_service.py::init_meilisearch_indexing {e}')\n\n\ndef extract_unique_providers_to_txt(media_list, country_code):\n provider_set = {\n provider.get(country_code).get('provider_name')\n for media in media_list\n for provider in media.providers\n if provider.get(country_code)\n }\n ordered_provider_list = sorted(provider_set)\n with open(f'../providers_{country_code}.txt', 'w') as file:\n for provider in ordered_provider_list:\n file.write(f'{provider}\\n')\n\n\ndef prune_non_ascii_media_from_db():\n \"\"\"Removes media with no genres or Animation that cannot be encoded with ASCII\n \"\"\"\n\n try:\n db = database.SessionLocal()\n media_list = crud.get_all_media(db=db)\n pbar_media_list = tqdm(media_list)\n pbar_media_list.set_description('Finding non-ASCII in titles')\n\n for media in pbar_media_list:\n if media.genres.__contains__('Animation') or len(media.genres) == 0:\n\n for letter in media.original_title:\n try:\n letter.encode(encoding='utf-8').decode('ascii')\n except UnicodeDecodeError:\n crud.delete_media_by_id(db=db, media_id=media.id)\n break\n print('Media with non-ASCII titles have been pruned')\n except Exception as e:\n print(e)\n","sub_path":"backend/app/db/database_service.py","file_name":"database_service.py","file_ext":"py","file_size_in_byte":5222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"45402449","text":"from django.conf.urls import patterns, include, url\nfrom fileExplorer import settings\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'fileExplorer.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.jade'}),\n url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/login/?next=/browser/'}),\n url(r'^', include('cloud_browser.urls')),\n)\n\nurlpatterns += patterns('',\n (r'^static/(?P.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),\n)\n","sub_path":"fileExplorer/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"69387489","text":"from logging import getLogger, DEBUG, basicConfig\nfrom core.exceptions import PushToRemoteError\nfrom nose.tools import assert_equal\nfrom sys import stderr\nfrom unittest import TestCase\nfrom core.remote.third_party_remotes.git_module import Remote\nfrom flexmock import flexmock\nfrom git import NoSuchPathError, InvalidGitRepositoryError, Repo\nfrom hamcrest import assert_that, equal_to, has_item\nfrom mock import patch, Mock, call\n\nbasicConfig(stream=stderr)\ngetLogger(\"SomeTest.testSomething\").setLevel(DEBUG)\nlog = getLogger(\"backup_process_tests\")\n\n\nclass GitTests(TestCase):\n\n def setUp(self):\n self.repo_name_patcher = patch(\n 'core.remote.third_party_remotes.git_module.REPO_NAME'\n )\n self.mock_repo_name = self.repo_name_patcher.start()\n\n self.repo_name_patcher = patch(\n 'core.remote.third_party_remotes.git_module.REPO_NAME'\n )\n self.mock_repo_name.REPO_NAME = 'some_repo_name'\n\n self.fake_git_repo = flexmock()\n flexmock(Repo).should_receive('__new__').and_return(self.fake_git_repo)\n\n self.git = Remote()\n self.git_mock = flexmock(self.git)\n\n @patch('core.remote.third_party_remotes.git_module.log')\n def test_invalid_git_repo_raises_when_creating_instance(self, m_log):\n flexmock(Repo).should_receive('__new__').and_raise(\n InvalidGitRepositoryError\n )\n r = Remote()\n assert_that(m_log.warn.call_count, equal_to(1))\n assert_that(r.repo, equal_to(''))\n\n @patch('core.remote.third_party_remotes.git_module.log')\n def test_path_does_not_exist_raises_when_creating_instance(self, m_log):\n flexmock(Repo).should_receive('__new__').and_raise(NoSuchPathError)\n with self.assertRaises(NoSuchPathError):\n Remote()\n assert_that(m_log.error.call_count, equal_to(1))\n\n @patch('core.remote.third_party_remotes.git_module.log')\n def test_unexpected_failure_gets_caught(self, m_log):\n flexmock(Repo).should_receive('__new__').and_raise(Exception)\n with self.assertRaises(Exception):\n Remote()\n assert_that(m_log.error.call_count, equal_to(1))\n\n @patch('core.remote.third_party_remotes.git_module.Git')\n def test_repo_is_cloned_if_it_does_not_exist(self, m_git):\n self.git.repo = \"\"\n\n self.git.fetch_from_remote()\n\n assert_equal(m_git.call_count, 1)\n\n @patch('core.remote.third_party_remotes.git_module.log')\n @patch('core.remote.third_party_remotes.git_module.Git')\n def test_remote_repo_fails_if_repo_already_exists(self, m_git, m_log):\n mock_repo = Mock()\n mock_repo.side_effect = Mock()\n self.git.repo = mock_repo\n\n self.git.fetch_from_remote()\n\n assert_that(\n mock_repo.method_calls, has_item(call.remotes.origin.pull())\n )\n assert_equal(m_git.call_count, 0)\n assert_equal(m_log.call_count, 0)\n\n @patch('core.remote.third_party_remotes.git_module.log')\n @patch('core.remote.third_party_remotes.git_module.Git')\n def test_pull_raises_exception_if_fails(self, m_git, m_log):\n mock_repo = Mock()\n mock_repo.remotes.origin.pull.side_effect = Exception\n\n self.git.repo = mock_repo\n\n self.git.fetch_from_remote()\n\n m_log.error.assert_called_once_with(\"Could not update repository: \")\n assert_equal(m_git.call_count, 0)\n\n @patch('core.remote.third_party_remotes.git_module.log')\n @patch('core.remote.third_party_remotes.git_module.Remote.commit')\n def test_successful_push(self, m_commit, m_log):\n m_commit.return_value = \"successful_commit\"\n mock_repo = Mock()\n mock_repo.remotes.origin.push.side_effect = \"great_success\"\n\n self.git.repo = mock_repo\n\n self.git.push_to_remote([\"stuff_to_commit\"])\n\n assert_that(m_log.error.call_count, equal_to(0))\n\n @patch('core.remote.third_party_remotes.git_module.log')\n @patch('core.remote.third_party_remotes.git_module.Remote.commit')\n def test_push_raises_when_commit_raises(self, m_commit, m_log):\n m_commit.side_effect = Exception\n mock_repo = Mock()\n self.git.repo = mock_repo\n\n with self.assertRaises(Exception):\n self.git.push_to_remote([\"stuff_to_commit\"])\n\n assert_that(mock_repo.remotes.origin.push.call_count, equal_to(0))\n assert_that(m_log.error.call_count, equal_to(1))\n\n @patch('core.remote.third_party_remotes.git_module.log')\n @patch('core.remote.third_party_remotes.git_module.Remote.commit')\n def test_push_raises_when_list_of_files_is_not_list(self, m_commit, m_log):\n mock_repo = Mock()\n self.git.repo = mock_repo\n\n with self.assertRaises(PushToRemoteError):\n self.git.push_to_remote(\"stuff_to_commit\")\n\n assert_that(m_commit.call_count, equal_to(0))\n assert_that(mock_repo.remotes.origin.push.call_count, equal_to(0))\n assert_that(m_log.error.call_count, equal_to(0))\n\n @patch('core.remote.third_party_remotes.git_module.log')\n @patch('core.remote.third_party_remotes.git_module.Remote.commit')\n def test_push_raises_when_git_push_raises(self, m_commit, m_log):\n m_commit.return_value = \"successful_commit\"\n mock_repo = Mock()\n mock_repo.remotes.origin.push.side_effect = Exception\n\n self.git.repo = mock_repo\n\n with self.assertRaises(Exception):\n self.git.push_to_remote([\"stuff_to_commit\"])\n\n assert_that(m_log.error.call_count, equal_to(1))\n\n def test_commit_rejects_if_list_of_files_is_not_list(self):\n commit_id = self.git.commit('some_message', \"not_a_list\")\n\n assert_that(\"\", equal_to(commit_id))\n\n def test_successful_commit(self):\n mock_repo = Mock()\n mock_repo.index.add.side_effect = lambda x: True\n index_mock = Mock()\n mock_repo.index.commit.return_value = index_mock\n index_mock.name_rev.return_value = 'a_commit_id'\n\n self.git.repo = mock_repo\n\n commit_id = self.git.commit('some_message', [\"a_file\", \"another_file\"])\n assert_that('a_commit_id', equal_to(commit_id.return_value))\n\n def test_add_to_index_fails_and_returns_empty_commit_id(self):\n mock_repo = Mock()\n mock_repo.index.add.side_effect = OSError\n\n self.git.repo = mock_repo\n\n commit_id = self.git.commit('some_message', [\"a_file\", \"another_file\"])\n assert_that('', equal_to(commit_id))\n\n def test_commit_fails_returns_empty_commit_id(self):\n mock_repo = Mock()\n mock_repo.index.add.side_effect = lambda x: True\n mock_repo.index.commit.side_effect = Exception\n\n self.git.repo = mock_repo\n\n commit_id = self.git.commit('some_message', [\"a_file\", \"another_file\"])\n assert_that('', equal_to(commit_id))\n\n","sub_path":"app/tests/git_tests.py","file_name":"git_tests.py","file_ext":"py","file_size_in_byte":6805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"428584841","text":"#!/usr/bin/env python\n# ------------------------------------------------------------------------------------------------------%\n# Created by \"Thieu\" at 22:08, 01/03/2021 %\n# %\n# Email: nguyenthieu2102@gmail.com %\n# Homepage: https://www.researchgate.net/profile/Nguyen_Thieu2 %\n# Github: https://github.com/thieu1995 %\n# ------------------------------------------------------------------------------------------------------%\n\nimport concurrent.futures as parallel\nfrom functools import partial\nimport numpy as np\nimport time\nfrom mealpy.optimizer import Optimizer\n\n\nclass BaseSA(Optimizer):\n \"\"\"\n The original version of: Simulated Annealing (SA)\n \"\"\"\n\n def __init__(self, problem, epoch=10000, pop_size=100, max_sub_iter=10, t0=1000, t1=1, move_count=5,\n mutation_rate=0.1, mutation_step_size=0.1, mutation_step_size_damp=0.99, **kwargs):\n \"\"\"\n Args:\n problem ():\n epoch (int): maximum number of iterations, default = 10000\n pop_size (int): number of population size, default = 100\n max_sub_iter (): Maximum Number of Sub-Iteration (within fixed temperature)\n t0 (): Initial Temperature\n t1 (): Final Temperature\n move_count (): Move Count per Individual Solution\n mutation_rate (): Mutation Rate\n mutation_step_size (): Mutation Step Size\n mutation_step_size_damp (): Mutation Step Size Damp\n **kwargs ():\n \"\"\"\n super().__init__(problem, kwargs)\n self.nfe_per_epoch = pop_size * max_sub_iter * move_count\n self.sort_flag = True\n\n self.epoch = epoch\n self.pop_size = pop_size\n self.max_sub_iter = max_sub_iter\n self.t0 = t0\n self.t1 = t1\n self.move_count = move_count\n self.mutation_rate = mutation_rate\n self.mutation_step_size = mutation_step_size\n self.mutation_step_size_damp = mutation_step_size_damp\n\n def mutate(self, position, sigma):\n mu = self.mutation_rate\n # Select Mutating Variables\n pos_new = position + sigma * np.random.uniform(self.problem.lb, self.problem.ub)\n pos_new = np.where(np.random.uniform(0, 1, self.problem.n_dims) < mu, position, pos_new)\n\n if np.all(pos_new == position): # Select at least one variable to mutate\n pos_new[np.random.randint(0, self.problem.n_dims)] = np.random.uniform()\n return self.amend_position_faster(pos_new)\n\n def solve(self, mode='sequential'):\n \"\"\"\n Args:\n mode (str): 'sequential', 'thread', 'process'\n + 'sequential': recommended for simple and small task (< 10 seconds for calculating objective)\n + 'thread': recommended for IO bound task, or small computing task (< 2 minutes for calculating objective)\n + 'process': recommended for hard and big task (> 2 minutes for calculating objective)\n\n Returns:\n [position, fitness value]\n \"\"\"\n if mode != \"sequential\":\n print(\"SA is support sequential mode only!\")\n exit(0)\n self.termination_start()\n pop = self.create_population(mode, self.pop_size)\n pop, g_best = self.get_global_best_solution(pop) # We sort the population\n self.history.save_initial_best(g_best)\n\n # Initial Temperature\n t = self.t0 # Initial Temperature\n t_damp = (self.t1 / self.t0) ** (1.0 / self.epoch) # Calculate Temperature Damp Rate\n sigma = self.mutation_step_size # Initial Value of Step Size\n\n for epoch in range(0, self.epoch):\n time_epoch = time.time()\n\n # Sub-Iterations\n for g in range(0, self.max_sub_iter):\n\n # Create new population\n pop_new = []\n for i in range(0, self.pop_size):\n for j in range(0, self.move_count):\n # Perform Mutation (Move)\n pos_new = self.mutate(pop[i][self.ID_POS], sigma)\n pos_new = self.amend_position_faster(pos_new)\n fit_new = self.get_fitness_position(pos_new)\n pop_new.append([pos_new, fit_new])\n\n # Columnize and Sort Newly Created Population\n pop_new, g_best = self.update_global_best_solution(pop_new)\n pop_new = pop_new[:self.pop_size]\n\n # Randomized Selection\n for i in range(0, self.pop_size):\n # Check if new solution is better than current\n if self.compare_agent(pop_new[i], pop[i]):\n pop[i] = pop_new[i].copy()\n else:\n # Compute difference according to problem type\n delta = abs(pop_new[i][self.ID_FIT][self.ID_TAR] - pop[i][self.ID_FIT][self.ID_TAR])\n p = np.exp(-delta / t) # Compute Acceptance Probability\n if np.random.uniform() <= p: # Accept / Reject\n pop[i] = pop_new[i].copy()\n # Update Temperature\n t = t_damp * t\n sigma = self.mutation_step_size_damp * sigma\n\n # update global best position\n pop, g_best = self.update_global_best_solution(pop) # We sort the population\n\n ## Additional information for the framework\n time_epoch = time.time() - time_epoch\n self.history.list_epoch_time.append(time_epoch)\n self.history.list_population.append(pop.copy())\n self.print_epoch(epoch + 1, time_epoch)\n if self.termination_flag:\n if self.termination.mode == 'TB':\n if time.time() - self.count_terminate >= self.termination.quantity:\n self.termination.logging(self.verbose)\n break\n elif self.termination.mode == 'FE':\n self.count_terminate += self.nfe_per_epoch\n if self.count_terminate >= self.termination.quantity:\n self.termination.logging(self.verbose)\n break\n elif self.termination.mode == 'MG':\n if epoch >= self.termination.quantity:\n self.termination.logging(self.verbose)\n break\n else: # Early Stopping\n temp = self.count_terminate + self.history.get_global_repeated_times(self.ID_FIT, self.ID_TAR, self.EPSILON)\n if temp >= self.termination.quantity:\n self.termination.logging(self.verbose)\n break\n\n ## Additional information for the framework\n self.save_optimization_process()\n return self.solution[self.ID_POS], self.solution[self.ID_FIT][self.ID_TAR]\n","sub_path":"mealpy/physics_based/SA.py","file_name":"SA.py","file_ext":"py","file_size_in_byte":7230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"175403927","text":"import re, os\n\nmyDirectory = os.path.expanduser(\"~/SocInBox/scanning/portscandata.txt\")\nf = open(myDirectory, \"r\")\n\nwhile True:\n\t#reading each line of the file\n\tline = f.readline()\n\n\t#break if no more line\n\tif not line: break\n\n\t#using regex to grab port number and banner \t\n\tx = re.findall(r'([\\d]+): b[\\'\\\"](.*)[\\'\\\"]', line)[0]\n\tprint (x[0] + \" \" + x[1])\n","sub_path":".virtualenvs/backend/patching/patch.py","file_name":"patch.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"603222891","text":"# Copyright 2016 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ------------------------------------------------------------------------------\nfrom __future__ import division\n\nimport uuid\nimport hashlib\nimport base64\nfrom base64 import b64encode\nimport time\nimport random\nimport requests\nimport yaml\nimport math\nimport sys\nimport logging\n\nfrom sawtooth_signing import create_context\nfrom sawtooth_signing import CryptoFactory\nfrom sawtooth_signing import ParseError\nfrom sawtooth_signing.secp256k1 import Secp256k1PrivateKey\n\nfrom sawtooth_sdk.protobuf.transaction_pb2 import TransactionHeader\nfrom sawtooth_sdk.protobuf.transaction_pb2 import Transaction\nfrom sawtooth_sdk.protobuf.batch_pb2 import BatchList\nfrom sawtooth_sdk.protobuf.batch_pb2 import BatchHeader\nfrom sawtooth_sdk.protobuf.batch_pb2 import Batch\nfrom sawtooth_sdk.processor.exceptions import InternalError\n\nfrom sawtooth_job.job_exceptions import JobException\n\n\ndef _sha512(data):\n return hashlib.sha512(data).hexdigest()\n\n# constant, to calculate extra rewards\nP = 10\n\nclass JobClient:\n \n\n def __init__(self, base_url, keyfile=None):\n\n self._base_url = base_url\n\n if keyfile is None:\n self._signer = None\n return\n\n try:\n with open(keyfile) as fd:\n private_key_str = fd.read().strip()\n except OSError as err:\n raise JobException(\n 'Failed to read private key {}: {}'.format(keyfile, str(err)))\n\n try:\n private_key = Secp256k1PrivateKey.from_hex(private_key_str)\n except ParseError as e:\n raise JobException(\n 'Unable to load private key: {}'.format(str(e)))\n\n self._signer = CryptoFactory(create_context('secp256k1')) \\\n .new_signer(private_key)\n\n # propose a job record\n def create(self, jobId, receiverId, publisherId, data_size, start_time, duration, guaranteed_rt, test_rt, base_rewards, is_integrity, wait=None):\n if test_rt < guaranteed_rt:\n extra_rewards = round(P*(guaranteed_rt - test_rt) / guaranteed_rt, 1)\n elif not is_integrity:\n extra_rewards = 0\n base_rewards = 0\n elif test_rt > guaranteed_rt:\n extra_rewards = 0\n base_rewards = 0.5*base_rewards\n return self._send_transaction(\n jobId,\n receiverId,\n publisherId,\n str(data_size),\n str(start_time),\n str(duration),\n str(guaranteed_rt),\n str(test_rt),\n str(base_rewards),\n str(extra_rewards),\n is_integrity,\n \"create\",\n wait=wait,\n )\n\n # get job response as input, choose a receiver\n # candidates format:\n # [receiverId,publisherId,start_time,guaranteed_rt], an array\n def chooseReceiver(self, candidates):\n # get receivers response, pick start time as a param\n receivers_id = []\n # store all servers' guaranteed response time\n guaranteed_rts = {}\n \n for candidateId, guaranteed_rt in candidates.items():\n receivers_id.append(candidateId)\n guaranteed_rts[candidateId] = float(guaranteed_rt)\n\n print(\"=====guaranteed_rts: \", guaranteed_rts)\n # for candidate in candidates:\n # # receiverId, publisherId, start_time, guaranteed_rt = candidate.split(',')\n # receiverId, guaranteed_rt = candidate.split(',')\n # receivers_id.append(receiverId)\n # guaranteed_rts[receiverId] = float(guaranteed_rt)\n \n # get reputation of receivers\n repus = self.computeReputation(receivers_id)\n print('++++ reputation +++++')\n print(repus)\n \n # print('++++ receiver_delays +++++')\n # print(receiver_delays)\n\n # print('++++ working_time +++++')\n # print(working_time)\n\n normalized_repus = self.normalization(\"repu\", repus)\n normalized_guaranteed_rt = self.normalization(\"rt\", guaranteed_rts)\n \n # print('++++ normalized_working_time +++++')\n # print(normalized_working_time)\n # print('++++ normalized_delay +++++')\n # print(normalized_delay)\n # print('++++ normalized_repus +++++')\n # print(normalized_repus)\n\n # compute scores for receivers, choose the best\n # call create function with parms\n return self.chooseOne(receivers_id, normalized_repus, normalized_guaranteed_rt)\n\n def chooseOne(self, receivers, reputation, guaranteed_rt):\n guaranteed_rt_weight = 0.5\n reputation_weight = 0.5\n\n combine = {}\n for receiverId in receivers:\n repu_s = reputation_weight*reputation[receiverId] if reputation else 0\n guar_s = guaranteed_rt_weight*guaranteed_rt[receiverId] if guaranteed_rt else 0\n combine[receiverId] = repu_s*reputation_weight + guar_s*guaranteed_rt_weight\n print('++++ choose one combine +++++')\n print(combine)\n s = sorted(combine.items(), key=lambda x: x[1],reverse = True)\n # return (receiverId, guaranteed_rt)\n return s[0]\n\n\n def normalization(self, target_type, data):\n if data:\n sorted_data = sorted(data.items(), key=lambda x: x[1])\n max = sorted_data[len(data)-1][1]\n min = sorted_data[0][1]\n normalized = {}\n for key in data.keys():\n if max == min:\n normalized[key] = 1\n elif target_type == \"repu\":\n normalized[key] = (data[key] - min) / (max - min)\n elif target_type == \"rt\":\n normalized[key] = (max - data[key]) / (max - min)\n return normalized\n\n\n def computeReputation(self, receiverIds):\n # current time in millisecond\n # current_time = time.time()\n # current_time = 1593871200000\n\n # store each node's available rewards, used for validation phase\n print('++++++++create log file++++++++')\n logger = logging.getLogger()\n hdlr = logging.FileHandler('/home/ubuntu/reputation.log')\n logger.addHandler(hdlr) \n logger.setLevel(logging.INFO)\n\n # get all job from chain\n job_list = [\n job.split(',')\n for jobs in self.list()\n for job in jobs.decode().split('|')\n ]\n\n print('job_list: ', job_list)\n # construct job record for reputation computation\n # required: start_time \n # extra_rewards \n job_record = {}\n jobs = []\n if job_list is not None:\n for job_data in job_list:\n jobId, receiverId, publisherId, data_size, start_time, duration, guaranteed_rt, test_rt, base_rewards, extra_rewards, is_integrity = job_data\n # store jobs according to receiverId\n job_record.setdefault(receiverId, []).append({\n 'start_time': start_time,\n 'extra_rewards': extra_rewards\n })\n jobs.append({\n 'receiverId': receiverId,\n 'publisherId': publisherId,\n 'base_rewards': float(base_rewards),\n 'extra_rewards': float(extra_rewards)\n })\n else:\n raise JobException(\"Could not retrieve game listing.\")\n\n print('++++++++job record in chain++++++++')\n print(job_record)\n \n # based on extra rewards, reflecting histroy performance\n # only compute for who has expressed interests\n reputation_receivers = self.reputationBasedOnRewards(receiverIds, job_record)\n # or\n # reputation_receivers = self.reputationWithPunishment(receiverIds, job_record)\n print('++++++++ reputation_receivers n++++++++')\n print(reputation_receivers)\n\n for receiverId in receiverIds:\n if not receiverId in reputation_receivers.keys():\n reputation_receivers[receiverId] = 0.0\n\n recvBaseRewards = {}\n recvExtraRewards = {}\n # initialize \n for receiverId in receiverIds:\n recvBaseRewards[receiverId] = 0\n recvExtraRewards[receiverId] = 0\n\n for job in jobs:\n recvBaseRewards[job['receiverId']] += job['base_rewards']\n recvExtraRewards[job['receiverId']] += job['extra_rewards']\n\n if recvBaseRewards and recvExtraRewards:\n for receiverId in receiverIds:\n info = receiverId + ' - ' +str(recvBaseRewards[receiverId]) + ' - ' + str(recvExtraRewards[receiverId]) + ' - ' + str(round(reputation_receivers[receiverId], 3))\n print('++++++++write log++++++++')\n print(info)\n logger.info(info)\n\n return reputation_receivers\n\n def reputationBasedOnRewards(self, receiverIds, job_record):\n B = 0.2\n reward_score = {}\n rewards = {}\n RECENT_JOB_NUM = 20\n print('+++++ unsorted print(job_record) ++++')\n print(job_record)\n # sort by start time\n for receiverId, records in job_record.items():\n job_record[receiverId] = sorted(records, key=lambda x: x['start_time'], reverse=True)\n print('+++++ sorted print(job_record) ++++')\n print(job_record)\n # extra rewards on each record of receivers on recent X number of jobs\n i = 0\n for receiverId, records in job_record.items():\n if receiverId in receiverIds:\n for record in records:\n if i 0:\n wait_time = 0\n begin_time = time.time()\n response = self._send_request(\n \"batches\", batch_list.SerializeToString(),\n 'application/octet-stream'\n )\n while wait_time < wait:\n status = self._get_status(\n batch_id,\n wait - int(wait_time)\n )\n wait_time = time.time() - begin_time\n\n if status != 'PENDING':\n return response\n\n return response\n print('send request')\n return self._send_request(\n \"batches\", batch_list.SerializeToString(),\n 'application/octet-stream',\n )\n\n def _create_batch_list(self, transactions):\n transaction_signatures = [t.header_signature for t in transactions]\n\n header = BatchHeader(\n signer_public_key=self._signer.get_public_key().as_hex(),\n transaction_ids=transaction_signatures\n ).SerializeToString()\n\n signature = self._signer.sign(header)\n\n batch = Batch(\n header=header,\n transactions=transactions,\n header_signature=signature)\n return BatchList(batches=[batch])\n","sub_path":"job_python/sawtooth_job/job_client.py","file_name":"job_client.py","file_ext":"py","file_size_in_byte":18264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"212105805","text":"from django.core.management.base import BaseCommand, CommandError\nimport requests, datetime\nfrom bs4 import BeautifulSoup\nfrom core.models import JobDetails, JobCategory\n\nclass Command(BaseCommand):\n\t\n def get_cleandata(self, soup, id):\n try:\n text = soup.find(id=id).get_text()\n except:\n text = \"\"\n pass\n return text\n \n def get_jobdetails(self, url):\n get_jobs = requests.get(url)\n soup = BeautifulSoup(get_jobs.content, 'html.parser')\n title = self.get_cleandata(soup, \"jdPostingTitle\")\n address = self.get_cleandata(soup, \"job-location-name\")\n category = self.get_cleandata(soup, \"job-team-name\")\n summary = self.get_cleandata(soup, \"jd-job-summary\")\n jobid = self.get_cleandata(soup, \"jobNumber\")\n post_date = self.get_cleandata(soup, \"jobPostDate\")\n qualifications = self.get_cleandata(soup, \"jd-key-qualifications\")\n description = self.get_cleandata(soup, \"jd-description\")\n education = self.get_cleandata(soup, \"jd-education-experience\")\n\n return {\n \"jobid\": jobid,\n \"url\": url,\n \"title\" : title,\n \"address\": address,\n \"category\" : category,\n \"summary\": summary,\n \"post_date\": post_date,\n \"qualifications\": qualifications,\n \"description\": description,\n \"education\": education\n }\n\n def get_jobs(self, url, jobdetails, count_page):\n try:\n get_jobs = requests.get(url)\n soup = BeautifulSoup(get_jobs.content, 'html.parser')\n tableResult = soup.findAll(id=\"tblResultSet\")\n tbody = tableResult[0].select('tbody')\n for tr in list(tbody):\n firsttr = tr.select('tr')\n firsta = firsttr[0].select('a')\n detail_url = \"https://jobs.apple.com\"+firsta[0].get(\"href\")\n jobdetails.append(self.get_jobdetails(detail_url))\n pagination = soup.find(class_=\"results-pagination\")\n next_url = pagination.find(class_=\"pagination__next\")\n a = next_url.select('a')[0].get(\"href\")\n if a and count_page < 6:\n print(\"next url\", a)\n return self.get_jobs(a, jobdetails, count_page + 1)\n except Exception as e:\n print(str(e))\n \n return jobdetails\n\n\n def handle(self, *args, **options):\n jobdetails = [] \n self.get_jobs(\"https://jobs.apple.com/en-us/search\", jobdetails, 1)\n for key, value in enumerate(jobdetails):\n print(value['title'], value['post_date'])\n post_date = \"\"\n if value['post_date']:\n post_date = datetime.datetime.strptime(value['post_date'], \"%b %d, %Y\")\n\n try:\n jobcat = JobCategory.objects.filter(title=value['category']).first()\n if not jobcat:\n jobcat = JobCategory.objects.create(title=value['category'])\n check_exists = JobDetails.objects.filter(jobid=value['jobid']).first()\n if not check_exists:\n \n JobDetails.objects.create(\n title=value['title'],\n jobid = value['jobid'],\n category = jobcat,\n url = value['url'],\n address = value['address'],\n summary = value['summary'],\n post_date = post_date,\n description = value['description'],\n qualifications = value['qualifications'],\n education = value['education'],\n )\n except Exception as e:\n print(str(e))\n\n","sub_path":"job/core/management/commands/scrap_jobs.py","file_name":"scrap_jobs.py","file_ext":"py","file_size_in_byte":3826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"328071552","text":"# This is a script to delete the final page in a pdf\r\n\r\nimport PyPDF2 as pdf\r\n\r\npdf1File = open('ANNEXE3.pdf', 'rb')\r\n\r\n\r\npdf1Reader = pdf.PdfFileReader(pdf1File)\r\npdfWriter = pdf.PdfFileWriter()\r\n\r\nfor pageNum in range(pdf1Reader.numPages-1):\r\n pageObj = pdf1Reader.getPage(pageNum)\r\n pdfWriter.addPage(pageObj)\r\n\t\r\npdfOutputFile = open('outputpdf.pdf','wb')\r\npdfWriter.write(pdfOutputFile)\r\npdfOutputFile.close()\r\npdf1File.close()","sub_path":"deletefinalpage.py","file_name":"deletefinalpage.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"257530557","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 2 16:00:03 2017\n\n@author: marcduda\n\"\"\"\n\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\nfrom sklearn import metrics\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Activation, MaxPooling2D, Conv2D, MaxPooling1D, Conv1D\nfrom sklearn.preprocessing import LabelBinarizer\nfrom keras.utils.np_utils import to_categorical\nfrom sklearn.metrics import roc_auc_score\n\nX = np.load(\"datasetSTFTWithNoise2D.npy\")\ny = np.load(\"labelsSTFTWithNoise2D.npy\")\n# data preparation, shuffling and splitting\nX, y = shuffle(X, y, random_state=0)\nX_train2D, X_test2D, y_train, y_test = train_test_split(\n X, y, test_size=0.15, random_state=39)\nX_train2D = X_train2D/np.max(X_train2D) # normalization of the training set\nX_test2D = X_test2D/np.max(X_test2D) # normalization of the testing set\n(m, n, p) = X_train2D.shape\nX_train = np.reshape(X_train2D, (m, n*p))\n\n(i, j, k) = X_test2D.shape\nX_test = np.reshape(X_test2D, (i, j*k))\n\n# encoding the labels into categorical labels\nlb = LabelBinarizer()\ny_encoded = lb.fit_transform(y_train)\n\ny_binary_train = to_categorical(y_train)\ny_binary_test = to_categorical(y_test)\n#%% First architecture : fully connected layers\nclass_weight_dl = {0: 3.9, 1: 1}\ndim_features = X_train.shape[1]\nmodel_dl = Sequential()\nmodel_dl.add(Dense(30, input_dim=dim_features, activation='softmax'))\nmodel_dl.add(Dropout(.7))\nmodel_dl.add(Dense(20, activation='relu'))\nmodel_dl.add(Dense(20, activation='softmax'))\nmodel_dl.add(Dropout(.7))\nmodel_dl.add(Dense(10, activation='relu'))\nmodel_dl.add(Dense(2, activation='sigmoid'))\n\n# Compile model\nmodel_dl.compile(loss='categorical_crossentropy',\n optimizer='adam', metrics=['accuracy'])\n\n# Fit the model\nmodel_dl.fit(X_train, y_binary_train, epochs=20,\n batch_size=1000, class_weight=class_weight_dl)\n\n# evaluate the model\nscores = model_dl.evaluate(X_test, y_binary_test)\nprint(\"\\n%s: %.2f%%\" % (model_dl.metrics_names[1], scores[1]*100))\n\n\n# predict the labels of the test set and print some metrics to compare it with the correct labels\npredictions = model_dl.predict(X_test)\nprediction_binary = [i for i in np.argmax(predictions, 1)]\nprint(\"STFT DL part, metrics on test set:\")\nprint(metrics.classification_report(y_test, prediction_binary))\nprint(\"STFT DL part, roc on test set:\")\nprint(roc_auc_score(y_test, prediction_binary))\n\n#%% Second architecture : one-dimensional convolutional layers\nclass_weight_cnn = {0: 3, 1: 1} # 65\nmodel_cnn = Sequential()\n\n\nmodel_cnn.add(Conv2D(filters=5, kernel_size=(20, 1), strides=5, padding='same', data_format='channels_last', dilation_rate=1,\n activation='relu', use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', input_shape=(n, p, 1)))\nmodel_cnn.add(MaxPooling2D(pool_size=(2, 1)))\nmodel_cnn.add(Dropout(.25))\nmodel_cnn.add(Conv2D(filters=10, kernel_size=(\n 5, 1), strides=1, activation='relu'))\nmodel_cnn.add(Activation('softmax'))\nmodel_cnn.add(MaxPooling2D(pool_size=(2, 1)))\nmodel_cnn.add(Dropout(.25))\nmodel_cnn.add(Flatten())\nmodel_cnn.add(Dense(50, activation='relu'))\nmodel_cnn.add(Dropout(.5))\nmodel_cnn.add(Dense(2, activation='softmax'))\n\n\n# Compile model\nmodel_cnn.compile(loss='categorical_crossentropy',\n optimizer='adam', metrics=['accuracy'])\n\n# Fit the model\nmodel_cnn.fit(np.reshape(X_train2D, (m, n, p, 1)), y_binary_train,\n epochs=20, batch_size=1000, class_weight=class_weight_cnn)\n\n# evaluate the model\nscores_cnn = model_cnn.evaluate(np.reshape(\n X_test2D, (i, j, k, 1)), y_binary_test, verbose=1)\nprint(\"\\n%s: %.2f%%\" %\n (model_cnn.metrics_names[1], scores_cnn[1]*100)) # , y_test\n\n\n# predict the labels of the test set and print some metrics to compare it with the correct labels\npredictions_cnn = model_cnn.predict(np.reshape(X_test2D, (i, j, k, 1)))\nprediction_binary_cnn = [i for i in np.argmax(predictions_cnn, 1)]\nprint(\"STFT 2D CNN part, metrics on test set:\")\nprint(metrics.classification_report(y_test, prediction_binary_cnn))\nprint(\"STFT 2D CNN part, roc on test set:\")\nprint(roc_auc_score(y_test, prediction_binary_cnn))\n\n\n#%% Third architecture : two-dimensional convolutional layers\nclass_weight_cnn1D = {0: 3, 1: 1} # 65\nmodel_cnn1D = Sequential()\n\nmodel_cnn1D.add(Conv1D(filters=5, kernel_size=20, padding='same', dilation_rate=1, activation='relu',\n use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', input_shape=(dim_features, 1)))\nmodel_cnn1D.add(MaxPooling1D(pool_size=5))\nmodel_cnn1D.add(Dropout(.25))\nmodel_cnn1D.add(Conv1D(filters=10, kernel_size=20, strides=1,\n padding='same', activation='relu'))\nmodel_cnn1D.add(MaxPooling1D(pool_size=5))\nmodel_cnn1D.add(Dropout(.25))\nmodel_cnn1D.add(Flatten())\nmodel_cnn1D.add(Dense(50, activation='relu'))\nmodel_cnn1D.add(Dropout(.5))\nmodel_cnn1D.add(Dense(2, activation='softmax'))\n\n\n# Compile model\nmodel_cnn1D.compile(loss='categorical_crossentropy',\n optimizer='adam', metrics=['accuracy'])\n\n# Fit the model\nmodel_cnn1D.fit(np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1)), y_binary_train,\n epochs=20, batch_size=1000, class_weight=class_weight_cnn, validation_split=0.1)\n\n# evaluate the model\nscores_cnn1D = model_cnn1D.evaluate(np.reshape(\n X_test, (X_test.shape[0], X_test.shape[1], 1)), y_binary_test, verbose=1)\nprint(\"\\n%s: %.2f%%\" %\n (model_cnn.metrics_names[1], scores_cnn[1]*100)) # , y_test\n\n# predict the labels of the test set and print some metrics to compare it with the correct labels\npredictions_cnn1D = model_cnn1D.predict(np.reshape(\n X_test, (X_test.shape[0], X_test.shape[1], 1)))\nprediction_binary_cnn1D = [i for i in np.argmax(predictions_cnn1D, 1)]\nprint(\"STFT 1D CNN part, metrics on test set:\")\nprint(metrics.classification_report(y_test, prediction_binary_cnn1D))\nprint(\"STFT 1D CNN part, roc on test set:\")\nprint(roc_auc_score(y_test, prediction_binary_cnn1D))\n","sub_path":"dsChallenges/speechRecognition/STFTDeepLearning.py","file_name":"STFTDeepLearning.py","file_ext":"py","file_size_in_byte":6096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"156348891","text":"import os\nimport datetime\n\nfrom flask import escape\nfrom google.cloud import storage\nfrom google.oauth2 import service_account\n\nimport environ\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\n# check if .env file exists\nenv_file = os.path.join(BASE_DIR, \".env\")\n# If no .env has been provided, pull it from Secret Manager\nif os.path.isfile(env_file):\n env = environ.Env()\n env.read_env(env_file)\n\nstorage_client = None\nif os.getenv(\"APP_ENV\", None) == \"LOCAL\":\n GOOGLE_APPLICATION_CREDENTIALS = service_account.Credentials.from_service_account_file(\n os.path.join(BASE_DIR, env(\"GOOGLE_APPLICATION_CREDENTIALS_FILE\"))\n )\n storage_client = storage.Client(\n credentials=GOOGLE_APPLICATION_CREDENTIALS\n )\nelse:\n storage_client = storage.Client()\n\n\ndef copy_blob(request=None):\n \"\"\"Copies a blob from one bucket to another with a new name.\"\"\"\n time = datetime.datetime.now().strftime(\"%H%M%S\")\n bucket_name = os.getenv(\"SOURCE_BUCKET\")\n blob_name = os.getenv(\"SOURCE_BLOB_NAME\")\n destination_bucket_name = os.getenv(\"TARGET_BUCKET\")\n destination_blob_name = os.getenv(\"TAGET_BLOB_NAME\")+time\n \n # storage_client = storage.Client()\n\n source_bucket = storage_client.bucket(bucket_name)\n source_blob = source_bucket.blob(blob_name)\n destination_bucket = storage_client.bucket(destination_bucket_name)\n\n blob_copy = source_bucket.copy_blob(\n source_blob, destination_bucket, destination_blob_name\n )\n\n print(\n \"Blob {} in bucket {} copied to blob {} in bucket {}.\".format(\n source_blob.name,\n source_bucket.name,\n blob_copy.name,\n destination_bucket.name,\n )\n )\n\nif __name__ == \"__main__\":\n copy_blob(None)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"514330699","text":"import graphene\nfrom lingvodoc.schema.gql_holders import (CreatedAt,\n LingvodocObjectType,\n IdHolder,\n MarkedForDeletion,\n AdditionalMetadata,\n Name,\n About,\n del_object,\n acl_check_by_id,\n ResponseError,\n LingvodocID\n)\nfrom lingvodoc.models import (\n Organization as dbOrganization,\n Client,\n User as dbUser,\n BaseGroup as dbBaseGroup,\n Group as dbGroup,\n DBSession\n)\nfrom lingvodoc.utils.creation import add_user_to_group\n\n\nclass Organization(LingvodocObjectType):\n \"\"\"\n #created_at | timestamp without time zone | NOT NULL\n #id | bigint | NOT NULL DEFAULT nextval('organization_id_seq'::regclass)\n #marked_for_deletion | boolean | NOT NULL\n #name | text |\n #about | text |\n #additional_metadata | jsonb |\n \"\"\"\n dbType = dbOrganization\n class Meta:\n interfaces = (CreatedAt,\n IdHolder,\n MarkedForDeletion,\n AdditionalMetadata,\n Name,\n About\n )\n pass\n\nclass CreateOrganization(graphene.Mutation):\n \"\"\"\n example:\n mutation {\n create_organization(name: \"new\", about: \"about\") {\n organization {\n name\n }\n triumph\n }\n }\n\n (this example works)\n return:\n {\n\t\"data\": {\n\t\t\"create_organization\": {\n\t\t\t\"organization\": {\n\t\t\t\t\"name\": \"new\"\n\t\t\t},\n\t\t\t\"triumph\": true\n\t\t}\n\t}\n}\n \"\"\"\n\n class Arguments:\n name = graphene.String(required=True)\n about = graphene.String(required=True)\n\n organization = graphene.Field(Organization)\n triumph = graphene.Boolean()\n\n @staticmethod\n @acl_check_by_id('create', 'organization')\n def mutate(root, info, **args):\n name = args.get('name')\n about = args.get('about')\n\n client_id = info.context[\"client_id\"]\n client = DBSession.query(Client).filter_by(id=client_id).first()\n if not client:\n raise ResponseError(message=\"Invalid client id (not registered on server). Try to logout and then login.\")\n user = DBSession.query(dbUser).filter_by(id=client.user_id).first()\n if not user:\n raise ResponseError(message=\"This client id is orphaned. Try to logout and then login once more.\")\n\n dborganization = dbOrganization(name=name,\n about=about)\n if user not in dborganization.users:\n dborganization.users.append(user)\n DBSession.add(dborganization)\n DBSession.flush()\n\n bases = DBSession.query(dbBaseGroup).filter_by(subject='organization')\n for base in bases:\n group = dbGroup(parent=base, subject_object_id=dborganization.id)\n add_user_to_group(user, group)\n DBSession.add(group)\n\n DBSession.flush()\n organization = Organization(name=dborganization.name, about = dborganization.about, id = dborganization.id)\n organization.dbObject = dborganization\n return CreateOrganization(organization=organization, triumph=True)\n\nclass UpdateOrganization(graphene.Mutation):\n \"\"\"\n example:\n mutation {\n update_organization(organization_id: 1, name: \"new2\") {\n organization {\n name,\n id,\n about\n }\n triumph\n }\n }\n (this example works)\n return:\n {\n \"data\": {\n \"update_organization\": {\n \"organization\": {\n \"name\": \"new2\",\n \"id\": 1,\n \"about\": \"about\"\n },\n \"triumph\": true\n }\n }\n }\n \"\"\"\n\n class Arguments:\n organization_id = graphene.Int(required=True)\n add_users = graphene.List(graphene.Int)\n delete_users = graphene.List(graphene.Int) # TODO: LingvodocID()? (no)\n name = graphene.String()\n about = graphene.String()\n\n organization = graphene.Field(Organization)\n triumph = graphene.Boolean()\n\n @staticmethod\n @acl_check_by_id('edit', 'organization')\n def mutate(root, info, **args):\n organization_id = args.get('organization_id')\n dborganization = DBSession.query(dbOrganization).filter_by(id=organization_id).first()\n\n client_id = info.context[\"client_id\"]\n client = DBSession.query(Client).filter_by(id=client_id).first()\n if not client:\n raise ResponseError(message=\"Invalid client id (not registered on server). Try to logout and then login.\")\n\n creator = DBSession.query(dbUser).filter_by(id=client.user_id).first()\n if not creator:\n raise ResponseError(message=\"This client id is orphaned. Try to logout and then login once more.\")\n if not dborganization or dborganization.marked_for_deletion:\n raise ResponseError(\"No such organization\")\n add_users = args.get('add_users')\n if add_users:\n for user_id in add_users:\n user = DBSession.query(dbUser).filter_by(id=user_id).first()\n if user not in dborganization.users:\n if not user in dborganization.users:\n dborganization.users.append(user)\n bases = DBSession.query(dbBaseGroup).filter_by(subject='organization')\n for base in bases:\n group = DBSession.query(dbGroup).filter_by(base_group_id=base.id,\n subject_object_id=dborganization.id).first()\n add_user_to_group(user, group)\n delete_users = args.get('delete_users')\n if delete_users:\n for user_id in delete_users:\n if user_id == creator.id:\n raise ResponseError(message=\"You shouldn't delete yourself\")\n user = DBSession.query(dbUser).filter_by(id=user_id).first()\n if user in dborganization.users:\n dborganization.users.remove(user)\n bases = DBSession.query(dbBaseGroup).filter_by(subject='organization')\n for base in bases:\n group = DBSession.query(dbGroup).filter_by(base_group_id=base.id,\n subject_object_id=dborganization.id).first()\n group.users.remove(user)\n name = args.get('name')\n if name:\n dborganization.name = name\n\n about = args.get('about')\n if about:\n dborganization.about = about\n\n organization = Organization(name=dborganization.name, about=dborganization.about, id=dborganization.id)\n organization.dbObject = dborganization\n return UpdateOrganization(organization=organization, triumph=True)\n\n\n# class DeleteOrganization(graphene.Mutation):\n# \"\"\"\n# example:\n# mutation {\n# delete_organization(organization_id: 6) {\n# field {\n# name,\n# id,\n# about\n# }\n# triumph\n# }\n# }\n#\n# (this example works)\n# return:\n# {\n# \"delete_organization\": {\n# \"field\": {\n# \"name\": \"new2\",\n# \"id\": 6,\n# \"about\": \"about\"\n# },\n# \"triumph\": true\n# }\n# }\n# \"\"\"\n#\n# class Arguments:\n# organization_id = graphene.Int()\n#\n# organization = graphene.Field(Organization)\n# triumph = graphene.Boolean()\n#\n# @staticmethod\n# def mutate(root, info, **args):\n# organization_id = args.get('organization_id')\n# dborganization = DBSession.query(dbOrganization).filter_by(id=organization_id).first()\n# if dborganization:\n# if not dborganization.marked_for_deletion:\n# del_object(dborganization)\n# organization = Organization(name=dborganization.name, about=dborganization.about, id=dborganization.id)\n# organization.dbObject = dborganization\n# return DeleteOrganization(organization=organization, triumph=True)\n# raise ResponseError(message=\"No such organization in the system\")","sub_path":"lingvodoc/schema/gql_organization.py","file_name":"gql_organization.py","file_ext":"py","file_size_in_byte":8396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"375515518","text":"'''a python class is like a blueprint ofcreating an instance\r\na class is like a blue print for a house, you will need the attributes and methods to build a house from a blueprint.\r\nliterally you can think of a python class as a class of students and the attributes or features of a class includes names of students, age ,gender and thier avarage perfomance. so a class here is more like a representative blue print holding the expected details of the instance/objects (students in this case)'''\r\n\r\nclass Pharmacy:\r\n #initialise the class fuction by defining the instances/object features (student features in this example)\r\n def __init__(self, first, last, age,gender):\r\n self.first =first\r\n self.last =last\r\n self.age = age\r\n self.gender=gender\r\n self.email = first + '.' + last + '@gmail.com'\r\n#create a func inside the class ,for calling out full student name, see line 25 and line 26 for alternative method\r\n def fullname(self):\r\n return '{} {}'.format(self.first, self.last)\r\n\r\n#pass in the values you have specified in the init method above for each student\r\nstudent_a = Pharmacy('joe', 'thomas',21,'male')\r\nstudent_b = Pharmacy('alice', 'baile',24,'female')\r\n #ONCE you have pass in the instances the student details will be run automatically in the class fucntion NB: instances must be passes in the right order as in the initialised func\r\n#now you can run the following comands depending on what you want to pull out of your class\r\n\r\nprint(student_a.email)\r\nprint(student_b.email)\r\nprint(student_a.fullname())\r\nprint('{} {}' .format(student_a.first, student_a.last))","sub_path":"classes and instances.py","file_name":"classes and instances.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"207355554","text":"import os\nfrom findex_gui.web import app\nfrom findex_gui.bin.misc import cwd\nfrom flask import render_template, request, flash, session, redirect, url_for, send_from_directory, abort\n\n\n@app.route(\"/static/\")\ndef static(filename):\n if filename.startswith(\"/\"):\n return abort(404)\n\n from findex_gui.web import themes\n\n filename = filename.replace(\"..\", \"\")\n filename = filename.replace(\"./\", \"\")\n\n if filename.startswith(\"meta/posters/\"):\n _cwd = cwd()\n filename = filename[13:]\n directory = \"%s/meta/posters/\" % _cwd\n if os.path.isfile(\"%s%s\" % (directory, filename)):\n return send_from_directory(directory, filename)\n\n search_dirs = [\"static/\"]\n\n if filename.startswith(\"themes/\"):\n spl = filename.split(\"/\")\n\n if len(spl) >= 3 and spl[2] == \"static\":\n filename = \"/\".join(spl[3:])\n search_dirs.insert(0, \"themes/%s/static/\" % spl[1])\n\n for search_dir in search_dirs:\n directory = \"%s/%s\" % (app.config[\"dir_base\"], search_dir)\n\n if os.path.isfile(directory + filename):\n return send_from_directory(directory, filename)\n\n return themes.render(\"errors/404\", status_code=404)\n","sub_path":"findex_gui/controllers/routes/static.py","file_name":"static.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"78072106","text":"import pandas as pd\nimport numpy as np\nimport re\nimport os\nfrom sklearn.cluster import KMeans\nimport ast\nimport itertools\nimport random\nfrom random import randint\nspice_feat = pd.read_excel('test4.xls')\nspice_feat = spice_feat.iloc[:,:7]\ndef clustering_based(user_feat):\n kmeans = KMeans(n_clusters = 5,random_state=0).fit(user_feat)\n user_feat['label'] = kmeans.labels_\n #print user_label\n\n user_feat = user_feat.sort_values(['label','Location'],ascending=[1,0])\n user = user_feat.drop_duplicates(subset=['Location','label'])\n user = user.groupby('label')['Location'].nlargest(3)\n return user,user_feat\n\n\ndef filter_food_loc(user_group,user_id,non_recom_list,user_feat,spice_feat):\n index = np.where(user_feat['user_guid']==user_id)[0][0]\n #print index\n #print user_feat['label']\n user_label = user_feat.loc[index,'label']\n loc = user_group[user_label].tolist()\n newspice_feat = spice_feat.set_index('food_id')\n spice = newspice_feat[newspice_feat['State'].isin(loc)]\n #print spice\n return filter_food_cal(spice,non_recom_list,user_feat,user_id),loc\n\n\n\ndef filter_food_cal(sspice,non_recom_list,user_feat,user_id):\n index = np.where(user_feat['user_guid']==user_id)[0][0]\n sspice = sspice[sspice['Type']==user_feat.loc[index,'NonVeg']]\n\n #sspice = sspice[sspice['Meal Size']==next_meal_size]\n #sspice = sspice[sspice['Place in Menu']==meal_type]\n\n #print spice\n s_spice = sspice.sort_values('count',ascending=[0])\n s_index = s_spice.index[~s_spice.index.isin(non_recom_list)]\n #print ' rec ',non_recom_list\n new_spices = s_spice[s_spice.index.isin(s_index)]\n #print new_spices\n new_spices = new_spices[new_spices['Calories']<=user_feat.loc[index,'Calories']]\n return new_spices\n\n\n\ndef recommendation(user_group,user_id,non_recom_list,user_feat,spice_feat):\n new_spices,loc = filter_food_loc(user_group,user_id,non_recom_list,user_feat,spice_feat)\n\n recommend = []\n\n index = np.where(user_feat['user_guid']==user_id)[0][0]\n new_spices2 = spice_feat[spice_feat['Type']==user_feat.loc[index,'NonVeg']]\n new_spices2 = new_spices2[new_spices2['Calories']<=user_feat.loc[index,'Calories']]\n #print new_spices2\n\n #even in random,at least 2 constraints are there, calory and veg/non-veg and maybe location(to be confirmed) too\n x = randint(0,9)\n x=5\n if(x==5):\n #print ('random') #to test\n y = randint(0,len(new_spices2)-1)\n #y = random.choice(new_spices2.index.values)\n #print y\n #print len(new_spices2)\n #print new_spices2.index.values\n #print new_spices2.index[y]\n index_to_append = new_spices2.index[y]\n #print random_feat.loc[index_to_append,'food_id']\n recommend.append(new_spices2.loc[index_to_append,'food_id'])\n\n\n for i in range(min(2,len(new_spices))):\n recommend.append(new_spices.index[i])\n\n if(len(recommend)<3):\n other_state_spice = spice_feat[spice_feat['State'].isin(loc)==False]\n\n other_state_spice = other_state_spice.sort_values('count',ascending= [0])\n new_other_state = other_state_spice[~other_state_spice.index.isin(non_recom_list)]\n\n if(len(new_other_state)>=(3-len(recommend))):\n for i in range(3-len(recommend)):\n recommend.append(new_other_state.index[i])\n\n if(len(recommend)<3):\n newlymade_spice = spice_feat.sort_values('count',ascending = [0])\n for i in range(3-len(recommend)):\n recommend.append(newlymade_spice.index[i])\n\n else:\n #print ('not random')\n for i in range(min(3,len(new_spices))):\n recommend.append(new_spices.index[i])\n\n if(len(recommend)<3):\n other_state_spice = spice_feat[spice_feat['State'].isin(loc)==False]\n\n other_state_spice = other_state_spice.sort_values('count',ascending= [0])\n new_other_state = other_state_spice[~other_state_spice.index.isin(non_recom_list)]\n if(len(new_other_state)>=(3-len(recommend))):\n for i in range(3-len(recommend)):\n recommend.append(new_other_state.index[i])\n if(len(recommend)<3):\n newlymade_spice = spice_feat.sort_values('count',ascending = [0])\n for i in range(3-len(recommend)):\n recommend.append(newlymade_spice.index[i])\n\n return recommend\n\n\ndef convert_list(row):\n #x = str(row['last_5_days_recommend'])\n y = str(row['last_5_days_bought'])\n #if isinstance(x,str):\n # x = ast.literal_eval(x)\n if isinstance(y,str):\n y = ast.literal_eval(y)\n\n #l1 = list(itertools.chain.from_iterable(x))\n l2 = list(itertools.chain.from_iterable(y))\n #print l1+l2\n return l2\n\n\ndef change_last_recommend(x,y):\n #print (row['last 5 days recommend'])\n new_recommend = []\n #print type(x) ,y,count\n if isinstance(x,str):\n x = ast.literal_eval(x)\n if isinstance(y,str):\n y = ast.literal_eval(y)\n for i in range(4):\n new_recommend.append(x[i+1])\n new_recommend.append(y)\n #print new_recommend\n return str(new_recommend)\n\n\ndef recommend_items(user_id,non_recom_list,user,user_feat,spice_feat):\n #print type(non_recom_list)\n l1 = recommendation(user,user_id,non_recom_list,user_feat,spice_feat)\n\n #l2 = recommendation_content(user_id,spice_feat,user_rating,non_recom_list,user_feat,output_df)\n\n return str(l1)\n\n\ndef change_type(x):\n if isinstance(x,str):\n x = ast.literal_eval(x)\n return x\n\n\ndef next_day_recommendation(user_feat,new_user_feat,spice_feat): #,user_rating):\n new_user_feat['last_5_days_recommend'] = new_user_feat.apply(lambda x: change_last_recommend(x['last_5_days_recommend'], x['recommends']), axis=1)\n new_user_feat['last_5_days_bought'] = new_user_feat.apply(lambda x: change_last_recommend(x['last_5_days_bought'], x['bought']), axis=1)\n new_user_feat['not_recommended'] = new_user_feat.apply(convert_list,axis=1)\n #print new_user_feat['last_5_days_recommend'][0]\n #print new_user_feat['last_5_days_bought'][0]\n #print new_user_feat['not_recommended'][0]\n user_group ,user_feat = clustering_based(user_feat)\n #spice = np.array(spice_feat.iloc[: ,0:4])\n #outputdf = content_based_reco(user_rating, spice)\n new_user_feat['not_recommended'] = new_user_feat.apply(lambda x:change_type(x['not_recommended']),axis=1)\n #new_user_feat['not_recommended'].to_csv('not_recommended.csv',encoding='utf-8',index = False)\n #print new_user_feat\n new_user_feat['recommends'] = new_user_feat.apply(lambda x:recommend_items(x['user_guid'],x['not_recommended'],user_group,user_feat,spice_feat),axis=1)\n #print new_user_feat\n return new_user_feat\n\ndef main_recommendation(new_user_feat,user_feat,index): #,user_rating):\n\n #index = np.where(new_user_feat['user_guid']==user_id)[0]\n\n x = new_user_feat.loc[index,'recommends']\n\n\n\n if isinstance(x,str):\n x = ast.literal_eval(x)\n\n temp_list = x #list(itertools.chain.from_iterable(x))\n\n dish1 = spice_feat.loc[temp_list[0],'Dish']\n dish2 = spice_feat.loc[temp_list[1],'Dish']\n dish3 = spice_feat.loc[temp_list[2],'Dish']\n #dish4 = spice_feat.loc[temp_list[3],'Dish']\n #dish5 = spice_feat.loc[temp_list[4],'Dish']\n recolist = []\n recolist.append(dish1)\n recolist.append(dish2)\n recolist.append(dish3)\n #recolist.append(dish4)\n #recolist.append(dish5)\n #print (str(temp_list[0])+' = '+dish1+','+str(temp_list[1])+'='+dish2+','+str(temp_list[2])+'='+dish3)\n\n previous_rating = user_feat.loc[index,'meal_size_rating']\n previous_size = user_feat.loc[index,'previous_meal_size']\n next_meal_size = previous_size\n\n if(previous_rating==0 and previous_size<2):\n next_meal_size = previous_size + 1\n elif (previous_rating==2 and previous_size>0):\n next_meal_size = previous_size - 1\n\n\n #meal_type = input('enter the meal type(0,1,2,3)')\n return {'recommend_list':recolist, 'next_meal':next_meal_size}\n #return next_meal_size\n\ndef change_recommendation(user_feat,spice_feat,new_user_feat):\n new_user_feat = next_day_recommendation(user_feat,new_user_feat,spice_feat)\n new_user_feat.to_csv('new_user_feat.csv',encoding='utf-8',index = False)\n","sub_path":"main_recommend.py","file_name":"main_recommend.py","file_ext":"py","file_size_in_byte":8297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"224870856","text":"import re\nimport math\nfrom datetime import datetime\n\nfrom dateutil.relativedelta import relativedelta\n\nimport metadate.locales.en as locale_en\nfrom metadate.scanner import Scanner\n\nfrom metadate.classes import MetaRelative\nfrom metadate.classes import MetaDate\nfrom metadate.classes import MetaOrdinal\nfrom metadate.classes import MetaUnit\nfrom metadate.classes import MetaPeriod\nfrom metadate.classes import MetaModifier\nfrom metadate.classes import MetaRange\nfrom metadate.classes import MetaBetween\nfrom metadate.utils import log\nfrom metadate.utils import UNITS\nfrom metadate.utils import BOUNDARIES\nfrom metadate.utils import erase_level\nUNITS_REV = {v: k for k, v in UNITS.items()}\n\n\ndef get_relevant_parts(matches):\n strike = 0\n bundles = [[]]\n for m in matches:\n if isinstance(m, str):\n strike = 1\n else:\n if strike:\n bundles.append([m])\n else:\n bundles[-1].append(m)\n strike = 0\n return bundles\n\n\ndef between_allowed(x, y, text):\n start = x.span[1]\n end = y.span[0]\n return re.match(\"^[ -]*(and)?[ -]*$\", text[start:end])\n\n\ndef merge_ordinal_unit(matches, text):\n news = []\n t = 0\n last = False\n n = len(matches)\n spans = []\n for i, m in enumerate(matches):\n if i != n - 1 and isinstance(m, MetaOrdinal):\n if last and not between_allowed(last, m, text):\n t = 0\n t += float(m.amount)\n last = m\n spans.append(m.span)\n continue\n elif isinstance(m, MetaUnit):\n m.modifier *= t if t else 1\n m.span = [m.span] + spans\n spans = []\n news.append(m)\n return news\n\n\ndef cleanup_relevant_parts(bundles, locale):\n cleaned_bundles = []\n for bundle in bundles:\n modifier = False\n meta_units = []\n new = []\n for x in bundle:\n if isinstance(x, MetaModifier): # \"this\"\n if meta_units:\n for mu in meta_units:\n rd = relativedelta(**{mu.unit + 's': mu.modifier * locale.MODIFIERS[x.x]})\n new.append(MetaRelative(rd, level=UNITS[mu.unit], span=[x.span, mu.span]))\n modifier = x\n meta_units = []\n elif modifier:\n if isinstance(x, MetaUnit):\n if x.unit == \"quarter\":\n rd_kwargs = {\"months\": 3 * x.modifier * locale.MODIFIERS[modifier.x],\n \"day\": 1}\n else:\n rd_kwargs = {x.unit + 's': x.modifier * locale.MODIFIERS[modifier.x]}\n rd = relativedelta(**rd_kwargs)\n new.append(MetaRelative(rd, level=UNITS[x.unit], span=[x.span, modifier.span]))\n elif isinstance(x, MetaDate):\n # if hasattr(x, \"month\"):\n # print(\"relative\", x.month, modifier)\n # if hasattr(x, \"season\"):\n # print(\"relative\", x.season, modifier)\n new.append(x)\n elif isinstance(x, MetaRelative):\n\n if x.rd.weekday is not None:\n # eg \"next\" tuesday adds +1 week\n weeks = locale.MODIFIERS[modifier.x]\n # \"this\" also adds +1, \"past\" should be -1\n if weeks == 0:\n weeks = 1\n x.rd.weeks += weeks\n modifier = False\n\n new.append(x)\n\n elif isinstance(x, MetaUnit):\n meta_units.append(x)\n modifier = False\n else:\n if not isinstance(x, MetaOrdinal):\n new.append(x)\n meta_units = []\n modifier = False\n cleaned_bundles.append(new)\n cleaned_bundles = [x for x in cleaned_bundles if any(\n [isinstance(y, MetaDate) or isinstance(y, MetaRelative) for y in x])]\n return cleaned_bundles\n\n\ndef resolve_end_period(start_date, level, future, now):\n future_changed = False\n start_date = erase_level(start_date, level)\n if level == 9: # year\n end_date = start_date + relativedelta(years=1)\n elif level == 8: # season\n end_date = start_date + relativedelta(months=3)\n elif level == 7: # quarter\n for cap in [1, 4, 7, 10]:\n if start_date.month <= cap:\n break\n end_month = (cap + 3)\n if end_month > 12:\n end_date = start_date + relativedelta(month=end_month % 12, day=1, years=1)\n else:\n end_date = start_date + relativedelta(month=end_month, day=1)\n elif level == 6: # month\n end_date = start_date + relativedelta(months=1)\n elif level == 5: # week\n end_date = start_date + relativedelta(days=7)\n elif level == 4: # day\n end_date = start_date + relativedelta(days=1)\n elif level == 3: # hour\n end_date = start_date + relativedelta(hours=1)\n elif level == 2: # minute\n end_date = start_date + relativedelta(minutes=1)\n elif level == 1: # second\n end_date = start_date + relativedelta(seconds=1)\n elif level == 0: # microsecond\n end_date = start_date + relativedelta(microseconds=1)\n if future and end_date < now:\n start_date = start_date.replace(year=start_date.year + 1)\n end_date = end_date.replace(year=end_date.year + 1)\n future_changed = True\n elif future and start_date < now:\n start_date = now\n future_changed = True\n return start_date, end_date, future_changed\n\n\ndef flatten_inner(l):\n span = []\n for s in l:\n if isinstance(s, list):\n span.extend(flatten_span(s))\n else:\n span.append(s)\n return span\n\n\ndef flatten_span(l):\n return sorted(set(flatten_inner(l)))\n\n\ndef get_min_level(cleaned_bundle):\n level = 100\n for x in cleaned_bundle:\n if isinstance(x, (MetaRelative, MetaUnit, MetaDate)):\n level = min(x.level, level)\n return level\n\n\ndef datify(cleaned_bundle, future):\n now = datetime.now()\n span = flatten_span([x.span for x in cleaned_bundle])\n level = get_min_level(cleaned_bundle)\n # print(level)\n rdt, erdt = resolve_dt(cleaned_bundle, now)\n if erdt is not None:\n start_date = rdt + resolve_rd(cleaned_bundle)\n end_date = erdt + resolve_rd(cleaned_bundle)\n start_date, _, _ = resolve_end_period(start_date, level, future, now)\n end_date = erase_level(erdt, level)\n else:\n resolved_rd = resolve_rd(cleaned_bundle)\n try:\n start_date = rdt + resolved_rd\n except TypeError:\n resolved_rd.years = int(resolved_rd.years)\n resolved_rd.months = int(resolved_rd.months)\n start_date = rdt + resolved_rd\n\n start_date, end_date, _ = resolve_end_period(start_date, level, future, now)\n return start_date, end_date, level, span\n\n# flexible for running with a default init of locale_en\nen_scanner = Scanner(locale_en)\n\n\ndef has_between(bundle):\n return any(isinstance(x, MetaBetween) for x in bundle)\n\n\ndef merge_dt(mdt, dt):\n # mdt is a made-up mutable dt\n # month is precomputed so that day can be init\n month = month = mdt[1] if mdt[1] > -1 else dt.month\n day = mdt[2] if mdt[2] > -1 else dt.day\n ndt = datetime(year=mdt[0] if mdt[0] > -1 else dt.year,\n month=month,\n day=min(day, BOUNDARIES[month]),\n hour=mdt[3] if mdt[3] > -1 else dt.hour,\n minute=mdt[4] if mdt[4] > -1 else dt.minute,\n second=mdt[5] if mdt[5] > -1 else dt.second,\n microsecond=mdt[6] if mdt[6] > -1 else dt.microsecond)\n return ndt\n\n\ndef resolve_dt(cleaned_bundle, now):\n indices = {'year': 0, 'month': 1, 'day': 2, 'hour': 3,\n 'minute': 4, 'second': 5, 'microsecond': 6}\n dts = [-1, -1, -1, -1, -1, -1, -1]\n edts = [-1, -1, -1, -1, -1, -1, -1]\n contains_between = has_between(cleaned_bundle)\n for d in cleaned_bundle:\n if isinstance(d, MetaDate):\n for x in d.__dict__:\n if x not in ['level', 'span']:\n if dts[indices[x]] != -1:\n if not contains_between:\n raise ValueError(\"Field already known in dt, should not overwrite?\")\n else:\n dts[indices[x]] = getattr(d, x)\n edts[indices[x]] = getattr(d, x)\n dt = merge_dt(dts, now)\n edt = merge_dt(edts, now) if contains_between else None\n return dt, edt\n\n\ndef resolve_rd(cleaned_bundle):\n indices = {'year': 0, 'month': 1, 'day': 2, 'hour': 3,\n 'minute': 4, 'second': 5, 'microsecond': 6}\n rds = relativedelta()\n for d in cleaned_bundle:\n if isinstance(d, MetaRelative):\n rds += d.rd\n return rds\n\n\ndef handle_meta_range(cleaned_bundle, future, locale, text):\n now = datetime.now()\n phase = 0\n mrange = None\n relatives = []\n metadates = []\n for x in cleaned_bundle:\n if phase == 0 and isinstance(x, MetaRange):\n phase = 1\n mrange = x\n elif phase == 1 or phase == 2 and isinstance(x, MetaRelative):\n phase = 2\n relatives.append(x)\n elif phase == 2 or phase == 3 and isinstance(x, MetaDate):\n phase = 3\n metadates.append(x)\n if phase < 2:\n return None\n # case 1: MetaRange, MetaRelative, MetaRelative, etc\n # log(\"relatives\", relatives, True)\n # log(\"metadates\", metadates, True)\n if not metadates:\n # in this case, the start_date becomes \"now\" adjusted for level\n # the end_date is the start_date + relativedeltas following\n level = get_min_level(relatives)\n rds = relativedelta()\n start_date = erase_level(now, 1)\n for x in relatives:\n rds += x.rd\n try:\n end_date = start_date + rds\n except TypeError:\n rds.years = int(rds.years)\n rds.months = int(rds.months)\n end_date = start_date + rds\n span = flatten_span([mrange.span, [x.span for x in relatives]])\n if start_date > end_date:\n start_date, end_date = end_date, start_date\n return MetaPeriod(start_date, end_date, level, span, locale.NAME, text)\n else:\n spans = flatten_span([flatten_span(x.span) for x in relatives])\n words = [text[x[0]:x[1]].lower() for x in spans]\n # generic\n dt, _ = resolve_dt(metadates, now)\n dt_level = get_min_level(metadates)\n rd_level = get_min_level(relatives)\n if \"first\" in words:\n # this is actually the logic for !first! days of, not \"next days of\"\n # case 2: MetaRange, MetaRelative, MetaRelative, etc, MetaDate, Metadate, etc\n start_date, _, future_changed = resolve_end_period(dt, dt_level, future, now)\n end_date = erase_level(dt, dt_level) + resolve_rd(relatives)\n elif \"last\" in words:\n _, end_date, future_changed = resolve_end_period(dt, dt_level, future, now)\n start_date = erase_level(end_date, dt_level) + resolve_rd(relatives)\n else:\n raise NotImplementedError(\"What's the case here?\")\n if future_changed:\n start_date = start_date + relativedelta(years=1) # I think also here?\n end_date = end_date + relativedelta(years=1)\n span = flatten_span([mrange.span] + [x.span for x in relatives] +\n [x.span for x in metadates])\n return MetaPeriod(start_date, end_date, min(rd_level, dt_level), span, locale.NAME, text)\n\n\ndef parse_date(text, future=True, locale=locale_en, multi=False, verbose=False):\n if multi:\n raise NotImplementedError(\"multi\")\n log(\"\\nSentence\", text, verbose)\n scanner = en_scanner if locale == locale_en else Scanner(locale)\n matches, _ = scanner.scan(text)\n log(\"matches\", matches, verbose=verbose)\n parts = get_relevant_parts(matches)\n log(\"1\", parts, verbose=verbose)\n merged = [merge_ordinal_unit(x, text) for x in parts]\n log(\"2\", merged, verbose=verbose)\n cleaned_parts = cleanup_relevant_parts(merged, locale)\n log(\"3\", cleaned_parts, verbose)\n if not cleaned_parts:\n return [] if multi else None\n cleaned_parts = sorted(cleaned_parts, key=len, reverse=True)\n now = datetime.now()\n cleaned_bundle = cleaned_parts[0]\n\n handle_meta_result = handle_meta_range(cleaned_bundle, future, locale, text)\n if handle_meta_result:\n log(\"4meta\", handle_meta_result, verbose)\n return handle_meta_result\n start_date, end_date, level, span = datify(cleaned_bundle, future)\n mp = MetaPeriod(start_date, end_date, UNITS_REV[level], span, locale.NAME, text)\n log(\"4default\", mp, verbose)\n if future and mp.start_date < now:\n return None\n return mp\n","sub_path":"metadate/parse_date.py","file_name":"parse_date.py","file_ext":"py","file_size_in_byte":13016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"423721729","text":"#/usr/bin/env python\n\nimport os\nimport argparse\nimport subprocess\n\ndef main():\n parser = argparse.ArgumentParser(description='Pull log files from the roboRIO')\n parser.add_argument('--team', default='1678', help='What team number to use for the roboRIO.')\n parser.add_argument('--address', help='What IP address to fetch from. Not compatible with --team')\n parser.add_argument('--user', default='admin', help='What user to log in as on the roboRIO')\n parser.add_argument('--remote-path', default='/media/sda1/logs/', help='What path to fetch logs from.')\n parser.add_argument('--local-path', default=None, help=\"What path to write logs to. Defaults to logs/[roborio address] in the repo's root\")\n parser.add_argument('--num-logs', default=10, help=\"How many logs (from the current log) do you want to pull\")\n\n args = parser.parse_args()\n\n if args.address == None:\n rio_address = \"roborio-{}-frc.local\".format(args.team)\n else:\n rio_address = args.address\n rio_user = args.user\n rio_path = args.remote_path\n if args.local_path == None:\n local_path = os.path.abspath(os.path.dirname(__file__)) + \"/../logs/{}/\".format(rio_address) # Write to robot-code/logs/\n else:\n local_path = args.local_path\n subprocess.call([\"mkdir\", \"-p\", local_path])\n\n # Get directory names of the past n logs\n file_list_command = [\"ssh\", \"{user}@{address}\".format(user=rio_user, address=rio_address),\n \"ls\", \"-1t\", \"{}\".format(rio_path), \"|\", # List all logs, sorted by time\n \"head\" , \"-n\", \"{}\".format(args.num_logs)]\n proc = subprocess.Popen(file_list_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = proc.communicate()\n\n rsync_remote_path = [\"{user}@{address}:{path}\".format(user=rio_user, address=rio_address, path=rio_path)]\n for line in stdout.split():\n rsync_remote_path.append(\":\" + rio_path + line + \" \")\n\n rsync_args = [\"--verbose\", \"--archive\", \"--times\", \"--human-readable\", \"--progress\"]\n rsync_command = [\"rsync\"] + rsync_args + rsync_remote_path + [local_path]\n\n subprocess.call(rsync_command)\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/pull_logs.py","file_name":"pull_logs.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"439135765","text":"import os\nimport json\nimport bpy\nfrom bpy.types import PropertyGroup\nfrom .. utils.registration import get_prefs\n\nfrom .. enums.enums import (\n tile_main_systems,\n tile_types,\n base_systems,\n tile_blueprints,\n curve_types,\n geometry_types,\n base_socket_side,\n units,\n material_mapping,\n openlock_column_types)\n\nfrom .. lib.utils.update_scene_props import load_material_libraries\n\n\n# Radio buttons used in menus\nclass MT_Radio_Buttons(PropertyGroup):\n def update_mapping_axis(self, context):\n axis = context.window_manager.mt_radio_buttons.mapping_axis\n material = context.object.active_material\n tree = material.node_tree\n nodes = tree.nodes\n axis_node = nodes['Wrap Around Axis']\n\n if axis == 'X':\n axis_node.inputs[0].default_value = 1\n axis_node.inputs[1].default_value = 0\n axis_node.inputs[2].default_value = 0\n elif axis == 'Y':\n axis_node.inputs[0].default_value = 0\n axis_node.inputs[1].default_value = 1\n axis_node.inputs[2].default_value = 0\n elif axis == 'Z':\n axis_node.inputs[0].default_value = 0\n axis_node.inputs[1].default_value = 0\n axis_node.inputs[2].default_value = 1\n\n mapping_axis: bpy.props.EnumProperty(\n items=[\n ('X', 'X', 'X', '', 0),\n ('Y', 'Y', 'Y', '', 1),\n ('Z', 'Z', 'Z', '', 2)\n ],\n default='Z',\n description='Mapping axis for wrap around material projection',\n update=update_mapping_axis\n )\n\n\n# A cutter item used by mt_cutters_collection and mt_trimmers_collection\nclass MT_Cutter_Item(PropertyGroup):\n def update_use_cutter(self, context):\n if self.parent is not \"\":\n parent_obj = bpy.data.objects[self.parent]\n bool_mod = parent_obj.modifiers[self.name + '.bool']\n bool_mod.show_viewport = self.value\n\n if parent_obj.mt_object_props.linked_object is not None:\n linked_obj = parent_obj.mt_object_props.linked_object\n bool_mod = linked_obj.modifiers[self.name + '.bool']\n bool_mod.show_viewport = self.value\n\n name: bpy.props.StringProperty(\n name=\"Cutter Name\")\n value: bpy.props.BoolProperty(\n name=\"\",\n default=True,\n update=update_use_cutter)\n parent: bpy.props.StringProperty(\n name=\"\")\n\n\nclass MT_Trimmer_Item(PropertyGroup):\n def update_use_trimmer(self, context):\n obj = context.object\n if self.name + '.bool' in obj.modifiers:\n bool_mod = obj.modifiers[self.name + '.bool']\n bool_mod.show_viewport = self.value\n\n name: bpy.props.StringProperty(\n name=\"Trimmer Name\")\n value: bpy.props.BoolProperty(\n name=\"\",\n default=False,\n update=update_use_trimmer)\n parent: bpy.props.StringProperty(\n name=\"\")\n\n\nclass MT_Scene_Properties(PropertyGroup):\n def change_tile_type(self, context):\n self.update_size_defaults(context)\n self.update_subdiv_defaults(context)\n\n def update_size_defaults(self, context):\n '''updates tile and base size defaults depending on what we are generating'''\n scene_props = context.scene.mt_scene_props\n if scene_props.mt_tile_type in (\n 'RECTANGULAR_FLOOR',\n 'TRIANGULAR_FLOOR',\n 'CURVED_FLOOR',\n 'STRAIGHT_FLOOR',\n 'SEMI_CIRC_FLOOR'):\n scene_props.mt_tile_z = 0.3\n scene_props.mt_base_z = 0.2755\n scene_props.mt_tile_x = 2\n scene_props.mt_tile_y = 2\n scene_props.mt_base_x = 2\n scene_props.mt_base_y = 2\n elif scene_props.mt_tile_type == 'CORNER_FLOOR':\n scene_props.mt_tile_z = 0.3\n scene_props.mt_base_z = 0.2755\n scene_props.mt_tile_x = 2\n scene_props.mt_tile_y = 0.5\n scene_props.mt_base_x = 2\n scene_props.mt_base_y = 0.5\n elif scene_props.mt_tile_type == 'CONNECTING_COLUMN':\n scene_props.mt_base_x = 0.5\n scene_props.mt_base_y = 0.5\n scene_props.mt_base_z = 0.2755\n scene_props.mt_tile_x = 0.5\n scene_props.mt_tile_y = 0.5\n scene_props.mt_tile_z = 2\n else:\n scene_props.mt_tile_x = 2\n scene_props.mt_tile_y = 0.3149\n scene_props.mt_tile_z = 2\n scene_props.mt_base_x = 2\n scene_props.mt_base_y = 0.5\n scene_props.mt_base_z = 0.2755\n\n\n\n def update_subdiv_defaults(self, context):\n scene_props = context.scene.mt_scene_props\n if scene_props.mt_tile_type == 'STRAIGHT_WALL':\n scene_props.mt_x_native_subdivisions = 15\n scene_props.mt_y_native_subdivisions = 3\n scene_props.mt_z_native_subdivisions = 15\n elif scene_props.mt_tile_type == 'STRAIGHT_FLOOR':\n scene_props.mt_x_native_subdivisions = 15\n scene_props.mt_y_native_subdivisions = 3\n scene_props.mt_z_native_subdivisions = 1\n elif scene_props.mt_tile_type == 'CURVED_WALL':\n scene_props.mt_curve_native_subdivisions = 20\n scene_props.mt_y_native_subdivisions = 3\n scene_props.mt_z_native_subdivisions = 15\n elif scene_props.mt_tile_type == 'CURVED_FLOOR':\n scene_props.mt_curve_native_subdivisions = 20\n scene_props.mt_y_native_subdivisions = 3\n scene_props.mt_z_native_subdivisions = 1\n elif scene_props.mt_tile_type == 'CORNER_WALL':\n scene_props.mt_leg_1_native_subdivisions = 15\n scene_props.mt_leg_2_native_subdivisions = 15\n scene_props.mt_width_native_subdivisions = 3\n scene_props.mt_z_native_subdivisions = 15\n elif scene_props.mt_tile_type == 'CORNER_FLOOR':\n scene_props.mt_leg_1_native_subdivisions = 15\n scene_props.mt_leg_2_native_subdivisions = 15\n scene_props.mt_width_native_subdivisions = 3\n scene_props.mt_z_native_subdivisions = 1\n elif scene_props.mt_tile_type == 'RECTANGULAR_FLOOR':\n scene_props.mt_x_native_subdivisions = 15\n scene_props.mt_y_native_subdivisions = 15\n scene_props.mt_z_native_subdivisions = 1\n elif scene_props.mt_tile_type == 'TRIANGULAR_FLOOR':\n scene_props.mt_x_native_subdivisions = 15\n scene_props.mt_y_native_subdivisions = 15\n scene_props.mt_z_native_subdivisions = 1\n scene_props.mt_opposite_native_subdivisions = 15\n elif scene_props.mt_tile_type == 'SEMI_CIRC_FLOOR':\n scene_props.mt_x_native_subdivisions = 15\n scene_props.mt_y_native_subdivisions = 15\n scene_props.mt_z_native_subdivisions = 1\n scene_props.mt_curve_native_subdivisions = 20\n elif scene_props.mt_tile_type == 'CONNECTING_COLUMN':\n scene_props.mt_x_native_subdivisions = 3\n scene_props.mt_y_native_subdivisions = 3\n scene_props.mt_z_native_subdivisions = 15\n\n def update_disp_strength(self, context):\n obj = bpy.context.object\n obj_props = obj.mt_object_props\n tile = bpy.data.collections[obj_props.tile_name]\n tile.mt_tile_props.displacement_strength = context.scene.mt_scene_props.mt_displacement_strength\n if obj_props.geometry_type == 'DISPLACEMENT':\n if 'Displacement' in obj.modifiers:\n mod = obj.modifiers['Displacement']\n mod.strength = context.scene.mt_scene_props.mt_displacement_strength\n\n def update_disp_subdivisions(self, context):\n '''Updates the numnber of subdivisions used by the displacement material modifier'''\n obj = bpy.context.object\n obj_props = obj.mt_object_props\n if obj_props.geometry_type == 'DISPLACEMENT':\n if 'Subsurf' in obj.modifiers:\n modifier = obj.modifiers['Subsurf']\n modifier.levels = context.scene.mt_scene_props.mt_subdivisions\n\n def update_material_mapping(self, context):\n '''updates which mapping method to use for a material'''\n material = context.object.active_material\n tree = material.node_tree\n nodes = tree.nodes\n\n map_meth = context.scene.mt_scene_props.mt_material_mapping_method\n\n if 'master_mapping' in nodes:\n mapping_node = nodes['master_mapping']\n if map_meth == 'WRAP_AROUND':\n map_type_node = nodes['wrap_around_map']\n tree.links.new(\n map_type_node.outputs['Vector'],\n mapping_node.inputs['Vector'])\n elif map_meth == 'TRIPLANAR':\n map_type_node = nodes['triplanar_map']\n tree.links.new(\n map_type_node.outputs['Vector'],\n mapping_node.inputs['Vector'])\n elif map_meth == 'OBJECT':\n map_type_node = nodes['object_map']\n tree.links.new(\n map_type_node.outputs['Color'],\n mapping_node.inputs['Vector'])\n elif map_meth == 'GENERATED':\n map_type_node = nodes['generated_map']\n tree.links.new(\n map_type_node.outputs['Color'],\n mapping_node.inputs['Vector'])\n elif map_meth == 'UV':\n map_type_node = nodes['UV_map']\n tree.links.new(\n map_type_node.outputs['Color'],\n mapping_node.inputs['Vector'])\n\n def update_UV_island_margin(self, context):\n '''Reruns UV smart project for preview and displacement object'''\n\n if len(bpy.context.selected_editable_objects) > 0:\n obj = bpy.context.object\n if obj.type == 'MESH':\n obj_props = obj.mt_object_props\n if obj_props.geometry_type in ('DISPLACEMENT', 'PREVIEW'):\n linked_obj = obj_props.linked_object\n\n tile = bpy.data.collections[obj_props.tile_name]\n tile_props = tile.mt_tile_props\n\n scene_props = context.scene.mt_scene_props\n UV_island_margin = scene_props.mt_UV_island_margin\n tile_props.UV_island_margin = UV_island_margin\n\n for ob in (obj, linked_obj):\n ctx = {\n 'object': ob,\n 'active_object': ob,\n 'selected_objects': [ob]\n }\n bpy.ops.uv.smart_project(ctx, island_margin=UV_island_margin)\n\n if obj_props.geometry_type == 'DISPLACEMENT':\n bpy.ops.scene.mt_return_to_preview()\n bpy.ops.scene.mt_make_3d()\n\n def load_material_enums(self, context):\n '''Constructs a material Enum from materials found in the materials asset folder'''\n enum_items = []\n if context is None:\n return enum_items\n\n if context.scene.mt_scene_props.mt_is_just_activated is True:\n load_material_libraries(dummy=None)\n\n prefs = get_prefs()\n\n materials = bpy.data.materials\n for material in materials:\n # prevent make-tile adding the default material to the list\n if material.name != prefs.secondary_material and material.name != 'Material':\n enum = (material.name, material.name, \"\")\n enum_items.append(enum)\n return enum_items\n\n def create_object_type_enums(self, context):\n prefs = get_prefs()\n\n object_defaults = os.path.join(\n prefs.assets_path,\n \"object_definitions\",\n \"object_defaults.json\"\n )\n\n items = set()\n enum_items = []\n\n with open(object_defaults) as json_file:\n data = json.load(json_file)\n for i in data['Objects']:\n items.add(i['Type'])\n\n for item in items:\n enum = (item, item, \"\")\n enum_items.append(enum)\n\n return enum_items\n\n mt_object_types: bpy.props.EnumProperty(\n items=create_object_type_enums,\n name=\"Object Type\"\n )\n\n mt_is_just_activated: bpy.props.BoolProperty(\n description=\"Has the add-on just been activated. Used to populate materials list first time round\",\n default=False\n )\n\n mt_last_selected: bpy.props.PointerProperty(\n name=\"Last Selected Object\",\n type=bpy.types.Object\n )\n\n mt_tile_name: bpy.props.StringProperty(\n name=\"Tile Name\",\n default=\"Tile\"\n )\n\n mt_tile_units: bpy.props.EnumProperty(\n items=units,\n name=\"Units\",\n default='INCHES'\n )\n\n mt_tile_blueprint: bpy.props.EnumProperty(\n items=tile_blueprints,\n name=\"Blueprint\",\n default='OPENLOCK'\n )\n\n mt_main_part_blueprint: bpy.props.EnumProperty(\n items=tile_main_systems,\n name=\"Main System\",\n default='OPENLOCK'\n )\n\n mt_tile_type: bpy.props.EnumProperty(\n items=tile_types,\n name=\"Type\",\n default=\"STRAIGHT_WALL\",\n update=change_tile_type\n )\n\n mt_base_blueprint: bpy.props.EnumProperty(\n items=base_systems,\n name=\"Base Type\",\n default='OPENLOCK'\n )\n\n mt_UV_island_margin: bpy.props.FloatProperty(\n name=\"UV Margin\",\n default=0.01,\n precision=4,\n min=0,\n step=0.1,\n description=\"Tweak this if you have gaps in material at edges of tiles when you Make3D\",\n update=update_UV_island_margin\n )\n\n # Native Subdivisions #\n mt_x_native_subdivisions: bpy.props.IntProperty(\n name=\"X\",\n description=\"The number of times to subdivide the X axis on creation\",\n default=15\n )\n\n mt_y_native_subdivisions: bpy.props.IntProperty(\n name=\"Y\",\n description=\"The number of times to subdivide the Y axis on creation\",\n default=3\n )\n\n mt_z_native_subdivisions: bpy.props.IntProperty(\n name=\"Z\",\n description=\"The number of times to subdivide the Z axis on creation\",\n default=15\n )\n\n mt_opposite_native_subdivisions: bpy.props.IntProperty(\n name=\"Opposite Side\",\n description=\"The number of times to subdivide the edge opposite the root angle on triangular tile creation\",\n default=15\n )\n\n mt_curve_native_subdivisions: bpy.props.IntProperty(\n name=\"Curved Side\",\n description=\"The number of times to subdivide the curved side of a tile\",\n default=15\n )\n\n mt_leg_1_native_subdivisions: bpy.props.IntProperty(\n name=\"Leg 1\",\n description=\"The number of times to subdivide the length of leg 1 of the tile\",\n default=15\n )\n\n mt_leg_2_native_subdivisions: bpy.props.IntProperty(\n name=\"Leg 2\",\n description=\"The number of times to subdivide the length of leg 2 of the tile\",\n default=15\n )\n\n mt_width_native_subdivisions: bpy.props.IntProperty(\n name=\"Width\",\n description=\"The number of times to subdivide each leg along its width\",\n default=3\n )\n\n mt_material_mapping_method: bpy.props.EnumProperty(\n items=material_mapping,\n description=\"How to map the active material onto an object\",\n name=\"Material Mapping Method\",\n update=update_material_mapping,\n default='OBJECT'\n )\n\n mt_displacement_strength: bpy.props.FloatProperty(\n name=\"Displacement Strength\",\n description=\"Overall Displacement Strength\",\n default=0.1,\n step=1,\n precision=3,\n update=update_disp_strength\n )\n\n mt_tile_material_1: bpy.props.EnumProperty(\n items=load_material_enums,\n name=\"Material\"\n )\n\n mt_tile_resolution: bpy.props.IntProperty(\n name=\"Resolution\",\n description=\"Bake resolution of displacement maps. Higher = better quality but slower. Also images are 32 bit so 4K and 8K images can be gigabytes in size\",\n default=1024,\n min=1024,\n max=8192,\n step=1024,\n )\n\n mt_subdivisions: bpy.props.IntProperty(\n name=\"Subdivisions\",\n description=\"How many times to subdivide the displacement mesh with a subsurf modifier. Higher = better but slower.\",\n default=3,\n soft_max=8,\n update=update_disp_subdivisions\n )\n\n # Tile and base size. We use seperate floats so that we can only show\n # customisable ones where appropriate. These are wrapped up\n # in a vector and passed on as tile_size and base_size\n\n # Tile size\n mt_tile_x: bpy.props.FloatProperty(\n name=\"X\",\n default=2.0,\n step=0.5,\n precision=3,\n min=0\n )\n\n mt_tile_y: bpy.props.FloatProperty(\n name=\"Y\",\n default=2,\n step=0.5,\n precision=3,\n min=0\n )\n\n mt_tile_z: bpy.props.FloatProperty(\n name=\"Z\",\n default=2.0,\n step=0.1,\n precision=3,\n min=0\n )\n\n # Base size\n mt_base_x: bpy.props.FloatProperty(\n name=\"X\",\n default=2.0,\n step=0.5,\n precision=3,\n min=0\n )\n\n mt_base_y: bpy.props.FloatProperty(\n name=\"Y\",\n default=0.5,\n step=0.5,\n precision=3,\n min=0\n )\n\n mt_base_z: bpy.props.FloatProperty(\n name=\"Z\",\n default=0.3,\n step=0.1,\n precision=3,\n min=0\n )\n\n # Corner wall and triangular base specific\n mt_angle: bpy.props.FloatProperty(\n name=\"Base Angle\",\n default=90,\n step=5,\n precision=1\n )\n\n mt_leg_1_len: bpy.props.FloatProperty(\n name=\"Leg 1 Length\",\n description=\"Length of leg\",\n default=2,\n step=0.5,\n precision=2\n )\n\n mt_leg_2_len: bpy.props.FloatProperty(\n name=\"Leg 2 Length\",\n description=\"Length of leg\",\n default=2,\n step=0.5,\n precision=2\n )\n\n # Openlock curved wall specific\n mt_base_socket_side: bpy.props.EnumProperty(\n items=base_socket_side,\n name=\"Socket Side\",\n default=\"INNER\",\n )\n\n # Used for curved wall tiles\n mt_base_radius: bpy.props.FloatProperty(\n name=\"Base inner radius\",\n default=2.0,\n step=0.5,\n precision=3,\n min=0,\n )\n\n mt_wall_radius: bpy.props.FloatProperty(\n name=\"Wall inner radius\",\n default=2.0,\n step=0.5,\n precision=3,\n min=0\n )\n\n # used for curved floors\n mt_curve_type: bpy.props.EnumProperty(\n items=curve_types,\n name=\"Curve type\",\n default=\"POS\",\n description=\"Whether the tile has a positive or negative curvature\"\n )\n\n # Openlock connecting column specific\n mt_openlock_column_type: bpy.props.EnumProperty(\n items=openlock_column_types,\n name=\"Column type\",\n default=\"O\"\n )\n\n # TODO: Fix hack to make 360 curved wall work. Ideally this should merge everything\n mt_degrees_of_arc: bpy.props.FloatProperty(\n name=\"Degrees of arc\",\n default=90,\n step=45,\n precision=1,\n max=359.999,\n min=0\n )\n\n # used for rescaling objects\n mt_base_unit: bpy.props.EnumProperty(\n name=\"Base Unit\",\n items=units\n )\n\n mt_target_unit: bpy.props.EnumProperty(\n name=\"Target Unit\",\n items=units\n )\n\n\nclass MT_Object_Properties(PropertyGroup):\n is_mt_object: bpy.props.BoolProperty(\n name=\"Is MakeTile Object\",\n default=False\n )\n\n tile_name: bpy.props.StringProperty(\n name=\"Tile Name\"\n )\n\n geometry_type: bpy.props.EnumProperty(\n name=\"Geometry Type\",\n items=geometry_types\n )\n\n # Collection of cutters that can be turned on or off\n # by MakeTile.\n cutters_collection: bpy.props.CollectionProperty(\n name=\"Cutters Collection\",\n type=MT_Cutter_Item\n )\n\n linked_object: bpy.props.PointerProperty(\n name=\"Linked Object\",\n type=bpy.types.Object,\n description=\"Used for storing a reference from a preview object to a displacement object and vice versa\"\n )\n\n\nclass MT_Tile_Properties(PropertyGroup):\n is_mt_collection: bpy.props.BoolProperty(\n name=\"Is MakeTile collection\",\n default=False)\n\n tile_name: bpy.props.StringProperty(\n name=\"Tile Name\"\n )\n\n # Tile type #\n tile_blueprint: bpy.props.EnumProperty(\n items=tile_blueprints,\n name=\"Blueprint\",\n description=\"Blueprint for entire tile - e.g. openLOCK or Plain\")\n\n main_part_blueprint: bpy.props.EnumProperty(\n items=tile_main_systems,\n name=\"Main System\",\n description=\"Blueprint for main part of tile. \\\n # E.g. for a wall this would be the system used for the \\\n #vertical bit\")\n\n base_blueprint: bpy.props.EnumProperty(\n items=base_systems,\n name=\"Base System\",\n description=\"Blueprint for base of the tile.\")\n\n tile_type: bpy.props.EnumProperty(\n items=tile_types,\n name=\"Type\",\n description=\"The type of tile e.g. Straight Wall, Curved Floor\",\n default=\"STRAIGHT_WALL\",\n )\n\n # Native Subdivisions #\n x_native_subdivisions: bpy.props.IntProperty(\n name=\"X\",\n description=\"The number of times to subdivide the X axis on creation\",\n default=15\n )\n\n y_native_subdivisions: bpy.props.IntProperty(\n name=\"Y\",\n description=\"The number of times to subdivide the Y axis on creation\",\n default=3\n )\n\n z_native_subdivisions: bpy.props.IntProperty(\n name=\"Z\",\n description=\"The number of times to subdivide the Z axis on creation\",\n default=15\n )\n\n opposite_native_subdivisions: bpy.props.IntProperty(\n name=\"Opposite Side\",\n description=\"The number of times to subdivide the edge opposite the root angle on triangular tile creation\",\n default=1\n )\n\n curve_native_subdivisions: bpy.props.IntProperty(\n name=\"Curved Side\",\n description=\"The number of times to subdivide the curved side of a tile\",\n default=1\n )\n\n leg_1_native_subdivisions: bpy.props.IntProperty(\n name=\"Leg 1\",\n description=\"The number of times to subdivide the length of leg 1 of the tile\",\n default=15\n )\n\n leg_2_native_subdivisions: bpy.props.IntProperty(\n name=\"Leg 2\",\n description=\"The number of times to subdivide the length of leg 2 of the tile\",\n default=15\n )\n\n width_native_subdivisions: bpy.props.IntProperty(\n name=\"Width\",\n description=\"The number of times to subdivide each leg along its width\",\n default=3\n )\n\n # Subsurf modifier subdivisions #\n subdivisions: bpy.props.IntProperty(\n name=\"Subdivisions\",\n description=\"Subsurf modifier subdivision levels\",\n default=3\n )\n\n # UV smart projection correction\n UV_island_margin: bpy.props.FloatProperty(\n name=\"UV Margin\",\n default=0.012,\n min=0,\n step=0.001,\n description=\"Tweak this if you have gaps at edges of tiles when you Make3D\"\n )\n\n # Dimensions #\n tile_size: bpy.props.FloatVectorProperty(\n name=\"Tile Size\"\n )\n\n base_size: bpy.props.FloatVectorProperty(\n name=\"Base size\"\n )\n\n base_radius: bpy.props.FloatProperty(\n name=\"Base Radius\"\n )\n\n wall_radius: bpy.props.FloatProperty(\n name=\"Wall Radius\"\n )\n\n base_socket_side: bpy.props.EnumProperty(\n name=\"Socket Side\",\n items=base_socket_side\n )\n\n degrees_of_arc: bpy.props.FloatProperty(\n name=\"Degrees of Arc\"\n )\n\n angle: bpy.props.FloatProperty(\n name=\"Angle\"\n )\n\n leg_1_len: bpy.props.FloatProperty(\n name=\"Leg 1 Length\"\n )\n\n leg_2_len: bpy.props.FloatProperty(\n name=\"Leg 2 Length\"\n )\n\n curve_type: bpy.props.EnumProperty(\n name=\"Curve Type\",\n items=curve_types\n )\n\n openlock_column_type: bpy.props.EnumProperty(\n items=openlock_column_types,\n name=\"Column type\"\n )\n\n tile_units: bpy.props.EnumProperty(\n name=\"Tile Units\",\n items=units\n )\n\n displacement_strength: bpy.props.FloatProperty(\n name=\"Displacement Strength\"\n )\n\n tile_resolution: bpy.props.IntProperty(\n name=\"Tile Resolution\"\n )\n\n\n\n\n\ndef register():\n # Property group containing radio buttons\n bpy.types.WindowManager.mt_radio_buttons = bpy.props.PointerProperty(\n type=MT_Radio_Buttons\n )\n\ndef unregister():\n del bpy.types.WindowManager.mt_radio_buttons\n","sub_path":"property_groups/property_groups.py","file_name":"property_groups.py","file_ext":"py","file_size_in_byte":24794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"476225979","text":"import os\nfrom flask import Flask, request, abort, jsonify, make_response\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_cors import CORS\nimport random\n\nfrom models import setup_db, Question, Category\n\nQUESTIONS_PER_PAGE = 10\n\n\ndef create_app(test_config=None):\n # create and configure the app\n app = Flask(__name__)\n\n # db init\n setup_db(app)\n\n cors = CORS(app, resources={r\"/api/*\": {\"origins\": \"*\"}})\n\n @app.after_request\n def after_request(response):\n response.headers.add(\n \"Access-Control-Allow-Headers\", \"Content-Type,Authorization\"\n )\n response.headers.add(\n \"Access-Control-Allow-Methods\", \"GET,POST,DELETE,OPTIONS\"\n )\n response.headers.add(\"Access-Control-Allow-Credentials\", \"true\")\n\n return response\n\n @app.route(\"/api/categories\")\n def get_categories():\n \"\"\" \n endpoint for retrieving all question categories\n \"\"\"\n\n # get all categories\n try:\n categories = query_all_categories()\n\n res = {\"categories\": categories}\n\n return jsonify(res)\n except:\n abort(404)\n\n def query_all_categories():\n # decoupled from get_categories so it can be used elsewhere\n \"\"\"Query to get all categories. \n\n Returns:\n List of all categories\n\n \"\"\"\n\n categories = Category.query.all()\n formatted_categories = {cat.id: cat.type for cat in categories}\n return formatted_categories\n\n @app.route(\"/api/questions\")\n def get_questions():\n \"\"\"\n endpoint for retrieving all questions\n \"\"\"\n try:\n # get page from args\n page = request.args.get(\"page\")\n\n # actual page for pagination...\n page_int = 0\n\n # convert to int\n if page:\n page_int = int(page)\n else:\n page_int = 1\n\n # set questions per page\n per_page = QUESTIONS_PER_PAGE\n\n # get questions for current page (paginated)\n questions = Question.query.order_by(Question.id.asc()).paginate(\n page_int, per_page, error_out=True\n )\n\n # formatted questions in array\n formatted_questions = [q.format() for q in questions.items]\n\n # get all categories\n # categories = Category.query.all()\n categories = query_all_categories()\n\n current_category = Category.query.order_by(\n Category.type.asc()\n ).first()\n\n # for some reason need to return as a dict not list/array?\n # formatted_categories = {cat.id: cat.type for cat in categories}\n\n # return as JSON\n return jsonify(\n questions=formatted_questions,\n total_questions=questions.total,\n categories=categories,\n current_category=current_category.id,\n )\n except:\n abort(404)\n\n @app.route(\"/api/questions\", methods=[\"POST\"])\n def get_questions_by_query():\n \"\"\"\n endpoint to retrieve a question based on query term\n \"\"\"\n\n # get request data (body)\n body = request.get_json()\n\n if body is None:\n abort(422)\n\n # get searchTerm from body\n query_term = body.get(\"searchTerm\")\n\n # search result\n query_result = Question.query.filter(\n Question.question.ilike(f\"%{query_term}%\")\n ).all()\n\n if len(query_result):\n formatted_result = [q.format() for q in query_result]\n return jsonify({\"questions\": formatted_result})\n else:\n abort(404)\n\n @app.route(\"/api/categories//questions\")\n def get_questions_by_category(category_id):\n \"\"\"\n endpoint to retrieve questions by category\n \"\"\"\n\n # page from args\n page = request.args.get(\"page\")\n\n page_int = 0\n\n if page:\n page_int = int(page)\n else:\n page_int = 1\n\n # questions per page for pagination\n per_page = QUESTIONS_PER_PAGE\n\n category = Category.query.get(category_id)\n\n if category:\n # get category id as int\n category_id_int = int(category.id)\n\n questions = Question.query.filter_by(\n category=category_id_int\n ).paginate(page_int, per_page, error_out=True)\n\n # clean up questions for response\n formatted_questions = [q.format() for q in questions.items]\n\n return jsonify(\n {\n \"questions\": formatted_questions,\n \"total_questions\": len(questions.items),\n \"current_category\": category_id,\n \"categories\": query_all_categories(),\n }\n )\n # if category doesn't exist return error\n else:\n abort(404)\n\n @app.route(\"/api/questions/\", methods=[\"DELETE\"])\n def delete_question(question_id):\n \"\"\"\n delete question by question_id\n \"\"\"\n\n # get the question by id\n question = Question.query.get(question_id)\n\n # if question exists, delete it and send a response\n if question:\n question.delete()\n res = make_response(\n jsonify(\n {\n \"message\": f\"successfully deleted question id: {question_id}\"\n }\n ),\n 200,\n )\n return res\n else:\n abort(404)\n\n @app.route(\"/api/questions/create\", methods=[\"POST\"])\n def create_question():\n # get body data as json\n body = request.get_json()\n\n if body is None:\n abort(422)\n\n question = (body.get(\"question\"),)\n answer = (body.get(\"answer\"),)\n category = (body.get(\"category\"),)\n difficulty = body.get(\"difficulty\")\n\n if not all([question, answer, category, difficulty]):\n abort(422)\n\n new_question = Question(\n question=question,\n answer=answer,\n category=category,\n difficulty=difficulty,\n )\n\n # insert\n new_question.insert()\n\n # response\n res = make_response(jsonify(new_question.format()), 201)\n\n return res\n\n @app.route(\"/api/quizzes\", methods=[\"POST\"])\n def play_quiz():\n # get category and previous ques params\n body = request.get_json()\n\n if body is None:\n # if no body then set init values\n previous_questions = []\n quiz_category = {}\n else:\n previous_questions = body.get(\"previous_questions\", [])\n quiz_category = body.get(\"quiz_category\", {})\n\n if quiz_category is None:\n # get all questions if there is no category set\n questions = Question.query.all()\n elif quiz_category[\"id\"] == 0:\n questions = Question.query.all()\n else:\n # get questions for current category\n questions = (\n Question.query.order_by(Question.id)\n .filter_by(category=str(quiz_category[\"id\"]))\n .all()\n )\n\n # if no previous questions, get the first question\n if len(previous_questions) == 0:\n question = questions[0]\n else:\n question = next(\n (q for q in questions if q.id not in previous_questions), None\n )\n\n # format it for res\n if question is None:\n result_question = \"\"\n category = \"\"\n else:\n result_question = question.format()\n category = (\n Category.query.filter_by(id=str(result_question[\"category\"]))\n .first()\n .format()\n )\n\n # return as json\n return jsonify({\"question\": result_question, \"quiz_category\": category})\n\n # error handlers\n @app.errorhandler(404)\n def not_found(error):\n return (\n jsonify({\"success\": False, \"error\": 404, \"message\": \"Not found\"}),\n 404,\n )\n\n @app.errorhandler(422)\n def unprocessable(error):\n return (\n jsonify(\n {\"success\": False, \"error\": 422, \"message\": \"unprocessable\"}\n ),\n 422,\n )\n\n return app\n","sub_path":"projects/02_trivia_api/backend/flaskr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"132591689","text":"import json\nimport logging\nimport math\nimport random\nimport time\nimport traceback\nfrom datetime import datetime, timezone\nfrom threading import Thread\nfrom typing import List, Tuple\n\nimport cuwais\nimport numpy\nimport requests\nfrom cuwais.common import Outcome\nfrom cuwais.config import config_file\nfrom cuwais.database import Submission, Result, Match\nfrom cuwais.gamemodes import Gamemode\nfrom sqlalchemy import func, and_\n\nlogging.basicConfig(\n format='%(asctime)s.%(msecs)03d %(levelname)-8s %(message)s' if config_file.get(\"debug\") else '%(message)s',\n level=logging.DEBUG if config_file.get(\"debug\") else logging.WARNING,\n datefmt='%Y-%m-%d %H:%M:%S')\nlogger = logging.getLogger(__name__)\n\n\ndef _get_all_latest_healthy_submissions() -> List[Tuple[Submission, float]]:\n \"\"\"Gets a list of submissions along with their healths from 1 to 0.\n Submissions with health 0 are omitted as they should not be run\"\"\"\n with cuwais.database.create_session() as database_session:\n healthy_subq = database_session.query(\n Submission.id,\n func.count(Result.id).label('healthies')\n ).join(Submission.results)\\\n .group_by(Submission.id)\\\n .filter(Result.healthy == True)\\\n .subquery()\n\n most_recent_subq = database_session.query(\n Submission.user_id,\n func.max(Submission.submission_date).label('maxdate')\n ).join(\n healthy_subq,\n and_(\n Submission.id == healthy_subq.c.id\n )\n ).group_by(Submission.user_id)\\\n .filter(Submission.active == True)\\\n .subquery()\n\n total_results_subq = database_session.query(\n Submission.id,\n func.count(Result.id).label('total')\n ).join(Submission.results)\\\n .group_by(Submission.id)\\\n .subquery()\n\n res = database_session.query(\n Submission,\n healthy_subq.c.healthies,\n total_results_subq.c.total\n ).join(\n healthy_subq,\n and_(\n Submission.id == healthy_subq.c.id\n )\n ).join(\n total_results_subq,\n and_(\n Submission.id == total_results_subq.c.id\n )\n ).join(\n most_recent_subq,\n and_(\n Submission.user_id == most_recent_subq.c.user_id,\n Submission.submission_date == most_recent_subq.c.maxdate\n )\n ).all()\n\n return [(sub, h/t) for sub, h, t in res]\n\n\ndef _get_all_untested_submissions() -> List[Submission]:\n logger.debug(f\"Getting untested submissions\")\n with cuwais.database.create_session() as database_session:\n logger.debug(f\"Got session\")\n # All submissions with no results\n res = database_session.query(Submission)\\\n .outerjoin(Submission.results)\\\n .filter(Result.id == None)\\\n .all()\n\n logger.debug(f\"Untested submissions: {res}\")\n return res\n\n\ndef _calculate_delta_scores_pair(a_score, b_score, winner_weight):\n \"\"\"\n Typical Elo rating delta calculation for a 2-player game\n\n Winner weight is the expected amount that player 1 will win from the given game,\n I.e. 1 for a win-loss situation, 0.5 for a draw/stalemate\n \"\"\"\n k = float(config_file.get(\"score_turbulence\"))\n\n a_rating = 10 ** (a_score / 400)\n b_rating = 10 ** (b_score / 400)\n\n a_expected = a_rating / (a_rating + b_rating)\n\n delta = k * (winner_weight - a_expected)\n\n return delta\n\n\ndef _calculate_delta_scores(outcomes: List[Outcome], current_elos: List[float]):\n \"\"\"\n Calculates a set of Elo deltas for a collection of results for submissions with current estimated Elos\n\n Uses an arbitrary algorithm explained below.\n\n This algorithm must satisfy a few constraints:\n For 2-player games it must behave as the typical Elo algorithm above\n For every game, the total amount of Elo won and lost must be 0 (No net gain/loss in the system)\n If a player wins they should gain Elo and if they lose they should lose Elo\n After a settling period, the long-term behaviour of any player's Elo should be stationary, assuming a fixed\n probability of winning\n Players with a handicap should be penalised less for a loss. A handicap may be either a high score difference,\n or imbalanced teams.\n\n Idea: Group players into faux teams based on the outcome - win, loss or draw.\n Sum the Elo ratings for each team and calculate the 3 pair swings as if each team were a player.\n All 3 pairings should sum to 0, so spread out each Elo delta across each team member to ensure no net change\n\n E.g. 5 players, (Win, Loss, Draw, Loss, Draw), with Elo ratings (1000, 2000, 3000, 4000, 5000).\n For the teams (Win, Loss, Draw) we have effective Elos of (1000, 6000, 8000)\n So we calculate the swings for each pairing (WinLoss, WinDraw, LossDraw)\n And distribute Elo,\n (Delta Win, Delta Loss, Delta Draw) = ((WinLoss + WinDraw) / 1, (-WinLoss - LossDraw) / 2, (LossDraw - WinDraw) / 2)\n\n There are a few edge cases here (that all come up pretty often):\n - There may be 0 players on a 'team'\n - All players may be on one team\n\n To solve the empty teams, we simply omit the pairing if one of the teams has 0 players.\n This still preserves the closed team assumption\n\n To solve the single team issue, we add an extra step:\n If there is only one team, we assume that all of the players within each that have drawn.\n To calculate the score in this case we assume that every player draws with their Elo opposite.\n\n E.g. If 5 players win with ratings (1000, 2000, 3000, 4000, 5000), we say that player 1 drew with player 5,\n 2 with 4 and player 3's rating remains unchanged.\n \"\"\"\n\n # Group\n counts = {o: 0 for o in Outcome}\n totals = {o: 0 for o in Outcome}\n group_elos = {o: [] for o in Outcome}\n for outcome, elo in zip(outcomes, current_elos):\n counts[outcome] += 1\n totals[outcome] += elo\n group_elos[outcome].append(elo)\n\n # Inter-Group deltas\n win_loss = 0\n win_draw = 0\n loss_draw = 0\n if counts[Outcome.Win] > 0 and counts[Outcome.Loss] > 0:\n win_loss = _calculate_delta_scores_pair(totals[Outcome.Win], totals[Outcome.Loss], 1)\n if counts[Outcome.Win] > 0 and counts[Outcome.Draw] > 0:\n win_draw = _calculate_delta_scores_pair(totals[Outcome.Win], totals[Outcome.Draw], 1)\n if counts[Outcome.Loss] > 0 and counts[Outcome.Draw] > 0:\n loss_draw = _calculate_delta_scores_pair(totals[Outcome.Draw], totals[Outcome.Loss], 1)\n\n # Intra-Group deltas\n single_team_elos = []\n single_team_outcome = None\n if counts[Outcome.Win] == counts[Outcome.Loss] == 0:\n single_team_outcome = Outcome.Draw\n elif counts[Outcome.Win] == counts[Outcome.Draw] == 0:\n single_team_outcome = Outcome.Loss\n elif counts[Outcome.Loss] == counts[Outcome.Draw] == 0:\n single_team_outcome = Outcome.Win\n\n if single_team_outcome is not None:\n single_team_elos = sorted(group_elos[single_team_outcome])\n\n # Player deltas\n deltas = []\n for outcome, elo in zip(outcomes, current_elos):\n # Inter-Group portion\n if outcome == Outcome.Win:\n delta = win_loss + win_draw\n delta /= counts[Outcome.Win]\n elif outcome == Outcome.Loss:\n delta = -win_loss - loss_draw\n delta /= counts[Outcome.Loss]\n else: # result.outcome == Outcome.Draw\n delta = loss_draw - win_draw\n delta /= counts[Outcome.Draw]\n\n # Intra-Group portion for single team result sets\n if outcome == single_team_outcome:\n position_in_team = single_team_elos.index(elo)\n opponent_position = len(single_team_elos) - position_in_team - 1\n opponent_elo = single_team_elos[opponent_position]\n\n if opponent_position != position_in_team:\n delta += _calculate_delta_scores_pair(elo, opponent_elo, 0.5)\n\n deltas.append(delta)\n\n logger.debug(f\"Calculated some ELO Deltas: {deltas}, winners: {outcomes}\")\n\n # Assertions\n assert len(deltas) == len(outcomes)\n assert -0.000001 < sum(deltas) < 0.000001\n # Check that this works the same as Elo for two player games\n if len(outcomes) == 2:\n if outcomes[0] == outcomes[1] == Outcome.Draw:\n exp_delta = _calculate_delta_scores_pair(min(current_elos), max(current_elos), 0.5)\n assert math.isclose(max(deltas), exp_delta, rel_tol=1e-9, abs_tol=0.0)\n if outcomes[0] != outcomes[1]:\n v = 1 if outcomes[0] == Outcome.Win else 0\n exp_delta = _calculate_delta_scores_pair(current_elos[0], current_elos[1], v)\n assert math.isclose(deltas[0], exp_delta, rel_tol=1e-9, abs_tol=0.0)\n\n return deltas\n\n\ndef _get_elos(submission_ids: list):\n init = float(config_file.get(\"initial_score\"))\n\n with cuwais.database.create_session() as database_session:\n subq = database_session.query(\n Submission.user_id,\n func.sum(Result.points_delta).label('elo')\n ).filter(Submission.id.in_(submission_ids))\\\n .join(Submission.results)\\\n .group_by(Submission.user_id)\\\n .subquery(\"t1\")\n\n res = database_session.query(\n Submission.id,\n subq.c.elo\n ).filter(\n Submission.id.in_(submission_ids),\n Submission.user_id == subq.c.user_id\n ).all()\n\n elo_lookup = {v[\"id\"]: v[\"elo\"] for v in res}\n\n elos = [elo_lookup.get(i, 0) + init for i in submission_ids]\n\n logger.debug(f\"Calculated some ELOs: {elos}\")\n\n return elos\n\n\ndef _save_result(submissions: List[Submission],\n result: dict,\n update_scores: bool) -> Match:\n logger.debug(f\"Saving result: submissions: {submissions}, result: {result}\")\n submission_ids = [submission.id for submission in submissions]\n submission_results = result[\"submission_results\"]\n if not len(submission_ids) == len(submission_results):\n raise ValueError(\"Bad submission ID count\")\n\n deltas = [0] * len(submission_ids)\n if update_scores:\n elos = _get_elos(submission_ids)\n outcomes = [Outcome(r[\"outcome\"]) for r in submission_results]\n deltas = _calculate_delta_scores(outcomes, elos)\n\n with cuwais.database.create_session() as database_session:\n match = Match(match_date=datetime.now(tz=timezone.utc), recording=json.dumps(result[\"recording\"]))\n\n database_session.add(match)\n\n for submission_id, submission_result, delta in zip(submission_ids, submission_results, deltas):\n result = Result(match=match,\n submission_id=submission_id,\n outcome=int(submission_result[\"outcome\"]),\n healthy=submission_result[\"healthy\"],\n points_delta=delta,\n player_id=submission_result[\"player_id\"],\n prints=submission_result[\"printed\"],\n result_code=submission_result[\"result_code\"])\n database_session.add(result)\n\n database_session.commit()\n\n return match\n\n\ndef _run_match(gamemode: Gamemode, options, submissions: List[Submission]) -> dict:\n submission_hashes = [submission.files_hash for submission in submissions]\n response = requests.get('http://runner:8080/run', {\n \"options\": json.dumps(options),\n \"gamemode\": gamemode.name,\n \"submissions\": json.dumps(submission_hashes),\n })\n\n if response.status_code != 200:\n logger.error(\"Error running match: \" + response.text)\n raise requests.exceptions.RequestException(f\"Non-ok response code: {response.status_code}\")\n\n return response.json()\n\n\ndef _run_typical_match(gamemode: Gamemode, options) -> bool:\n logger.debug(\"Starting typical match\")\n\n # Get n sumbissions\n submissions = []\n if gamemode.player_count > 0:\n newest = _get_all_latest_healthy_submissions()\n if len(newest) < gamemode.player_count:\n return False\n newest_submissions = [submission for submission, _ in newest]\n healths = numpy.array([health for _, health in newest])\n logger.debug(f\"Got newest submissions {newest_submissions}, with healths {healths}\")\n healths *= (1 / numpy.sum(healths))\n i_submissions = numpy.random.choice(len(newest_submissions), size=gamemode.player_count, replace=False, p=healths)\n for i in i_submissions:\n submissions.append(newest_submissions[i])\n\n # Run & parse\n logger.debug(\"Running typical match\")\n result = _run_match(gamemode, options, submissions)\n logger.debug(f\"Ran typical match. Result {result}\")\n\n # Save\n update_scores = True in {r[\"healthy\"] for r in result[\"submission_results\"]}\n _save_result(submissions, result, update_scores)\n\n return True\n\n\ndef _run_test_match(gamemode: Gamemode, options) -> bool:\n logger.debug(\"Starting test match\")\n\n # Get n sumbissions\n submissions = []\n if gamemode.player_count > 0:\n newest = _get_all_untested_submissions()\n if len(newest) == 0:\n return False\n submissions = [random.choice(newest)] * gamemode.player_count\n\n # Run & parse\n logger.debug(\"Running test match\")\n result = _run_match(gamemode, options, submissions)\n logger.debug(f\"Ran test match. Result {result}\")\n\n # Record successes and failures\n _save_result(submissions, result, False)\n\n return True\n\n\nclass Matchmaker(Thread):\n def __init__(self, gamemode: Gamemode, options: dict, seconds_per_run: int):\n super().__init__()\n self.gamemode = gamemode\n self.options = options\n self.seconds_per_run = seconds_per_run\n self.daemon = True\n\n def _run_one(self) -> bool:\n try:\n # Prioritise running test matches\n ran = _run_test_match(self.gamemode, self.options)\n if ran:\n return True\n\n return _run_typical_match(self.gamemode, self.options)\n except requests.exceptions.RequestException as e:\n logger.error(\"Could not connect to the submission runner: \" + str(e.strerror))\n except Exception:\n traceback.print_exc()\n return False\n\n def run(self) -> None:\n if self.gamemode.player_count < 1:\n return\n\n while True:\n start = time.process_time_ns()\n\n success = self._run_one()\n diff = (time.process_time_ns() - start) / 1e9\n\n wait_time = self.seconds_per_run - diff\n\n if not success:\n wait_time + random.randint(1, max(2, self.seconds_per_run)) # Pause for a while on failure\n\n wait_time += 0.05 * self.seconds_per_run * (random.random() - 0.5) # Pause for a while so we're not in sync\n\n time.sleep(max(0.0, wait_time))\n\n\ndef run_matchmakers():\n # Get some options\n gamemode, options = Gamemode.get_from_config()\n matchmakers = int(config_file.get(\"matchmaker.matchmakers\"))\n seconds_per_run = int(config_file.get(\"matchmaker.target_seconds_per_game\"))\n\n # Start up matchmakers\n for i in range(matchmakers - 1):\n matchmaker = Matchmaker(gamemode, options, seconds_per_run)\n matchmaker.start()\n\n # Have the main thread run the last one\n matchmaker = Matchmaker(gamemode, options, seconds_per_run)\n matchmaker.run()\n","sub_path":"app/matchmaker.py","file_name":"matchmaker.py","file_ext":"py","file_size_in_byte":15552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"506031445","text":"import unittest\nimport cv2\nimport os\nimport glob\nimport re\nimport numpy as np\n\nfrom adjustExposures import newTable, getHistogram\n\nclass SimpleTestCase(unittest.TestCase):\n\n def test_newTable(self):\n upGamma = 4.0\n downGamma = 0.25\n\n testTable = newTable()\n testUpTable = newTable(upGamma)\n testDownTable = newTable(downGamma)\n\n self.assertTrue(np.not_equal(testTable, testUpTable).any())\n self.assertTrue(np.not_equal(testTable, testDownTable).any())\n self.assertTrue(len(testTable) == len(testUpTable))\n self.assertTrue(len(testTable) == len(testDownTable))\n\n def test_getHistogram(self):\n testPath = glob.glob('testUnitPathInExp/*jpg')\n testImage = cv2.imread(testPath[0])\n testHist = getHistogram(testImage)\n\n self.assertTrue(isinstance(testHist,np.ndarray))\n self.assertTrue(np.ndarray.size != 0)\n","sub_path":"Testing/dataCollectionTests/adjustExposures_unitTest.py","file_name":"adjustExposures_unitTest.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"436878042","text":"import time\n\nfrom pyramid.location import lineage\n\nfrom .. import utils\n###################\n# API\n###################\ndef node_load(conn, reg, id):\n node_table = reg.dbmeta.tables['node']\n row = conn.execute(\n node_table.select().where(node_table.c.id == id)\n ).fetchone()\n if row:\n node = reg.creg.create(**dict(row))\n return node\n\n\ndef nodes_load(conn, reg, ids, pids):\n node_table = reg.dbmeta.tables['node']\n rows = conn.execute(\n node_table.select().where(node_table.c.id.in_(pids))\n )\n parents = {}\n for row in rows:\n parents[row.id] = reg.creg.create(**dict(row))\n\n rows = conn.execute(\n node_table.select().where(node_table.c.id.in_(ids))\n )\n nodes = []\n for row in rows:\n node = reg.creg.create(**dict(row))\n node.__parent__ = parents[node.pid]\n nodes.append(node)\n return nodes\n\n\ndef node_has_children(node):\n conn = node._conn\n reg = node._reg\n node_table = reg.dbmeta.tables['node']\n has_children_query = select([func.count(node_table.c.id)])\\\n .where(node_table.c.pid == node.id)\\\n .where(node_table.c.title != \"\")\n\n has_children = conn.execute(has_children_query).scalar()\n return has_children\n\n\ndef node_delete(node):\n conn = node._conn\n reg = node._reg\n node_table = reg.dbmeta.tables['node']\n\n delete_node_query = node_table\\\n .delete().where(node_table.c.id == node.id)\n conn.execute(delete_node_query)\n\n\n\ndef node_delete_chunks(node):\n conn = node._conn\n reg = node._reg\n node_table = reg.dbmeta.tables['node']\n\n chunks_query = select([node_table.c.id])\\\n .where(node_table.c.pid == node.id)\\\n .where(node_table.c.title == \"\")\n chunk_ids = [x['id'] for x in conn.execute(chunks_query)]\n\n delete_chunks_query = node_table\\\n .delete().where(node_table.c.pid.in_(chunk_ids))\n conn.execute(delete_chunks_query)\n\n\ndef root_create(conn, reg, **attrs):\n node_table = reg.dbmeta.tables['node']\n\n root = reg.creg.create(**attrs)\n q_insert = node_table.insert().values(dict(root.attr_items()))\n res = conn.execute(q_insert)\n return root\n\n\ndef sequential_name(node, conn, reg):\n node_table = reg.dbmeta.tables['node']\n\n # get last name of node (not chunk or not service)\n q_last = node_table.select()\\\n .where(node_table.c.pid==node.id)\\\n .where(node_table.c.is_service == None)\\\n .where(node_table.c.is_leaf == None)\\\n .order_by(node_table.c.name.desc())\n row = conn.execute(q_last).fetchone()\n\n if row:\n name = \"{:07d}\".format(int(row['name']) + 1)\n else:\n name = '0000001'\n return name\n\n\n\ndef node_insert(parent, node, registry, autonaming=None):\n \"\"\"Add node in parent and save to database\"\"\"\n reg = registry\n now = int(time.time())\n node.created_at = now\n node.modified_at = now\n\n # set name\n if node.node_type != \"root\":\n # if predefined title in schema\n # title = reg.creg.metadata(node).get('title')\n # if title:\n # node.title = title\n\n if getattr(node, '__name__', None) in {None, '', u''}:\n autoname = reg.creg.metadata(node).get('autoname')\n if autoname == \"sequential\":\n name = sequential_name(parent, conn=conn, reg=reg)\n else:\n if not getattr(node, 'title', None):\n raise AttributeError(\"If name is not set,\"\n \" title must be set\")\n name = utils.title_to_name(node.title)\n else:\n name = node.__name__\n parent[name] = node\n\n\ndef ensure_columns(node, conn, reg):\n creg = reg.creg\n schema = creg.metadata(node)['schema']\n attrs, chunks = prepare_attrs(node, schema)\n node_table = reg.dbmeta.tables['node']\n\n # Keep order of inserted columns\n for attr in attrs:\n if attr['key'] in node_table.columns.keys():\n continue\n #log.debug(\"Creating column: %s (%s) on %r\" % (column,\n # _type, self.table.name))\n create_column(attr, conn, reg)\n\n engine = reg.sqlalchemy_engine\n reg.dbmeta = get_metadata(engine)\n\n\ndef create_column(attr, conn, reg):\n node_table = reg.dbmeta.tables['node']\n\n engine = reg.sqlalchemy_engine\n table_name = node_table.description\n column = Column(attr['key'], attr['type'])\n column_name = column.compile(dialect=engine.dialect)\n column_type = column.type.compile(engine.dialect)\n conn.execute('ALTER TABLE %s ADD COLUMN %s %s' % (table_name, column_name, column_type))\n\n\ndef node_update(node, data, request):\n \"\"\"Update loaded node\"\"\"\n creg = request.registry.creg\n if data:\n schema = creg.schema[node.node_type]\n data = utils.deserialize(data, schema)\n for k, v in data.items():\n setattr(node, k, v)\n\n node.modified_at = int(time.time())\n\n\ndef prepare_attrs(node, schema):\n def alchemy_type(v, key):\n if v == 'NoneType':\n return\n if key == \"acl\":\n return PyramidACL\n\n t = {\n 'str': UnicodeText,\n 'bool': Boolean,\n 'datetime': DateTime,\n 'float': Float,\n 'int': Integer\n }\n return t[v]\n\n attrs = []\n chunks = {}\n for key, value in node.attr_items():\n try:\n # TODO: validate value according to schema type\n attr_type = schema[key]['type']\n except KeyError:\n attr_type = type(value).__name__\n if attr_type == 'unicode': # fix for python2\n attr_type = 'str'\n\n if attr_type == 'nested':\n chunks[key] = value\n else:\n alchemytype = alchemy_type(attr_type, key)\n if alchemytype:\n attr = {\n 'key': key,\n 'value': value,\n 'type': alchemytype\n }\n attrs.append(attr)\n\n return attrs, chunks\n\n\ndef node_get_children(context,\n pagenum=1,\n with_leafs=False,\n with_user_info=False,\n prefetch_related=None):\n pagenum -= 1\n items_per_page = context._items_per_page\n reg = context._reg\n conn = context._conn\n node_table = reg.dbmeta.tables['node']\n\n def node_from_row(row):\n node = reg.creg.create(**dict(row))\n node.__parent__ = context\n context._data[node.__name__] = node\n return node\n\n nids = [] # children nids\n uids = set() # children uids\n nodes = [] # children nodes\n users = {} # children users\n children_query = select([node_table]).where(node_table.c.pid == context.id)\\\n .where(node_table.c.is_service == None)\\\n .order_by(node_table.c.created_at.asc())\\\n .offset(pagenum * items_per_page)\\\n .limit(items_per_page)\n if not with_leafs:\n children_query = children_query.where(node_table.c.is_leaf == None)\n\n for row in conn.execute(children_query).fetchall():\n nids.append(row.id)\n uids.add(row.uid)\n node = node_from_row(row)\n nodes.append(node)\n\n\n if with_user_info and uids:\n q_children_users = select([node_table])\\\n .where(node_table.c.id.in_(list(uids)))\n\n for row in conn.execute(q_children_users).fetchall():\n node = reg.creg.create(**dict(row))\n users[row.id] = node\n\n for node in nodes:\n if with_user_info:\n node._user = users[node.uid]\n if row.title:\n # child\n context._data[node.__name__] = node\n else:\n # chunk\n setattr(context, node.__name__, node)\n\n return nodes\n\n\ndef node_id_by_path(request, path):\n reg = request.registry\n conn = request.conn\n node_table = reg.dbmeta.tables['node']\n query = select([node_table]).where(node_table.c.node_path == path)\n id = conn.execute(query).scalar()\n return id\n\n\ndef get_breadcrumb(context, request):\n def get_title(context):\n return getattr(context, \"title\", None) or context.__name__.capitalize()\n\n return [(request.resource_path(context), get_title(context))\n for context in reversed(list(lineage(context)))]\n\n\ndef as_dict(context, request, schema_only=False):\n creg = request.registry.creg\n\n node_dict = {}\n try:\n schema = creg.schema[context.node_type]\n except KeyError:\n schema = {\n '__name__': {\n 'type': 'str',\n }\n }\n\n attrs = vars(context).copy()\n\n for k, v in attrs.items():\n if (k.startswith('_') and k !=\"__name__\") or k == \"data\":\n continue\n\n if schema_only and not schema.get(k):\n continue\n\n if getattr(context, k, None):\n node_dict[k] = getattr(context, k)\n\n node_dict['path'] = request.resource_path(context)\n return node_dict\n","sub_path":"cube/node/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":9153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"342820757","text":"#this is to test, expirament, and maybe implement a method of interacting with matrices\r\n#0,0 is in the top right corner\r\n\r\n#define global variables so all methods can access and change them\r\nx = 0\r\ny = 0\r\n\r\ndef printMatrix(Matrix):\r\n for i in range(0, x):\r\n print('[', end = ' ')\r\n for j in range(0, y):\r\n print(str(Matrix[i][j]), end = ' ')\r\n print(']')\r\n\r\ndef populMatrix(Matrix):\r\n for i in range(0, x):\r\n row = \"\\nFor the \" + str((i + 1)) + \" row:\"\r\n print(row)\r\n for j in range(0, y):\r\n column = \"For the \" + str((j + 1)) + \" column:\"\r\n print(column, end = '')\r\n Matrix[i][j] = eval(input(' '))\r\n\r\ndef scalarMultMatrix(a, Matrix):\r\n for i in range(0, x):\r\n for j in range(0, y):\r\n Matrix[i][j] = Matrix[i][j] * a\r\n\r\n#ask the user to describe the matrix eg m X n\r\nx, y = eval(input(\"Please enter the matrix dimensions: \"))\r\n\r\n#for some reason it won't allow anything besides a square matrix\r\n#the list will be \"square\" which means data might be accedentally added\r\n#in areas that won't be used, just means to be careful\r\n\r\nmaxSize = 0\r\nif(x != y):\r\n if(x > y):\r\n maxSize = x\r\n else:\r\n maxSize = y\r\nelse:\r\n maxSize = x\r\n\r\n#set the matrix to the requested size, don't add one because of range() funkyness, there is a 0,0\r\nmatrix = [[0 for s in range(maxSize)] for s in range(maxSize)]\r\n\r\n#get values for matrix\r\npopulMatrix(matrix)\r\n\r\n#get a scalar to multiply the matrix by and then multiply\r\nscalar = eval(input(\"Enter a scalar for multiplication: \"))\r\nscalarMultMatrix(scalar, matrix)\r\n\r\n#now show them your matrix\r\nprintMatrix(matrix)\r\n\r\n","sub_path":"Other Maths/Matrix.py","file_name":"Matrix.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"55074363","text":"__author__ = 'dorjan hitaj'\nimport xml.etree.cElementTree as ET\nimport numpy\nimport os\nimport nltk\nfrom collections import Counter\nimport signal\nimport spacy\n\nnlp = spacy.load('en')\n\nclass TimeoutException(Exception):\n pass\n\ndef timeout_handler(signum, frame):\n raise TimeoutException\n\nsignal.signal(signal.SIGALRM, timeout_handler)\n\ndef countDotsUpTo(splitted_text, index1):\n whole = numpy.array(splitted_text[0:index1])\n s = numpy.where(whole == '.')[0]\n return len(s)\n\ndef checkDot(space_splitted, index1, index2_start):\n\n to_return = dict()\n dots = countDotsUpTo(space_splitted, index1)\n ind = numpy.array(space_splitted[index1-dots:index2_start-dots])\n\n s = numpy.where(ind == '.')[0]\n if len(s) > 0:\n to_return['answer'] = 0\n return to_return\n else:\n whole = numpy.array(space_splitted[0:index1-dots])\n s2 = numpy.where(whole == '.')[0]\n\n second_part = numpy.array(space_splitted[index2_start-dots:])\n s3 = numpy.where(second_part == '.')[0]\n if len(s2)>0 and len(s3)>0:\n sentence_start = int(s2[len(s2)-1])+1\n sentence_end = int(s3[0])+index2_start-dots\n\n sentence = ' '.join(space_splitted[sentence_start:sentence_end+1])\n # print('---> ', sentence)\n else:\n # sentence_end = index2_start-dots+1\n # sentence = ' '.join(space_splitted[0:sentence_end+1])\n # print('-> ', sentence)\n sentence = ' ==000== '\n x = ' '.join(ind)\n to_return['answer'] = 1\n to_return['between'] = x\n to_return['num_dots'] = dots\n\n to_return['sentence'] = sentence.strip()\n return to_return\n\n\ndef verbInPhrase(postagged_phrase):\n verbs_list = ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']\n flag = 0\n print(postagged_phrase)\n for a in postagged_phrase:\n print(a[1])\n if a[1] in verbs_list:\n flag = 1\n break\n print(flag)\n return flag\n\nverbs_list = ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']\nstart = ''\n\npath = '/home/dorjan/Desktop/homework3_files/files'\n\narticles_count = 0\nlines_read = 0\nfiles_count = 0\nrelational_instances = list()\nrelational_phrases = list()\n\nfor filename in os.listdir(path):\n\n lines_read = 0\n files_count += 1\n articles_list = list()\n article_string = ''\n fullname = os.path.join(path, filename)\n with open(fullname) as fileobject:\n for line in fileobject:\n if lines_read == 0:\n article_string += line\n elif lines_read > 0:\n if line.startswith(start):\n articles_list.append(article_string)\n article_string = ''\n article_string += line\n else:\n article_string += line\n lines_read += 1\n print('Going to parsing: ', files_count)\n\n dori = 0\n article_c = 0\n error_count = 0\n\n for article in articles_list:\n article_c+=1\n signal.alarm(120)\n try:\n\n try:\n # print(article_c)\n tree = ET.ElementTree(ET.fromstring(article))\n root = tree.getroot()\n text = root.find('text')\n whole_text = text.text\n space_splitted = whole_text.split(' ')\n x = root.find('annotations')\n\n hyper_link_count = 0\n HL1_index_end=None\n HL1_index=None\n HL2_index_end=None\n HL2_index=None\n dot_counter = 0\n hyperlink_list = list()\n\n for atype in x.findall('annotation'):\n annotation_index = atype.find('anchorStart')\n annotation_index_end = atype.find('anchorEnd')\n annotation_type = atype.find('type')\n annotation_babelnet_id = atype.find('babelNetID')\n\n if annotation_type.text == 'HL':\n hl_dict = dict()\n hl_dict['anchorStart'] = int(annotation_index.text)\n hl_dict['anchorEnd'] = int(annotation_index_end.text)\n hl_dict['babelnet_id'] = annotation_babelnet_id.text\n hyperlink_list.append(hl_dict)\n\n for hyperlink1 in hyperlink_list:\n for hyperlink2 in hyperlink_list:\n\n if (hyperlink1['anchorStart'] < hyperlink2['anchorStart']) and (int(hyperlink2['anchorStart']) < int(hyperlink1['anchorStart'])+20):\n try:\n answer = checkDot(space_splitted, hyperlink1['anchorEnd'], hyperlink2['anchorStart'])\n if answer['answer'] == 1:\n idict = dict()\n pos = answer['between'].split()\n k = nltk.pos_tag(pos)\n flag = 0\n for a in k:\n if a[1] in verbs_list:\n flag = 1\n break\n if flag == 1:\n idict['h1'] = ' '.join(space_splitted[hyperlink1['anchorStart']-answer['num_dots']:hyperlink1['anchorEnd']-answer['num_dots']])\n idict['h1_babelnet_id'] = hyperlink1['babelnet_id']\n idict['phrase'] = answer['between']\n idict['h2'] = ' '.join(space_splitted[hyperlink2['anchorStart']-answer['num_dots']:hyperlink2['anchorEnd']-answer['num_dots']])\n idict['h2_babelnet_id'] = hyperlink2['babelnet_id']\n\n idict['sentence'] = answer['sentence']\n relational_instances.append(idict)\n relational_phrases.append(answer['between'])\n else:\n # print('breaking')\n break\n except:\n print('Error here')\n except:\n error_count+=1\n except TimeoutException:\n continue\n else:\n signal.alarm(0)\n print('Done processing: ', article_c-error_count, ' Numbe rof error articles ', error_count)\n\nprint('Going to relation cleaning...')\nphrases_to_write = list()\ninstances_to_write = list()\n\ncounted_phrases = Counter(relational_phrases)\n\nfor key, value in counted_phrases.items():\n\n line = key.strip()\n phrase = unicode('x '+line+' y')\n parse_phrase = nlp(phrase)\n flag = 0\n for word in parse_phrase:\n dep = str(word.dep_)\n wtext = word.text\n wtext2 = str(wtext.encode('utf8'))\n if dep.find('subj')>-1 and wtext2.strip() == 'x':\n flag+=1\n if (dep.find('obj')>-1 or dep.find('comp')>-1 or dep.find('attr')>-1) and wtext2.strip() == 'y':\n flag+=1\n if value > 3 and flag == 2:\n phrases_to_write.append(key)\n\n\nfor relation_tuple in relational_instances:\n if relation_tuple['phrase'] in phrases_to_write:\n instances_to_write.append(relation_tuple)\n\n\nprint(len(phrases_to_write))\nprint(len(instances_to_write))\nfilehandle_p = open('phrases0.txt', 'a')\nfor phrase in phrases_to_write:\n filehandle_p.write(phrase.encode('utf8'))\n filehandle_p.write('\\n')\n\n\nfilehandle_i = open('instances0.txt', 'a')\nfor phrase in instances_to_write:\n sent = phrase['sentence']\n # s = sent.encode('utf8')\n to_write = phrase['h1']+\" | \"+phrase['phrase']+\" | \"+phrase['h2']+\" | \"+sent+\" | \"+phrase['h1_babelnet_id']+\" | \"+phrase['h2_babelnet_id']\n filehandle_i.write(to_write.encode('utf8'))\n filehandle_i.write('\\n')","sub_path":"homework3/src/navigli_moro_information_extraction.py","file_name":"navigli_moro_information_extraction.py","file_ext":"py","file_size_in_byte":7998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"385831439","text":"import sys\nimport math\nfrom numpy import binary_repr\n\ndef encode_bin(s):\n ans = \"\"\n c, ind, ln = s[0], 0, len(s)\n while ind discord.Embed:\n total_users_count = sum(\n [len(option_users) for option_users in self.data.values()]\n )\n\n embed = embed_message(\n f\"Poll: {self.name}\",\n f\"{self.description}\\n**{total_users_count} votes**\",\n f\"Asked by {self.author.display_name} | ID: {self.id}\",\n )\n\n # sort the data by most answers\n self.data = {\n k: v\n for k, v in sorted(\n self.data.items(), key=lambda item: len(item[1]), reverse=True\n )\n }\n\n # add options\n for option_name, option_users in self.data.items():\n option_users_count = len(option_users)\n\n # number of text elements\n n = 10\n\n # get value text\n text = \"\"\n try:\n progress = option_users_count / total_users_count\n except ZeroDivisionError:\n progress = 0\n for i in range(int(progress * n)):\n text += \"▓\"\n for i in range(n - int(progress * n)):\n text += \"░\"\n\n embed.add_field(\n name=option_name,\n value=f\"{text} {int(progress * 100)}%\",\n inline=False,\n )\n\n return embed\n\n # save the stuff in DB\n async def _dump_to_db(self) -> int:\n return await insert_poll(\n poll_id=self.id,\n poll_name=self.name,\n poll_description=self.description,\n poll_data=self.data,\n author_id=self.author.id,\n guild_id=self.guild.id,\n channel_id=self.channel.id,\n message_id=self.message.id if self.message else None,\n )\n\n # add an option\n async def add_new_option(self, ctx: SlashContext, option: str):\n self.data.update({option: []})\n\n # run the post init again to add components\n self.__post_init__()\n\n await self._edit(edit_ctx=ctx)\n\n # remove an option\n async def remove_option(self, ctx: SlashContext, option: str):\n try:\n self.data.pop(option)\n\n # run the post init again to remove components\n self.__post_init__()\n\n await self._edit(edit_ctx=ctx)\n except KeyError:\n await ctx.send(\n hidden=True,\n embed=embed_message(\"Error\", \"That option doesn't exist\"),\n )\n\n # add a user to a poll option\n async def add_user(\n self, select_ctx: ComponentContext, member: discord.Member, option: str\n ):\n # remove user from all other options\n for option_users in self.data.values():\n try:\n option_users.remove(member.id)\n except ValueError:\n pass\n\n # add user to option\n self.data[option].append(member.id)\n await self._edit(select_ctx=select_ctx)\n\n # update poll\n async def _edit(\n self, select_ctx: ComponentContext = None, edit_ctx: SlashContext = None\n ):\n assert select_ctx or edit_ctx, \"Only one param can be chosen and one must be\"\n\n embed = self._get_embed()\n await self._dump_to_db()\n\n if edit_ctx:\n await self.message.edit(\n embed=embed,\n components=self.select,\n )\n await edit_ctx.send(\n hidden=True,\n embed=embed_message(\"Success\", \"Your poll was edited\"),\n )\n\n else:\n await select_ctx.edit_origin(\n embed=embed,\n components=self.select,\n )\n\n # create poll\n async def create(self, create_ctx: SlashContext) -> None:\n # dumping to db twice to get the ID\n self.id = await self._dump_to_db()\n embed = self._get_embed()\n self.message = await create_ctx.send(\n embed=embed,\n components=self.select,\n )\n await self._dump_to_db()\n\n # disable poll\n async def disable(self, edit_ctx: SlashContext):\n await self.message.edit(\n components=[],\n )\n await edit_ctx.send(\n hidden=True,\n embed=embed_message(\"Success\", \"Your poll was edited\"),\n )\n\n\n# get the poll object\nasync def get_poll_object(\n guild: discord.Guild, poll_id: int = None, poll_message_id: int = None\n) -> Optional[Poll]:\n assert poll_id or poll_message_id, \"Only one param can be chosen and one must be\"\n\n # get the DB entry\n record = await get_poll(\n poll_id=int(poll_id) if poll_id else None,\n poll_message_id=poll_message_id,\n )\n\n # check if the poll is from that guild\n if guild.id != record[\"guild_id\"]:\n return None\n\n channel = guild.get_channel(record[\"channel_id\"])\n\n return Poll(\n id=record[\"id\"],\n name=record[\"name\"],\n description=record[\"description\"],\n data=record[\"data\"],\n guild=guild,\n channel=channel,\n author=guild.get_member(record[\"author_id\"]),\n message=await channel.fetch_message(record[\"message_id\"]),\n )\n\n\n# create the poll\nasync def create_poll_object(\n ctx: SlashContext,\n name: str,\n description: str,\n guild: discord.Guild,\n channel: discord.TextChannel,\n) -> None:\n poll = Poll(\n name=name,\n description=description,\n guild=guild,\n channel=channel,\n author=ctx.author,\n )\n await poll.create(ctx)\n","sub_path":"ElevatorBot/functions/poll.py","file_name":"poll.py","file_ext":"py","file_size_in_byte":6924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"560806292","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 01 16:37:42 2014\n\n@author: Israel\n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef plotCharts(dataframe):\n '''Plots a historgram for each series of the dataframe passed'''\n \n for p in dataframe.columns:\n label = \"%04d\" % (p,)\n plt.figure(p)\n plt.hist(np.array(dataframe[p]),100,range=[-1,1])\n plt.title(str(p)+\" Positions\")\n plt.xlabel('Daily Return')\n plt.plot()\n plt.savefig('histogram_'+label+'_pos.pdf')\n\n","sub_path":"im965/assgn11/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"267421154","text":"# -*- encoding: utf-8 -*-\n\nfrom .base import Resource\nfrom pysis.core.sis_datetime import convertToDateTime\nfrom datetime import datetime\n\n__service__ = 'Outputs'\n\nclass Outputs(Resource):\n \n def __str__(self):\n return ''\n \n def getFields(self):\n \n if not hasattr(self, 'id'): \n raise AttributeError(str(self.id), \"Service must have id\")\n assert isinstance(self.id, int)\n \n service = self.importService(__service__) \n return service.getFields(self.id) \n \n def getData(self, timeStart=None, timeEnd=None, window=None, field=\"\"):\n \n if not hasattr(self, 'id'): \n raise AttributeError(str(self.id), \"Service must have id\")\n assert isinstance(self.id, int)\n assert isinstance(field, str)\n \n timeStart = convertToDateTime(timeStart)\n timeEnd = convertToDateTime(timeEnd)\n \n #Validate time parameters\n validTimeParams = [\n (type(None), type(None), type(None)), #no time params\n (datetime, datetime, int), #all time params\n (datetime, type(None), int), #timeStart and window\n (type(None), type(None), int) #window only\n ] \n timeElements = (type(timeStart), type(timeEnd), type(window))\n \n isTimeParamsValid = timeElements in validTimeParams \n if not isTimeParamsValid:\n raise ValueError(\"Invalid combination of time parameters.\") \n \n service = self.importService(__service__)\n \n #Check the field name\n if self.enableParamChecks:\n outputFields = self.getFields()\n \n isValid = False\n for validField in outputFields:\n if field == validField.field_human_name:\n isValid = True\n break\n if not isValid: \n raise ValueError(\"Invalid field name: '%s'\" % field)\n \n return service.getData(self.id, timeStart, timeEnd, window, field)\n \n \n \n","sub_path":"pysis/resources/outputs.py","file_name":"outputs.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"230489041","text":"# -*- coding: utf-8 -*-\nimport json\nimport decorator\nimport re\nfrom xml.dom import minidom\nfrom robot.api import logger\n\n\"\"\"\nLibrary for logging request and response, which based on [ http://docs.python-requests.org/en/latest| requests ] library.\n\"\"\"\n\n\ndef write_log(response, multi_lines_response=False):\n \"\"\"\n Logging of http-request and response\n\n *Args:*\\n\n _response_ - object [ http://docs.python-requests.org/en/latest/api/#requests.Response | \"Response\" ]\n\n *Responce:*\\n\n Formatted output of request and response in test log\n\n Example:\n | *Test cases* | *Action* | *Argument* | *Argument* | *Argument* |\n | Simple Test | RequestsLibrary.Create session | Alias | http://www.example.com | |\n | | ${response}= | RequestsLibrary.Get request | Alias | / |\n | | RequestsLogger.Write log | ${response} | | |\n \"\"\"\n\n msg = []\n # информация о запросе\n msg.append(\n '> {0} {1}'.format(response.request.method, response.request.url))\n for req_key, req_value in response.request.headers.iteritems():\n msg.append('> {header_name}: {header_value}'.format(header_name=req_key,\n header_value=req_value))\n msg.append('>')\n if response.request.body:\n msg.append(response.request.body)\n msg.append('* Elapsed time: {0}'.format(response.elapsed))\n msg.append('>')\n # информация о ответе\n msg.append('< {0} {1}'.format(response.status_code, response.reason))\n for res_key, res_value in response.headers.iteritems():\n msg.append('< {header_name}: {header_value}'.format(header_name=res_key,\n header_value=res_value))\n msg.append('<')\n # тело ответа\n converted_string = ''\n if response.content:\n # получение кодировки входящего сообщения\n responce_content_type = response.headers.get('content-type')\n if 'application/json' in responce_content_type:\n if multi_lines_response:\n content_lines = response.content.splitlines()\n for i in range(len(content_lines)):\n response_content = get_decoded_response_body(content_lines[i], responce_content_type)\n converted_string_new = json.loads(response_content)\n converted_string_new = json.dumps(converted_string_new, sort_keys=True,\n ensure_ascii=False, indent=4,\n separators=(',', ': '))\n converted_string = converted_string + converted_string_new + '\\n'\n else:\n response_content = get_decoded_response_body(response.content, responce_content_type)\n converted_string = json.loads(response_content)\n converted_string = json.dumps(converted_string, sort_keys=True,\n ensure_ascii=False, indent=4,\n separators=(',', ': '))\n elif 'application/xml' in responce_content_type:\n if multi_lines_response:\n content_lines = response.content.splitlines()\n for i in range(len(content_lines)):\n response_content = get_decoded_response_body(content_lines[i], responce_content_type)\n xml = minidom.parseString(response_content)\n converted_string_new = xml.toprettyxml()\n converted_string = converted_string + converted_string_new + '\\n'\n else:\n if multi_lines_response:\n content_lines = response.content.splitlines()\n for i in range(len(content_lines)):\n response_content = get_decoded_response_body(content_lines[i], responce_content_type)\n msg.append(response_content)\n # вывод сообщения в лог\n logger.info('\\n'.join(msg))\n if converted_string:\n logger.info(converted_string)\n\n\ndef get_decoded_response_body(response_content, responce_content_type):\n match = re.findall(re.compile('charset=(.*)'),\n responce_content_type)\n # перекодирование тела ответа в соответствие с кодировкой, если она присутствует в ответе\n if len(match) == 0:\n return response_content\n else:\n responce_charset = match[0]\n return response_content.decode(responce_charset)\n\n\ndef _log_decorator(func, *args, **kwargs):\n response = func(*args, **kwargs)\n write_log(response)\n return response\n\n\ndef _log_decorator_multi_lines(func, *args, **kwargs):\n response = func(*args, **kwargs)\n write_log(response, True)\n return response\n\n\ndef log_decorator(func):\n \"\"\"\n Decorator for http-requests. Logging request and response.\n Decorated function must return response object [ http://docs.python-requests.org/en/latest/api/#requests | Response ]\n\n Example:\n\n | @RequestsLogger.log_decorator\n | def get_data(alias, uri)\n | response = _request_lib_instance().get_request(alias, uri)\n | return response\n\n Output:\n Formatted output of request and response in test log\n \"\"\"\n\n func.cache = {}\n return decorator.decorator(_log_decorator, func)\n\n\ndef log_decorator_multi_lines(func):\n \"\"\"\n Decorator for http-requests. Logging request and multi lines response.\n Decorated function must return response object [ http://docs.python-requests.org/en/latest/api/#requests | Response ]\n\n Example:\n\n | @RequestsLogger.log_decorator_multi_lines\n | def get_data(alias, uri)\n | response = _request_lib_instance().get_request(alias, uri)\n | return response\n\n Output:\n Formatted output of request and response in test log\n \"\"\"\n\n func.cache = {}\n return decorator.decorator(_log_decorator_multi_lines, func)\n","sub_path":"demoREST_PS_RF/RequestsLogger.py","file_name":"RequestsLogger.py","file_ext":"py","file_size_in_byte":6259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"332299758","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[4]:\n\n\nimport cv2\nimport numpy as np\n\nface_classifier = cv2.CascadeClassifier('C:/Users/prati/Anaconda3/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml')\n\n\ndef face_extractor(img):\n\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n faces = face_classifier.detectMultiScale(gray,1.3,5)\n\n if faces is():\n return None\n\n for(x,y,w,h) in faces:\n cropped_face = img[y:y+h, x:x+w]\n\n return cropped_face\n\n\ncap = cv2.VideoCapture(0)\ncount = 0\n\nwhile True:\n ret, frame = cap.read()\n if face_extractor(frame) is not None:\n count+=1\n face = cv2.resize(face_extractor(frame),(200,200))\n face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)\n\n file_name_path = 'C:/Users/prati/OneDrive/Desktop/OpenCV-master/faces/user'+str(count)+'.jpg'\n cv2.imwrite(file_name_path,face)\n\n cv2.putText(face,str(count),(50,50),cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),2)\n cv2.imshow('Face Cropper',face)\n else:\n print(\"Face not Found\")\n pass\n\n if cv2.waitKey(1)==13 or count==100:\n break\n\ncap.release()\ncv2.destroyAllWindows()\nprint('Colleting Samples Complete!!!')\n\n\n# In[13]:\n\n\nimport cv2\nimport numpy as np\nfrom os import listdir\nfrom os.path import isfile, join\n\ndata_path = 'C:/Users/prati/OneDrive/Desktop/OpenCV-master/faces/'\nonlyfiles = [f for f in listdir(data_path) if isfile(join(data_path,f))]\n\nTraining_Data, Labels = [], []\n\nfor i, files in enumerate(onlyfiles):\n image_path = data_path + onlyfiles[i]\n images = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)\n Training_Data.append(np.asarray(images, dtype=np.uint8))\n Labels.append(i)\n\nLabels = np.asarray(Labels, dtype=np.int32)\n\n#print(dir (cv2.face))\nmodel = cv2.face.LBPHFaceRecognizer_create()\n#reconocimiento = cv2.face.LBPHFaceRecognizer_create()\n#cv2.face.EigenFaceRecognizer_create()\nmodel.train(np.asarray(Training_Data), np.asarray(Labels))\n\nprint(\"Model Training Complete!!!!!\")\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Untitled1.py","file_name":"Untitled1.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"286416938","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 28 17:13:01 2017\n\n@author: khoefle\n\"\"\"\n\n\n##Imports the Tensorflow library\nimport tensorflow as tf\n\nwith tf.device('/gpu:0'): #with tf.device('/cpu:0'):\n #Define the constant, with a value, datatype, and a representive name\n nc1 = tf.constant(10,tf.float32,name='const1')\n nc2 = tf.constant(11,tf.float32,name='const2')\n \n #Define the place holder x\n x = tf.placeholder(tf.float32,name='x')\n \n #Define the variable y\n y = tf.Variable(5.0,tf.float32,name='y')\n \n #Describe the subtraction\n ns = x - y;\n \n #Describe the addition\n na = tf.add(nc1,nc2)\n \n #Describe the divison\n nd = tf.divide(na,ns)\n \n #Create the Session object \n with tf.Session() as session:\n wr = tf.summary.FileWriter('./simpleExample',session.graph)\n \n \n #Initialize variables\n init = tf.global_variables_initializer()\n \n #parse to session\n session.run(init)\n print(session.run(nd,{x:7.0}))\n \n wr.close()\n \n \n","sub_path":"Lesson3/constAddParamVarDivWithWriter.py","file_name":"constAddParamVarDivWithWriter.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"259125203","text":"import sys\nfrom PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QAction, QLineEdit, QMessageBox, QLabel, QCheckBox\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtCore import pyqtSlot, QSize\nfrom requestData import requestData\nfrom responseData import graphing\nfrom timeSeriesPlot import timeSeriesPlot\nfrom SMAPlot import SMAPlot\n\nclass Window_1(QMainWindow):\n\n def __init__(self):\n super().__init__()\n self.title = 'Stock Analysis'\n self.left = 10\n self.top = 10\n self.width = 400\n self.height = 140\n self.initUI()\n\n def initUI(self):\n self.setWindowTitle(self.title)\n self.setGeometry(self.left, self.top, self.width, self.height)\n\n self.textbox =QLabel('Enter a stock',self)\n self.textbox.move(20,20)\n self.textbox.resize(280,40)\n\n self.textStuff = QLineEdit(self)\n self.textStuff.move(20,60)\n self.textStuff.resize(280,20)\n\n self.button1 = QPushButton('Analyze' ,self)\n self.button1.move(20,80)\n self.button1.resize(150,30)\n\n #connect button to function on_click\n self.button1.clicked.connect(self.on_click)\n self.show()\n\n \n def on_click(self):\n self.textboxValue = self.textStuff.text()\n self.dialog = Window_2(self.textboxValue)\n self.dialog.show()\n\n\nclass Window_2(QMainWindow):\n\n def __init__(self, stockValue):\n super().__init__()\n self.stockValue = stockValue\n self.title = \"Another WindoWwww\"\n self.left = 150\n self.top = 150\n self.width = 400\n self.height = 450\n self.initUI()\n\n def initUI(self):\n self.setWindowTitle(self.title)\n self.setGeometry(self.left, self.top, self.width, self.height)\n\n self.textbox = QLabel('Graphs for ' + self.stockValue, self)\n self.textbox.move(20,20)\n self.textbox.resize(150,30)\n\n self.graphButton1 = QPushButton('Line Graph', self)\n self.graphButton1.resize(150,30)\n self.graphButton1.move(20,60)\n\n self.graphButton2 = QPushButton('Time Series Plot', self)\n self.graphButton2.resize(150,30)\n self.graphButton2.move(20,90)\n\n\n self.graphButton3 = QPushButton('SMA Plot', self)\n self.graphButton3.resize(150,30)\n self.graphButton3.move(20,120)\n\n self.graphButton1.clicked.connect(self.graphButton_1)\n self.graphButton2.clicked.connect(self.graphButton_2)\n self.graphButton3.clicked.connect(self.graphButton_3)\n\n def graphButton_1(self):\n print('button1')\n daysList, openList,highList, lowList, closeList = requestData.weekly_OLH_Data(self.stockValue)\n graphing.past_week_open_low_high(self.stockValue, daysList, openList, highList, lowList, closeList)\n\n def graphButton_2(self):\n print('button2')\n timeSeriesPlot.timeSeriesPlot(self.stockValue)\n \n\n def graphButton_3(self):\n print('button3')\n SMAPlot.SMAPlot(self.stockValue)\n \n \n\n\n \n","sub_path":"stockware/GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"90897093","text":"import logging\nimport os\nfrom subprocess import call\nimport time\n\nimport botocore # amazon api\n\nfrom ramp_database.tools import set_predictions\nfrom ramp_database.tools import set_time\nfrom ramp_database.tools import set_scores\nfrom ramp_database.tools import set_submission_state\nfrom ramp_database.tools import get_submissions\nfrom ramp_database.tools import get_submission_state\nfrom ramp_database.tools import get_submission_by_id\nfrom ramp_database.tools import set_submission_max_ram\nfrom ramp_database.tools import score_submission\nfrom ramp_database.tools import set_submission_error_msg\nfrom ramp_database.tools import get_event_nb_folds\n\nfrom ..base import _get_traceback\n\nfrom .api import (\n AWS_CONFIG_SECTION,\n TRAIN_LOOP_INTERVAL_SECS_FIELD,\n HOOKS_SECTION,\n HOOK_SUCCESSFUL_TRAINING, HOOK_START_TRAINING, HOOK_FAILED_TRAINING,\n CHECK_STATUS_INTERVAL_SECS_FIELD,\n MEMORY_PROFILING_FIELD, LOCAL_LOG_FOLDER_FIELD,\n launch_ec2_instances, terminate_ec2_instance,\n _tag_instance_by_submission, _add_or_update_tag,\n list_ec2_instance_ids, _is_ready, _get_tags,\n upload_submission, launch_train, download_log,\n _training_finished, _training_successful,\n _get_submission_max_ram, download_mprof_data, download_predictions,\n _get_log_content, _wait_until_train_finished)\n\n\nlogger = logging.getLogger('ramp_aws')\n\n\ndef train_loop(config, event_name):\n \"\"\"\n This function starts a training loop for a given event\n The loop waits for any submission with the state 'new' then\n create an ec2 instance to train the submission on it.\n\n Parameters\n ----------\n\n event_name : str\n event name\n \"\"\"\n conf_aws = config[AWS_CONFIG_SECTION]\n secs = conf_aws[TRAIN_LOOP_INTERVAL_SECS_FIELD]\n while True:\n # Launch new instances for new submissions\n submissions = get_submissions(config, event_name, 'new')\n for submission_id, _ in submissions:\n submission = get_submission_by_id(config, submission_id)\n submission_name = _get_submission_folder_name(submission_id)\n if submission.is_sandbox:\n continue\n try:\n instance, = launch_ec2_instances(conf_aws, nb=1)\n except botocore.exceptions.ClientError as ex:\n logger.info('Exception when launching a new instance : \"{}\"'\n .format(ex))\n logger.info('Skipping...')\n continue\n nb_trials = 0\n while nb_trials < conf_aws.get('new_instance_nb_trials', 20):\n if instance.state.get('name') == 'running':\n break\n nb_trials += 1\n time.sleep(conf_aws.get('new_instance_check_interval', 6))\n\n _tag_instance_by_submission(conf_aws, instance.id, submission_name)\n _add_or_update_tag(conf_aws, instance.id, 'train_loop', '1')\n _add_or_update_tag(conf_aws, instance.id, 'event_name', event_name)\n logger.info('Launched instance \"{}\" for submission \"{}\"'.format(\n instance.id, submission))\n set_submission_state(config, submission.id, 'sent_to_training')\n # Score tested submissions\n submissions = get_submissions(config, event_name, 'tested')\n for submission_id, _ in submissions:\n label = _get_submission_label_by_id(config, submission_id)\n logger.info('Scoring submission : {}'.format(label))\n score_submission(config, submission_id)\n _run_hook(config, HOOK_SUCCESSFUL_TRAINING, submission_id)\n # Get running instances and process events\n instance_ids = list_ec2_instance_ids(conf_aws)\n for instance_id in instance_ids:\n if not _is_ready(conf_aws, instance_id):\n continue\n tags = _get_tags(conf_aws, instance_id)\n # Filter instances that were not launched\n # by the training loop API\n # if 'submission_id' not in tags: # no longer added to tags\n # continue\n if tags.get('event_name') != event_name:\n continue\n if 'train_loop' not in tags:\n continue\n # Process each instance\n submission_name = tags['Name']\n assert submission_name.startswith('submission_')\n submission_id = int(submission_name[11:])\n submission = get_submission_by_id(config, submission_id)\n label = '{}_{}'.format(submission_id, submission.name)\n state = get_submission_state(config, submission_id)\n submissions_dir = os.path.split(submission.path)[0]\n if state == 'sent_to_training':\n exit_status = upload_submission(\n conf_aws, instance_id, submission_name, submissions_dir)\n if exit_status != 0:\n logger.error(\n 'Cannot upload submission \"{}\"'\n ', an error occured'.format(label))\n continue\n # start training HERE\n exit_status = launch_train(\n conf_aws, instance_id, submission_name)\n if exit_status != 0:\n logger.error(\n 'Cannot start training of submission \"{}\"'\n ', an error occured.'.format(label))\n continue\n set_submission_state(config, submission_id, 'training')\n _run_hook(config, HOOK_START_TRAINING, submission_id)\n\n elif state == 'training':\n # in any case (successful training or not)\n # download the log\n download_log(conf_aws, instance_id, submission_name)\n if _training_finished(conf_aws, instance_id, submission_name):\n logger.info(\n 'Training of \"{}\" finished, checking '\n 'if successful or not...'.format(label))\n submission = get_submission_by_id(config, submission_id)\n actual_nb_folds = get_event_nb_folds(\n config, submission.event.name\n )\n if _training_successful(\n conf_aws,\n instance_id,\n submission_name,\n actual_nb_folds):\n logger.info('Training of \"{}\" was successful'\n .format(label))\n if conf_aws.get(MEMORY_PROFILING_FIELD):\n logger.info('Download max ram usage info of \"{}\"'\n .format(label))\n download_mprof_data(\n conf_aws, instance_id, submission_name\n )\n max_ram = _get_submission_max_ram(\n conf_aws, submission_name\n )\n logger.info('Max ram usage of \"{}\": {}MB'\n .format(label, max_ram))\n set_submission_max_ram(\n config, submission_id, max_ram\n )\n\n logger.info('Downloading the predictions of \"{}\"'\n .format(label))\n path = download_predictions(\n conf_aws, instance_id, submission_name)\n set_predictions(config, submission_id, path)\n set_time(config, submission_id, path)\n set_scores(config, submission_id, path)\n set_submission_state(config, submission_id, 'tested')\n else:\n logger.info('Training of \"{}\" failed'.format(label))\n set_submission_state(\n config, submission_id, 'training_error')\n error_msg = _get_traceback(\n _get_log_content(conf_aws, submission_name)\n )\n set_submission_error_msg(\n config, submission_id, error_msg)\n _run_hook(config, HOOK_FAILED_TRAINING, submission_id)\n # training finished, so terminate the instance\n terminate_ec2_instance(conf_aws, instance_id)\n time.sleep(secs)\n\n\ndef launch_ec2_instance_and_train(config, submission_id):\n \"\"\"\n This function does the following steps:\n\n 1) launch a new ec2 instance\n 2) upload the submission into the ec2 the instance\n 3) train the submission\n 4) get back the predictions and the log\n 5) terminate the ec2 instance.\n\n Parameters\n ----------\n\n config : dict\n configuration\n\n submission_id : int\n submission id\n\n \"\"\"\n conf_aws = config[AWS_CONFIG_SECTION]\n instance, = launch_ec2_instances(conf_aws, nb=1)\n set_submission_state(config, submission_id, 'sent_to_training')\n _wait_until_ready(config, instance.id)\n train_on_existing_ec2_instance(config, instance.id, submission_id)\n terminate_ec2_instance(conf_aws, instance.id)\n\n\ndef _wait_until_ready(config, instance_id):\n \"\"\"\n Wait until an ec2 instance is ready.\n\n Parameters\n ----------\n\n config : dict\n configuration\n\n instance_id : str\n\n \"\"\"\n logger.info('Waiting until instance \"{}\" is ready...'.format(instance_id))\n conf_aws = config[AWS_CONFIG_SECTION]\n secs = int(conf_aws[CHECK_STATUS_INTERVAL_SECS_FIELD])\n while not _is_ready(conf_aws, instance_id):\n time.sleep(secs)\n\n\ndef train_on_existing_ec2_instance(config, instance_id, submission_id):\n \"\"\"\n Train a submission on a ready ec2 instance\n the steps followed by this function are the following:\n 1) upload the submission code to the instance\n 2) launch training in a screen\n 3) wait until training is finished\n 4) download the predictions\n 5) download th log\n 6) set the predictions in the database\n 7) score the submission\n \"\"\"\n conf_aws = config[AWS_CONFIG_SECTION]\n upload_submission(conf_aws, instance_id, submission_id)\n launch_train(conf_aws, instance_id, submission_id)\n set_submission_state(config, submission_id, 'training')\n _run_hook(config, HOOK_START_TRAINING, submission_id)\n _wait_until_train_finished(conf_aws, instance_id, submission_id)\n download_log(conf_aws, instance_id, submission_id)\n\n label = _get_submission_label_by_id(config, submission_id)\n submission = get_submission_by_id(config, submission_id)\n actual_nb_folds = get_event_nb_folds(config, submission.event.name)\n if _training_successful(conf_aws, instance_id, submission_id,\n actual_nb_folds):\n logger.info('Training of \"{}\" was successful'.format(\n label, instance_id))\n if conf_aws[MEMORY_PROFILING_FIELD]:\n logger.info('Download max ram usage info of \"{}\"'.format(label))\n download_mprof_data(conf_aws, instance_id, submission_id)\n max_ram = _get_submission_max_ram(conf_aws, submission_id)\n logger.info('Max ram usage of \"{}\": {}MB'.format(label, max_ram))\n set_submission_max_ram(config, submission_id, max_ram)\n\n logger.info('Downloading predictions of : \"{}\"'.format(label))\n predictions_folder_path = download_predictions(\n conf_aws, instance_id, submission_id)\n set_predictions(config, submission_id, predictions_folder_path)\n set_time(config, submission_id, predictions_folder_path)\n set_scores(config, submission_id, predictions_folder_path)\n set_submission_state(config, submission_id, 'tested')\n logger.info('Scoring \"{}\"'.format(label))\n score_submission(config, submission_id)\n _run_hook(config, HOOK_SUCCESSFUL_TRAINING, submission_id)\n else:\n logger.info('Training of \"{}\" in \"{}\" failed'.format(\n label, instance_id))\n set_submission_state(config, submission_id, 'training_error')\n error_msg = _get_traceback(\n _get_log_content(conf_aws, submission_id))\n set_submission_error_msg(config, submission_id, error_msg)\n _run_hook(config, HOOK_FAILED_TRAINING, submission_id)\n\n\ndef _run_hook(config, hook_name, submission_id):\n \"\"\"\n run hooks corresponding to hook_name\n \"\"\"\n conf_aws = config[AWS_CONFIG_SECTION]\n hooks = conf_aws.get(HOOKS_SECTION)\n if not hooks:\n return\n if hook_name in hooks:\n submission = get_submission_by_id(config, submission_id)\n submission_folder_name = _get_submission_folder_name(submission_id)\n submission_folder = os.path.join(\n conf_aws[LOCAL_LOG_FOLDER_FIELD],\n submission_folder_name)\n env = {\n 'RAMP_AWS_SUBMISSION_ID': str(submission_id),\n 'RAMP_AWS_SUBMISSION_NAME': submission.name,\n 'RAMP_AWS_EVENT': submission.event.name,\n 'RAMP_AWS_TEAM': submission.team.name,\n 'RAMP_AWS_HOOK': hook_name,\n 'RAMP_AWS_SUBMISSION_FOLDER': submission_folder\n }\n env.update(os.environ)\n cmd = hooks[hook_name]\n if type(cmd) == list:\n cmd = ';'.join(cmd)\n logger.info('Running \"{}\" for hook {}'.format(cmd, hook_name))\n return call(cmd, shell=True, env=env)\n\n\ndef _get_submission_folder_name(submission_id):\n return 'submission_{:09d}'.format(submission_id)\n\n\ndef _get_submission_label_by_id(config, submission_id):\n submission = get_submission_by_id(config, submission_id)\n return _get_submission_label(submission)\n\n\ndef _get_submission_label(submission):\n # Submissions in AWS are tagged by the label\n label = '{}_{}'.format(submission.id, submission.name)\n return label\n","sub_path":"ramp-engine/ramp_engine/aws/aws_train.py","file_name":"aws_train.py","file_ext":"py","file_size_in_byte":14011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"368527381","text":"# -*- coding: utf-8 -*-\n# Copyright 2015, 2016 OpenMarket Ltd\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 abc\nfrom typing import TYPE_CHECKING, Any, Dict\n\nfrom synapse.types import RoomStreamToken\n\nif TYPE_CHECKING:\n from synapse.app.homeserver import HomeServer\n\n\nclass Pusher(metaclass=abc.ABCMeta):\n def __init__(self, hs: \"HomeServer\", pusherdict: Dict[str, Any]):\n self.hs = hs\n self.store = self.hs.get_datastore()\n self.clock = self.hs.get_clock()\n\n self.pusher_id = pusherdict[\"id\"]\n self.user_id = pusherdict[\"user_name\"]\n self.app_id = pusherdict[\"app_id\"]\n self.pushkey = pusherdict[\"pushkey\"]\n\n # This is the highest stream ordering we know it's safe to process.\n # When new events arrive, we'll be given a window of new events: we\n # should honour this rather than just looking for anything higher\n # because of potential out-of-order event serialisation.\n self.max_stream_ordering = self.store.get_room_max_stream_ordering()\n\n def on_new_notifications(self, max_token: RoomStreamToken) -> None:\n # We just use the minimum stream ordering and ignore the vector clock\n # component. This is safe to do as long as we *always* ignore the vector\n # clock components.\n max_stream_ordering = max_token.stream\n\n self.max_stream_ordering = max(max_stream_ordering, self.max_stream_ordering)\n self._start_processing()\n\n @abc.abstractmethod\n def _start_processing(self):\n \"\"\"Start processing push notifications.\"\"\"\n raise NotImplementedError()\n\n @abc.abstractmethod\n def on_new_receipts(self, min_stream_id: int, max_stream_id: int) -> None:\n raise NotImplementedError()\n\n @abc.abstractmethod\n def on_started(self, have_notifs: bool) -> None:\n \"\"\"Called when this pusher has been started.\n\n Args:\n should_check_for_notifs: Whether we should immediately\n check for push to send. Set to False only if it's known there\n is nothing to send\n \"\"\"\n raise NotImplementedError()\n\n @abc.abstractmethod\n def on_stop(self) -> None:\n raise NotImplementedError()\n\n\nclass PusherConfigException(Exception):\n \"\"\"An error occurred when creating a pusher.\"\"\"\n","sub_path":"synapse/push/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"350644480","text":"import asyncio\nfrom io import BytesIO\n\nimport aiohttp\nfrom tqdm import tqdm\n\nfrom .utils import RangeNotSupportedError, hook_print, retry\n\n\nclass Funnel:\n def __init__(self, url, range, session, block_size, piece_size):\n self.url = url\n self.range = range\n self.session = session\n self.block_size = block_size\n self.piece_size = piece_size\n self.blocks = asyncio.Queue(maxsize=2)\n\n async def __aenter__(self):\n self.producer = asyncio.ensure_future(self.produce_blocks())\n return self\n\n async def __aexit__(self, type, value, tb):\n self.producer.cancel()\n while not self.blocks.empty():\n self.blocks.get_nowait()\n await self.producer\n\n # needs Python 3.6\n async def __aiter__(self):\n while not (self.producer.done() and self.blocks.empty()):\n chunk = await self.blocks.get()\n if isinstance(chunk, Exception):\n raise chunk\n yield chunk\n\n @retry\n async def request_range(self, range, bar):\n headers = {'Range': 'bytes={0.begin}-{0.end}'.format(range)}\n async with self.session.get(self.url, headers=headers) as resp:\n if resp.status != 206:\n raise RangeNotSupportedError\n data = BytesIO()\n async for chunk in resp.content.iter_any():\n bar.update(len(chunk))\n data.write(chunk)\n return data.getvalue()\n\n async def produce_blocks(self):\n for nr, block in enumerate(self.range.subranges(self.block_size)):\n with tqdm(\n desc=f'Block #{nr}',\n leave=False,\n dynamic_ncols=True,\n total=block.size(),\n unit='B',\n unit_scale=True,\n unit_divisor=1024) as bar, hook_print(bar.write):\n futures = [\n asyncio.ensure_future(self.request_range(r, bar))\n for r in block.subranges(self.piece_size)\n ]\n try:\n results = await asyncio.gather(*futures)\n await self.blocks.put(b''.join(results))\n except (asyncio.CancelledError, aiohttp.ClientError) as exc:\n for f in futures:\n f.cancel()\n # Notify the consumer to leave\n # -- which is waiting at the end of this queue!\n await self.blocks.put(exc)\n return\n","sub_path":"video_funnel/funnel.py","file_name":"funnel.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"375685887","text":"\"\"\" \nThe TIME_CONVERSIONS.py module gathers classes and functions for time system transformations\n(e.g. between seconds from 1970 to datetime format). \n\nMODULES CALLED:\nNUMPY, TIME, DATETIME, CALENDAR\n \nMODIFICATION HISTORY:\nCreated by Ing. Freddy Galindo (frederickgalindo@gmail.com). ROJ Aug 13, 2009.\n\"\"\"\n\nimport numpy\nimport time\n#import datetime as dt\nimport calendar\n\nclass Time:\n \"\"\"\n time(year,month,dom,hour,min,secs)\n\n An object represents a date and time of certain event..\n\n Parameters\n ----------\n YEAR = Number of the desired year. Year must be valid values from the civil calendar.\n Years B.C.E must be represented as negative integers. Years in the common era are repre-\n sented as positive integers. In particular, note that there is no year 0 in the civil\n calendar. 1 B.C.E. (-1) is followed by 1 C.E. (1).\n\n MONTH = Number of desired month (1=Jan, ..., 12=December).\n\n DOM = Number of day of the month.\n\n HOUR = Number of the hour of the day. By default hour=0\n\n MINS = Number of the minute of the hour. By default min=0\n\n SECS = Number of the second of the minute. By default secs=0.\n \n Examples\n --------\n time_info = time(2008,9,30,12,30,00)\n\n time_info = time(2008,9,30)\n \"\"\"\n \n def __init__(self,year=None,month=None,dom=None,hour=0,mins=0,secs=0):\n # If one the first three inputs are not defined, it takes the current date.\n date = time.localtime()\n if year==None:year=date[0]\n if month==None:month=date[1]\n if dom==None:dom=date[2]\n \n # Converting to arrays\n year = numpy.array([year]); month = numpy.array([month]); dom = numpy.array([dom])\n hour = numpy.array([hour]); mins = numpy.array([mins]); secs = numpy.array([secs])\n \n # Defining time information object.\n self.year = numpy.atleast_1d(year)\n self.month = numpy.atleast_1d(month)\n self.dom = numpy.atleast_1d(dom)\n self.hour = numpy.atleast_1d(hour)\n self.mins = numpy.atleast_1d(mins)\n self.secs = numpy.atleast_1d(secs)\n \n def change2julday(self):\n \"\"\"\n Converts a datetime to Julian days.\n \"\"\"\n \n # Defining constants\n greg = 2299171 # incorrect Julian day for Oct, 25, 1582.\n min_calendar = -4716\n max_calendar = 5000000\n \n min_year = numpy.nanmin(self.year)\n max_year = numpy.nanmax(self.year)\n if (min_yearmax_calendar):\n print (\"Value of Julian date is out of allowed range\")\n return -1\n\n noyear = numpy.sum(self.year==0)\n if noyear>0:\n print (\"There is no year zero in the civil calendar\")\n return -1\n\n # Knowing if the year is less than 0.\n bc = self.year<0 \n \n # Knowing if the month is less than March. \n inJanFeb = self.month<=2\n \n jy = self.year + bc - inJanFeb\n jm = self.month + (1 + 12*inJanFeb)\n \n # Computing Julian days.\n jul= numpy.floor(365.25*jy) + numpy.floor(30.6001*jm) + (self.dom+1720995.0)\n\n # Test whether to change to Gregorian Calendar\n if numpy.min(jul) >= greg:\n ja = numpy.int32(0.01*jy)\n jul = jul + 2 - ja + numpy.int32(0.25*ja)\n else:\n gregchange = numpy.where(jul >= greg)\n if gregchange[0].size>0: \n ja = numpy.int32(0.01 + jy[gregchange])\n jy[gregchange] = jy[gregchange] + 2 - ja + numpy.int32(0.25*ja)\n\n # Determining machine-specific parameters affecting floating-point.\n eps = 0.0 # Replace this line for a function to get precision.\n eps = abs(jul)*0.0 > eps\n \n jul = jul + (self.hour/24. -0.5) + (self.mins/1440.) + (self.secs/86400.) + eps \n \n return jul[0]\n \n def change2secs(self): \n \"\"\"\n Converts datetime to number of seconds respect to 1970.\n \"\"\"\n \n year = self.year\n if year.size>1: year = year[0]\n\n month = self.month\n if month.size>1: month = month[0]\n \n dom = self.dom\n if dom.size>1: dom = dom[0]\n \n # Resizing hour, mins and secs if it was necessary.\n hour = self.hour\n if hour.size>1:hour = hour[0]\n if hour.size==1:hour = numpy.resize(hour,year.size)\n \n mins = self.mins\n if mins.size>1:mins = mins[0]\n if mins.size==1:mins = numpy.resize(mins,year.size)\n\n secs = self.secs\n if secs.size>1:secs = secs[0]\n if secs.size==1:secs = numpy.resize(secs,year.size)\n\n # Using time.mktime to compute seconds respect to 1970.\n secs1970 = numpy.zeros(year.size)\n for ii in numpy.arange(year.size):\n secs1970[ii] = time.mktime((int(year[ii]),int(month[ii]),int(dom[ii]),\\\n int(hour[ii]),int(mins[ii]),int(secs[ii]),0,0,0))\n\n secs1970 = numpy.int32(secs1970 - time.timezone)\n \n return secs1970\n\n def change2strdate(self,mode=1):\n \"\"\"\n change2strdate method converts a date and time of certain event to date string. The\n string format is like localtime (e.g. Fri Oct 9 15:00:19 2009).\n \n Parameters\n ----------\n None.\n \n Return\n ------\n \n Modification History\n --------------------\n Created by Freddy R. Galindo, ROJ, 09 October 2009.\n \n \"\"\"\n \n secs = numpy.atleast_1d(self.change2secs())\n strdate = []\n for ii in numpy.arange(numpy.size(secs)): \n secs_tmp = time.localtime(secs[ii] + time.timezone)\n if mode==1:\n strdate.append(time.strftime(\"%d-%b-%Y (%j) %H:%M:%S\",secs_tmp))\n elif mode==2: \n strdate.append(time.strftime(\"%d-%b-%Y (%j)\",secs_tmp))\n \n strdate = numpy.array(strdate)\n\n return strdate\n\n\nclass Secs:\n \"\"\"\n secs(secs):\n \n An object represents the number of seconds respect to 1970.\n \n Parameters\n ----------\n \n SECS = A scalar or array giving the number of seconds respect to 1970.\n \n Example:\n --------\n secs_info = secs(1251241373)\n \n secs_info = secs([1251241373,1251241383,1251241393]) \n \"\"\"\n def __init__(self,secs): \n self.secs = secs\n \n def change2julday(self):\n \"\"\"\n Convert seconds from 1970 to Julian days.\n \"\"\"\n \n secs_1970 = time(1970,1,1,0,0,0).change2julday()\n \n julian = self.secs/86400.0 + secs_1970\n \n return julian\n \n def change2time(self): \n \"\"\"\n Converts seconds from 1970 to datetime.\n \"\"\"\n \n secs1970 = numpy.atleast_1d(self.secs)\n \n datetime = numpy.zeros((9,secs1970.size))\n for ii in numpy.arange(secs1970.size):\n tuple = time.gmtime(secs1970[ii])\n datetime[0,ii] = tuple[0]\n datetime[1,ii] = tuple[1]\n datetime[2,ii] = tuple[2]\n datetime[3,ii] = tuple[3]\n datetime[4,ii] = tuple[4]\n datetime[5,ii] = tuple[5]\n datetime[6,ii] = tuple[6]\n datetime[7,ii] = tuple[7]\n datetime[8,ii] = tuple[8]\n\n datetime = numpy.int32(datetime)\n\n return datetime\n\n\nclass Julian: \n \"\"\"\n julian(julian):\n \n An object represents julian days.\n \n Parameters\n ----------\n \n JULIAN = A scalar or array giving the julina days.\n \n Example:\n --------\n julian_info = julian(2454740)\n \n julian_info = julian([2454740,2454760,2454780])\n \"\"\"\n def __init__(self,julian):\n self.julian = numpy.atleast_1d(julian)\n \n def change2time(self): \n \"\"\"\n change2time method converts from julian day to calendar date and time.\n \n Return\n ------\n year = An array giving the year of the desired julian day.\n month = An array giving the month of the desired julian day. \n dom = An array giving the day of the desired julian day.\n hour = An array giving the hour of the desired julian day.\n mins = An array giving the minute of the desired julian day.\n secs = An array giving the second of the desired julian day.\n \n Examples\n --------\n >> jd = 2455119.0 \n >> [yy,mo,dd,hh,mi,ss] = TimeTools.julian(jd).change2time()\n >> print ([yy,mo,dd,hh,mi,ss])\n [2009] [10] [ 14.] [ 12.] [ 0.] [ 0.]\n \n Modification history\n -------------------- \n Translated from \"Numerical Recipies in C\", by William H. Press, Brian P. Flannery,\n Saul A. Teukolsky, and William T. Vetterling. Cambridge University Press, 1988.\n Converted to Python by Freddy R. Galindo, ROJ, 06 October 2009.\n \"\"\"\n\n min_julian = -1095 \n max_julian = 1827933925\n if (numpy.min(self.julian) < min_julian) or (numpy.max(self.julian) > max_julian):\n print ('Value of Julian date is out of allowed range.')\n return None\n\n # Beginning of Gregorian calendar\n igreg = 2299161\n julLong = numpy.floor(self.julian + 0.5) \n minJul = numpy.min(julLong)\n \n if (minJul >= igreg):\n # All are Gregorian\n jalpha = numpy.int32(((julLong - 1867216) - 0.25)/36524.25)\n ja = julLong + 1 + jalpha - numpy.int32(0.25*jalpha)\n else: \n ja = julLong\n gregChange = numpy.where(julLong >= igreg)\n if gregChange[0].size>0:\n jalpha = numpy.int32(((julLong[gregChange]-1867216) - 0.25)/36524.25)\n ja[gregChange] = julLong[gregChange]+1+jalpha-numpy.int32(0.25*jalpha)\n\n # clear memory.\n jalpha = -1\n \n jb = ja + 1524\n jc = numpy.int32(6680. + ((jb-2439870)-122.1)/365.25)\n jd = numpy.int32(365.*jc + (0.25*jc))\n je = numpy.int32((jb - jd)/30.6001)\n \n dom = jb - jd - numpy.int32(30.6001*je)\n month = je - 1\n month = ((month - 1) % 12) + 1\n month = numpy.atleast_1d(month)\n year = jc - 4715\n year = year - (month > 2)*1\n year = year - (year <= 0)*1\n year = numpy.atleast_1d(year)\n \n # Getting hours, minutes, seconds\n fraction = self.julian + 0.5 - julLong\n eps_0 = dom*0.0 + 1.0e-12\n eps_1 = 1.0e-12*numpy.abs(julLong)\n eps = (eps_0>eps_1)*eps_0 + (eps_0<=eps_1)*eps_1\n \n hour_0 = dom*0 + 23\n hour_2 = dom*0 + 0\n hour_1 = numpy.floor(fraction*24.0 + eps)\n hour = ((hour_1>hour_0)*23) + ((hour_1<=hour_0)*hour_1)\n hour = ((hour_1=hour_2)*hour_1)\n \n fraction = fraction - (hour/24.0)\n mins_0 = dom*0 + 59\n mins_2 = dom*0 + 0\n mins_1 = numpy.floor(fraction*1440.0 + eps)\n mins = ((mins_1>mins_0)*59) + ((mins_1<=mins_0)*mins_1)\n mins = ((mins_1=mins_2)*mins_1)\n \n secs_2 = dom*0 + 0\n secs_1 = (fraction - mins/1440.0)*86400.0\n secs = ((secs_1=secs_2)*secs_1)\n\n return year,month,dom,hour,mins,secs\n\n def change2secs(self):\n \"\"\"\n Converts from Julian days to seconds from 1970. \n \"\"\"\n \n jul_1970 = Time(1970,1,1,0,0,0).change2julday()\n \n secs = numpy.int32((self.julian - jul_1970)*86400)\n \n return secs\n\n def change2lst(self,longitude=-76.8667):\n \"\"\"\n CT2LST converts from local civil time to local mean sideral time \n \n longitude = The longitude in degrees (east of Greenwich) of the place for which\n the local sideral time is desired, scalar. The Greenwich mean sideral time (GMST)\n can be found by setting longitude=0.\n \"\"\"\n\n # Useful constants, see Meus, p. 84\n c = numpy.array([280.46061837, 360.98564736629, 0.000387933, 38710000.0])\n jd2000 = 2451545.0\n t0 = self.julian - jd2000\n t = t0/36525.\n \n # Computing GST in seconds\n theta = c[0] + (c[1]*t0) + (t**2)*(c[2]-t/c[3])\n \n # Computing LST in hours\n lst = (theta + longitude)/15.0\n neg = numpy.where(lst < 0.0)\n if neg[0].size>0:lst[neg] = 24.0 + (lst[neg] % 24)\n lst = lst % 24.0\n\n return lst\n\n\nclass date2doy:\n def __init__(self,year,month,day):\n self.year = year\n self.month = month\n self.day = day\n\n def change2doy(self):\n if calendar.isleap(self.year) == True:\n tfactor = 1\n else:\n tfactor = 2\n\n day = self.day\n month = self.month \n \n doy = numpy.floor((275*month)/9.0) - (tfactor*numpy.floor((month+9)/12.0)) + day - 30\n \n return numpy.int32(doy)\n\n\nclass Doy2Date:\n def __init__(self,year,doy):\n self.year = year\n self.doy = doy\n \n def change2date(self):\n months = numpy.arange(12) + 1\n\n first_dem = date2doy(self.year,months,1)\n first_dem = first_dem.change2doy() \n \n imm = numpy.where((self.doy - first_dem) > 0)\n \n month = imm[0].size\n dom = self.doy -first_dem[month - 1] + 1\n\n return month, dom\n","sub_path":"SIR/radarsys/apps/abs/utils/TimeTools.py","file_name":"TimeTools.py","file_ext":"py","file_size_in_byte":13546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"648011324","text":"\"\"\" Nama : Pawitro Purbangkoro\r\n NIM : L200170045\r\n Kelas: B \"\"\"\r\n\r\n#nomor1\r\ndef cetakSiku(x) :\r\n for i in range(x+1) :\r\n print((\"x\")*i)\r\n\r\n#nomor2\r\ndef gambarlahPersegiEmpat(x, y) :\r\n for i in range(x) :\r\n if i == 0 or i == x-1 :\r\n print((\"@\")*y)\r\n else:\r\n print((\"@\")+(\" \")*(y-2)+(\"@\"))\r\n\r\n#nomor3.a\r\ndef jumlahHurufVokal (a):\r\n vok = \"aiueo\"\r\n jumlah = 0\r\n for x in a :\r\n if x.lower() in vok:\r\n jumlah +=1\r\n return (len(a),jumlah)\r\n\r\n#nomor3.b\r\ndef jumlahHurufKonsonan (a):\r\n vok = \"aiueo\"\r\n jumlah = 0\r\n for x in a :\r\n if x.lower() not in vok:\r\n jumlah +=1\r\n return (len(a),jumlah)\r\n\r\n#nomor4\r\ndef rerata(b):\r\n hasil = float(sum(b))/float(len(b))\r\n return hasil\r\n\r\n#nomor5\r\nfrom math import sqrt as sq\r\ndef apakahPrima(n):\r\n\r\n n = int(n)\r\n assert n >= 0\r\n primaKecil = [2, 3, 5 ,7, 11]\r\n bknPrimaKecil = [0, 1, 4, 6, 8, 9, 10]\r\n # mengecek bilangan prima selalu lebih besar dari 1\r\n if n in primaKecil:\r\n return True\r\n elif n in bknPrimaKecil:\r\n return False\r\n else:\r\n # mengecek faktor pembagi dengan operasi modulus\r\n for i in range(2,int(sq(n))+1):\r\n if (n % i) == 0:\r\n print (n,\"bukan bilangan prima\")\r\n print (\"karena\", n,\"dikalikan\",n//n,\"hasilnya adalah\",n)\r\n break\r\n else:\r\n print (n,\"adalah bilangan prima\")\r\n\r\n#nomor6\r\nlow = 2\r\nup = 1000\r\nfor num in range(low,up+1):\r\n if num>1:\r\n for i in range(2,num):\r\n if(num%i == 0):\r\n break\r\n else:\r\n print(num)\r\n \r\n#nomor7\r\ndef faktorPrima(x) : # x adalah bilangan yang diinputkan untuk di dicari faktor prima nya\r\n a = [] #untuk menyimpan bilangan prima\r\n b = [] #untuk menyimpan faktor prima dari bilangan yg diinputkan\r\n hasil = 0\r\n bil = x\r\n prima =True\r\n for i in range(2,x):\r\n prima = True\r\n for u in range(2, i) :\r\n if i % u == 0 :\r\n prima = False\r\n if prima :\r\n a.append(i) #menambahkan bilangan prima ke variabel a\r\n idx = 0\r\n while bil > 1 : \r\n try: #try untuk mengatasi error ketika index out of range,msal list pnya 5 data maka ketika mengindex data ke6 akan error.\r\n if (bil%a[idx]) == 0 : # a[idx] untuk mengambil bilangan prima dari list a berdasarkan indexing nya\r\n hasil = bil/a[idx]\r\n bil = hasil\r\n b.append(a[idx])#memasukkan faktor primanya ke 'b'\r\n else :\r\n idx = idx + 1\r\n except IndexError :\r\n break\r\n print (b)\r\n\r\n#nomor8\r\ndef apakahTerkandung(h,k):\r\n return h.lower() in k.lower()\r\n\r\n#nomor9\r\ndef ProgCetakAngka(n):\r\n i = 0\r\n for i in range (n):\r\n if i % 3 == 2 and i % 5 == 4:\r\n print(\"Python UMS\")\r\n elif i % 3 == 2:\r\n print(\"Python\")\r\n elif i % 5 == 4:\r\n print(\"UMS\")\r\n else:\r\n print(i + 1)\r\n\r\n#nomor10\r\ndef selesaikanABC(a,b,c):\r\n if a <= 0 and b <= 0 and c <= 0:\r\n print(\"Determinannya Positif. Persamaan mempunyai akar Real\")\r\n else:\r\n print(\"Determinannya Negatif. Persamaan tidak mempunyai akar Real\")\r\n \r\n#nomor11\r\nimport datetime;\r\ndef apakahKabisat(n):\r\n if (n % 4) == 0:\r\n if (n % 100) == 0:\r\n if (n % 400) == 0:\r\n print (\"Tahun Kabisat\")\r\n else:\r\n print(\"Bukan Tahun Kabisat\")\r\n else:\r\n print(\"Tahun Kabisat\")\r\n else:\r\n print(\"Bukan Tahun Kabisat\")\r\n\r\n#nomor12\r\nangka = 25\r\n \r\nprint(\"Permainan Tebak Angka\")\r\nprint(\"Ssya Menyimpan Sebuah Angka bulat Antara 1 sampai 100. Coba tebak\")\r\n\r\nwhile angka != -1:\r\n \r\n masukkan = int(input(\"Masukan Tebakan :>\"))\r\n\r\n if masukkan == angka:\r\n print(\"Ya. Anda Benar\", angka)\r\n break\r\n elif masukkan > angka:\r\n print(\"Itu Terlalu Besar. Coba Lagi\")\r\n elif masukkan < angka:\r\n print(\"Itu Terlalu Kecil. Coba Lagi\")\r\n\r\n#nomor13\r\ndef katakan(bil):\r\n angka = [\"\",\"Satu \",\"Dua \",\"Tiga \",\"Empat \",\"Lima \",\"Enam \",\r\n \"Tujuh \",\"Delapan \",\"Sembilan \",\"Sepuluh \",\"Sebelas \"]\r\n hasil = \"\"\r\n n = int(bil)\r\n if n >= 0 and n <= 11:\r\n\r\n \r\n hasil = angka[n]\r\n elif n < 20:\r\n hasil = katakan(n-10) + \"Belas \"\r\n elif n < 100:\r\n hasil = katakan(n/10) + \"Puluh \" + katakan(n%10)\r\n elif n < 200:\r\n hasil = \"Seratus \" + katakan(n-100)\r\n elif n < 1000:\r\n hasil = katakan(n/100) + \"Ratus \" + katakan(n%100)\r\n elif n < 2000:\r\n hasil = \"Seribu \" + katakan(n-1000)\r\n elif n < 1000000:\r\n hasil = katakan(n/1000) + \"Ribu \" + katakan(n%1000) \r\n elif n < 1000000000:\r\n hasil = katakan(n/1000000) + \"Juta \" + katakan(n%1000000)\r\n elif n > 1000000000:\r\n hasil = 'Maaf, program tidak membaca angka lebih dari Satu Milyar'\r\n return hasil\r\n\r\n\r\na = 1\r\nwhile a != 0:\r\n a = input(' Masukkan angka dari 1 sd 1.000.000.000: ')\r\n huruf = katakan(a)\r\n print(huruf +'Rupiah')\r\n break\r\n\r\n#nomor14\r\ndef formatRupiah(n):\r\n y = str(n)\r\n if len(y) <= 3 :\r\n return 'Rp ' + y \r\n else :\r\n p = y[-3:]\r\n q = y[:-3]\r\n return (formatRupiah(q) + '.' + p)\r\n print ('Rp' + (formatRupiah(q)) + '.' + p) \r\n","sub_path":"Modul 1/modul1.py","file_name":"modul1.py","file_ext":"py","file_size_in_byte":5560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"514838793","text":"from odoo import models, fields\n\n\nclass VmBlogInherit(models.Model):\n _inherit = \"vm.course\"\n\n blog_id = fields.Many2one('blog.blog', 'Blog', readonly=True, )\n blogs_count = fields.Integer(compute='blogs_count_compute')\n\n def create_blog(self):\n blog_obj = self.env['blog.blog']\n blog = blog_obj.search([('name', '=', self.name)])\n\n if blog.exists():\n self.blog_id = blog.id\n else:\n blog_obj.create({\n 'name': self.name,\n })\n self.blog_id = blog_obj.search([('name', '=', self.name)]).id\n\n\n def action_view_blogpost(self):\n action = self.env.ref('website_blog.action_blog_post').read()[0]\n action['domain'] = [('blog_id', '=', self.blog_id.id)]\n return action\n\n\n\n def blogs_count_compute(self):\n self.blogs_count = self.env['blog.post'].search_count([('blog_id', '=', self.blog_id.id)])\n","sub_path":"viseducat_lms_blog/models/course.py","file_name":"course.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"298658765","text":"#!/usr/bin/env python\n\nimport rospy\nfrom std_msgs.msg import Float64\nfrom nav_msgs.msg import Odometry\nfrom tf.transformations import euler_from_quaternion\n\n\nclass StateRepublisher():\n STATE_TOPIC = '/state'\n\n PUBLISHING_POSE_TOPIC_X = '/controls/state/pose/x'\n PUBLISHING_POSE_TOPIC_Y = '/controls/state/pose/y'\n PUBLISHING_POSE_TOPIC_Z = '/controls/state/pose/z'\n PUBLISHING_POSE_TOPIC_ROLL = '/controls/state/pose/roll'\n PUBLISHING_POSE_TOPIC_PITCH = '/controls/state/pose/pitch'\n PUBLISHING_POSE_TOPIC_YAW = '/controls/state/pose/yaw'\n\n PUBLISHING_TWIST_TOPIC_X = '/controls/state/twist/x'\n PUBLISHING_TWIST_TOPIC_Y = '/controls/state/twist/y'\n PUBLISHING_TWIST_TOPIC_Z = '/controls/state/twist/z'\n PUBLISHING_TWIST_TOPIC_ROLL = '/controls/state/twist/roll'\n PUBLISHING_TWIST_TOPIC_PITCH = '/controls/state/twist/pitch'\n PUBLISHING_TWIST_TOPIC_YAW = '/controls/state/twist/yaw'\n\n def __init__(self):\n self._pub_pose_x = rospy.Publisher(self.PUBLISHING_POSE_TOPIC_X, Float64, queue_size=3)\n self._pub_pose_y = rospy.Publisher(self.PUBLISHING_POSE_TOPIC_Y, Float64, queue_size=3)\n self._pub_pose_z = rospy.Publisher(self.PUBLISHING_POSE_TOPIC_Z, Float64, queue_size=3)\n self._pub_pose_roll = rospy.Publisher(self.PUBLISHING_POSE_TOPIC_ROLL, Float64, queue_size=3)\n self._pub_pose_pitch = rospy.Publisher(self.PUBLISHING_POSE_TOPIC_PITCH, Float64, queue_size=3)\n self._pub_pose_yaw = rospy.Publisher(self.PUBLISHING_POSE_TOPIC_YAW, Float64, queue_size=3)\n\n self._pub_twist_x = rospy.Publisher(self.PUBLISHING_TWIST_TOPIC_X, Float64, queue_size=3)\n self._pub_twist_y = rospy.Publisher(self.PUBLISHING_TWIST_TOPIC_Y, Float64, queue_size=3)\n self._pub_twist_z = rospy.Publisher(self.PUBLISHING_TWIST_TOPIC_Z, Float64, queue_size=3)\n self._pub_twist_roll = rospy.Publisher(self.PUBLISHING_TWIST_TOPIC_ROLL, Float64, queue_size=3)\n self._pub_twist_pitch = rospy.Publisher(self.PUBLISHING_TWIST_TOPIC_PITCH, Float64, queue_size=3)\n self._pub_twist_yaw = rospy.Publisher(self.PUBLISHING_TWIST_TOPIC_YAW, Float64, queue_size=3)\n\n rospy.init_node('state_republisher')\n rospy.Subscriber(self.STATE_TOPIC, Odometry, self.receive_odometry)\n rospy.spin()\n\n def receive_odometry(self, odometry):\n # xyz Position\n self._pub_pose_x.publish(odometry.pose.pose.position.x)\n self._pub_pose_y.publish(odometry.pose.pose.position.y)\n self._pub_pose_z.publish(odometry.pose.pose.position.z)\n # rpy Orientation\n roll, pitch, yaw = euler_from_quaternion([odometry.pose.pose.orientation.x,\n odometry.pose.pose.orientation.y,\n odometry.pose.pose.orientation.z,\n odometry.pose.pose.orientation.w])\n self._pub_pose_roll.publish(roll)\n self._pub_pose_pitch.publish(pitch)\n self._pub_pose_yaw.publish(yaw)\n\n # Linear Velocity\n self._pub_twist_x.publish(odometry.twist.twist.linear.x)\n self._pub_twist_y.publish(odometry.twist.twist.linear.y)\n self._pub_twist_z.publish(odometry.twist.twist.linear.z)\n # Angular Velocity\n self._pub_twist_roll.publish(odometry.twist.twist.angular.x)\n self._pub_twist_pitch.publish(odometry.twist.twist.angular.y)\n self._pub_twist_yaw.publish(odometry.twist.twist.angular.z)\n\n\ndef main():\n StateRepublisher()\n\nif __name__ == '__main__':\n main()\n","sub_path":"catkin_ws/src/controls/scripts/state_republisher.py","file_name":"state_republisher.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"649038893","text":"import json\nimport re\nfrom bs4 import BeautifulSoup\nfrom functions import GetHtmlText\nfrom models import *\n\ndef toolInfoGet():\n f = open('item.json', 'r', encoding = 'utf-8')\n item = json.load(f)\n for a in item:\n Str1 = re.sub('
', '\\n', a['des1'][3:-4])\n Str2 = re.sub('[<>/]', '', Str1)\n Item = toolInfo(a['item_id'], a['item_name'], a['price'], a['total_price'], Str2)\n db.session.add(Item)\n db.session.commit()\n\ndef summonerInfoGet():\n f = open('summoner.json', 'r', encoding = 'utf-8')\n item = json.load(f)\n for a in item:\n Item = summonerInfo(a['summoner_id'], a['summoner_name'], a['summoner_rank'], a['summoner_description'])\n db.session.add(Item)\n db.session.commit()\n\n\n\ndef Analyze(RE, Text):\n match = re.search(RE, Text)\n if match:\n A = match.group(0)\n B = A.split('%')[0]\n return eval(B[-2]) * 10\n else:\n return 100\n\ndef Solve(num):\n url_1 = 'http://pvp.qq.com/web201605/herodetail/'\n url_2 = '.shtml'\n Text = GetHtmlText(url_1 + str(num) + url_2)\n if (Text != None):\n soup = BeautifulSoup(Text, 'html.parser')\n id = num\n name = soup.h2.string\n hp = Analyze(r'', Text)\n atk = Analyze(r'', Text)\n eff = Analyze(r'', Text)\n dfc = Analyze(r'', Text)\n match = re.search(r'data-imgname=\"[^\"]*', Text)\n skin = re.sub(r'\\|', ',', match.group(0).split('\"')[1])\n Item = heroInfo(id, name, hp, atk, eff, dfc, skin)\n db.session.add(Item)\n db.session.commit()\n\ndef heroInfoGet():\n for i in range(100, 530):\n print(i)\n Solve(i)\n\ndef getInfo():\n toolInfoGet()\n summonerInfoGet()\n heroInfoGet()\n\n\n","sub_path":"spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"467432249","text":"import pytest\n\nimport pdfstream.utils.dct_ops as dct_ops\n\n\ndef test_paths():\n dct = {\n \"k1\": {\n \"k11\": \"v11\",\n \"k12\": {\n \"k121\": \"v121\"\n }\n },\n \"k2\": [\"v21\", \"v22\"]\n }\n assert list(dct_ops.paths(dct)) == [\n (\"k1\", \"k11\", \"v11\"),\n (\"k1\", \"k12\", \"k121\", \"v121\"),\n (\"k2\", 0, \"v21\"),\n (\"k2\", 1, \"v22\")\n ]\n\n\ndef test_to_dict(test_data):\n dct_ops.to_dict(test_data[\"Ni_config\"])\n\n\n@pytest.mark.parametrize(\n \"dct, op, expect\",\n [\n (\n {\"k0\": {\"k1\": 0, \"k2\": 1}},\n lambda x: x + 1,\n {\"k0\": {\"k1\": 1, \"k2\": 2}}\n )\n ]\n)\ndef test_iter_dct(dct, op, expect):\n dct1 = dct_ops.iter_dct(dct, op)\n assert dct1 == expect\n\n\n@pytest.mark.parametrize(\n \"dct, keys, expect\",\n [\n ({\"k\": {\"k1\": \"v\"}}, (\"k\", \"k1\"), \"v\"),\n ({\"k\": \"v\"}, tuple(), {\"k\": \"v\"}),\n ]\n)\ndef test_get_value(dct, keys, expect):\n value = dct_ops.get_value(dct, keys=keys)\n assert value == expect\n","sub_path":"tests/utils/test_dct_ops.py","file_name":"test_dct_ops.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"161557","text":"from datetime import datetime\nimport time\n\nimport cv2\n\n\ndef webcam_record(src=0, output_path=None):\n \"\"\"\n Record video from a video capture source and write to .mp4 file. Output\n FPS is equal to average FPS over the duration of the recording.\n \"\"\"\n if output_path is None:\n output_path = datetime.now().strftime(\"%Y%m%d%H%M%s.mp4\")\n\n if not output_path.endswith(\".mp4\"):\n output_path += \".mp4\"\n\n cap = cv2.VideoCapture(src)\n assert cap.isOpened(), \"VideoCapture not opened\"\n\n frames = []\n start_time = time.time()\n while True:\n grabbed, frame = cap.read()\n if not grabbed:\n break\n\n frames.append(frame)\n cv2.imshow(\"Stream\", frame)\n if cv2.waitKey(1) == ord(\"q\"):\n break\n\n end_time = time.time()\n cap.release()\n\n assert frames, \"No frames captured\"\n\n average_fps = int(1 / ((end_time - start_time) / len(frames)))\n h, w = frames[0].shape[:2]\n writer = cv2.VideoWriter(\n output_path, cv2.VideoWriter_fourcc(*\"mp4v\"), average_fps, (w, h)\n )\n\n for frame in frames:\n writer.write(frame)\n writer.release()\n","sub_path":"cam_util.py","file_name":"cam_util.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"449078813","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\nfrom pycharm.Crawling.TTACrawler.models import tta\nfrom pycharm.Crawling.TTACrawler.SQLAlchemy_base import db_session\nfrom pycharm.Crawling.TTACrawler.SQLAlchemy_base import init_db\n\ndef show_tables():\n queries = db_session.query(tta)\n entries = [dict(id=q.id, page=q.page, startchar=q.startchar, category=q.category, word=q.word, synonym=q.synonym, synonym2=q.synonym2) for q in queries]\n print(entries)\n\n\ndef exploit_data(soup, start_char, page):\n div_class_left_box = soup.find(\"div\", {\"class\" : \"left_box\"})\n\n div_class_subject_oneline = div_class_left_box.find_all(\"div\", {\"class\" : \"subject_oneline\"})\n\n if len(div_class_subject_oneline) == 0 :\n return False\n\n for i in div_class_subject_oneline :\n first_value = re.sub(\"[\\n\\r\\t]\", \"\", i.find(\"span\").text.strip()) # category\n second_value = re.sub(\"[\\n\\r\\t]\", \"\", i.find(\"a\").text.strip()) # word synonym synonym2\n word_list = re.split(\"[\\(\\,]\", second_value)\n\n print(first_value)\n print(second_value)\n\n word1 = word_list[0].strip()\n try:\n word2 = word_list[1].strip().replace(\")\", \"\")\n except:\n word2 = \"\"\n\n try:\n word3 = word_list[2].strip().replace(\")\", \"\")\n except:\n word3 = \"\"\n\n t = tta(page=page, startchar=start_char, category=first_value, word=word1, synonym=word2, synonym2=word3)\n db_session.add(t)\n db_session.commit()\n\n show_tables()\n\n return True\n\n\ndef setting_data(baseurl, parameter, add_parameter, add_parameter_value):\n\n hangul = [\"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\"]\n for consonant in hangul :\n add_parameter_value[0] = 1\n add_parameter_value[1] = consonant\n\n while True :\n url = baseurl + parameter\n\n for i in range(len(add_parameter)) :\n url = url + \"&\" + str(add_parameter[i]) + str(add_parameter_value[i])\n\n html = requests.get(url=url)\n soup = BeautifulSoup(html.text)\n\n isContinue = exploit_data(soup, consonant, add_parameter_value[0])\n\n if isContinue == False :\n break\n\n add_parameter_value[0] = str(int(add_parameter_value[0]) + 1)\n\ndef main() :\n # db 생성\n init_db()\n\n # setting parameter\n baseurl = \"http://terms.tta.or.kr/dictionary/searchFirstList.do?\"\n parameter = \"searchContent=conts01&searchRange=all&listCount=10&orderby=kor_subject&reFlag=N&orderbyOption=TRUE&firstWord=Y&div_big_cd_in=51,107,50&searchCate=bigram\"\n add_parameter = [\"listPage=\", \"firstWordVal=\"]\n add_parameter_value = [\"1\", \"ㄱ\"]\n setting_data(baseurl, parameter, add_parameter, add_parameter_value)\n db_session.close()\n\nmain()","sub_path":"python_module/pycharm/Crawling/TTACrawler/TTA_Crawling.py","file_name":"TTA_Crawling.py","file_ext":"py","file_size_in_byte":2816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"120463814","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\n\nclass MHMove:\n \"\"\"\n Generic Metropolis Hastings move.\n Subclass or add a proposal function directly\n\n Parameters\n ----------\n\n get_proposal:\n It should take as input the parameters (current_samples) and return the proposed parameters and the log-hastings correction\n \"\"\"\n\n def __init__(self, get_proposal):\n self.get_proposal = get_proposal\n\n def propose(self, current_samples, loss_current, log_posterior):\n \"\"\"\n Propose parameter, do the accept/reject step, and return return the new samples, loss\n and whether the parameters were accepted or not.\n\n Parameters\n ----------\n current_samples: dict\n current samples\n\n loss_current: float\n\n log_posterior: function\n log-posterior\n\n Returns\n -------\n new_samples: dict\n Dictionary of samples (so either the newly accepted ones or previously kept ones)\n loss_new: float\n Loss corresponding to the samples returned\n accepted: Bool\n Whether or not the sample was accepted\n \"\"\"\n new_samples, log_hastings = self.get_proposal(current_samples=current_samples)\n\n loss_new = log_posterior(**new_samples)\n\n alpha = loss_new - loss_current + log_hastings\n exp_sample = - np.random.exponential()\n # print(\"loss_new: {:.1f}\".format(loss_new))\n # print(\"accept parameter alpha: {:.1f}\\n\".format(alpha))\n\n if alpha > exp_sample:\n return new_samples, loss_new, True\n else:\n return current_samples, loss_current, False\n","sub_path":"MCMC/moves/mh.py","file_name":"mh.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"287182059","text":"\"\"\" MYFAVE BEST DEALS COUPON SCRAPPER\n\"\"\"\nimport json\nimport utils\nimport random\n\ncities = ['bandung', 'jakarta', 'bali', 'medan', 'surabaya']\nhome_url = 'https://myfave.com'\ndata_per_page = 24\nallCouponList = []\n# Regex for Parsing\nmain_div = r'OffersViewNonCat'\ndetail_div = r'BuyNowSticky'\ndata_script = r'.*listings: \\[{(.*)}\\],\\n'\nnumpage_script = r'.*meta: \".*\",'\ncategory_script = r'\"category\":{\"name\":(.*),\"id\"'\n\n## Scrape coupons from various cities\n## isRequestAll to request all pages in each city\ndef scrapeAllCoupons(cities, isRequestAll):\n allCouponList = []\n for city in cities:\n url = home_url+'/cities/'+city+'/best-selling-deals'\n print('\\n---> Scrape best deals in ' + city)\n localCouponList = scrapeMultiPages(url, isRequestAll) # Get coupon data from current city\n currCouponList = allCouponList\n allCouponList = mergeCouponLists(currCouponList, localCouponList)\n #Scrape details\n print('\\n---> Scrape Page Details')\n allCouponList = scrapePageDetail(allCouponList)\n return allCouponList\n\n## Scrape pages \n## return couponList json object\ndef scrapeMultiPages(url, isRequestAll):\n counter = 1 # Control timelimit for scrapper\n i = 1\n print('>>> Scrape Page ' + str(i))\n soup = utils.getRawSource(url, counter)\n localCouponList = parseMainPage(soup)\n if (isRequestAll):\n # Find total pages\n result = utils.getTextPattern(soup, main_div, numpage_script)\n sum_data = int(result.group(0).split('\"')[1])\n page_count = round(sum_data/data_per_page)\n num_page = page_count\n else:\n num_page = 1\n # Scrape pages\n while (i < num_page):\n counter += 1\n i += 1\n urlNext = url+'?page='+str(i)\n print('>>> Scrape Page ' + str(i))\n soup = utils.getRawSource(urlNext, counter)\n nextCouponList = parseMainPage(soup)\n localCouponList += nextCouponList\n return localCouponList\n \n## Parse page of item thumbnails on BeautifulSoup form to json object\ndef parseMainPage(soup):\n result = utils.getTextPattern(soup, main_div, data_script)\n jsonStr = '[{' + result.group(1) + '}]'\n couponList = json.loads(jsonStr)\n couponList = formCouponList(couponList)\n return couponList\n\n## Add and format couponList fields\ndef formCouponList(couponList):\n for i in range(0, len(couponList)):\n couponList[i] = formatCoupon(couponList[i])\n return couponList\n\n## Return formatted coupon with neccessary fields added\ndef formatCoupon(coupon):\n newCoupon = {}\n newCoupon['id'] = coupon['id']\n newCoupon['title'] = coupon['name']\n newCoupon['original_price'] = coupon['original_price_cents']/100\n newCoupon['discounted_price'] = coupon['discounted_price_cents']/100\n newCoupon['discount'] = coupon['discount']\n newCoupon['start_date'] = coupon['start_date']\n newCoupon['due_date'] = coupon['end_date']\n newCoupon['purchases_count'] = coupon['purchases_count']\n newCoupon['today_purchases_count'] = coupon['today_purchases_count']\n\n newCoupon['partner'] = {}\n newCoupon['partner']['company_name'] = coupon['company_name']\n newCoupon['partner']['location'] = {}\n newCoupon['partner']['location']['latitude'] = coupon['latitude']\n newCoupon['partner']['location']['longitude'] = coupon['longitude']\n\n newCoupon['average_rating'] = coupon['average_rating']\n newCoupon['number_of_clicks'] = coupon['hotness']\n \n #newCoupon['description'] = coupon['description'] \n #newCoupon['url'] = coupon['url']\n city = coupon['url'].split('/')[2]\n newCoupon['customer_city'] = [city]\n\n return newCoupon\n\n## Scrape detail page of a coupon item\ndef scrapePageDetail(couponList):\n numItem = len(couponList)\n count = 1\n for coupon in couponList:\n city = coupon['customer_city'][0]\n url = home_url+'/cities/'+city+'/offers/'+str(coupon['id'])\n print(' ['+str(count)+'/'+str(numItem)+'] Scrape item id='+ str(coupon['id']))\n soup = utils.getRawSource(url, 1)\n #Get Category\n result = utils.getTextPattern(soup, detail_div, category_script)\n coupon['category'] = result.group(1).split('\"')[1]\n count += 1\n return couponList\n\n## Check if a coupon object already on couponList\n## Return index of occurence if available, otherwise return -1\ndef checkCouponOccurence(coupon, couponList):\n i = 0\n while (i 1.13\n # services is always the second element\n services_list = compose_output_tuple[1]\n except conferrors.ConfigurationError as e:\n log.exit(\"Wrong compose configuration:\\n{}\", e)\n else:\n return services_list\n\n def get_handle(self):\n return TopLevelCommand(project_from_options(self.project_dir, self.options))\n\n def build_images(\n self, builds, current_version, current_uid, current_gid,\n force_pull=True, no_cache=False,\n ):\n\n try:\n compose_handler = self.get_handle()\n\n for image, build in builds.items():\n\n service = build.get('service')\n log.verbose(\"Building image: {}\", image)\n\n options = {\n '--no-cache': no_cache,\n '--parallel': True,\n '--pull': force_pull,\n '--force-rm': True,\n 'SERVICE': [service],\n }\n\n build_args = []\n # NOTE: we can set only 1 variable since options is a dict\n build_args.append(\"{}={}\".format(\"RAPYDO_VERSION\", current_version))\n build_args.append(\"{}={}\".format(\"CURRENT_UID\", current_uid))\n build_args.append(\"{}={}\".format(\"CURRENT_GID\", current_gid))\n\n if len(build_args) > 0:\n options['--build-arg'] = build_args\n\n compose_handler.build(options=options)\n log.info(\"Built image: {}\", image)\n\n return\n except SystemExit:\n log.info(\"SystemExit during template building\")\n\n def command(self, command, options=None, nofailure=False):\n\n # NOTE: debug defaults\n # tmp = self.get_defaults(command)\n # print(\"TEST\", tmp, type(tmp))\n # # exit(1)\n\n compose_handler = self.get_handle()\n method = getattr(compose_handler, command)\n\n if options is None:\n options = {}\n\n if options.get('SERVICE', None) is None:\n options['SERVICE'] = []\n\n log.debug(\"{}'{}'\", compose_log, command)\n\n out = None\n # sometimes this import stucks... importing here to avoid unnecessary waits\n from docker.errors import APIError\n try:\n out = method(options=options)\n except SystemExit as e:\n # NOTE: we check the status here.\n # System exit is received also when a normal command finished.\n if e.code < 0:\n log.warning(\"Invalid code returned: {}\", e.code)\n elif e.code > 0:\n log.exit(\"Compose received: system.exit({})\", e.code, error_code=e.code)\n else:\n log.verbose(\"Executed compose {} w/{}\", command, options)\n except (clierrors.UserError, cerrors.OperationFailedError, BuildError) as e:\n msg = \"Failed command execution:\\n{}\".format(e)\n if nofailure:\n raise AttributeError(msg)\n else:\n log.exit(msg)\n except APIError as e:\n log.exit(\"Failed docker container:\\n{}\", e)\n except (ProjectError, NoSuchService) as e:\n log.exit(str(e))\n else:\n log.verbose(\"Executed compose {} w/{}\", command, options)\n\n return out\n\n @staticmethod\n def split_command(command):\n \"\"\"\n Split a command into command + args_array\n \"\"\"\n if command is None:\n return (None, [])\n\n # pieces = command.split()\n pieces = shlex.split(command)\n try:\n shell_command = pieces[0]\n shell_args = pieces[1:]\n except IndexError:\n # no command, use default\n shell_command = None\n shell_args = []\n\n return (shell_command, shell_args)\n\n def start_containers(\n self,\n services,\n detach=True,\n scale=None,\n skip_dependencies=False,\n abort_on_container_exit=False,\n no_recreate=False,\n ):\n \"\"\"\n Start containers (docker-compose up)\n \"\"\"\n\n if scale is None:\n scale = {}\n\n options = {\n 'SERVICE': services,\n '--no-deps': skip_dependencies,\n '--detach': detach,\n '--build': None,\n '--no-color': False,\n '--remove-orphans': False,\n '--abort-on-container-exit': abort_on_container_exit,\n '--no-recreate': no_recreate,\n '--force-recreate': False,\n '--always-recreate-deps': False,\n '--no-build': False,\n '--scale': scale,\n }\n\n try:\n return self.command('up', options)\n except NetworkConfigChangedError as e:\n log.exit(\n \"{}.\\n{} ({})\",\n e,\n \"Remove previously created networks and try again\",\n \"you can use rapydo clean or docker system prune\"\n )\n\n def create_volatile_container(\n self, service, command=None, publish=None, detach=False\n ):\n \"\"\"\n Execute a command on a not container\n \"\"\"\n\n if publish is None:\n publish = []\n\n if len(publish) <= 0:\n service_post = True\n else:\n service_post = False\n\n shell_command, shell_args = self.split_command(command)\n\n options = {\n 'SERVICE': service,\n '--publish': publish,\n '--service-ports': service_post,\n 'COMMAND': shell_command,\n 'ARGS': shell_args,\n '-e': [],\n '--volume': [],\n '--rm': True,\n '--no-deps': True,\n '--name': None,\n '--user': None,\n '--workdir': None,\n '--entrypoint': None,\n '--detach': detach,\n '--use-aliases': False, # introduced with compose 1.21\n '-T': False,\n '--label': None,\n }\n\n return self.command('run', options)\n\n def exec_command(\n self, service, user=None, command=None, disable_tty=False, nofailure=False\n ):\n \"\"\"\n Execute a command on a running container\n \"\"\"\n shell_command, shell_args = self.split_command(command)\n options = {\n 'SERVICE': service,\n 'COMMAND': shell_command,\n 'ARGS': shell_args,\n '--index': '1',\n '--user': user,\n '-T': disable_tty,\n '--env': None,\n '--workdir': None,\n # '-d': False,\n '--detach': False,\n '--privileged': False,\n }\n if shell_command is not None:\n log.debug(\n \"Command: {}({}+{})\", service.lower(), shell_command, shell_args\n )\n try:\n out = self.command('exec_command', options, nofailure=nofailure)\n except NoSuchService:\n if nofailure:\n raise AttributeError(\"Cannot find service: {}\".format(service))\n else:\n log.exit(\"Cannot find a running container called {}\", service)\n else:\n return out\n\n @staticmethod\n def command_defaults(command):\n if command in ['run']:\n return Compose.set_defaults(\n variables=[\n 'COMMAND',\n 'T',\n 'e',\n 'entrypoint',\n 'user',\n 'label',\n 'publish',\n 'service-ports',\n 'name',\n 'workdir',\n 'volume',\n 'no-deps',\n 'use-aliases',\n ],\n merge={'--rm': True},\n )\n else:\n log.exit(\"No default implemented for: {}\", command)\n\n @staticmethod\n def set_defaults(variables, merge=None):\n if merge is None:\n options = {}\n else:\n options = merge\n for variable in variables:\n if len(variable) == 1:\n key = '-' + variable\n elif variable.upper() == variable:\n key = variable\n else:\n key = '--' + variable\n options[key] = None\n log.verbose('defaults: {}', options)\n return options\n","sub_path":"controller/compose.py","file_name":"compose.py","file_ext":"py","file_size_in_byte":9850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"111022257","text":"# -*- coding:utf8 -*-\n__author__ = 'etu6'\n\nimport json\nfrom pprint import pprint\ndata = {\n 'name' : 'ACME',\n 'shares' : 100,\n 'price' : 542.23\n}\njson_str = json.dumps(data)\npprint(json_str)\n\nfrom urllib.request import urlopen\nu = urlopen('http://test.api.etu6.org/news/list?pagesize=1')\nresp = json.loads(u.read().decode('utf-8'))\nprint(resp)\n\nclass JSONObject:\n def __init__(self,d):\n self.__dict__=d\n\ndata=json.loads(resp,object_hook=JSONObject)\nprint(data.result)\n\nfrom collections import OrderedDict\ns = '{\"name\": \"ACME\", \"shares\": 50, \"price\": 490.1}'\ndata = json.loads(s, object_pairs_hook=OrderedDict)\nprint(data)","sub_path":"cookbook/section6/6.2.py","file_name":"6.2.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"212775839","text":"##\n## Construya una tabla que contenga _c1 y una lista\n## separada por ':' de los valores de la columna _c2\n## para el archivo tbl0.tsv\n## \nimport pandas as pd\n#import numpy as np\ndatos = pd.read_csv('tbl0.tsv',delimiter='\\t',encoding='utf-8')\nc1=datos['_c1'].unique()\nVector=[]\nfor z in c1:\n yx=datos[datos['_c1']==z]\n Vector.append(list(yx['_c2'])) \nVector2=[]\nfor c in range(len(Vector)):\n Vector2.append([str(c1[c]), str(sorted(Vector[c])).replace('[','').replace(']','').replace(', ',':')])\ndatos2=pd.DataFrame(Vector2, columns=['_c1','lista'])\ndatos2.sort_values(by=['_c1'])\n\n","sub_path":"q09.py","file_name":"q09.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"407410586","text":"import numpy as np\nfrom neural_wrappers.readers import H5BatchedDatasetReader\nfrom functools import partial\nfrom overrides import overrides\n\n# For some reasons, results are much better if provided data is in range -1 : 1 (not 0 : 1 or standardized).\nclass GANReader(H5BatchedDatasetReader):\n\tdef __init__(self, datasetPath:str, latentSpaceSize:int):\n\t\tsuper().__init__(\n\t\t\tdatasetPath,\n\t\t\tdataBuckets = {\"data\" : [\"rgb\"]},\n\t\t\tdimGetter = {\"rgb\" : \\\n\t\t\t\tlambda dataset, index : dataset[\"images\"][index.start : index.stop]},\n\t\t\tdimTransform = {\n\t\t\t\t\"data\" : {\"rgb\" : lambda x : (np.float32(x) / 255 - 0.5) * 2}\n\t\t\t}\n\t\t)\n\t\tself.latentSpaceSize = latentSpaceSize\n\n\t@overrides\n\tdef __len__(self) -> int:\n\t\treturn len(self.getDataset()[\"images\"])\n\n\tdef __getitem__(self, index):\n\t\titem, MB = super().__getitem__(index)\n\t\t# MB = index.stop - index.start\n\t\treturn (np.random.randn(MB, self.latentSpaceSize).astype(np.float32), item[\"data\"][\"rgb\"]), MB\n","sub_path":"examples/mnist-gan/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"98073251","text":"import colorama\nimport os\nimport ossi\nimport sys\nimport time\n\n\nsettings = {\n\t'host': '10.200.177.71',\n\t'port': '5023',\n\t'username': 'dadmin',\n\t'password': 'dadmin1',\n\t'pin': 'dadmin1',\n}\n\nMAPPING = {\n\t'6c02ff00': 'Major',\n\t'6c08ff00': 'Trunks',\n\t'6c0aff00': 'Links Down',\n\t'6c0cff00': '# Logins',\n\t'6c03ff00': 'Minor',\n\t'6c0bff00': 'Links Up',\n\t'6c04ff00': 'Warnings',\n}\n\nif __name__ == '__main__':\n\ttest = ossi.Ossi(settings)\n\ttest.connect()\n\tt = test.command('sta tru 1')\n\timport ipdb\n\tipdb.set_trace()\n\toutput = test.multiple_to_dict(t)\n\tprint(output)\n\ttest.disconnect()","sub_path":"status_trunk.py","file_name":"status_trunk.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"334748644","text":"import click\n\nfrom globus_cli.parsing import common_options, endpoint_id_arg\nfrom globus_cli.safeio import formatted_print\nfrom globus_cli.services.auth import LazyIdentityMap\nfrom globus_cli.services.transfer import get_client\n\n\n@click.command(\"list\", help=\"List of permissions on an endpoint\")\n@common_options\n@endpoint_id_arg\ndef list_command(endpoint_id):\n \"\"\"\n Executor for `globus endpoint permission list`\n \"\"\"\n client = get_client()\n\n rules = client.endpoint_acl_list(endpoint_id)\n\n resolved_ids = LazyIdentityMap(\n x[\"principal\"] for x in rules if x[\"principal_type\"] == \"identity\"\n )\n\n def principal_str(rule):\n principal = rule[\"principal\"]\n if rule[\"principal_type\"] == \"identity\":\n username = resolved_ids.get(principal)\n return username or principal\n elif rule[\"principal_type\"] == \"group\":\n return (u\"https://app.globus.org/groups/{}\").format(principal)\n else:\n principal = rule[\"principal_type\"]\n\n return principal\n\n formatted_print(\n rules,\n fields=[\n (\"Rule ID\", \"id\"),\n (\"Permissions\", \"permissions\"),\n (\"Shared With\", principal_str),\n (\"Path\", \"path\"),\n ],\n )\n","sub_path":"globus_cli/commands/endpoint/permission/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"132320668","text":"import asyncio, random\nfrom asyncio import Future\n\ndef gen():\n value = 1\n while True:\n receive = yield value\n value = 'got: %s' % receive\n\n\ng = gen()\nprint(g.send(None))\nprint(g.send('hello'))\nprint(g.send(123456))\n\n@asyncio.coroutine\ndef countdown1(n):\n while n > 0:\n print(n)\n n = n - 1\n\n # 通常yield from后都是接的耗时操作, yield from等于for in yield\n yield from asyncio.sleep(0.3)\n\n\nprint(\"-----yield from------\")\n# loop = asyncio.get_event_loop()\n# loop.run_until_complete(asyncio.wait([countdown1(5)]))\n# loop.close()\n\n\nasync def countdown2(n):\n t = n\n while n > 0:\n print(n)\n # async-await 替代 @asyncio.coroutine 和yield from\n await asyncio.sleep(0.3)\n n -= 1\n\n return t\n\n\nasync def async_await_test():\n # print(await asyncio.gather(countdown2(3), countdown2(5)))\n\n # Wait for at most 1 second\n # try:\n # print(await asyncio.wait_for(countdown2(5), timeout=1.0))\n # except asyncio.TimeoutError:\n # print(\"timeout\")\n\n for f in asyncio.as_completed([countdown2(3), countdown2(2), countdown2(1)]):\n print(\"as_completed:{} all_task:{}\".format(await f, len(asyncio.all_tasks())))\n\n # asyncio.shield(countdown2(3))\n\n\nasync def custom_future_test1():\n r = await fu\n print(\"custom_future_test1 complete {}\".format(r))\n\n\nasync def custom_future_test2():\n await asyncio.sleep(2)\n fu.set_result(666)\n print(\"custom_future_test2 complete\")\n\n\nprint(\"-----async-await-----\")\n# asyncio.run(async_await_test())\n\nprint(\"-----custom-future-----\")\nfu = Future()\nloop = asyncio.get_event_loop()\nloop.run_until_complete(asyncio.wait([custom_future_test1(), custom_future_test2()]))\nloop.close()\n\nprint(\"end\")","sub_path":"test/coroutine.py","file_name":"coroutine.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"258484912","text":"#!/usr/bin/env python\n\"\"\"\nThis scripts goes through the wordpress posts and re-formats them for use\nin the _posts folder. It should be run from the wordpress folder.\n\"\"\"\n\nimport os\n\npath = os.path.normpath(os.path.join(os.getcwd(), 'posts'))\nfiles = os.listdir(path)\n\nfor fname in files:\n # Set up new file name\n date = fname.split('-', 1)[0]\n date = '-'.join((date[0:4], date[4:6], date[6:8]))\n newf = date + '-' + fname.split('-', 1)[1]\n newf = os.path.normpath(os.path.join('../_posts/', newf))\n\n # Read file\n with open(os.path.join('posts', fname), 'r') as f:\n lines = f.readlines()\n\n # Grab the index of content start line\n i = 0\n for line in lines:\n if line.startswith('#'):\n break\n else:\n i += 1\n\n # Parse header lines\n header = lines[0:i-1]\n header = {h.split(':', 1)[0]: h.split(':', 1)[1].strip() for h in header}\n newheader = 'title: ' + header['title'] + '\\n'\n newheader += '#link: ' + header['link'] + '\\n'\n newheader += 'permalink: /posts/' + date[0:4] + '/' + date[5:7] \\\n + '/' + header['post_name'] + '\\n'\n newheader += 'date: ' + date + '\\n'\n\n # Write new file\n print(date)\n #print('Writing {}'.format(newf))\n with open(newf, 'w') as f:\n f.write('---\\n')\n f.write(newheader)\n f.write('---\\n')\n f.write('\\n')\n # Note, we're not writing the title line here\n f.write(''.join(lines[i+1:]))\n","sub_path":"wordpress/convert_posts.py","file_name":"convert_posts.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"121741687","text":"import pygame\nimport os\nfrom piece import Piece\n\nclass Game():\n def __init__(self, board,screenSize):\n self.board = board\n self.screenSize = screenSize\n self.pieceSize = self.screenSize[0] // self.board.getSize()[1], self.screenSize[1] // self.board.getSize()[0]\n self.loadImages()\n \n\n def run (self):\n pygame.init()\n self.screen = pygame.display.set_mode(self.screenSize)\n running = True\n while running:\n for event in pygame.event.get():\n if(event.type == pygame.QUIT):\n running = False\n self.draw()\n pygame.display.flip()\n pygame.quit()\n\n def draw (self):\n topLeft = (0,0)\n for row in range (self.board.getSize()[0]):\n for col in range(self.board.getSize()[1]):\n piece = self.board.getPiece((row,col))\n image = self.getImage(piece)\n self.screen.blit(image, topLeft)\n topLeft = topLeft[0] + self.pieceSize[0], topLeft[1]\n topLeft = 0, topLeft[1] + self.pieceSize[1]\n \n def loadImages(self):\n self.images = {}\n for fileName in os.listdir(\"images\"):\n if (not fileName.endswith(\".png\")):\n continue\n image = pygame.image.load(r\"images/\" + fileName)\n image = pygame.transform.scale(image, self.pieceSize)\n self.images[fileName.split(\".\")[0]] = image\n\n def getImage(self, piece):\n string = \"unclicked-bomb\" if piece.getHasBomb() else \"block\"\n\n return self.images[string]\n \n \n\n\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"367594205","text":"from visual import *\r\nimport serial # Serial imported for Serial communication\r\nimport time # Required to use delay functions\r\n\r\nArduinoSerial = serial.Serial('com18',9600) # Create Serial port object called arduinoSerialData\r\ntime.sleep(2) # wait for 2 secounds for the communication to get established\r\n\r\nobj = box(pos=(-5,0,0), size=(0.1,4,4), color=color.white) \r\nwallL = box(pos=(-1,0,0), size=(0.2,12,12), color=color.cyan)\r\ntext(text='US sensor', axis=(0,1,0) , pos=(-2,-6,0), depth=-0.3, color=color.cyan)\r\n\r\nt = 0\r\n \r\nwhile 1:\r\n rate(100)\r\n t = int (ArduinoSerial.readline()) # read the serial data and print it as line\r\n t= t* 0.05\r\n obj.pos.x = t\r\n print(t)\r\n \r\n \r\n","sub_path":"Arduino.py","file_name":"Arduino.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"260130131","text":"#!/usr/bin/env python\n\n\"\"\"\n A joint controller class for the Arduino microcontroller\n Assumes standard hobby servos\n \n Borrowed heavily from Mike Feguson's ArbotiX code.\n \n Created for the UpDroid: http://www.updroid.com\n Author: Nathaniel Gallinger\n\n This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n \n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details at:\n \n http://www.gnu.org/licenses\n\"\"\"\n\nimport roslib; roslib.load_manifest('ros_arduino_python')\nimport rospy, actionlib\nimport os\n\nfrom std_msgs.msg import Float64\nfrom math import pi, radians\nfrom sensor_msgs.msg import JointState\nfrom control_msgs.msg import FollowJointTrajectoryAction\nfrom trajectory_msgs.msg import JointTrajectory\n\nclass HobbyServo:\n\n def __init__(self, controller, name):\n self.controller = controller\n self.name = name\n \n ns = controller.joint_dict+'/'+name+'/'\n \n self.id = int(rospy.get_param(ns+'id'))\n self.range = int(rospy.get_param(ns+'range', 180))\n \n msg = 'Joint added: ' + ns + ', id: ' + str(self.id) + ' range: ' + str(self.range)\n rospy.loginfo(msg)\n\n self.dirty = False # newly updated position?\n self.position = 0.0 # current position, as returned by servo (radians)\n self.desired = 0.0 # desired position (radians)\n self.cmd_prev = 0.0 # previous position sent (radians)\n self.velocity = 0.0 # moving speed\n self.time_prev = rospy.Time.now()\n \n # ROS interfaces\n rospy.Subscriber(name+'/command', Float64, self.commandCb)\n\n def setCurrentFeedback(self, reading):\n \"\"\" Update angle in radians by reading from servo \"\"\"\n # check validity\n if reading >= -(pi/2) and reading <= (pi/2):\n angle_prev = self.position\n self.position = reading\n # update velocity estimate\n t = rospy.Time.now()\n self.velocity = (self.position - angle_prev)/((t - self.time_prev).to_nsec()/1000000000.0)\n self.time_prev = t\n else:\n msg = 'Invalid read of servo: id ' + str(self.id) + ', value ' + str(reading)\n rospy.logdebug(msg)\n return\n if not self.controller.active:\n self.cmd_prev = self.position\n\n def setControlOutput(self, position):\n \"\"\" Set the position that controller is moving to. \n Returns output value in radians. \"\"\"\n self.desired = position\n self.dirty = True\n msg = self.name + ': new desired position set - ' + str(position)\n rospy.logdebug(msg)\n\n def commandCb(self, req):\n \"\"\" Float64 style command input. \"\"\"\n if self.controller and self.controller.active():\n # Under and action control, do not interfere\n return\n else:\n self.dirty = True\n self.desired = req.data\n \n\"\"\" Class to receive Twist commands and publish Odometry data \"\"\"\nclass JointController:\n def __init__(self, arduino, joint_dict, controller_name):\n self.arduino = arduino\n self.joint_dict = joint_dict\n self.controller_name = controller_name\n \n self.joints = list()\n self.joint_names = list()\n for name in rospy.get_param(self.joint_dict, dict()).keys():\n self.joints.append(HobbyServo(self, name))\n self.joint_names.append(name)\n\n # parameters: throttle rate and geometry\n self.rate = rospy.get_param('~joint_controller_rate', 10.0)\n self.t_delta = rospy.Duration(1.0/self.rate)\n self.t_next = rospy.Time.now() + self.t_delta\n\n # action server\n self.name = self.controller_name + '/follow_joint_trajectory'\n self.server = actionlib.SimpleActionServer(self.name, FollowJointTrajectoryAction, execute_cb=self.actionCb, auto_start=False)\n\n # good old trajectory\n rospy.Subscriber(self.name+'/command', JointTrajectory, self.commandCb)\n self.executing = False\n\n msg = self.name +': FollowController started'\n rospy.loginfo(msg)\n self.server.start()\n \n self.pub = rospy.Publisher('joint_states', JointState, queue_size=5)\n \n def scaleGripperRadiansToMeters(self, input):\n gripper_width_m = 0.036\n gripper_width_deg = 135.0\n in_closed = -radians(gripper_width_deg)/2\n in_open = radians(gripper_width_deg)/2\n out_closed = gripper_width_m/2\n out_open = 0\n return ((input - in_closed) * (out_open - out_closed) / (in_open - in_closed) + out_closed)\n\n def poll(self):\n if rospy.Time.now() > self.t_next:\n # Read Servo Position\n for joint in self.joints:\n joint.setCurrentFeedback(self.arduino.servo_read(joint.id))\n\n # Write Servo Position\n for joint in self.joints: \n if joint.dirty:\n self.arduino.servo_write(joint.id, joint.desired)\n joint.dirty = False\n msg = joint.name + ': position set - ' + str(joint.desired)\n rospy.logdebug(msg)\n\n msg = JointState()\n msg.header.stamp = rospy.Time.now()\n msg.name = list()\n msg.position = list()\n msg.velocity = list()\n for joint in self.joints:\n # Publish gripper joint as distance, not radian. Mimic position for \"fake\" joint.\n if joint.name == 'left_gripper_joint':\n gripper_distance = self.scaleGripperRadiansToMeters(joint.position)\n msg.name.append(joint.name)\n msg.position.append(gripper_distance)\n msg.velocity.append(joint.velocity)\n msg.name.append('left_gripper_joint_fake')\n msg.position.append(gripper_distance)\n msg.velocity.append(joint.velocity)\n elif joint.name == 'right_gripper_joint':\n gripper_distance = self.scaleGripperRadiansToMeters(joint.position)\n msg.name.append(joint.name)\n msg.position.append(gripper_distance)\n msg.velocity.append(joint.velocity)\n msg.name.append('right_gripper_joint_fake')\n msg.position.append(gripper_distance)\n msg.velocity.append(joint.velocity)\n else:\n msg.name.append(joint.name)\n msg.position.append(joint.position)\n msg.velocity.append(joint.velocity)\n self.pub.publish(msg)\n self.t_next = rospy.Time.now() + self.t_delta\n\n def actionCb(self, goal):\n msg = self.name + ': Action goal recieved.'\n rospy.loginfo(msg)\n traj = goal.trajectory\n\n if set(self.joint_names) != set(traj.joint_names):\n for j in self.joint_names:\n if j not in traj.joint_names:\n msg = 'Trajectory joint: \\n' + str(j) + '\\n does not match action controlled joints: \\n' + str(traj.joint_names)\n rospy.logerr(msg)\n self.server.set_aborted(text=msg)\n msg = 'Extra joints in trajectory'\n rospy.logwarn(msg)\n return\n\n if not traj.points:\n msg = 'Trajectory empy.'\n rospy.logerr(msg)\n self.server.set_aborted(text=msg)\n return\n\n try:\n indexes = [traj.joint_names.index(joint) for joint in self.joint_names]\n except ValueError as val:\n msg = 'Trajectory invalid.'\n rospy.logerr(msg)\n self.server.set_aborted(text=msg)\n return\n\n if self.executeTrajectory(traj): \n self.server.set_succeeded()\n else:\n self.server.set_aborted(text='Execution failed.')\n\n msg = self.name + ': Trajectory execution complete.'\n rospy.loginfo(msg)\n\n def commandCb(self, msg):\n # don't execute if executing an action\n if self.server.is_active():\n msg = self.name+': Received trajectory, but action is active'\n rospy.loginfo(msg)\n return\n self.executing = True\n self.executeTrajectory(msg)\n self.executing = False \n\n def executeTrajectory(self, traj):\n msg = self.name + ': Executing trajectory'\n rospy.loginfo(msg)\n rospy.logdebug(traj)\n # carry out trajectory\n try:\n indexes = [traj.joint_names.index(joint) for joint in self.joint_names]\n except ValueError as val:\n msg = 'Invalid joint in trajectory.'\n rospy.logerr(msg)\n return False\n\n # get starting timestamp, MoveIt uses 0, need to fill in\n start = traj.header.stamp\n if start.secs == 0 and start.nsecs == 0:\n start = rospy.Time.now()\n\n r = rospy.Rate(self.rate)\n position_prev = [ joint.position for joint in self.joints ]\n for point in traj.points:\n # wait until start\n while rospy.Time.now() + rospy.Duration(0.01) < start:\n rospy.sleep(0.01)\n desired = [ point.positions[k] for k in indexes ]\n endtime = start + point.time_from_start\n # run until end\n while rospy.Time.now() + rospy.Duration(0.01) < endtime:\n err = [ (d-c) for d,c in zip(desired,position_prev) ]\n velocity = [ abs(x / (self.rate * (endtime - rospy.Time.now()).to_sec())) for x in err ]\n for i in range(len(self.joints)):\n if err[i] > 0.001 or err[i] < -0.001:\n cmd = err[i] \n top = velocity[i]\n if cmd > top:\n cmd = top\n elif cmd < -top:\n cmd = -top\n position_cmd = position_prev[i] + cmd\n self.joints[i].setControlOutput(position_cmd)\n else:\n velocity[i] = 0\n r.sleep()\n\n return True\n\n def active(self):\n \"\"\" Is controller overriding servo internal control? \"\"\"\n return self.server.is_active() or self.executing\n","sub_path":"ros_arduino_python/src/ros_arduino_python/joint_controller.py","file_name":"joint_controller.py","file_ext":"py","file_size_in_byte":10793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"399693109","text":"import os\nfrom unittest import mock\n\nimport pytest\nfrom kubernetes.client import ApiException\nfrom kubernetes.client import V1Capabilities\nfrom kubernetes.client import V1Container\nfrom kubernetes.client import V1HostPathVolumeSource\nfrom kubernetes.client import V1ObjectMeta\nfrom kubernetes.client import V1Pod\nfrom kubernetes.client import V1PodSpec\nfrom kubernetes.client import V1ResourceRequirements\nfrom kubernetes.client import V1SecurityContext\nfrom kubernetes.client import V1Volume\nfrom kubernetes.client import V1VolumeMount\nfrom pyrsistent import pmap\nfrom pyrsistent import v\n\nfrom task_processing.plugins.kubernetes.kubernetes_pod_executor import KubernetesPodExecutor\nfrom task_processing.plugins.kubernetes.kubernetes_pod_executor import KubernetesTaskMetadata\nfrom task_processing.plugins.kubernetes.kubernetes_pod_executor import KubernetesTaskState\nfrom task_processing.plugins.kubernetes.task_config import KubernetesTaskConfig\nfrom task_processing.plugins.kubernetes.types import PodEvent\n\n\n@pytest.fixture\ndef k8s_executor(mock_Thread):\n with mock.patch(\n \"task_processing.plugins.kubernetes.kube_client.kube_config.load_kube_config\",\n autospec=True\n ), mock.patch(\n \"task_processing.plugins.kubernetes.kube_client.kube_client\",\n autospec=True\n ), mock.patch.dict(os.environ, {\"KUBECONFIG\": \"/this/doesnt/exist.conf\"}):\n executor = KubernetesPodExecutor(namespace=\"task_processing_tests\")\n yield executor\n executor.stop()\n\n\ndef test_run_updates_task_metadata(k8s_executor):\n task_config = KubernetesTaskConfig(\n name=\"name\",\n uuid=\"uuid\",\n image=\"fake_image\",\n command=\"fake_command\"\n )\n k8s_executor.run(task_config=task_config)\n\n assert k8s_executor.task_metadata == pmap(\n {\n task_config.pod_name: KubernetesTaskMetadata(\n task_state_history=v((KubernetesTaskState.TASK_PENDING, mock.ANY)),\n task_config=task_config,\n node_name='',\n task_state=KubernetesTaskState.TASK_PENDING,\n ),\n },\n )\n\n\ndef test_run(k8s_executor):\n task_config = KubernetesTaskConfig(\n name=\"fake_task_name\",\n uuid=\"fake_id\",\n image=\"fake_docker_image\",\n command=\"fake_command\",\n cpus=1,\n memory=1024,\n disk=1024,\n volumes=[{\"host_path\": \"/a\", \"container_path\": \"/b\", \"mode\": \"RO\"}]\n )\n expected_container = V1Container(\n image=task_config.image,\n name=\"main\",\n command=[\"/bin/sh\", \"-c\"],\n args=[task_config.command],\n security_context=V1SecurityContext(\n capabilities=V1Capabilities(drop=list(task_config.cap_drop)),\n ),\n resources=V1ResourceRequirements(\n limits={\n \"cpu\": 1.0,\n \"memory\": \"1024.0Mi\",\n \"ephemeral-storage\": \"1024.0Mi\",\n }\n ),\n env=[],\n volume_mounts=[V1VolumeMount(\n mount_path=\"/b\",\n name=\"host--slash-a\",\n read_only=True,\n )],\n )\n expected_pod = V1Pod(\n metadata=V1ObjectMeta(\n name=task_config.pod_name,\n namespace=\"task_processing_tests\"\n ),\n spec=V1PodSpec(\n restart_policy=task_config.restart_policy,\n containers=[expected_container],\n volumes=[V1Volume(\n host_path=V1HostPathVolumeSource(path=\"/a\"),\n name=\"host--slash-a\",\n )],\n ),\n )\n\n assert k8s_executor.run(task_config) == task_config.pod_name\n assert k8s_executor.kube_client.core.create_namespaced_pod.call_args_list == [\n mock.call(body=expected_pod, namespace='task_processing_tests')\n ]\n\n\ndef test_run_failed_exception(k8s_executor):\n task_config = KubernetesTaskConfig(\n name=\"fake_task_name\",\n uuid=\"fake_id\",\n image=\"fake_docker_image\",\n command=\"fake_command\"\n )\n k8s_executor.kube_client.core.create_namespaced_pod.side_effect = ApiException(\n status=403, reason=\"Fake unauthorized message\")\n assert k8s_executor.run(task_config) is None\n\n\ndef test_process_event_enqueues_task_processing_events_pending_to_running(k8s_executor):\n mock_pod = mock.Mock(spec=V1Pod)\n mock_pod.metadata.name = \"test.1234\"\n mock_pod.status.phase = \"Running\"\n mock_pod.status.host_ip = \"1.2.3.4\"\n mock_event = PodEvent(\n type=\"MODIFIED\",\n object=mock_pod,\n raw_object=mock.Mock(),\n )\n k8s_executor.task_metadata = pmap({\n mock_pod.metadata.name: KubernetesTaskMetadata(\n task_config=mock.Mock(spec=KubernetesTaskConfig),\n task_state=KubernetesTaskState.TASK_PENDING,\n task_state_history=v(),\n )\n })\n\n k8s_executor._process_pod_event(mock_event)\n\n assert k8s_executor.event_queue.qsize() == 1\n # in normal usage this would actually have 2 items, but we're obiviating the inital PENDING\n # state for this test\n assert len(k8s_executor.task_metadata[mock_pod.metadata.name].task_state_history) == 1\n\n\n@pytest.mark.parametrize(\n \"phase\", (\n \"Succeeded\",\n \"Failed\",\n )\n)\ndef test_process_event_enqueues_task_processing_events_running_to_terminal(k8s_executor, phase):\n mock_pod = mock.Mock(spec=V1Pod)\n mock_pod.metadata.name = \"test.1234\"\n mock_pod.status.phase = phase\n mock_pod.status.host_ip = \"1.2.3.4\"\n mock_event = PodEvent(\n type=\"MODIFIED\",\n object=mock_pod,\n raw_object=mock.Mock(),\n )\n k8s_executor.task_metadata = pmap({\n mock_pod.metadata.name: KubernetesTaskMetadata(\n task_config=mock.Mock(spec=KubernetesTaskConfig),\n task_state=KubernetesTaskState.TASK_RUNNING,\n task_state_history=v(),\n )\n })\n\n k8s_executor._process_pod_event(mock_event)\n\n assert k8s_executor.event_queue.qsize() == 1\n assert len(k8s_executor.task_metadata) == 0\n\n\n@pytest.mark.parametrize(\n \"phase,task_state\", (\n (\"Succeeded\", KubernetesTaskState.TASK_FINISHED),\n (\"Failed\", KubernetesTaskState.TASK_FAILED),\n (\"Running\", KubernetesTaskState.TASK_RUNNING),\n (\"Pending\", KubernetesTaskState.TASK_PENDING),\n )\n)\ndef test_process_event_enqueues_task_processing_events_no_state_transition(\n k8s_executor,\n phase,\n task_state,\n):\n mock_pod = mock.Mock(spec=V1Pod)\n mock_pod.metadata.name = \"test.1234\"\n mock_pod.status.phase = phase\n mock_pod.status.host_ip = \"1.2.3.4\"\n mock_event = PodEvent(\n type=\"MODIFIED\",\n object=mock_pod,\n raw_object=mock.Mock(),\n )\n k8s_executor.task_metadata = pmap({\n mock_pod.metadata.name: KubernetesTaskMetadata(\n task_config=mock.Mock(spec=KubernetesTaskConfig),\n task_state=task_state,\n task_state_history=v(),\n )\n })\n\n k8s_executor._process_pod_event(mock_event)\n\n assert k8s_executor.event_queue.qsize() == 0\n assert len(k8s_executor.task_metadata) == 1\n assert k8s_executor.task_metadata[mock_pod.metadata.name].task_state == task_state\n # in reality, this would have some entries, but we're not filling out task_state_history\n # for tests, so checking that the size is 0 is the same as checking that we didn't transition\n # to a new state\n assert len(k8s_executor.task_metadata[mock_pod.metadata.name].task_state_history) == 0\n\n\ndef test_pending_event_processing_loop_processes_remaining_events_after_stop(k8s_executor):\n k8s_executor.pending_events.put(\n PodEvent(\n type=\"ADDED\",\n object=mock.Mock(),\n raw_object=mock.Mock(),\n )\n )\n k8s_executor.stopping = True\n\n with mock.patch.object(\n k8s_executor,\n \"_process_pod_event\",\n autospec=True,\n ) as mock_process_event:\n k8s_executor._pending_event_processing_loop()\n\n mock_process_event.assert_called_once()\n assert k8s_executor.pending_events.qsize() == 0\n\n\ndef test_process_event_enqueues_task_processing_events_deleted(\n k8s_executor,\n):\n mock_pod = mock.Mock(spec=V1Pod)\n mock_pod.metadata.name = \"test.1234\"\n mock_pod.status.phase = \"Running\"\n mock_pod.status.host_ip = \"1.2.3.4\"\n mock_event = PodEvent(\n type=\"DELETED\",\n object=mock_pod,\n raw_object=mock.Mock(),\n )\n k8s_executor.task_metadata = pmap({\n mock_pod.metadata.name: KubernetesTaskMetadata(\n task_config=mock.Mock(spec=KubernetesTaskConfig),\n task_state=KubernetesTaskState.TASK_RUNNING,\n task_state_history=v(),\n )\n })\n\n k8s_executor._process_pod_event(mock_event)\n\n assert k8s_executor.event_queue.qsize() == 1\n assert len(k8s_executor.task_metadata) == 0\n","sub_path":"tests/unit/plugins/kubernetes/kubernetes_pod_executor_test.py","file_name":"kubernetes_pod_executor_test.py","file_ext":"py","file_size_in_byte":8786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"168844144","text":"# multithreaded/multiprocessing disk scanner experiment\n\nfrom __future__ import print_function\n\nimport argparse\nimport logging\nimport os\nimport sys\nimport Queue\nimport threading\nimport time\n\nN = 1000\nQ = 4\n\nlogging.basicConfig(level=logging.DEBUG,\n format='[%(levelname)s] (%(threadName)-10s) %(message)s',\n )\n\n# -----------------------------------------------------------------------------------\n\ndef main():\n\tlogging.debug(\"Start\")\n\targs = CommandLine()\n\n\twalkq = Queue.Queue(100)\n\twalk = threading.Thread(name='walker', target=walker, args=(args.path, walkq))\n\twalk.setDaemon(True)\n\twalk.start()\n\n\treadq = []\n\treadthread = []\n\tfor q in range(Q):\n\t\treadq.append(Queue.Queue(100))\n\t\ttid = threading.Thread(name='reader-%d' % q, target=reader, args=(q, readq[q]))\n\t\ttid.setDaemon(True)\n\t\ttid.start()\n\t\treadthread.append(tid)\n\n\tnq = 0\n\twhile True:\n\t\tif walkq.empty():\n\t\t\ttime.sleep(.1)\n\t\t\tcontinue\n\n\t\titem = walkq.get()\n\t\tif item[0] == 'Q':\n\t\t\twalkq.task_done()\n\t\t\tbreak\n\t\tif item[0] == 'F':\n\t\t\tfor file in item[2]:\n\t\t\t\tpath = os.path.join(item[1], file)\n\t\t\t\t#logging.debug(\"Queue %-5d %s\" % (nq, shorten(path)))\n\t\t\t\treadq[nq].put(['R', path])\n\t\t\t\tnq += 1\n\t\t\t\tif nq == 4:\n\t\t\t\t\tnq = 0\n\t\t\twalkq.task_done()\n\n\tlogging.debug(\"Finished scanning\")\n\n\tfor q in range(Q):\n\t\treadq[q].put(['Q', 0])\n\tfor q in range(Q):\n\t\treadthread[q].join()\n\n# -----------------------------------------------------------------------------------\n\ndef shorten(s):\n\tif len(s) < 40:\n\t\treturn s.encode('utf-8')\n\tshorts = s[0:15] + '..' + s[-23:]\n\treturn shorts.encode('utf-8')\n\n# -----------------------------------------------------------------------------------\n\ndef CommandLine():\n\tparser = argparse.ArgumentParser(fromfile_prefix_chars='@')\n\tparser.add_argument('path', nargs='?', type=unicode, default=u\".\", help='local path to scan')\n\targs = parser.parse_args()\n\targs.path = os.path.realpath(args.path)\n\treturn args\n\n# -----------------------------------------------------------------------------------\n\ndef walker(path, walkq):\n\tlogging.debug(\"Start\")\n\tfor origin, dirs, files in os.walk(path):\n\t\tfor i in xrange(0, len(dirs), N):\n\t\t\twalkq.put(['D', origin, dirs[i:i+N]])\n\t\tfor i in xrange(0, len(files), N):\n\t\t\twalkq.put(['F', origin, files[i:i+N]])\n\twalkq.put(['Q', 0, []])\n\tlogging.debug(\"Finished\")\n\n# -----------------------------------------------------------------------------------\n\ndef reader(q, readq):\n\tlogging.debug(\"Start\")\n\tBLOCKSIZE = 16*256*256\n\twhile True:\n\t\titem = readq.get()\n\t\tif item[0] == 'Q':\n\t\t\treadq.task_done()\n\t\t\tbreak\n\t\tif item[0] == 'R':\n\t\t\tbytes = 0\n\t\t\tshortname = shorten(item[1])\n\t\t\t#logging.debug(\"Reading %s\" % shortname)\n\t\t\twith open(item[1], 'rb') as f:\n\t\t\t\twhile True:\n\t\t\t\t\tbuf = f.read(BLOCKSIZE)\n\t\t\t\t\tbytes += len(buf)\n\t\t\t\t\tif len(buf)==0:\n\t\t\t\t\t\tbreak;\n\t\t\t#logging.debug(\"Read %-6d %s\" % (bytes, shortname))\n\t\t\treadq.task_done()\n\tlogging.debug(\"Finished\")\n\n# -----------------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n\tstart = time.time()\n\tmain()\n\tend = time.time()\n\tprint(\"elapsed: %.02f\" % (end - start))\n","sub_path":"historical/python/multitest/threadread.py","file_name":"threadread.py","file_ext":"py","file_size_in_byte":3115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"256838656","text":"###\n# Copyright (c) 2017, Jonathan \"gratefu\" Surman\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions, and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions, and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the author of this software nor the name of\n# contributors to this software may be used to endorse or promote products\n# derived from this software without specific prior written consent.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n###\n###\nimport time\nimport datetime\nimport re\nimport urllib.request as urlreq\nimport urllib.parse as urlparse\nimport urllib\nimport supybot.ircdb as ircdb\nimport supybot.schedule as schedule\nimport json\nimport supybot.registry as registry\nimport supybot.conf as conf\nimport supybot.utils as utils\nfrom supybot.commands import *\nimport supybot.plugins as plugins\nimport supybot.ircutils as ircutils\nimport supybot.callbacks as callbacks\nimport supybot.ircmsgs as ircmsgs\ntry:\n from supybot.i18n import PluginInternationalization\n _ = PluginInternationalization('Translate')\nexcept ImportError:\n # Placeholder that allows to run the plugin on a bot\n # without the i18n module\n _ = lambda x: x\n\n# User-Agent field to send when downloading url (some pages require one of firefox, chrome, ie etc.)\n_USER_AGENT = \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0\"\n# Accept-Language field to send when downloading url (this one should be fine, english - USA)\n_ACCEPT_LANGUAGE = \"en-US;q=0.7,en;q=0.3\"\n# time in seconds to keep data in cache\n_CACHE_TIME = 300\n# number of download cache slots\n_CACHE_SLOTS = 50\n# don't cache download if number of characters is greater this one (prevents caching very large pages)\n_CACHE_MAXCHARS = 50000\n# if UTF-8 decoding of downloaded data fails, use this one (west european i think)\n# will cause some garbage/weird letters for non-ascii (>127) characters, but usually is fine\n_FAILSAFE_HTTP_ENCODING = \"ISO-8859-1\"\n# download result: success\nDL_OK = 0\n# download result: error 404: Not Found\nDL_HTTP404 = 1\n# download result: some other http error (ie. 5xx - server failure)\nDL_HTTP_ERROR = 2\n# download result: general network-level error (ie. non-existent url or no route to host)\nDL_NET_ERROR = 3\n# download result: other errors - for example out of memory, system socket failure\nDL_OS_ERROR = 4\n\nclass Translate(callbacks.Plugin):\n \"\"\"Translate text using Yandex\"\"\"\n threaded = True\n\n def __init__(self, irc):\n # set __parent - double _ means that coder really really doesn't it to be accessed out\n # of script. __parent will hold parent class - which is \"callbacks.Plugin\"\n self.__parent = super(Translate, self)\n # call parent's init method - so plugin is initiated properly\n self.__parent.__init__(irc)\n\n # this is list keeping max _CACHE_SLOTS amount of dictionaries (perl's hash tables)\n # of url/cache expiration time/page content\n self._download_cache = []\n # narrow_search is dictionary that keeps data of found players if more than one\n # key has form \"network&channel nick!user@host\" - quite messed, eh?\n for i in range(_CACHE_SLOTS):\n self._download_cache.append({\"time\": 0, \"url\": \"\"})\n\n def _get_url(self, url):\n \"\"\"Download file from url\"\"\"\n # headers is dictionary (perl's hash - remember?) that holds fields of HTML request\n # some www servers may be grumpy if no proper headers are sent, they can return error 5xx\n # or even block your ip for some time\n headers = { \"User-Agent\": _USER_AGENT, \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\", \"Accept-Language\": _ACCEPT_LANGUAGE }\n # findall works like perl's /string/g - result of it is list (perl's array) of captured groups\n f = re.findall(\"https?://([^/?]+)\", url)\n # if found - len(f) is number of items in list (also number of characters in string - not here)\n if len(f) > 0:\n # if captured group is not empty (i don't know why i did it.. (X+) will always be something\n if len(f[0]) > 0:\n # set \"Host\" item of dictionary \"headers\"\n headers[\"Host\"] = f[0]\n # create url Request object (url + headers) - second parameter (here: None) would be data\n # to send with POST method (ie. image upload or FORM Submit data)\n # urlreq is \"nickname\" for full name - urllib.request\n # (see \"import urllib.request as urlreq\")\n req = urlreq.Request(url, None, headers)\n try:\n # try - because opening url may raise an exception - this is perfectly normal in python!\n urlobj = urlreq.urlopen(req)\n except urllib.error.HTTPError as e:\n # if exception of type urllib.error.HTTPError happened, store it in \"e\" and process\n # e.code is code of HTTP result (404 is famous Document not found)\n if e.code == 404:\n # return tuple (unmodifiable - proper word is \"immutable\" list)\n # first item is error code, second is page content - here empty (None)\n return (DL_HTTP404, None)\n else:\n # other HTTP error than 404 - for example 500: Server failure.\n return (DL_HTTP_ERROR, None)\n except urllib.error.URLError as e:\n # handle URLError - for example bad hostname - like www.example.commmm\n return (DL_NET_ERROR, None)\n except OSError as e:\n # all other errors (to be precise - exceptions)\n return (DL_OS_ERROR, None)\n else:\n # else block of try is executed when there were no exceptions\n # read data from returned url object\n data = urlobj.read()\n try:\n # data is \"bytes\" type (python raw data type, array of bytes, nothing similar in perl)\n # bytes need to be decoded into string - try to use most common - UTF-8\n # in a perfect world, we should read it from url object or page header, but.. :P\n content = data.decode(\"UTF-8\")\n except:\n # if decoding failed (data is not utf - for example, contains byte 255 - illegal in utf8 - decode it with fallback predefined charset ( ISO-8859-1 is western europe, and this will never\n # fail to decode, but some weird chars may appear)\n content = data.decode(self._FAILSAFE_HTTP_ENCODING)\n # return tuple - you should already know what tuple is - of error code DL_OK - no error, and string which is page content\n return (DL_OK, content)\n\n def _download(self, url, queries=None, nocache=False):\n \"\"\"Downloads data from url, retrieving it from cache if possible.\n Returns tuple (_DL_*, data).\n queries is dictionary of queries to append.\"\"\"\n # it's in bad style to modify received arguments content, so assign to new variable\n fullurl = url\n # TODO: order of queries may vary, so technically same url appears as different one\n # \"queries\" is dictionary of pairs \"name\": \"value\"\n # ie. https://www.example.com?name=value\n # if not None (some queries were given) construct query string from it\n if queries is not None:\n # add question mark and query string\n fullurl = fullurl + \"?\" + urlparse.urlencode(queries)\n # if nocache is False (default), try to see if data is cached (if True, always download)\n # use nocache=True if you always want \"fresh\" content\n if not nocache:\n # i = 0 to _CACHE_SLOTS - 1 (remember how \"range\" works ?)\n for i in range(_CACHE_SLOTS):\n # if _download_cache[i] (which is dictionary) value of key \"url\" is our url\n # and cache didn't expired...\n if self._download_cache[i][\"url\"] == fullurl and self._download_cache[i][\"time\"] > time.time():\n # refresh cache - set it again to _CACHE_TIME seconds from now (time.time())\n self._download_cache[i][\"time\"] = time.time() + _CACHE_TIME\n # return OK code and \"content\" value, which is cached page content\n return (DL_OK, self._download_cache[i][\"content\"])\n\n # in other cases (either nocache is True, or cache wasn't found) download page\n result, content = self._get_url(fullurl)\n # if OK, and page content is no more than _CACHE_MAXCHARS (so we don't cache crazy\n # 200 MB page)\n if result == DL_OK and len(content) <= _CACHE_MAXCHARS:\n # this is a bit complex routine, the purpose is to find expired cache, and if none is\n # expired, find oldest cache\n # \"expired\" will be set to cache item number in cache list, if expired cache was found\n expired = -1\n # minvalue stores smallest time to expire\n minvalue = 1000000\n # minpos stores smallest expiration time position in cache list\n minpos = -1\n # i = 0 .. _CACHE_SLOTS - 1 (entire array)\n for i in range(_CACHE_SLOTS):\n # get timestamp (time when cache is considered expired)\n stamp = self._download_cache[i][\"time\"]\n # if expired..\n if stamp > time.time():\n # we found expired item, store index in \"expired\" and exit loop\n expired = i\n break\n # else, if not expired, calculate seconds left to expire\n delta = stamp - time.time()\n # if delta is lower than minvalue, we've found new smallest value\n if delta < minvalue:\n # so store it's value in \"minvalue\" and position in \"minpos\"\n minvalue = delta\n minpos = i\n # loop ended, we either found expired item (expired will be item number instead of -1)\n if expired >= 0:\n idx = expired\n else:\n # or none was expired, so we get \"oldest\" item (smallest expiration time)\n # (we could also call .sort method with custom key function on array - advanced)\n # it would look like this: _download_cache.sort(key=lambda x: x[\"time\"]),\n # see (1) at end of file for explanation\n idx = minpos\n # nevertheless, we have weakest entry now, so use it\n # store url, expiration timestamp and page content\n self._download_cache[idx][\"url\"] = fullurl\n self._download_cache[idx][\"time\"] = time.time() + _CACHE_TIME\n self._download_cache[idx][\"content\"] = content\n # finally, return tuple (result, page content / None)\n return (result, content)\n\n def translate(self, irc, msg, args, lang, input):\n \"\"\" \n Translates text using Yandex\n \"\"\"\n\n languages = [\"az-ru\", \"be-bg\", \"be-cs\", \"be-de\", \"be-en\", \"be-es\", \"be-fr\", \"be-it\", \"be-pl\", \"be-ro\", \"be-ru\", \"be-sr\",\n \"be-tr\", \"bg-be\", \"bg-ru\", \"bg-uk\", \"ca-en\", \"ca-ru\", \"cs-be\", \"cs-en\", \"cs-ru\", \"cs-uk\", \"da-en\", \"da-ru\", \"de-be\",\n \"de-en\", \"de-es\", \"de-fr\", \"de-it\", \"de-ru\", \"de-tr\", \"de-uk\", \"el-en\", \"el-ru\", \"en-be\", \"en-ca\", \"en-cs\", \"en-da\",\n \"en-de\", \"en-el\", \"en-es\", \"en-et\", \"en-fi\", \"en-fr\", \"en-hu\", \"en-it\", \"en-lt\", \"en-lv\", \"en-mk\", \"en-nl\", \"en-no\",\n \"en-pt\", \"en-ru\", \"en-sk\", \"en-sl\", \"en-sq\", \"en-sv\", \"en-tr\", \"en-uk\", \"es-be\", \"es-de\", \"es-en\", \"es-ru\", \"es-uk\",\n \"et-en\", \"et-ru\", \"fi-en\", \"fi-ru\", \"fr-be\", \"fr-de\", \"fr-en\", \"fr-ru\", \"fr-uk\", \"hr-ru\", \"hu-en\", \"hu-ru\", \"hy-ru\",\n \"it-be\", \"it-de\", \"it-en\", \"it-ru\", \"it-uk\", \"lt-en\", \"lt-ru\", \"lv-en\", \"lv-ru\", \"mk-en\", \"mk-ru\", \"nl-en\", \"nl-ru\",\n \"no-en\", \"no-ru\", \"pl-be\", \"pl-ru\", \"pl-uk\", \"pt-en\", \"pt-ru\", \"ro-be\", \"ro-ru\", \"ro-uk\", \"ru-az\", \"ru-be\", \"ru-bg\",\n \"ru-ca\", \"ru-cs\", \"ru-da\", \"ru-de\", \"ru-el\", \"ru-en\", \"ru-es\", \"ru-et\", \"ru-fi\", \"ru-fr\", \"ru-hr\", \"ru-hu\", \"ru-hy\",\n \"ru-it\", \"ru-lt\", \"ru-lv\", \"ru-mk\", \"ru-nl\", \"ru-no\", \"ru-pl\", \"ru-pt\", \"ru-ro\", \"ru-sk\", \"ru-sl\", \"ru-sq\", \"ru-sr\",\n \"ru-sv\", \"ru-tr\", \"ru-uk\", \"sk-en\", \"sk-ru\", \"sl-en\", \"sl-ru\", \"sq-en\", \"sq-ru\", \"sr-be\", \"sr-ru\", \"sr-uk\", \"sv-en\",\n \"sv-ru\", \"tr-be\", \"tr-de\", \"tr-en\", \"tr-ru\", \"tr-uk\", \"uk-bg\", \"uk-cs\", \"uk-de\", \"uk-en\", \"uk-es\", \"uk-fr\", \"uk-it\",\n \"uk-pl\", \"uk-ro\", \"uk-ru\", \"uk-sr\", \"uk-tr\", \"en-pl\"]\n langslist = \"{}\".format(', '.join(languages))\n def_lang = self.registryValue(\"lang_default\")\n key = self.registryValue(\"yandexkey\")\n\n if lang in \"--languages\":\n irc.reply(\"\\x02Support Translations\\x02: {}\".format(langslist))\n elif lang in languages:\n input = urllib.parse.quote(input)\n url = \"https://translate.yandex.net/api/v1.5/tr.json/translate?key={}&text={}&lang={}\".format(key, input, lang)\n result, content = self._download(url)\n content_json = json.loads(content)\n irc.reply(\"\\x02Translate\\x02: {}\".format(content_json[\"text\"][0]))\n elif def_lang in languages and lang not in languages:\n input = urllib.parse.quote(input)\n url = \"https://translate.yandex.net/api/v1.5/tr.json/translate?key={}&text={}&lang={}\".format(key, input, def_lang)\n result, content = self._download(url)\n content_json = json.loads(content)\n irc.reply(\"\\x02Translate\\x02: {}\".format(content_json[\"text\"][0]))\n else:\n lang = lang.upper()\n supybot = registry.Group()\n supybot.setName('supybot')\n trigger = str(conf.supybot.reply.whenAddressedBy.chars())\n irc.reply(\"\\x02ERROR\\x02: {} Translation Not Found - Use {}translate --languages to get a full list.\".format(lang, trigger))\n\n t = wrap(translate, (['somethingWithoutSpaces', optional('text')]))\n translate = wrap(translate, (['somethingWithoutSpaces', optional('text')]))\n\nClass = Translate\n\n\n# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:\n","sub_path":"Translate/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":15276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"160609630","text":"import hashlib, sys\n\nfrom charm.toolbox.pairinggroup import PairingGroup,ZR,G1,G2,GT,pair\n\nfrom charm.toolbox.enum import Enum\nfrom charm.toolbox.secretutil import SecretUtil\nfrom charm.toolbox.secretshare import SecretShare\nfrom charm.core.math import pairing\nfrom charm.toolbox.iterate import dotprod2\nfrom charm.core.math.pairing import hashPair as DeriveKey\nfrom charm.core.engine.util import objectToBytes, bytesToObject\n#from charm.toolbox.symcrypto import AuthenticatedCryptoAbstraction\nfrom charm.toolbox.conversion import Conversion\nfrom charm.toolbox.bitstring import Bytes\n#import hashlib\n\ngroupObjBuiltInFuncs = None\nutilBuiltInFuncs = None\nshareBuiltInFuncs = None\n\nlistIndexNoOfN_StrToId = 9\nlistIndexNoOfl_StrToId = 10\n\nMNT160 = \"SS512\"\n\ndef isList(object):\n objectTypeName = None\n\n try:\n objectTypeName = type(object).__name__\n except:\n sys.exit(\"builtInFuncs.py: could not obtain type/name of object passed in to isList.\")\n\n if (objectTypeName == 'list'):\n return 1\n\n return 0\n\ndef objectOut(group, d):\n\tgetUserGlobals()\n\ts = \"\"\n\tkeys = d.keys()\n\tfor i in keys:\n\t\tif type(d[i]) == pairing:\n\t\t\ts += str(i) + \"=\" + group.serialize(d[i]).decode() + \"\\n\"\n\t\telse:\n\t\t\ts += str(i) + \"=\" + d[i].decode()\n\treturn s\n\ndef writeToFile(name, s):\n\tgetUserGlobals()\n\tfd = open(name, 'w')\n\tfd.write(s)\n\tfd.close()\n\ndef createPolicy(policy_str):\n\tgetUserGlobals()\n\treturn utilBuiltInFuncs.createPolicy(policy_str)\n\ndef getAttributeList(policy):\n\tgetUserGlobals()\n\treturn utilBuiltInFuncs.getAttributeList(policy)\n\ndef calculateSharesDict(s, policy):\n\tgetUserGlobals()\n\treturn utilBuiltInFuncs.calculateSharesDict(s, policy)\n\ndef calculateSharesList(s, policy):\n\tgetUserGlobals()\n\treturn utilBuiltInFuncs.calculateSharesList(s, policy)\n\ndef prune(policy, S):\n\tgetUserGlobals()\n\treturn utilBuiltInFuncs.prune(policy, S)\n\ndef getCoefficients(policy):\n\tgetUserGlobals()\n\treturn utilBuiltInFuncs.getCoefficients(policy)\n\ndef recoverCoefficientsDict(inputDict):\n\tgetUserGlobals()\n\t#print(\"it got here\")\n\treturn shareBuiltInFuncs.recoverCoefficientsDict(inputDict)\n\ndef genShares(mk0, dOver, n, q, wHash):\n\tgetUserGlobals()\n\treturn shareBuiltInFuncs.genShares(mk0, dOver, n, q, wHash)\n\ndef intersection_subset(w, CT0, d):\n\tgetUserGlobals()\n\treturn shareBuiltInFuncs.intersection_subset(w, CT0, d)\n\ndef sha1(message):\n\tgetUserGlobals()\n\thashObj = hashlib.new('sha1') \n\th = hashObj.copy()\n\th.update(bytes(message, 'utf-8'))\n\treturn Bytes(h.digest())\n\ndef strToId(pk, strID):\n\tgetUserGlobals()\n\thash = sha1(strID)\n\tval = Conversion.OS2IP(hash)\n\tbstr = bin(val)[2:]\n\n\tv=[]\n\n\tfor i in range(pk[listIndexNoOfN_StrToId]):\n\t\tbinsubstr = bstr[pk[listIndexNoOfl_StrToId]*i : pk[listIndexNoOfl_StrToId]*(i+1)]\n\t\tprint(binsubstr)\n\t\tintval = int(binsubstr, 2)\n\t\tintelement = groupObjBuiltInFuncs.init(ZR, intval)\n\t\tv.append(intelement)\n\n\treturn v\n\ndef getUserGlobals():\n\tglobal groupObjBuiltInFuncs, utilBuiltInFuncs, shareBuiltInFuncs\n\n\tif (groupObjBuiltInFuncs == None):\n\t\tgroupObjBuiltInFuncs = PairingGroup(MNT160)\n\n\tif (utilBuiltInFuncs == None):\n\t\tutilBuiltInFuncs = SecretUtil(groupObjBuiltInFuncs, verbose=False)\n\n\tif (shareBuiltInFuncs == None):\n\t\tshareBuiltInFuncs = SecretShare(groupObjBuiltInFuncs, False)\n","sub_path":"auto_outsrc/parser/SCRATCH/builtInFuncs.py","file_name":"builtInFuncs.py","file_ext":"py","file_size_in_byte":3235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"37043294","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 15 18:46:14 2017\n\n@author: mohamed\n\"\"\"\n\nfrom sqlalchemy import Column, Integer, String\n\nfrom pydatabase.table.tableobject import TableObject\n\n\nclass Month(TableObject,TableObject.Base):\n\t\n\tmonth_number = Column(Integer)\n\tyear = Column(Integer)\n\tmonth_name = Column(String)\n\tmonth_names = {1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'Jul',8:'Aug',9:'Sep',10:'Oct',11:'Nov',12:'Dec'}\n\tmonth_nameToNumber = {'Jan':1,'Feb':2,'Mar':3,'Apr':4,'May':5,'Jun':6,'Jul':7,'Aug':8,'Sep':9,'Oct':10,'Nov':11,'Dec':12}\n\tmonth_days = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}\n\n\t@classmethod\n\tdef createMonthFromYearAndMonth(cls,year,month_number):\n\t\tmonth = Month()\n\t\tmonth.year = year\n\t\tmonth.month_number = month_number\n\t\tmonth.month_name = cls.month_names[month_number]\n\t\tmonth.id = month.calcId()\n\t\treturn month\n\t@classmethod\n\tdef populateDimension(cls):\n\t\tstartYear = 2010\n\t\tendYear = 2030\n\t\tfor y in range(startYear,endYear+1):\n\t\t\tfor m in range(1,13):\n\t\t\t\tmonth = cls.createMonthFromYearAndMonth(y,m)\n\t\t\t\tmonth.insert()\n\tdef calcId(self):\n\t\treturn int(str(self.year) + str(self.month_number).zfill(2))\n\t@classmethod\n\tdef convertDatetimeToId(cls, timestamp):\n\t\treturn cls.createFromDateTime(timestamp).id\n\n\t@classmethod\n\tdef createFromId(cls, id):\n\t\ts = str(id)\n\t\tm = Month()\n\t\tm.id = id\n\t\tm.year = int(s[0:4])\n\t\tm.month_number = int(s[4:6])\n\t\treturn m\n\t@classmethod\n\tdef createFromDateTime(cls,timestamp):\n\t\tm = Month()\n\t\tm.year = timestamp.year\n\t\tm.month_number = timestamp.month\n\t\tm.id = m.calcId()\n\t\treturn m\n\n\tdef getNumberOfDays(self):\n\t\tif self.month_number==2 and (self.year % 4)==0:\n\t\t\treturn 29\n\t\treturn self.month_days[self.month_number]\n\tdef getPreviousMonth(self):\n\t\tpm = Month()\n\t\tif self.month_number==1:\n\t\t\tpm.year = self.year-1\n\t\t\tpm.month_number = 12\n\t\telse:\n\t\t\tpm.year = self.year\n\t\t\tpm.month_number = self.month_number-1\n\t\tpm.id = pm.calcId()\n\t\treturn pm\n\n\t@classmethod\n\tdef fillDF(cls,df, fromMonth, toMonth, month_field, values):\n\t\tcurrentMonth = fromMonth\n\t\twhile currentMonth.monthDiff(toMonth) <= 0:\n\t\t\ttemp = df[df[month_field] == currentMonth.id]\n\t\t\tif temp.empty:\n\t\t\t\tvaluesToInsert = [currentMonth.id]\n\t\t\t\tvaluesToInsert.extend(values)\n\t\t\t\tdf.loc[-1] = valuesToInsert\n\t\t\t\tdf.index = df.index + 1\n\t\t\tcurrentMonth = currentMonth.getNextMonth()\n\t\tdf.sort_values(month_field, inplace=True)\n\t\treturn df\n\n\tdef getNextMonth(self):\n\t\treturn self.getFutureMonth(1)\n\n\tdef getFutureMonth(self,increment):\n\t\tnm = Month()\n\t\tif self.month_number+increment > 12:\n\t\t\tnm.year = self.year + 1\n\t\t\tnm.month_number = self.month_number+increment-12\n\t\telse:\n\t\t\tnm.year = self.year\n\t\t\tnm.month_number = self.month_number + increment\n\t\tnm.id = nm.calcId()\n\t\treturn nm\n\t#return +ve if month is earlier month\n\tdef monthDiff(self,month):\n\t\tyearDiff = self.year - month.year\n\t\td = yearDiff*12\n\t\tif self.month_number>=month.month_number:\n\t\t\td += self.month_number - month.month_number\n\t\telse:\n\t\t\td -= month.month_number - self.month_number\n\t\treturn d","sub_path":"pydatabase/dimension/month.py","file_name":"month.py","file_ext":"py","file_size_in_byte":3040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"37474692","text":"#!/usr/bin/env python\nfrom __future__ import print_function\n#import tkinter as tk\nfrom tkinter import ttk\n#from sqlalchemy.sql.expression import column\nimport os\n\n\n#import PyPDF2\n\n\n#f = open(os.path.expanduser(\"~/Life/LOL.pdf\"), 'rb')\n#read_pdf = PyPDF2.PdfFileReader(f)\n#print(f)\n\n\npath = './Codeforces/'\n\ncontests = []\nfor entry_name in os.listdir(path):\n entry_path = os.path.join(path, entry_name)\n if os.path.isdir(entry_path):\n contests.append(entry_name)\n#contests.sort()\nprint(contests)\n\n#files = os.listdir(path)\n#contests = []\n#for name in files:\n# print(name)\n# contests.append(name)\n#print(contests)\n\n\n\n\n\n\n\n\n\n\"\"\"import wx\nimport wx.lib.sized_controls as sc\n\nfrom wx.lib.pdfviewer import pdfViewer, pdfButtonPanel\n\nclass PDFViewer(sc.SizedFrame):\n def __init__(self, parent, **kwds):\n super(PDFViewer, self).__init__(parent, **kwds)\n\n paneCont = self.GetContentsPane()\n self.buttonpanel = pdfButtonPanel(paneCont, wx.ID_ANY,\n wx.DefaultPosition, wx.DefaultSize, 0)\n self.buttonpanel.SetSizerProps(expand=True)\n self.viewer = pdfViewer(paneCont, wx.ID_ANY, wx.DefaultPosition,\n wx.DefaultSize,\n wx.HSCROLL|wx.VSCROLL|wx.SUNKEN_BORDER)\n\n self.viewer.SetSizerProps(expand=True, proportion=1)\n\n # introduce buttonpanel and viewer to each other\n self.buttonpanel.viewer = self.viewer\n self.viewer.buttonpanel = self.buttonpanel\n\n\nif __name__ == '__main__':\n import wx.lib.mixins.inspection as WIT\n app = WIT.InspectableApp(redirect=False)\n\n pdfV = PDFViewer(None, size=(800, 600))\n pdfV.viewer.LoadFile(r'LOL.pdf')\n pdfV.Show()\n\n app.MainLoop()\n\"\"\"\n\n\n\n\n\n\n\n\n\n\n\nfrom tkinter import *\nwindow = Tk()\nwindow.title(\"Grinder\")\nwindow.geometry('600x500')\nlbl = Label(window, text=\"CodeForces Grinder\", font=(\"Arial Bold\", 20))\n\n\ncomboExample = ttk.Combobox(window, values=contests, width=64)\n#pprint(dict(comboExample))\ncomboExample.grid(column=0, row=3)\ncomboExample.current(0)\ncomboExample2 = ttk.Combobox(window, values=[\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\"], width=64)\n#pprint(dict(comboExample))\ncomboExample2.grid(column=0, row=4)\ncomboExample2.current(0)\n\n\n\nlbl.grid(column=0, row=0)\n#txt = Entry(window,width=10)\n#txt.grid(column=0, row=3)\ndef clicked():\n #import os\n #f = open(os.path.expanduser(\"~/Life/deeplearningbook.pdf\"))\n import subprocess\n #subprocess.run([\"ls\", \"-l\"])\n happy = comboExample.get()\n filen = re.split(\"#| \", happy)\n for x in range(len(filen)):\n if len(filen[x]) == 0:\n filen[x] = \"\\#\"\n else:\n filen[x] = chr(92) + filen[x]\n #filen[x] = filen[x][1:len(filen[x])]\n\n #print (filen)\n #for x in range(len(happy)):\n # if happy[x] == ' ' or happy[x] == '#':\n #beginn = happy[0:x]\n #end = happy[x:len(happy)]\n #happy = beginn+ \" \" + end\n #x += 1\n\n num = comboExample2.get()\n\n\n #print(happy)\n #print(\"fjdlsfjasfs\")\n #file = 'open ~/LIfe/Codeforces/A\\ B/A.pdf'\n #subprocess.call('\"open ~/LIfe/Codeforces/101\\\\:\\\\ Codeforces\\\\ Beta\\\\ Round\\\\ #79\\\\ \\\\(Div.\\\\ 1\\ Only\\\\)/A.pdf\"')\n #os.system('\"' + file + '\"')\n\n\n import os\n\n path = './Codeforces'\n\n\n\n files = os.listdir(path)\n print(comboExample.current())\n #for i in range(100):\n # print(files[i])\n\n\n\n #file = \"/Users/jefferyfan/LIfe/Codeforces/14:\\ Codeforces\\ Beta\\ Round\\ \\#14\\ \\(Div.\\ 2\\)/A.pdf\"\n\n #os.system(\"'open /Users/jefferyfan/LIfe/Codeforces/14:\\ Codeforces\\ Beta\\ Round\\ \\#14\\ \\(Div.\\ 2\\)/A.pdf\")\n #os.system('\"' + cmd + '\"')\n\n task = [\"open\", \"./Codeforces/\" + files[comboExample.current()] + \"/\" + chr(comboExample2.current() + 65) + \".pdf\"]\n subprocess.check_call(task)\n\n #os.system(cmd)\n\n #os.system('ls ./Codeforces/')\n\n #open(os.path.expanduser(\"~/Life/deeplearningbook.pdf\"))\n\n # print the number of pages in pdf file\n #print(fileReader.numPages)\n\nbtn = Button(window, text=\"Enter\", command=clicked)\nbtn.grid(column=0, row=5)\nwindow.mainloop()","sub_path":"LIfe/LOL.py","file_name":"LOL.py","file_ext":"py","file_size_in_byte":4142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"316317423","text":"T = int(input())\nf = open(\"pancake.w\", \"w\")\n\ndef print_res(i, res):\n f.write(\"Case #\" + str(i+1) + \": \" + str(res) + \"\\n\")\n\nfor i in range(T):\n pancakes = raw_input()\n res = 0\n see_blank = False\n saw_smiley = False\n for p in pancakes:\n if p == '+':\n if see_blank:\n see_blank = False\n res += 1\n if saw_smiley:\n res += 1\n saw_smiley = True\n else:\n see_blank = True\n if see_blank:\n see_blank = False\n res += 1\n if saw_smiley:\n res += 1 \n print_res(i, res)\n\nf.close()\n","sub_path":"codes/CodeJamCrawler/16_0_2/louislai/pancake.py","file_name":"pancake.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"542965191","text":"import mysql.connector as mysqlcon\n\n#Connexion à notre serveur sql et création de notre objet connecteur :\nbdd = mysqlcon.connect(port=8081,\n host='localhost',\n user= 'root',\n password= 'root')\n\n#Création de notre objet curseur sql :\nmycursor = bdd.cursor()\n\n#Création de notre database :\nmycursor.execute(\"CREATE DATABASE Binomotron\")\n\n#Connexion à notre db nouvellement crée :\nbdd.config(database = 'Binomotron')\nbdd.reconnect()\n\n#Régénération du curseur sur la nouvelle connexion :\nmycursor = bdd.cursor()\n\n#Création de notre table d'apprenants :\nmycursor.execute(\"CREATE TABLE apprenants (id_apprenant INT(11) PRIMARY KEY AUTO_INCREMENT, nom VARCHAR(50), prenom VARCHAR(50), photo VARCHAR(50))\")\n\n\n#Insertion de tout le monde dans la table :\nmycursor.execute(\"INSERT INTO apprenants (nom, prenom, photo)\\\n VALUES \\\n ('Bonneau', 'Amaury', NULL),\\\n ('Pertron', 'Aude ', NULL),\\\n ('Le Berre', 'Baptiste', NULL),\\\n ('Le Goff', 'Baptiste', NULL),\\\n ('Guillen', 'Celine', NULL),\\\n ('Karfaoui', 'Christelle', NULL),\\\n ('Mbarga Mvogo', 'Christian', NULL),\\\n ('Cloatre', 'Erwan', NULL),\\\n ('Moulard', 'Eva', NULL),\\\n ('Verpoest', 'Guillaume', NULL),\\\n ('Ibanni', 'Jamal', NULL),\\\n ('Le Joncour', 'Jérémy', NULL),\\\n ('Furiga', 'Julien', NULL),\\\n ('Maintier', 'Ludivine', NULL),\\\n ('Bokalli', 'Luigi', NULL),\\\n ('Le Moal', 'Patricia', NULL),\\\n ('Sabia', 'Paul', NULL),\\\n ('Hergoualc''h', 'Pereg', NULL),\\\n ('Rioual', 'Ronan', NULL),\\\n ('Chaigneau', 'Thomas', NULL);\")\nbdd.commit()\n\n#Création de notre table de groupes :\nmycursor.execute(\"CREATE TABLE groupes (id_groupe INT(11) PRIMARY KEY AUTO_INCREMENT, libelle VARCHAR (50));\")\n\n#Création de notre table de projets :\nmycursor.execute(\"CREATE TABLE projets (id_projet INT(11) PRIMARY KEY AUTO_INCREMENT, libelle VARCHAR (50), date_debut DATE, date_fin DATE);\")\n\n#Création de notre table intermédaire qui relie toutes les autres :\nmycursor.execute(\"CREATE TABLE apprenants_groupes (\\\n id_apprenant int(11),\\\n id_groupe int(11),\\\n id_projet int(11),\\\n FOREIGN KEY (id_apprenant) REFERENCES apprenants(id_apprenant),\\\n FOREIGN KEY (id_groupe) REFERENCES groupes(id_groupe),\\\n FOREIGN KEY (id_projet) REFERENCES projets(id_projet)\\\n );\")\n","sub_path":"creation_db_binomotron.py","file_name":"creation_db_binomotron.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"498863290","text":"from datetime import datetime\nimport time\nimport sys, csv\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nimport RPi.GPIO as GPIO\nimport numpy as np\n\nMAX_DURATION = 3\n\nNUM_ATTEMPTS = 2\nTRANSMIT_PIN = 17\n\nbar_width = 0.00020\nblock_break = 0.09316\n\nsm_delay = 0.00034\nmd_delay = 0.00330\nlg_delay = 0.01340\n\ncontrol_measures = [[], []]\n\ndef logTransmission(output, delta_time):\n control_measures[0].append(delta_time)\n control_measures[1].append(output)\n\ndef load_signature(path):\n x = []\n y = []\n with open(path, newline='') as f:\n reader = csv.reader(f, delimiter=',')\n try:\n for i, row in enumerate(reader):\n if i == 0: continue # skip header\n float_x = float(row[0])\n int_y = int(row[1])\n\n x.append(float_x)\n y.append(int_y)\n\n print('File loaded.')\n return [x,y]\n except csv.Error as e:\n sys.exit('file {}, line {}: {}'.format(path, reader.line_num, e))\n\n\ndef transmit_code(in_signal = None):\n\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(TRANSMIT_PIN, GPIO.OUT)\n\n arg = ''\n if in_signal:\n arg = '{}/'.format(in_signal)\n\n fpath = '../generated/{}signature.csv'.format(arg)\n\n print(\"Transmitting signature:\", fpath)\n\n code = load_signature(fpath)\n \n start_time = datetime.now()\n\n for t in range(NUM_ATTEMPTS):\n print(\"Transmitting signal (attempt {})\".format(t+1))\n\n delta_time = datetime.now() - start_time\n\n for i in range(len(code[0])):\n seconds = int(code[0][i])\n microseconds = (code[0][i] * 1000000) % 1000000\n \n if code[1][i] == 1:\n GPIO.output(TRANSMIT_PIN, 1)\n elif code[1][i] == 0:\n GPIO.output(TRANSMIT_PIN, 0)\n else:\n print(\"Found neither 1 or 2. Error?\")\n continue\n\n time.sleep(code[0][i])\n \n GPIO.cleanup()\n\nif __name__ == '__main__':\n\n try:\n if sys.argv[1:]:\n for arg in sys.argv[1:]:\n print(\"ARG:\", arg)\n transmit_code(arg)\n time.sleep(0.5)\n else:\n transmit_code()\n\n print(\"Success\")\n sys.stdout.flush()\n \n except:\n e = sys.exc_info()[0]\n print(e)\n sys.stdout.flush()\n \n # for arg in sys.argv[1:]:\n # exec('transmit_code(' + str(arg) + ')')\n\n # print(\"** Plotting results **\")\n # for i in range(len(control_measures[0])):\n # control_measures[0][i] = control_measures[0][i].seconds + control_measures[0][i].microseconds/1000000.0\n \n # plt.plot(control_measures[0], control_measures[1], 'go--', linewidth=bar_width)\n # plt.axis([0, MAX_DURATION, -1, 2])\n \n # plt.show()","sub_path":"backend/src/radiocom/src/3_transmit-signal.py","file_name":"3_transmit-signal.py","file_ext":"py","file_size_in_byte":2866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"19009494","text":"import pytest\nimport time\nfrom unittestzero import Assert\n\n\n@pytest.mark.nondestructive\n@pytest.mark.usefixtures(\"maximized\")\nclass TestChargeback():\n\n def test_chargeback(self, mozwebqa, home_page_logged_in):\n #Add a new Compute Chargeback\n home_pg = home_page_logged_in\n chargeback_pg = home_pg.header.site_navigation_menu(\"Virtual Intelligence\").sub_navigation_menu(\"Chargeback\").click()\n Assert.true(chargeback_pg.is_the_current_page)\n rates_pg = chargeback_pg.click_on_rates()\n compute_pg = rates_pg.click_on_compute()\n add_compute_chargeback_pg = compute_pg.click_on_add_new_chargeback_rate()\n Assert.true(add_compute_chargeback_pg.alloc_cpu_input)\n cancel_add_compute_chargeback = add_compute_chargeback_pg.click_on_cancel()\n \n #Add a new Storage Chargeback\n storage_pg = rates_pg.click_on_storage()\n add_storage_chargeback_pg = storage_pg.click_on_add_new_chargeback_rate()\n Assert.true(add_storage_chargeback_pg.alloc_disk_storage_input)\n cancel_add_storage_chargeback = add_storage_chargeback_pg.click_on_cancel()\n\n #Edit Compute Chargeback\n compute_pg = rates_pg.click_on_compute()\n existing_chargeback = \"Default\"\n selected_chargeback_pg = compute_pg.click_on_existing_chargeback(existing_chargeback)\n #remove_selected_chargeback_pg = selected_chargeback_pg.click_on_remove()\n edit_selected_chargeback_pg = selected_chargeback_pg.click_on_edit()\n Assert.true(edit_selected_chargeback_pg.description_input.get_attribute(\"value\") == \"Default\")\n Assert.true(edit_selected_chargeback_pg.alloc_cpu_input)\n edit_selected_chargeback_pg.click_on_cancel()\n\n\n #Edit Storage Chargeback\n storage_pg = rates_pg.click_on_storage()\n existing_chargeback = \"Default\"\n selected_chargeback_pg = storage_pg.click_on_existing_chargeback(existing_chargeback)\n #remove_selected_chargeback_pg = selected_chargeback_pg.click_on_remove()\n edit_selected_chargeback_pg = selected_chargeback_pg.click_on_edit()\n Assert.true(edit_selected_chargeback_pg.description_input.get_attribute(\"value\") == \"Default\")\n Assert.true(edit_selected_chargeback_pg.alloc_disk_storage_input)\n edit_selected_chargeback_pg.click_on_cancel()\n\n\n","sub_path":"tests/test_chargeback.py","file_name":"test_chargeback.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"96232854","text":"#!/usr/bin/python\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom dellemc_unity_sdk import runner\nfrom dellemc_unity_sdk import supportive_functions\n\nfrom dellemc_unity_sdk import constants\n\nANSIBLE_METADATA = {'metadata_version': '0.1',\n 'status': ['unstable'],\n 'supported_by': 'community'}\n\nparameters_all = {\n \"create\":\n {\n \"srcResourceId\": dict(required=True, type=str),\n \"dstResourceId\": dict(required=True, type=str),\n \"maxTimeOutOfSync\": dict(required=True, type=int),\n \"remoteSystem\": dict(type=object),\n \"srcSPAInterface\": dict(type=object),\n \"srcSPBInterface\": dict(type=object),\n \"dstSPAInterface\": dict(type=object),\n \"dstSPBInterface\": dict(type=object),\n \"autoInitiate\": dict(type=bool),\n \"name\": dict(type=str),\n \"members\": dict(type=list),\n \"hourlySnapReplicationPolicy\": dict(type=object),\n \"dailySnapReplicationPolicy\": dict(type=object),\n \"replicateExistingSnaps\": dict(type=bool)\n },\n \"modify\":\n {\n \"id\": dict(required=True, type=str),\n \"maxTimeOutOfSync\": dict(type=int),\n \"name\": dict(type=str),\n \"srcSPAInterface\": dict(type=object),\n \"srcSPBInterface\": dict(type=object),\n \"dstSPAInterface\": dict(type=object),\n \"dstSPBInterface\": dict(type=object),\n \"hourlySnapReplicationPolicy\": dict(type=object),\n \"dailySnapReplicationPolicy\": dict(type=object)\n },\n \"delete\":\n {\n \"id\": dict(required=True, type=str)\n },\n \"resume\":\n {\n \"id\": dict(required=True, type=str),\n \"srcSPAInterface\": dict(type=object),\n \"srcSPBInterface\": dict(type=object),\n \"dstSPAInterface\": dict(type=object),\n \"dstSPBInterface\": dict(type=object),\n \"forceFullCopy\": dict(type=bool)\n },\n \"pause\":\n {\n \"id\": dict(required=True, type=str)\n },\n \"sync\":\n {\n \"id\": dict(required=True, type=str)\n }\n}\n\ntemplate = {\n constants.REST_OBJECT: \"replicationSession\",\n constants.ACTIONS: {\n \"create\":\n {\n constants.ACTION_TYPE: constants.ActionType.UPDATE,\n constants.PARAMETER_TYPES: parameters_all.get(\"create\")\n },\n \"modify\":\n {\n constants.ACTION_TYPE: constants.ActionType.UPDATE,\n constants.PARAMETER_TYPES: parameters_all.get(\"modify\")\n },\n \"delete\":\n {\n constants.ACTION_TYPE: constants.ActionType.UPDATE,\n constants.PARAMETER_TYPES: parameters_all.get(\"delete\")\n },\n \"resume\":\n {\n constants.ACTION_TYPE: constants.ActionType.UPDATE,\n constants.PARAMETER_TYPES: parameters_all.get(\"resume\")\n },\n \"pause\":\n {\n constants.ACTION_TYPE: constants.ActionType.UPDATE,\n constants.PARAMETER_TYPES: parameters_all.get(\"pause\")\n },\n \"sync\":\n {\n constants.ACTION_TYPE: constants.ActionType.UPDATE,\n constants.PARAMETER_TYPES: parameters_all.get(\"sync\")\n }\n\n }\n}\n\n\ndef main():\n arguments = supportive_functions.create_arguments_for_ansible_module(template)\n\n ansible_module = AnsibleModule(arguments, supports_check_mode=True)\n runner.run(ansible_module, template)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"library/replicationSession.py","file_name":"replicationSession.py","file_ext":"py","file_size_in_byte":3654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"361045284","text":"import random\nA = [['Какой язык мы изучаем?','Python'],\n ['Как называется язык запросов к БД?','SQL'],\n ['Уж не в амперах ли измеряется сила тока?','В амперах'],\n ['Между кем и кем была русско-японская война?','Между Россией и Японией'],\n ['Какой сейчас год?','2017'],\n ['Сколько девушек в нашей группе?','Не считал'],\n ['Как называется команда подсчета длины строки?','len'],\n ['Что светит на небе ночью?','Луна'],\n ['В какой стране мы живём?','Россия'],\n ['Ноутбук какой фирмы использует наш преподаватель?','apple']]\ninp = ''\na = 0\nb = 0\nprint('Поиграем в загадки?')\nfor i in range(0,10):\n\tinp = str(input(A[i][0]))\n\tif str.upper(inp) == str.upper(A[i][1]):\n\t\ta += 1\n\t\tprint('Правильно!')\n\telse:\n\t\tb += 1\n\t\tprint('Неправильно!')\nprint('Спасибо, что уделили время! Правильных ответов {}, неправильных ответов {}'.format(a, b))\n\n\n\n\n","sub_path":"homework/homework_1_for.py","file_name":"homework_1_for.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"566559627","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 10 13:55:57 2018\n\n@author: ethan\n\"\"\"\n\n# Developer : Hamdy Abou El Anein\n\nimport random\nimport numpy as np\nimport pygame\nimport sys\nfrom pygame import *\n\n\npygame.init()\nfps = pygame.time.Clock()\n\n\nWHITE = (255, 255, 255)\nORANGE = (255,140,0)\nGREEN = (0, 255, 0)\nBLACK = (0, 0, 0)\n\n\nWIDTH = 1000\n#HEIGHT = 400\nHEIGHT = 600\nBALL_RADIUS = 20\nPAD_WIDTH = 8\nPAD_HEIGHT = 80\nHALF_PAD_WIDTH = PAD_WIDTH // 2\nHALF_PAD_HEIGHT = PAD_HEIGHT // 2\nball_pos = [0, 0]\nball_vel = [0, 0]\npaddle1_vel = 0\npaddle2_vel = 0\nl_score = 0\nr_score = 0\nscore_ball_y=0\nscore_paddle1_y= 0\ngeneration= 1\nlast_mean_score = 0\n\nwindow = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)\npygame.display.set_caption('Daylight Pong')\n#screen.set_alpha(None)\npygame.event.set_allowed([QUIT])\n \n\ndef ball_init(right):\n global ball_pos, ball_vel\n ball_pos = [WIDTH // 2, HEIGHT // 2]\n rand_num = np.random.uniform(np.pi/2 +.4,np.pi*3/2-0.4)\n vert= int(10*np.sin(rand_num))\n horz= int(10*np.cos(rand_num))\n\n \n #horz = random.randrange(1,3)*-1\n #vert = random.randrange(1,3)*(1-2*int(np.random.rand()>.5))\n\n #if right == False:\n # horz = - horz\n\n ball_vel = [horz, vert]\n #print(ball_vel)\n\n\ndef init():\n global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel, l_score, r_score # these are floats\n global score1, score2 # these are ints\n paddle1_pos = [HALF_PAD_WIDTH - 1, HEIGHT // 2]\n \n l_score = 0\n r_score = 0\n ball_init(True)\n # if random.randrange(0, 2) == 0:\n # ball_init(True)\n #else:\n # ball_init(False)\n\n\ndef draw(canvas,do_render):\n global paddle1_pos, paddle2_pos, ball_pos, ball_vel, l_score, r_score, paddle1_vel, score_ball_y,score_paddle1_y,generation, last_mean_score\n \n if(do_render):\n canvas.fill(BLACK)\n pygame.draw.line(canvas, WHITE, [WIDTH // 2, 0], [WIDTH // 2, HEIGHT], 1)\n pygame.draw.line(canvas, WHITE, [PAD_WIDTH, 0], [PAD_WIDTH, HEIGHT], 1)\n pygame.draw.line(canvas, WHITE, [WIDTH - PAD_WIDTH, 0], [WIDTH - PAD_WIDTH, HEIGHT], 1)\n pygame.draw.circle(canvas, WHITE, [WIDTH // 2, HEIGHT // 2], 70, 1)\n\n if abs(paddle1_vel) > 10:\n paddle1_vel = paddle1_vel/abs(paddle1_vel)*10\n\n if paddle1_pos[1] > HALF_PAD_HEIGHT and paddle1_pos[1] < HEIGHT - HALF_PAD_HEIGHT:\n paddle1_pos[1] += paddle1_vel\n elif paddle1_pos[1] == HALF_PAD_HEIGHT and paddle1_vel > 0:\n paddle1_pos[1] += paddle1_vel\n elif paddle1_pos[1] == HEIGHT - HALF_PAD_HEIGHT and paddle1_vel < 0:\n paddle1_pos[1] += paddle1_vel\n\n \n ball_pos[0] += int(ball_vel[0])\n ball_pos[1] += int(ball_vel[1])\n\n if(do_render):\n pygame.draw.circle(canvas, ORANGE, ball_pos, 20, 0)\n pygame.draw.polygon(canvas, GREEN, [[paddle1_pos[0] - HALF_PAD_WIDTH, paddle1_pos[1] - HALF_PAD_HEIGHT],\n [paddle1_pos[0] - HALF_PAD_WIDTH, paddle1_pos[1] + HALF_PAD_HEIGHT],\n [paddle1_pos[0] + HALF_PAD_WIDTH, paddle1_pos[1] + HALF_PAD_HEIGHT],\n [paddle1_pos[0] + HALF_PAD_WIDTH, paddle1_pos[1] - HALF_PAD_HEIGHT]], 0)\n \n if int(ball_pos[1]) <= BALL_RADIUS:\n ball_vel[1] = - ball_vel[1]\n if int(ball_pos[1]) >= HEIGHT + 1 - BALL_RADIUS:\n ball_vel[1] = -ball_vel[1]\n\n if int(ball_pos[0]) <= BALL_RADIUS + PAD_WIDTH and int(ball_pos[1]) in range(int(paddle1_pos[1]) - HALF_PAD_HEIGHT,\n int(paddle1_pos[1]) + HALF_PAD_HEIGHT, 1):\n ball_vel[0] = -ball_vel[0]\n ball_vel[0] *= 1.1\n ball_vel[1] *= 1.1\n \n elif int(ball_pos[0]) <= BALL_RADIUS + PAD_WIDTH:\n r_score += 1\n\n score_ball_y = ball_pos[1]\n score_paddle1_y = paddle1_pos[1]\n \n print('R scored')\n ball_init(True)\n\n\n elif int(ball_pos[0]) >= WIDTH + 1 - BALL_RADIUS - PAD_WIDTH:\n l_score += 1\n \n print('L scored Good Job')\n ball_init(False)\n\n if(do_render):\n myfont1 = pygame.font.SysFont(\"Comic Sans MS\", 20)\n label1 = myfont1.render(\"Score \" + str(l_score), 1, (255, 255, 0))\n canvas.blit(label1, (50, 20))\n \n myfont2 = pygame.font.SysFont(\"Comic Sans MS\", 10)\n label2 = myfont2.render(\"Generation \" + str(generation), 1, (255, 255, 0))\n canvas.blit(label2, (200, 20))\n \n myfont2 = pygame.font.SysFont(\"Comic Sans MS\", 10)\n label3 = myfont2.render(\"Last Performance Score \" + str(last_mean_score), 1, (255, 255, 0))\n canvas.blit(label3, (400, 20))\n #print(paddle1_pos[1])\n\n\ndef keydown(event):\n global paddle1_vel, paddle2_vel\n\n if event.key == K_UP:\n paddle2_vel = -8\n elif event.key == K_DOWN:\n paddle2_vel = 8\n elif event.key == K_z:\n paddle1_vel = -8\n elif event.key == K_s:\n paddle1_vel = 8\n\n\ndef keyup(event):\n global paddle1_vel, paddle2_vel\n\n if event.key in (K_z, K_s):\n paddle1_vel = 0\n elif event.key in (K_UP, K_DOWN):\n paddle2_vel = 0\n\n\n \nclass AI:\n n_inputs = 2\n n_hidden_1 = 5\n n_hidden_2 = 5\n n_outputs = 3\n \n mu = 0.01\n \n inp_to_hid_weights = np.zeros(n_inputs*n_hidden_1).reshape(n_hidden_1, n_inputs)\n hid_to_hid_weights = np.zeros(n_hidden_1*n_hidden_2).reshape(n_hidden_2, n_hidden_1)\n hid_to_out_weights = np.zeros(n_outputs*n_hidden_2).reshape(n_outputs, n_hidden_2)\n \n def __init__(self):\n self.inp_to_hid_weights = 1-2*np.random.rand(self.n_inputs*self.n_hidden_1).reshape(self.n_hidden_1, self.n_inputs)\n self.hid_to_hid_weights = 1-2*np.random.rand(self.n_hidden_1*self.n_hidden_2).reshape(self.n_hidden_2, self.n_hidden_1)\n self.hid_to_out_weights = 1-2*np.random.rand(self.n_hidden_2*self.n_outputs).reshape(self.n_outputs, self.n_hidden_2)\n \n @classmethod\n def from_weights(cls,w1,w2,w3):\n \n ai = cls()\n ai.inp_to_hid_weights = w1\n ai.hid_to_hid_weights = w2\n ai.hid_to_out_weights = w3\n return ai\n \n def spawn(self,n_children):\n children = []\n for i in range(n_children):\n #mu = self.mutation_const + self.mutation_const*np.random.rand()*0.1\n mu= 1/10\n \n w1= self.randomize_fraction(self.inp_to_hid_weights,mu)\n w2= self.randomize_fraction(self.hid_to_hid_weights,mu)\n w3= self.randomize_fraction(self.hid_to_out_weights,mu)\n ai = AI.from_weights(w1,w2,w3)\n children.append(ai)\n \n return children\n \n def randomize_fraction(self,w,fract):\n num_w = w.shape[0]* w.shape[1]\n #print(num_w)\n mu = fract\n rand_w_vec = np.array([0]*(num_w-round(num_w*mu)) + [1]*(round(num_w*mu))).reshape(len(w[:,0]), len(w[0,:]))\n #print(w)\n np.random.shuffle(rand_w_vec)\n rand_part = np.random.rand(num_w).reshape(len(w[:,0]), len(w[0,:]))*rand_w_vec\n w = w*abs(rand_w_vec-1)- rand_part\n return w\n #w=np.array([list(range(100))]).reshape(10,10)\n #w2 = (np.array(list(range(100)))*-1).reshape(10,10)\n \n #ai1 = AI.from_weights(w,w,w)\n #ai2 = AI.from_weights(w2,w2,w2)\n \n #ai3= ai1.sex(ai2,1)\n def sex(self,ai_B,n_children):\n children = []\n for i in range(n_children):\n mu = 1/50\n w1_A= self.inp_to_hid_weights\n w2_A= self.hid_to_hid_weights\n w3_A= self.hid_to_out_weights\n w1_B= ai_B.inp_to_hid_weights\n w2_B= ai_B.hid_to_hid_weights\n w3_B= ai_B.hid_to_out_weights\n \n num_w1 = self.inp_to_hid_weights.shape[0]*self.inp_to_hid_weights.shape[1]\n num_w2 = self.hid_to_hid_weights.shape[0]*self.hid_to_hid_weights.shape[1]\n num_w3 = self.hid_to_out_weights.shape[0]*self.hid_to_out_weights.shape[1]\n \n rand_w1_vec = np.array([0]*(num_w1-round(num_w1*1/2)) + [1]*(round(num_w1*1/2))).reshape(len(w1_A[:,0]), len(w1_A[0,:]))\n np.random.shuffle(rand_w1_vec)\n rand_w2_vec = np.array([0]*(num_w2-round(num_w2*1/2)) + [1]*(round(num_w2*1/2))).reshape(len(w2_A[:,0]), len(w2_A[0,:]))\n np.random.shuffle(rand_w2_vec)\n rand_w3_vec = np.array([0]*(num_w3-round(num_w3*1/2)) + [1]*(round(num_w3*1/2))).reshape(len(w3_A[:,0]), len(w3_A[0,:]))\n np.random.shuffle(rand_w3_vec)\n \n \n \n w1 = w1_A*abs(rand_w1_vec-1) + rand_w1_vec*w1_B\n w2 = w2_A*abs(rand_w2_vec-1) + rand_w2_vec*w2_B\n w3 = w3_A*abs(rand_w3_vec-1) + rand_w3_vec*w3_B\n \n w1= self.randomize_fraction(w1,mu)\n w2= self.randomize_fraction(w2,mu)\n w3= self.randomize_fraction(w3,mu)\n #print(w1,w2,w3)\n ai = AI.from_weights(w1,w2,w3)\n children.append(ai)\n return children\n \n \n def activation_function(self,x):\n return x\n \n def respond(self,ball_pos,pos):\n ball_px, ball_py = ball_pos\n #ball_vx, ball_vy = ball_vel\n #print([ball_px,ball_py,ball_vx, ball_vy,pos])\n \n inputs = np.array([ball_py,pos])\n \n summed_weighted_inputs = np.matmul(self.inp_to_hid_weights,inputs)\n hidden_1_out = np.array([self.activation_function(summed) for summed in summed_weighted_inputs])\n summed_weighted_hidden_1 = np.matmul(self.hid_to_hid_weights,hidden_1_out)\n hidden_2_out = np.array([self.activation_function(summed) for summed in summed_weighted_hidden_1])\n summed_weighted_hidden_2 = np.matmul(self.hid_to_out_weights,hidden_2_out)\n output = np.array([self.activation_function(summed) for summed in summed_weighted_hidden_2])\n return output\n \nai1 = AI()\nai2 = AI()\n\n\n\n\nbrawl_count= 0\nrend_state = False\n\nai1.inp_to_hid_weights\nai1.respond([123,100],23)\n\ndef fitness_score(AI,rend_state):\n init()\n count =0 \n while True:\n global paddle1_vel, paddle2_vel, l_score, score_ball_y, score_paddle_y\n \n \n \n draw(window,rend_state)\n if(l_score+r_score is not l_score):\n #print(score_ball_y)\n l_score = l_score* (1-((score_ball_y - score_paddle1_y)**2)/HEIGHT**2)\n print(l_score)\n return [l_score,r_score]\n \n\n if(count %1 ==0):\n resp1 = AI.respond(np.array(ball_pos),np.array(paddle1_pos[1]))\n resp1 = np.array(resp1)/max(resp1) == 1\n \n if(resp1[0]):\n paddle1_vel = -8\n if(resp1[1]):\n paddle1_vel= 0\n if(resp1[2]):\n paddle1_vel = 8\n #print('huh')\n \n \n for event in pygame.event.get():\n if event.type == KEYDOWN:\n keydown(event)\n elif event.type == KEYUP:\n keyup(event)\n elif event.type == QUIT:\n pygame.quit()\n sys.exit()\n \n pygame.display.update()\n fps.tick(1000)\n count+=1\n\nfits_for_scores = []\ndef fit_population(ais, show):\n global last_mean_score\n fit_scores= []\n new_ais = []\n for i in range(len(ais)):\n #print(i)\n fit_scores.append(fitness_score(ais[i], show)[0])\n \n total = sum(np.array(fit_scores))\n probs = fit_scores/total\n print(max(fit_scores))\n fits_for_scores.append((np.mean(fit_scores)))\n last_mean_score = np.mean(np.array(fits_for_scores))\n print(probs)\n choices= np.random.choice(list(range(len(ais))),size=(101,),p=probs , replace=True)\n \n for i in range(len(choices)-1):\n new_ais.extend(ais[choices[i]].sex(ais[choices[i+1]],1))\n \n return new_ais\n\n\ndef champion_finder(gens):\n global generation\n ais=[]\n for i in range(120):\n ais.append(AI())\n \n for i in range(gens):\n new_ais = fit_population(ais, i>-1)\n ais = new_ais\n generation+=1\n return ais\n\nais= champion_finder(50)\n\n#fitness_score(ais[2],True)\nfit_population(ais,True)","sub_path":"Game_Simple.py","file_name":"Game_Simple.py","file_ext":"py","file_size_in_byte":12261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"320855586","text":"import pandas as pd\nfrom itertools import chain, repeat\nfrom collections import namedtuple\n\nfrom blueshift_calendar import get_calendar\nfrom blueshift_data.readers import Library\n\nfrom zipline_pipeline.pipeline import Pipeline, SimplePipelineEngine\nfrom zipline_pipeline.pipeline import CustomFilter, CustomFactor\n#from zipline_pipeline.pipeline.data import EquityPricing\nfrom zipline_pipeline.pipeline.loaders import EquityPricingLoader\nimport zipline_pipeline.pipeline.domain as domain\nfrom blueshift_data.pipeline.domain import PricingDomain, BLUESHIFT_PIPELINE_SUPPORT\nfrom blueshift_data.pipeline.data import EquityPricing\n\ndef filter_universe(universe):\n class FilteredUniverse(CustomFilter):\n inputs = ()\n window_length = 1\n def compute(self,today,assets,out):\n in_universe = [True for asset in assets if asset not in universe]\n out[:] = in_universe\n \n return FilteredUniverse()\n\ndef period_returns(lookback):\n class SignalPeriodReturns(CustomFactor):\n inputs = [EquityPricing.close]\n def compute(self,today,assets,out,close_price):\n start_price = close_price[0]\n end_price = close_price[-1]\n returns = end_price/start_price - 1\n out[:] = returns\n \n return SignalPeriodReturns(window_length = lookback)\n\ndef make_strategy_pipeline(universe):\n pipe = Pipeline()\n momentum = period_returns(100)\n pipe.add(momentum,'momentum')\n universe_filter = filter_universe(universe)\n pipe.set_screen(universe_filter)\n\n return pipe\n\n# set up engine\ncal = get_calendar('NYSE')\nlib = Library(\"C:/Users/prodi/.blueshift/data/library/us-equities\")\ndaily_store = list(lib['1d'])[0]\nminute_store = list(lib['1m'])[0]\nadj_handler = minute_store.adjustments_handler\npipeline_loader = EquityPricingLoader.without_fx(daily_store, adj_handler)\n#BLUESHIFT_US_EQUITIES = domain.StoreDomain(daily_store)\n#BlueshiftUSEquityPricing = EquityPricing.specialize(BLUESHIFT_US_EQUITIES)\nPricingDomain.set_store(daily_store)\n\ndef get_loader(column):\n if column in EquityPricing.columns:\n return pipeline_loader\n raise ValueError(\n \"No PipelineLoader registered for column %s.\" % column\n )\n\nengine = SimplePipelineEngine(\n get_loader,\n lib,\n #domain.StoreDomain(daily_store),\n #BLUESHIFT_US_EQUITIES,\n PricingDomain,\n )\n\n# setup pipeline\nAttachedPipeline = namedtuple('AttachedPipeline', ['pipe','chunks', 'eager'])\npipelines = {}\nchunks = chain([5], repeat(126))\neager = True\npipeline = make_strategy_pipeline([])\npipelines['test'] = AttachedPipeline(pipeline, iter(chunks), eager)\n\n# run pipeline\nstart_session = pd.Timestamp('2010-02-01')\nend_session = pd.Timestamp('2010-04-30')\npipe, chunks, _ = pipelines['test']\nchunksize = next(chunks)\nsessions = cal.all_sessions\nstart_date_loc = sessions.get_loc(start_session)\nend_loc = min(\n start_date_loc + chunksize,\n sessions.get_loc(end_session)\n )\nstart_session = sessions[start_date_loc]\nend_session = sessions[end_loc]\n\nres = engine.run_pipeline(pipe, start_session, end_session)\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"90874504","text":"import slack\nimport quandl\nimport os\nimport logging\nfrom fpdf import FPDF\nimport datetime\nimport data\nimport benchmark\nimport metrics\nimport quantstats as qs\n\n\ndf, portfolioValue, historicalValue, portfolioValueExtended = data.pull_data('portfolio.csv')\ntotalHoldingStart, benchPortfolioValue = benchmark.create_benchmark(df, historicalValue)\nbenchmark.plot_benchmark(portfolioValue, benchPortfolioValue)\ntopGainers, topLosers = data.topGainersLosers(historicalValue, totalHoldingStart)\n\nmetrics.create_performance_plots(portfolioValueExtended)\nmetrics.create_corr_heatmap(list(df['Shares']), historicalValue)\n\n#qs.extend_pandas()\n#qs.reports.html(portfolioValueExtended['Portfolio'], \"SPY\", output='rif_vs_bench.html')\n\n#### ---------------- Creating PDF ---------------- ####\ntoday = datetime.date.today()\n# ---- Cover Page\npdf = FPDF(orientation='landscape')\npdf.set_margin(2)\npdf.add_page()\npdf.set_fill_color(128, 0, 0)\npdf.rect(x = 0, y = 0, w = pdf.w, h = 12, style = 'F')\n# ---- Date\npdf.set_font(\"Times\", size=22)\npdf.set_font(style='B')\npdf.set_text_color(237, 232, 228)\npdf.cell(txt=str(today), align='C')\n# ----\npdf.set_fill_color(128, 0, 0)\npdf.rect(x = 0, y = 198, w = pdf.w, h = 12, style = 'F')\npdf.image(x = -0.5, y = 12, w = pdf.w + 1, name='RIFLogo(B&W).png')\n\n# ---- Second Page\npdf.add_page()\npdf.set_fill_color(128, 0, 0)\npdf.rect(x = 0, y = 0, w = pdf.w, h = 12, style = 'F')\npdf.rect(x = 0, y = 198, w = pdf.w, h = 12, style = 'F')\npdf.set_fill_color(0, 0, 0)\npdf.rect(x = 0, y = 12, w = pdf.w, h = 186, style = 'F')\npdf.cell(0, 13, ln=1)\npdf.set_font(\"Times\", size=16, style='BU')\npdf.cell(125, 8, 'Top Gainers / Top Losers', align='C')\npdf.set_font(\"Times\", size=20, style='BU')\npercentGain = (((portfolioValue['Portfolio'][len(portfolioValue)-1] - portfolioValue['Portfolio'][0])/portfolioValue['Portfolio'][0])*100).round(2)\npdf.cell(((pdf.w/2) + (pdf.w/2 - 125)), 8, 'Performance for the current period: {change}%'.format(change = percentGain), ln=1, align='C')\npdf.image(x=135, y=47, w=(pdf.w+1)/2, name='Figures/portfolioVSbenchmark.png')\n\npdf.set_text_color(248, 240, 227)\npdf.set_font(\"Times\", size=14)\n\nlosersList = topLosers.to_records()\nlosersList = list(losersList)\ngainersList = topGainers.to_records()\ngainersList = list(gainersList)\n\nif len(gainersList) > len(losersList):\n gainersList = gainersList[0:len(losersList)]\nelif len(gainersList) < len(losersList):\n losersList = losersList[0:len(gainersList)]\n\nj = 0\nfor i in gainersList:\n pdf.set_text_color(0, 255, 0)\n pdf.cell(25, 8, str(i[0]))\n pdf.cell(50, 8, i[1])\n pdf.set_text_color(255, 0, 0)\n pdf.cell(25, 8, losersList[j][0])\n pdf.cell(25, 8, losersList[j][1], ln=1)\n j+=1\n\n# ---- Third Page\npdf.add_page()\npdf.set_fill_color(128, 0, 0)\npdf.rect(x = 0, y = 0, w = pdf.w, h = 12, style = 'F')\n\n# ----\npdf.set_fill_color(128, 0, 0)\npdf.rect(x = 0, y = 198, w = pdf.w, h = 12, style = 'F')\npdf.image(x = -0.5, y = 12, w = pdf.w + 1, name='Figures/monthly_returns.png')\n\n# ---- Fourth Page\npdf.add_page()\npdf.set_fill_color(128, 0, 0)\npdf.rect(x = 0, y = 0, w = pdf.w, h = 12, style = 'F')\n\n# ----\npdf.set_fill_color(128, 0, 0)\npdf.rect(x = 0, y = 198, w = pdf.w, h = 12, style = 'F')\npdf.image(x = -0.5, y = 12, w = pdf.w + 1, name='Figures/return_quantiles.png')\n\n# ---- Fifth Page\npdf.add_page()\npdf.set_fill_color(128, 0, 0)\npdf.rect(x = 0, y = 0, w = pdf.w, h = 12, style = 'F')\n\n# ----\npdf.set_fill_color(128, 0, 0)\npdf.rect(x = 0, y = 198, w = pdf.w, h = 12, style = 'F')\npdf.image(x = -0.5, y = 12, w = pdf.w + 1, name='Figures/portfolio_corr.png')\n\n# ---- Sixth Page\npdf.add_page()\npdf.set_fill_color(0, 0, 0)\npdf.rect(x = 0, y = 12, w = pdf.w, h = 186, style = 'F')\npdf.set_fill_color(128, 0, 0)\npdf.rect(x = 0, y = 0, w = pdf.w, h = 12, style = 'F')\n\n# ----\npdf.set_fill_color(128, 0, 0)\npdf.rect(x = 0, y = 198, w = pdf.w, h = 12, style = 'F')\npdf.image(x = -0.5, y = pdf.h-100, w = pdf.w + 1, name='Figures/rol_beta_sharpe.png')\npdf.image(x = -0.5, y = 12, w = pdf.w + 1, name='Figures/rol_beta_sortino.png')\n\n# ---- PDF Output\npdf.output('pdf_1.pdf')\n\n# ---- Call Bot and Send Portfolio\nclient = slack.WebClient(token = '####')\nclient.files_upload(channels = '#sector-materials', file='./pdf_1.pdf')\n\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":4234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"169369989","text":"# nohup python run_shap.py >> 1.log 2>&1 &\n# 0 108546\n# 1 108751\n\nimport numpy as np\nimport itertools\nfrom itertools import combinations\nimport torch\nfrom copy import deepcopy\n# from __future__ import absolute_import, division, print_function\n\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport argparse\nimport glob\nimport logging\nimport os\nimport random\nimport itertools\nimport numpy as np\nimport torch\n# import hedge_bert as hedge\nfrom torch.utils.data import (DataLoader, RandomSampler, SequentialSampler,\n TensorDataset)\nfrom torch.utils.data.distributed import DistributedSampler\nfrom tqdm import tqdm, trange\nfrom copy import copy, deepcopy\n# from pytorch_transformers import (WEIGHTS_NAME, BertConfig,BertForSequenceClassification, BertTokenizer)\n\n# from pytorch_transformers import AdamW, WarmupLinearSchedule\n\nfrom utils_glue import (convert_examples_to_features,output_modes, processors)\nimport time\nlogger = logging.getLogger(__name__)\n\ntorch.cuda.set_device(2)\n\ndef set_seed(args):\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if args.n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed)\n\ndef load_and_cache_examples(args, task, tokenizer, type):\n processor = processors[task]()\n output_mode = output_modes[task]\n label_list = processor.get_labels()\n cached_features_file = os.path.join(args.data_dir, 'cached_{}_{}_{}_{}'.format(\n type,\n list(filter(None, args.model_name_or_path.split('/'))).pop(),\n str(args.max_seq_length),\n str(task)))\n examples = processor.get_train_examples(args.data_dir)\n #print(examples)\n # examples = ['By comparison , it cost $ 103.7 million to build the NoMa infill Metro station , which opened in 2004 .']\n # label_list = ['pos','neg']\n output_mode = output_modes[task]\n \n features = convert_examples_to_features(examples, label_list, args.max_seq_length, tokenizer, output_mode,\n cls_token_at_end=bool(args.model_type in ['xlnet']),\n # xlnet has a cls token at the end\n cls_token=tokenizer.cls_token,\n cls_token_segment_id=2 if args.model_type in ['xlnet'] else 0,\n sep_token=tokenizer.sep_token,\n sep_token_extra=bool(args.model_type in ['roberta']),\n # roberta uses an extra separator b/w pairs of sentences, cf. github.com/pytorch/fairseq/commit/1684e166e3da03f5b600dbb7855cb98ddfcd0805\n pad_on_left=bool(args.model_type in ['xlnet']),\n # pad on the left for xlnet\n pad_token=tokenizer.convert_tokens_to_ids([tokenizer.pad_token])[0],\n pad_token_segment_id=4 if args.model_type in ['xlnet'] else 0,\n )\n logger.info(\"Saving features into cached file %s\", cached_features_file)\n torch.save(features, cached_features_file)\n \n # Convert to Tensors and build dataset\n all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)\n all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long)\n all_segment_ids = torch.tensor([f.segment_ids for f in features], dtype=torch.long)\n #for f in features:\n # print(f.ori_token)\n if output_mode == \"classification\":\n all_label_ids = torch.tensor([f.label_id for f in features], dtype=torch.long)\n elif output_mode == \"regression\":\n all_label_ids = torch.tensor([f.label_id for f in features], dtype=torch.float)\n dataset = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)\n return dataset\n\t\nclass arg(object):\n def __init__(self):\n self.data_dir = './dataset/IMDB'\n self.model_type = 'bert'\n self.model_name_or_path = 'bert-base-uncased' \n # self.model_name_or_path = 'gilf/english-yelp-sentiment'\n self.task_name = 'sst-2'\n self.output_dir = './output/IMDB'\n self.max_seq_length = 250\n self.start_pos = 0\n self.end_pos = 2000\n self.visualize = 1\n self.per_gpu_eval_batch_size = 1\n self.n_gpu = 1\n self.device = 'cuda'\nargs = arg()\n\ndef evaluate(args, model, tokenizer, eval_dataset, fileobject, start_pos=0, end_pos=100, vis=-1):\n eval_output_dir = args.output_dir\n if not os.path.exists(eval_output_dir):\n os.makedirs(eval_output_dir)\n\n args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)\n # Note that DistributedSampler samples randomly\n eval_sampler = SequentialSampler(eval_dataset)\n eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=1)\n\n # Eval!\n eval_loss = 0.0\n nb_eval_steps = 0\n preds = None\n out_label_ids = None\n count = start_pos\n start_time = time.time()\n results = []\n num =0\n for batch in itertools.islice(eval_dataloader, start_pos, end_pos):\n num+=1\n print(num)\n model.eval()\n batch = tuple(t.to(args.device) for t in batch)\n count += 1\n fileobject.write(str(count))\n fileobject.write('\\n')\n \n ori_text_idx = list(batch[0].cpu().numpy()[0])\n if 0 in ori_text_idx:\n ori_text_idx = [idx for idx in ori_text_idx if idx != 0]\n pad_start = len(ori_text_idx)\n print('len:',pad_start)\n with torch.no_grad():\n inputs = {'input_ids': torch.unsqueeze(batch[0][0,:pad_start], 0),\n 'attention_mask': torch.unsqueeze(batch[1][0,:pad_start], 0),\n 'token_type_ids': torch.unsqueeze(batch[2][0,:pad_start], 0) if args.model_type in ['bert', 'xlnet'] else None, # XLM and RoBERTa don't use segment_ids\n 'labels': batch[3]}\n # print(inputs)\n outputs = model(**inputs)\n global tttest\n tttest = outputs[-1]\n # print(len(outputs))\n # print(outputs)\n tmp_eval_loss, logits = outputs[:2]\n\n eval_loss += tmp_eval_loss.mean().item()\n nb_eval_steps += 1\n \n # print(count,len(inputs['input_ids'][0]) - 2)\n if preds is None:\n preds = logits.detach().cpu().numpy()\n out_label_ids = inputs['labels'].detach().cpu().numpy()\n else:\n preds = np.append(preds, logits.detach().cpu().numpy(), axis=0)\n out_label_ids = np.append(out_label_ids, inputs['labels'].detach().cpu().numpy(), axis=0)\n\n for btxt in ori_text_idx:\n if (tokenizer.ids_to_tokens[btxt] != '[CLS]' and tokenizer.ids_to_tokens[btxt] != '[SEP]'):\n fileobject.write(tokenizer.ids_to_tokens[btxt])\n fileobject.write(' ')\n fileobject.write(' >> ')\n if batch[3].cpu().numpy()[0] == 0:\n fileobject.write('0')\n fileobject.write(' ||| ')\n else:\n fileobject.write('1')\n fileobject.write(' ||| ')\n\n shap = HEDGE(model, inputs, args, thre=100)\n res = shap.shapely_matrix(model,inputs)\n results.append(res)\n return results\n\t\nclass HEDGE:\n def __init__(self, model, inputs, args, max_level=-1, thre=0.3):\n score = model(**inputs)[1].detach().cpu().numpy()\n score_norm = (np.exp(score) / np.sum(np.exp(score), axis=1))\n self.pred_label = np.argmax(score_norm)\n self.max_level = max_level\n self.output = []\n self.fea_num = len(inputs['input_ids'][0]) - 2\n self.level = 0\n self.args = args\n self.thre = thre\n input = inputs['input_ids'][0]\n mask_input = torch.zeros(input.shape, dtype=torch.long)\n mask_attention = torch.zeros(input.shape, dtype=torch.long)\n mask_type = torch.zeros(input.shape, dtype=torch.long)\n temp = {'input_ids': torch.unsqueeze(mask_input, 0).to(args.device),\n 'attention_mask': torch.unsqueeze(mask_attention, 0).to(args.device),\n 'token_type_ids': torch.unsqueeze(mask_type, 0).to(args.device),\n 'labels': inputs['labels']}\n # score = model(**temp)[1].detach().cpu().numpy()\n # score_norm = (np.exp(score) / np.sum(np.exp(score), axis=1))\n with torch.no_grad():\n ori_score = model(**temp)[-1][12].cpu().numpy()\n # ori_score = ori_score[0]\n self.ori_score = ori_score\n\n def set_contribution_func(self, model, fea_set, inputs, ori,tar):\n # input has just one sentence, input is a list\n args = self.args\n input = inputs['input_ids'][0]\n mask_input = torch.full(input.shape,tokenizer.mask_token_id)\n mask_input[0] = input[0]\n mask_input[-1] = input[-1]\n mask_attention = torch.zeros(input.shape, dtype=torch.long)\n mask_attention[0] = 1\n mask_attention[-1] = 1\n # mask_attention[ori+1] = 1\n # mask_input[ori+1] = input[ori+1]\n mask_type = torch.zeros(input.shape, dtype=torch.long)\n\n # mask the input with zero\n for fea_idx in fea_set:\n if type(fea_idx) == int:\n mask_input[fea_idx+1] = input[fea_idx+1] #+1 accounts for the CLS token at the begining\n mask_attention[fea_idx+1] = 1 #+1 accounts for the CLS token at the begining\n else:\n for idx in fea_idx:\n mask_input[idx+1] = input[idx+1] #+1 accounts for the CLS token at the begining\n mask_attention[idx+1] = 1 #+1 accounts for the CLS token at the begining\n temp = {'input_ids': torch.unsqueeze(mask_input, 0).to(args.device),\n 'attention_mask': torch.unsqueeze(mask_attention, 0).to(args.device),\n 'token_type_ids': torch.unsqueeze(mask_type, 0).to(args.device),\n 'labels': inputs['labels']}\n # send the mask_input into model\n with torch.no_grad():\n score = model(**temp)[-1][12][:, ori+1, :].cpu().numpy()\n score = score[0]\n # score = score[12][:, word_pos, :] \n # print(mask_attention)\n mask_input[tar+1] = input[tar+1]\n mask_attention[tar+1] = 1\n\n temp = {'input_ids': torch.unsqueeze(mask_input, 0).to(args.device),\n 'attention_mask': torch.unsqueeze(mask_attention, 0).to(args.device),\n 'token_type_ids': torch.unsqueeze(mask_type, 0).to(args.device),\n 'labels': inputs['labels']}\n\n with torch.no_grad():\n score2 = model(**temp)[-1][12][:, ori+1, :].cpu().numpy()\n score2 = score2[0]\n # print(mask_attention)\n # print(score)\n # print(score2)\n return np.linalg.norm(score - score2)\n # return np.dot(score, score2) / (np.linalg.norm(score) * np.linalg.norm(score2))\n\n def shapely_matrix(self,model,inputs):\n fea_num = self.fea_num\n if fea_num == 0:\n return -1\n fea_set = list(range(fea_num))\n scores = [[] for i in range(len(fea_set))]\n for i in fea_set:\n for j in fea_set:\n if i==j:\n scores[i].append(0)\n continue\n # print(i,j)\n new_fea_set = [ele for x, ele in enumerate(fea_set) if x!=j and x!=i]\n # print(new_fea_set)\n scores[i].append(self.shapely_value(model,inputs,new_fea_set,i,j))\n return scores\n\n def get_shapley_interaction_weight(self, d, s):\n return np.math.factorial(s) * np.math.factorial(d - s - 1) / np.math.factorial(d)\n\n def shapely_value(self,model,inputs,feature_set,ori,tar):\n fea_num = len(feature_set)\n #dict_subset = {r: list(combinations(feature_set, r)) for r in range(fea_num+1)}\n score = 0.0\n for i in range(fea_num+1):\n # if i<(fea_num+1)*0.9:\n # continue\n if i=100:\n break\n print_out(num)\n token_text = tokenizer.tokenize(' '.join(sentence))\n token_text.insert(0, '[CLS]')\n token_text.append('[SEP]')\n # print(len(res[num-1]))\n # print(len(line))\n # print(len(res[num-1]))\n in_result.append((line,token_text,res2[num-1]))\n # print(line)\n sen = ' '.join(sentence)\n sens.append(sen)\n sum += leng\n num += 1\n\n\nfrom dependency import _evaluation as dep_eval\nfrom dependency.dep_parsing import decoding as dep_parsing\nclass arg2(object):\n def __init__(self):\n self.probe = 'discourse'\n self.decoder = 'eisner'\n self.subword = 'avg'\n self.root = 'gold'\nargs = arg2()\ntrees, results, deprels = dep_parsing(in_result[0:99],args)\ndep_eval(trees, results)","sub_path":"run_shap2.py","file_name":"run_shap2.py","file_ext":"py","file_size_in_byte":15230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"247906795","text":"import argparse\nimport json\nimport math\nimport os\nimport paramiko\nimport re\nimport subprocess\nimport sys\nimport yaml\nfrom prettytable import PrettyTable\n\n# Gets the profile name for flavor name\ndef get_profile_name(flavor_name):\n cmd = \"openstack flavor show \" + flavor_name\n output = subprocess.check_output(cmd,shell=True)\n properties = ''\n for line in output.split('\\n'):\n if 'properties' in line:\n properties = line\n profile = ''\n if properties:\n profile_index = properties.index('capabilities:profile=')\n if profile_index >=0:\n profile_start_index = profile_index + len('capabilities:profile=') + 1\n profile_end_index = properties.index('\\'', profile_start_index, len(properties))\n profile = properties[profile_start_index:profile_end_index]\n return profile\n\n\n# Gets the first matching node UUID for flavor name\ndef get_node_uuid(flavor_name):\n node_uuid = ''\n profile_name = get_profile_name(flavor_name)\n cmd = \"openstack overcloud profiles list -f json\"\n output = subprocess.check_output(cmd,shell=True)\n profiles_list = json.loads(output)\n for profile in profiles_list:\n if profile[\"Current Profile\"] == profile_name:\n node_uuid = profile[\"Node UUID\"]\n break\n return node_uuid.strip()\n\n\n# Gets the flavor name for role name\ndef get_flavor_name(role_name):\n flavor_name = ''\n param_key = 'Overcloud' + role_name + 'Flavor'\n cmd = \"mistral run-action tripleo.parameters.get\"\n output = subprocess.check_output(cmd,shell=True)\n result = json.loads(output)\n if result and result.get('result', {}):\n env = result.get('result', {}).get('mistral_environment_parameters', {})\n if not env:\n env = result.get('result', {}).get('environment_parameters', {})\n if env:\n flavor_name = env.get(param_key, '')\n return flavor_name\n\n\n# Gets the physical and logical cpus info for all numa nodes.\ndef get_nodes_cores_info(client):\n dict_cpus = {}\n cmd = \"sudo lscpu -p=NODE,CORE,CPU | grep -v ^#\"\n stdin, stdout, stderr = client.exec_command(cmd)\n output = str(stdout.read())\n for line in output.split('\\n'):\n if line:\n cpu_info = line.split(',')\n node = int(cpu_info[0])\n cpu = int(cpu_info[1])\n thread = int(cpu_info[2])\n # CPU and NUMA node together forms a unique value, as cpu is\n # specific to a NUMA node\n # NUMA node id and cpu id tuple is used for unique key\n dict_key = node, cpu\n if dict_key in dict_cpus:\n if thread not in dict_cpus[dict_key]['thread_siblings']:\n dict_cpus[dict_key]['thread_siblings'].append(thread)\n else:\n cpu_item = {}\n cpu_item['thread_siblings'] = [thread]\n cpu_item['cpu'] = cpu\n cpu_item['numa_node'] = node\n dict_cpus[dict_key] = cpu_item\n return dict_cpus\n\n\n# Gets the DPDK NIC's mapping with NIC physical name and driver info for the given MAC.\ndef get_dpdk_nics_mapping(client, mac):\n cmd = \"sudo cat /var/lib/os-net-config/dpdk_mapping.yaml\"\n stdin, stdout, stderr = client.exec_command(cmd)\n output = str(stdout.read())\n dpdk_nics_map = yaml.load(output)\n for dpdk_nic_map in dpdk_nics_map:\n if dpdk_nic_map['mac_address'] == mac:\n return dpdk_nic_map\n else:\n msg = (\"Unable to determine DPDK NIC Mapping for MAC: '%(mac)s'\" % {'mac':mac})\n raise Exception(msg)\n\n\n# Gets the DPDK NIC's NUMA info\ndef get_dpdk_nics_info(client):\n dpdk_nics_info = []\n dpdk_nics = []\n cmd = \"sudo ovs-vsctl --columns=name,type,admin_state --format=json list interface\"\n stdin, stdout, stderr = client.exec_command(cmd)\n output = str(stdout.read())\n nics = json.loads(output)\n for nic in nics.get('data', []):\n if nic and str(nic[1]) == 'dpdk' and str(nic[2]) == 'up':\n dpdk_nics.append(str(nic[0]))\n if dpdk_nics:\n cmd = \"sudo ovs-vsctl --column=mac-in-use,mtu,status --format=json list interface \" + ' '.join(dpdk_nics)\n stdin, stdout, stderr = client.exec_command(cmd)\n output = str(stdout.read())\n nics_info = json.loads(output)\n for nic_info in nics_info.get('data', []):\n data = {}\n data['mac'] = nic_info[0]\n data['mtu'] = nic_info[1]\n for field in nic_info[2][1]:\n if field[0] == 'numa_id':\n data['numa_node'] = int(field[1])\n dpdk_nic_map = get_dpdk_nics_mapping(client, nic_info[0])\n data['nic'] = dpdk_nic_map['name']\n data['pci'] = dpdk_nic_map['pci_address']\n dpdk_nics_info.append(data)\n return dpdk_nics_info\n\n\n# Gets the total physical memory.\ndef get_physical_memory(client):\n mem_total_kb = 0\n # cmd = \"sudo cat /proc/meminfo | grep 'MemTotal' | grep -v ^#\"\n cmd =\"sudo dmidecode --type memory | grep 'Size' | grep '[0-9]'\"\n stdin, stdout, stderr = client.exec_command(cmd)\n output = str(stdout.read())\n for line in output.split('\\n'):\n if line:\n mem_info = line.split(':')[1].strip()\n mem_val = mem_info.split(' ')\n mem_unit = mem_val[1].strip(' ').lower()\n if mem_unit == 'kb':\n memory_kb = int(mem_val[0].strip(' '))\n elif mem_unit == 'mb':\n memory_kb = (int(mem_val[0].strip(' ')) * 1024)\n mem_total_kb += memory_kb\n return (mem_total_kb / 1024)\n\n\n# Gets the numa nodes list\ndef get_numa_nodes(client):\n nodes = []\n cmd = \"sudo lscpu -p=NODE | grep -v ^#\"\n stdin, stdout, stderr = client.exec_command(cmd)\n output = str(stdout.read())\n for line in output.split('\\n'):\n if line:\n node = int(line.strip(' '))\n if node not in nodes:\n nodes.append(node)\n return nodes\n\n\n# Computes round off MTU value in bytes\n# example: MTU value 9000 into 9216 bytes\ndef roundup_mtu_bytes(mtu):\n max_div_val = int(math.ceil(float(mtu) / float(1024)))\n return (max_div_val * 1024)\n\n\n# Calculates socket memory for a NUMA node\ndef calculate_node_socket_memory(numa_node, dpdk_nics_numa_info,\n overhead, packet_size_in_buffer,\n minimum_socket_memory):\n distinct_mtu_per_node = []\n socket_memory = 0\n\n # For DPDK numa node\n for nics_info in dpdk_nics_numa_info:\n if (numa_node == nics_info['numa_node'] and\n not nics_info['mtu'] in distinct_mtu_per_node):\n distinct_mtu_per_node.append(nics_info['mtu'])\n roundup_mtu = roundup_mtu_bytes(nics_info['mtu'])\n socket_memory += (((roundup_mtu + overhead)\n * packet_size_in_buffer) /\n (1024 * 1024))\n\n # For Non DPDK numa node\n if socket_memory == 0:\n socket_memory = minimum_socket_memory\n # For DPDK numa node\n else:\n socket_memory += 512\n\n socket_memory_in_gb = int(socket_memory / 1024)\n if socket_memory % 1024 > 0:\n socket_memory_in_gb += 1\n return (socket_memory_in_gb * 1024)\n\n\n# Gets the socket memory\ndef get_dpdk_socket_memory(client, dpdk_nics_numa_info, numa_nodes, minimum_socket_memory=1500):\n dpdk_socket_memory_list = []\n overhead = 800\n packet_size_in_buffer = 4096 * 64\n for node in numa_nodes:\n socket_mem = calculate_node_socket_memory(\n node, dpdk_nics_numa_info, overhead,\n packet_size_in_buffer,\n minimum_socket_memory)\n dpdk_socket_memory_list.append(socket_mem)\n\n return \"\\'\"+','.join([str(sm) for sm in dpdk_socket_memory_list])+\"\\'\"\n\n\n# Gets the installed osp release.\ndef get_osp_release(client):\n cmd = 'sudo cat /etc/rhosp-release | grep -v ^#'\n stdin, stdout, stderr = client.exec_command(cmd)\n output = str(stdout.read())\n if output:\n return output\n else:\n msg = \"Unable to determine 'OVS Version'\"\n raise Exception(msg)\n \n\n# Gets the CPU model\ndef get_cpu_model(client):\n cmd =\"sudo lscpu | grep 'Model name'\"\n stdin, stdout, stderr = client.exec_command(cmd)\n output = str(stdout.read())\n if output:\n return output.split(':')[1].strip(' \\n')\n else:\n msg = \"Unable to determine 'CPU Model name'\"\n raise Exception(msg)\n\n\n# Gets the tuned active profile\ndef get_tuned_active_profile(client):\n cmd =\"sudo tuned-adm active\"\n stdin, stdout, stderr = client.exec_command(cmd)\n output = str(stdout.read())\n if output:\n return output.split(':')[1].strip(' \\n')\n else:\n msg = \"Unable to determine tuned active profile\"\n raise Exception(msg)\n\n\n# Gets the CPU flages\ndef get_cpu_flags(client):\n cmd = \"sudo lscpu | grep 'Flags'\"\n stdin, stdout, stderr = client.exec_command(cmd)\n output = str(stdout.read())\n if output:\n return output.split(':')[1].strip(' \\n').split(' ')\n else:\n msg = \"Unable to determine 'CPU Flags'\"\n raise Exception(msg) \n\n\n# Derives kernel_args parameter\ndef get_kernel_args(client, hugepage_alloc_perc):\n kernel_args = {}\n cpu_flags = get_cpu_flags(client)\n if not is_supported_default_hugepages(cpu_flags):\n raise Exception(\"default huge page size 1GB is not supported\")\n\n total_memory = get_physical_memory(client)\n hugepages = int(float((total_memory / 1024) - 4) * (hugepage_alloc_perc / float(100)))\n iommu_info = ''\n cpu_model = get_cpu_model(client)\n if cpu_model.startswith('Intel'):\n kernel_args['intel_iommu'] = 'on'\n kernel_args['iommu'] = 'pt'\n kernel_args['default_hugepagesz'] = '1GB'\n kernel_args['hugepagesz'] = '1G'\n kernel_args['hugepages'] = str(hugepages)\n return kernel_args\n\n\n# Checks default 1GB hugepages support\ndef is_supported_default_hugepages(flags):\n return ('pdpe1gb' in flags)\n\n\n# Converts number format cpus into range format\ndef convert_number_to_range_list(num_list, array_format = False):\n num_list = [int(num.strip(' '))\n for num in num_list.split(\",\")]\n num_list.sort()\n range_list = []\n range_min = num_list[0]\n for num in num_list:\n next_val = num + 1\n if next_val not in num_list:\n if range_min != num:\n range_list.append(str(range_min) + '-' + str(num))\n else:\n range_list.append(str(range_min))\n next_index = num_list.index(num) + 1\n if next_index < len(num_list):\n range_min = num_list[next_index]\n\n if array_format:\n return '['+','.join([(\"\\'\"+thread+\"\\'\") for thread in range_list])+']'\n else:\n return ','.join(range_list)\n\n\n# Converts range format cpus into number list format\ndef convert_range_to_number_list(range_list):\n num_list = [] \n exclude_num_list = [] \n if isinstance(range_list, str):\n range_list = range_list.strip('[]').replace('\\'', '').replace(' ', '') \n if not isinstance(range_list, list): \n range_list = range_list.split(',') \n try: \n for val in range_list: \n val = val.strip(' ') \n if '^' in val: \n exclude_num_list.append(int(val[1:])) \n elif '-' in val: \n split_list = val.split(\"-\") \n range_min = int(split_list[0]) \n range_max = int(split_list[1]) \n num_list.extend(range(range_min, (range_max + 1))) \n else: \n num_list.append(int(val)) \n except ValueError as exc: \n err_msg = (\"Invalid number in input param \" \n \"'range_list': %s\" % exc) \n raise Exception(err_msg) \n \n # here, num_list is a list of integers \n return [num for num in num_list if num not in exclude_num_list]\n\n\n# gets the instance UUID by node UUID\ndef get_instance_uuid(node_uuid):\n instance_uuid = ''\n cmd = \"ironic --json node-list\"\n output = subprocess.check_output(cmd, shell=True)\n node_list = json.loads(output)\n for node in node_list:\n if node[\"uuid\"] == node_uuid:\n instance_uuid = node[\"instance_uuid\"] \n break\n return instance_uuid.strip()\n\n\n# gets the host ip address from instance UUID\ndef get_host_ip(instance_uuid):\n cmd = 'nova show ' + instance_uuid + ' | grep \"ctlplane network\"'\n output = subprocess.check_output(cmd, shell=True)\n host_ip = output.replace('ctlplane network', '').strip(' |\\n')\n return host_ip\n\n\n# returns whether containers based overcloud deployment.\ndef is_containers_based_deployment(client):\n containers_based_deployment = False\n cmd = 'ls -d /var/lib/kolla/config_files/'\n stdin, stdout, stderr = client.exec_command(cmd)\n if not str(stderr.read()):\n containers_based_deployment = True\n return containers_based_deployment\n\n\n# gets the PMD cpus from deployed env\ndef get_pmd_cpus_from_env(client):\n pmd_cpus_list = ''\n cmd = 'sudo ovs-vsctl --no-wait get Open_vSwitch . other_config:pmd-cpu-mask'\n stdin, stdout, stderr = client.exec_command(cmd)\n mask_val = str(stdout.read()).strip('\\\"\\n')\n if mask_val:\n pmd_cpus_list = get_cpus_list_from_mask_value(mask_val)\n return pmd_cpus_list\n\n\n# gets the PMD cpus from hiera data\ndef get_pmd_cpus_from_hiera(client, containers_based_dep):\n pmd_cpus_list = ''\n cmd = ''\n if containers_based_dep:\n cmd = 'sudo cat /etc/puppet/hieradata/service_configs.json'\n stdin, stdout, stderr = client.exec_command(cmd)\n hiera_json = json.loads(str(stdout.read()))\n pmd_cpus_list = hiera_json[\"vswitch::dpdk::pmd_core_list\"]\n if pmd_cpus_list:\n pmd_cpus_list = \"\\'\" + pmd_cpus_list + \"\\'\"\n else:\n cmd = 'sudo cat /etc/puppet/hieradata/service_configs.yaml | grep \"vswitch::dpdk::core_list\" | grep -v ^#'\n stdin, stdout, stderr = client.exec_command(cmd)\n pmd_cpus_list = str(stdout.read()).replace('vswitch::dpdk::core_list:', '').strip(' \\\"\\n')\n return pmd_cpus_list\n\n\n# gets the host cpus from deployed env\ndef get_host_cpus_from_env(client):\n host_cpus_list = ''\n cmd = 'sudo ovs-vsctl --no-wait get Open_vSwitch . other_config:dpdk-lcore-mask'\n stdin, stdout, stderr = client.exec_command(cmd)\n mask_val = str(stdout.read()).strip('\\\"\\n')\n if mask_val:\n host_cpus_list = get_cpus_list_from_mask_value(mask_val)\n return host_cpus_list\n \n\n# gets the DPDK socket memory from deployed env\ndef get_dpdk_socket_memory_from_env(client):\n dpdk_scoket_mem = ''\n cmd = 'sudo ovs-vsctl --no-wait get Open_vSwitch . other_config:dpdk-socket-mem'\n stdin, stdout, stderr = client.exec_command(cmd)\n dpdk_scoket_mem = str(stdout.read()).strip('\\\"\\n')\n return \"\\'\"+dpdk_scoket_mem+\"\\'\"\n\n\n# gets the DPDK socket memory from hiera data\ndef get_dpdk_socket_memory_from_hiera(client, containers_based_dep):\n dpdk_scoket_mem = ''\n cmd = ''\n if containers_based_dep:\n cmd = 'sudo cat /etc/puppet/hieradata/service_configs.json'\n stdin, stdout, stderr = client.exec_command(cmd)\n hiera_json = json.loads(str(stdout.read()))\n dpdk_scoket_mem = hiera_json[\"vswitch::dpdk::socket_mem\"]\n if dpdk_scoket_mem:\n dpdk_scoket_mem = \"\\'\" + dpdk_scoket_mem + \"\\'\"\n else:\n cmd = 'sudo cat /etc/puppet/hieradata/service_configs.yaml | grep \"vswitch::dpdk::socket_mem\" | grep -v ^#'\n stdin, stdout, stderr = client.exec_command(cmd)\n dpdk_scoket_mem = str(stdout.read()).replace('vswitch::dpdk::socket_mem:', '').strip(' \\n')\n return dpdk_scoket_mem\n\n\n# gets the nova reserved host memory from deployed env.\ndef get_nova_reserved_host_mem_from_env(client, containers_based_dep):\n nova_reserved_host_mem = 0\n cmd = 'sudo cat /etc/nova/nova.conf | grep \"reserved_host_memory_mb\" | grep -v ^#'\n if containers_based_dep:\n cmd = 'sudo cat /var/lib/config-data/nova_libvirt/etc/nova/nova.conf | grep \"reserved_host_memory_mb\" | grep -v ^#'\n stdin, stdout, stderr = client.exec_command(cmd)\n mem = str(stdout.read()).replace('reserved_host_memory_mb=', '').strip(' \\\"\\n')\n nova_reserved_host_mem = int(mem)\n return nova_reserved_host_mem\n\n\n# gets the nova reserved host memory from hiera.\ndef get_nova_reserved_host_mem_from_hiera(client, containers_based_dep):\n nova_reserved_host_mem = 0\n cmd = ''\n if containers_based_dep:\n cmd = 'sudo cat /etc/puppet/hieradata/service_configs.json'\n stdin, stdout, stderr = client.exec_command(cmd)\n hiera_json = json.loads(str(stdout.read()))\n nova_reserved_host_mem = hiera_json[\"nova::compute::reserved_host_memory\"]\n else:\n cmd = 'sudo cat /etc/puppet/hieradata/service_configs.yaml | grep \"nova::compute::reserved_host_memory\" | grep -v ^#' \n stdin, stdout, stderr = client.exec_command(cmd)\n mem = str(stdout.read()).replace('nova::compute::reserved_host_memory:', '').strip(' \\\"\\n')\n nova_reserved_host_mem = int(mem)\n return nova_reserved_host_mem\n\n\n# gets the nova cpus from deployed env\ndef get_nova_cpus_from_env(client, containers_based_dep):\n nova_cpus = ''\n cmd = 'sudo cat /etc/nova/nova.conf | grep \"vcpu_pin_set\" | grep -v ^#'\n if containers_based_dep:\n cmd = 'sudo cat /var/lib/config-data/nova_libvirt/etc/nova/nova.conf | grep \"vcpu_pin_set\" | grep -v ^#'\n stdin, stdout, stderr = client.exec_command(cmd)\n nova_cpus = str(stdout.read()).replace('vcpu_pin_set=', '').strip(' \\\"\\n')\n return nova_cpus\n\n\n# gets the nova cpus from hiera data\ndef get_nova_cpus_from_hiera(client, containers_based_dep):\n nova_cpus = ''\n cmd = ''\n if containers_based_dep:\n cmd = 'sudo cat /etc/puppet/hieradata/service_configs.json'\n stdin, stdout, stderr = client.exec_command(cmd)\n hiera_json = json.loads(str(stdout.read()))\n nova_cpus = hiera_json[\"nova::compute::vcpu_pin_set\"]\n if nova_cpus:\n if isinstance(nova_cpus, str):\n nova_cpus = str(nova_cpus)\n else:\n nova_cpus = str([str(nova_cpu) for nova_cpu in nova_cpus])\n else:\n cmd = 'sudo cat /etc/puppet/hieradata/service_configs.yaml | grep -v ^#'\n stdin, stdout, stderr = client.exec_command(cmd)\n for line in str(stdout.read()).split('\\n'):\n if 'nova::compute::vcpu_pin_set:' in line and '[' in line:\n nova_cpus = line.replace('nova::compute::vcpu_pin_set:', '').strip(' ')\n elif 'nova::compute::vcpu_pin_set:' in line and '[' not in line:\n nova_cpus = line.replace('nova::compute::vcpu_pin_set:', '').strip(' ')\n elif '[' in nova_cpus and ']' not in nova_cpus:\n nova_cpus += line.strip(' ')\n return nova_cpus\n\n\n# gets the host isolated cpus from deployed env.\ndef get_host_isolated_cpus_from_env(client):\n host_isolated_cpus = ''\n cmd ='sudo cat /etc/tuned/cpu-partitioning-variables.conf | grep \"isolated_cores\" | grep -v ^#'\n stdin, stdout, stderr = client.exec_command(cmd)\n output = str(stdout.read()).strip(' \\\"')\n for line in output.split('\\n'):\n if line.startswith('isolated_cores='):\n host_isolated_cpus = line.replace('isolated_cores=', '').strip(' \\\"\\n')\n return host_isolated_cpus\n\n\n# gets the DPDK memory channels from deployed env.\ndef get_dpdk_mem_channels_from_env(client):\n dpdk_mem_channels = '4'\n cmd = 'sudo ovs-vsctl --no-wait get Open_vSwitch . other_config:dpdk-extra'\n stdin, stdout, stderr = client.exec_command(cmd)\n output = str(stdout.read()).strip('\\\"\\n')\n if '-n' in output:\n extra_fields = output.split(' ')\n dpdk_mem_channels = extra_fields[extra_fields.index('-n')+1]\n return dpdk_mem_channels\n\n\n# gets the DPDK memory channels from hiera data.\ndef get_dpdk_mem_channels_from_hiera(client, containers_based_dep):\n dpdk_mem_channels = '4'\n cmd = ''\n if containers_based_dep:\n cmd = 'sudo cat /etc/puppet/hieradata/service_configs.json'\n stdin, stdout, stderr = client.exec_command(cmd)\n hiera_json = json.loads(str(stdout.read()))\n dpdk_mem_channels = hiera_json[\"vswitch::dpdk::memory_channels\"]\n if dpdk_mem_channels:\n dpdk_mem_channels = dpdk_mem_channels\n else:\n cmd = 'sudo cat /etc/puppet/hieradata/service_configs.yaml | grep \"vswitch::dpdk::memory_channels\" | grep -v ^#'\n stdin, stdout, stderr = client.exec_command(cmd)\n dpdk_mem_channels = str(stdout.read()).replace('vswitch::dpdk::memory_channels:', '').strip(' \\n')\n return '\\\"' +dpdk_mem_channels + '\\\"'\n\n\n# gets the kernel args from deployed env\ndef get_kernel_args_from_env(client, containers_based_dep):\n kernel_args = {}\n cmd = 'sudo cat /etc/default/grub | grep \"GRUB_CMDLINE_LINUX=\" | grep -v ^#'\n if containers_based_dep:\n cmd = 'sudo cat /etc/default/grub | grep \"TRIPLEO_HEAT_TEMPLATE_KERNEL_ARGS\" | grep -v ^#'\n stdin, stdout, stderr = client.exec_command(cmd)\n cmd_line = str(stdout.read()).replace('GRUB_CMDLINE_LINUX=', '').strip(' \\\"\\n')\n if cmd_line:\n cmd_args = cmd_line.split(' ')\n for arg in cmd_args:\n if ('hugepages' in arg or 'intel_iommu'in arg or \n 'iommu' in arg):\n boot_param = arg.split('=')\n kernel_args[boot_param[0]] = boot_param[1]\n return kernel_args\n\n\n# gets the kernel args from deployed env\ndef get_grub_update_status_from_env(client):\n grub_update_status = False\n cmd = 'sudo sudo cat /proc/cmdline | grep -v ^#'\n stdin, stdout, stderr = client.exec_command(cmd)\n cmd_line = str(stdout.read())\n if cmd_line:\n cmd_args = cmd_line.split(' ')\n for arg in cmd_args:\n if ('hugepages' in arg or 'intel_iommu'in arg or\n 'iommu' in arg):\n grub_update_status = True\n return grub_update_status\n\n\n# gets the cpus list from mask value\ndef get_cpus_list_from_mask_value(mask_val):\n cpus_list = []\n int_mask_val = int(mask_val, 16)\n bin_mask_val = bin(int_mask_val)\n bin_mask_val = str(bin_mask_val).replace('0b', '')\n rev_bin_mask_val = bin_mask_val[::-1] \n thread = 0\n for bin_val in rev_bin_mask_val:\n if bin_val == '1':\n cpus_list.append(thread)\n thread += 1\n return ','.join([str(thread) for thread in cpus_list])\n\n\n# gets the DPDK parameters value from deployed env\ndef get_parameters_value_from_env(client,\n containers_based_dep,\n host_ip):\n deployed_parameters = {}\n print('Collects the deployed value for parameters from node: %s' % host_ip)\n pmd_cpus_list = get_pmd_cpus_from_env(client)\n host_cpus_list = get_host_cpus_from_env(client)\n dpdk_socket_mem = get_dpdk_socket_memory_from_env(client)\n nova_reserved_host_mem = get_nova_reserved_host_mem_from_env(client,\n containers_based_dep)\n nova_cpus = get_nova_cpus_from_env(client, containers_based_dep)\n host_isolated_cpus = get_host_isolated_cpus_from_env(client)\n dpdk_mem_channels = get_dpdk_mem_channels_from_env(client)\n kernel_args = get_kernel_args_from_env(client, containers_based_dep)\n tuned = get_tuned_active_profile(client)\n deployed_parameters['NeutronDpdkCoreList'] = '\\'' + pmd_cpus_list + '\\''\n deployed_parameters['HostCpusList'] = '\\'' + host_cpus_list + '\\''\n deployed_parameters['NeutronDpdkSocketMemory'] = dpdk_socket_mem\n deployed_parameters['NeutronDpdkMemoryChannels'] = '\\\"' + dpdk_mem_channels +'\\\"'\n if not '[' in nova_cpus:\n nova_cpus = '\\'' + nova_cpus + '\\''\n deployed_parameters['NovaVcpuPinSet'] = nova_cpus\n deployed_parameters['NovaReservedHostMemory'] = nova_reserved_host_mem\n deployed_parameters['HostIsolatedCoreList'] = '\\'' + host_isolated_cpus + '\\''\n deployed_parameters['ComputeKernelArgs'] = kernel_args\n deployed_parameters['tuned'] = tuned\n return deployed_parameters\n\n\n# gets the DPDK parameters value from deployed env\ndef get_parameters_value_from_hiera(client, containers_based_dep, host_ip):\n hiera_parameters = {}\n print('Collects the hiera value for parameters from node: %s' % host_ip)\n pmd_cpus_list = get_pmd_cpus_from_hiera(client, containers_based_dep)\n dpdk_socket_mem = get_dpdk_socket_memory_from_hiera(client,\n containers_based_dep)\n nova_reserved_host_mem = get_nova_reserved_host_mem_from_hiera(client,\n containers_based_dep)\n nova_cpus = get_nova_cpus_from_hiera(client, containers_based_dep)\n dpdk_mem_channels = get_dpdk_mem_channels_from_hiera(client, containers_based_dep)\n hiera_parameters['NeutronDpdkCoreList'] = pmd_cpus_list\n hiera_parameters['NeutronDpdkSocketMemory'] = dpdk_socket_mem\n hiera_parameters['NeutronDpdkMemoryChannels'] = dpdk_mem_channels\n hiera_parameters['NovaVcpuPinSet'] = nova_cpus\n hiera_parameters['NovaReservedHostMemory'] = nova_reserved_host_mem\n return hiera_parameters\n\n\n# displays DPDK NICS NUMA info\ndef display_dpdk_nics_numa_info(cpus, dpdk_nics_info):\n print('DPDK NIC\\'s and NUMA node mapping:')\n for dpdk_nic in dpdk_nics_info:\n numa_node_cpus = []\n for cpu in cpus:\n if cpu['numa_node'] == dpdk_nic['numa_node']:\n numa_node_cpus.append(cpu['cpu'])\n print('NIC \\\"%(nic)s\\\": NUMA node %(node)d, '\n 'Physical CPU\\'s: %(node_cpus)s' % {\"nic\": dpdk_nic['nic'],\n \"node\": dpdk_nic['numa_node'],\n \"node_cpus\": sorted(numa_node_cpus)})\n print('')\n\n\n# Gets host cpus\ndef get_host_cpus_list(cpus):\n host_cpus_list = []\n numa_nodes_threads = {}\n # Creates a list for all available threads in each NUMA nodes\n for cpu in cpus:\n if not cpu['numa_node'] in numa_nodes_threads:\n numa_nodes_threads[cpu['numa_node']] = []\n numa_nodes_threads[cpu['numa_node']].extend(\n cpu['thread_siblings'])\n\n for numa_node in sorted(numa_nodes_threads.keys()):\n node = int(numa_node)\n # Gets least thread in NUMA node\n numa_node_min = min(numa_nodes_threads[numa_node])\n for cpu in cpus:\n if cpu['numa_node'] == node:\n # Adds threads from core which is having least thread\n if numa_node_min in cpu['thread_siblings']:\n host_cpus_list.extend(cpu['thread_siblings'])\n break\n\n return ','.join([str(thread) for thread in sorted(host_cpus_list)])\n\n\n# Gets the numa nodes list which are having DPDK NIC's\ndef get_dpdk_nics_numa_nodes(dpdk_nics_numa_info):\n dpdk_nics_numa_nodes = []\n for nics_info in dpdk_nics_numa_info:\n if nics_info['numa_node'] not in dpdk_nics_numa_nodes:\n dpdk_nics_numa_nodes.append(nics_info['numa_node'])\n return dpdk_nics_numa_nodes\n\n\n# Validation for DPDK core list (PMD cores)\ndef validate_dpdk_core_list(dict_cpus, dpdk_core_list, host_cpus,\n numa_nodes, dpdk_nics_numa_nodes, dpdk_nic_numa_cores_count):\n msg = ''\n dpdk_cores = []\n dpdk_cpus = dpdk_core_list.strip('\\\"\\' ').split(',')\n host_cpus = host_cpus.strip('\\\"\\' ').split(',')\n dup_host_cpus = []\n for dpdk_cpu in dpdk_cpus:\n if dpdk_cpu in host_cpus:\n dup_host_cpus.append(dpdk_cpu)\n for key, cpu in dict_cpus.items():\n if int(dpdk_cpu) in cpu['thread_siblings']:\n if key not in dpdk_cores:\n dpdk_cores.append(key)\n for thread in cpu['thread_siblings']:\n if str(thread) not in dpdk_cpus:\n msg += ('Missing thread siblings for thread: ' + dpdk_cpu + ' in PMD cores,'\n '\\n thread siblings: ' + str(cpu['thread_siblings'])+'.\\n')\n \n if dup_host_cpus:\n msg += 'Duplicated in host CPU\\'s: ' + str(dup_host_cpus) + '.\\n'\n if dpdk_cores:\n for node in numa_nodes:\n core_count = 0\n for dpdk_core in dpdk_cores:\n if node == dpdk_core[0]:\n core_count += 1\n if node in dpdk_nics_numa_nodes:\n if core_count < dpdk_nic_numa_cores_count:\n msg += ('Number of physical cores for DPDK NIC NUMA node('+ str(node) +') is less than'\n '\\n recommended cores \\'' + str(dpdk_nic_numa_cores_count) +'\\'.\\n')\n elif core_count > dpdk_nic_numa_cores_count:\n msg += ('Number of physical cores for DPDK NIC NUMA node('+ str(node) +') is greater'\n '\\n than recommended cores \\'' + str(dpdk_nic_numa_cores_count) +'\\'.\\n')\n else:\n if core_count == 0:\n msg += 'Missing physical cores for NUMA node: \\'' + str(node) + '\\' in PMD cores.\\n'\n if not msg:\n msg = 'valid.\\n'\n return msg\n\n\n# Validation for host cpus list\ndef validate_host_cpus(host_cpus_env, host_cpus):\n msg = 'expected: ' + host_cpus + '.\\n'\n if host_cpus.strip('\\'\"') == host_cpus_env.strip('\\'\"'):\n msg = 'valid.\\n'\n return msg\n\n\n# Validation for tuned status\ndef validate_tuned_status(tuned_profile_env):\n msg = 'expected: cpu-partitioning.\\n'\n if tuned_profile_env == 'cpu-partitioning':\n msg = 'enabled.\\n'\n return msg\n\n\n# Validation for DPDK socket memory\ndef validate_dpdk_socket_memory(dpdk_socket_memory_env, dpdk_socket_memory):\n msg = 'expected: ' + dpdk_socket_memory + '.\\n'\n if dpdk_socket_memory == dpdk_socket_memory_env:\n msg = 'valid.\\n'\n return msg\n\n\n# Validation for nova reserved host memory\ndef validate_nova_reserved_host_memory(nova_reserved_host_mem_env):\n host_mem = 4096\n msg = 'expected: ' + str(host_mem) + '.\\n'\n if nova_reserved_host_mem_env == host_mem:\n msg = 'valid.\\n'\n return msg\n\n\n# Validation for nova cpus\ndef validate_nova_cpus(dict_cpus, nova_cpus_env, dpdk_cpus_env, host_cpus, numa_nodes):\n msg = ''\n nova_cores = []\n nova_cpus = convert_range_to_number_list(nova_cpus_env)\n dpdk_cpus = dpdk_cpus_env.strip('\\\"\\' ').split(',')\n host_cpus = host_cpus.strip('\\\"\\' ').split(',')\n dup_dpdk_cpus = []\n dup_host_cpus = []\n for nova_cpu in nova_cpus:\n if str(nova_cpu) in host_cpus:\n dup_host_cpus.append(nova_cpu)\n if str(nova_cpu) in dpdk_cpus:\n dup_dpdk_cpus.append(nova_cpu)\n for key, cpu in dict_cpus.items():\n if nova_cpu in cpu['thread_siblings']:\n if key not in nova_cores:\n nova_cores.append(key)\n for thread in cpu['thread_siblings']:\n if thread not in nova_cpus:\n msg += ('Missing thread siblings for thread: ' + str(nova_cpu) + ' in nova cpus,'\n '\\n thread siblings: ' + str(cpu['thread_siblings'])+'.\\n')\n\n if dup_host_cpus:\n msg += 'Duplicated physical cores in host CPU\\'s: ' + str(dup_host_cpus) + '.\\n'\n if dup_dpdk_cpus:\n msg += 'Duplicated physical cores in PMD cores: ' + str(dup_dpdk_cpus) + '.\\n'\n if nova_cores:\n for node in numa_nodes:\n core_count = 0\n for nova_core in nova_cores:\n if node == nova_core[0]:\n core_count += 1\n if core_count == 0:\n msg += 'Missing physical cores for NUMA node: \\'' + str(node) + '\\' in nova cpus.\\n'\n if not msg:\n msg = 'valid.\\n'\n return msg\n\n\n# Validation for host isolated cpus\ndef validate_isol_cpus(dict_cpus, isol_cpus_env, host_cpus, numa_nodes):\n msg = ''\n isol_cores = []\n if not isol_cpus_env.strip('\"\\''):\n msg = 'Missing host isolated cpus.\\n'\n return msg\n\n isol_cpus = convert_range_to_number_list(isol_cpus_env)\n host_cpus = host_cpus.strip('\\\"\\' ').split(',')\n dup_host_cpus = []\n for isol_cpu in isol_cpus:\n if str(isol_cpu) in host_cpus:\n dup_host_cpus.append(isol_cpu)\n for key, cpu in dict_cpus.items():\n if isol_cpu in cpu['thread_siblings']:\n if key not in isol_cores:\n isol_cores.append(key)\n for thread in cpu['thread_siblings']:\n if thread not in isol_cpus:\n msg += ('Missing thread siblings for thread: ' + str(isol_cpu) + ' in host isolated cpus,'\n '\\n thread siblings: ' + str(cpu['thread_siblings'])+'.\\n')\n\n if dup_host_cpus:\n msg += 'Duplicated in host CPU\\'s: ' + str(dup_host_cpus) + '.\\n'\n if isol_cores:\n for node in numa_nodes:\n core_count = 0\n for isol_core in isol_cores:\n if node == isol_core[0]:\n core_count += 1\n if core_count == 0:\n msg += 'Missing physical cores for NUMA node: \\'' + str(node) + '\\' in host isolated cpus.\\n'\n if not msg:\n msg = 'valid.\\n'\n return msg\n\n\n# Validation for kernel args\ndef validate_kernel_args(deployed_kernel_args, derived_kernel_args, grub_update_status):\n msg = ('expected: default_hugepagesz=' + derived_kernel_args['default_hugepagesz'] +\n '\\n hugepages='+ derived_kernel_args['hugepagesz'] +\n '\\n hugepages=' + derived_kernel_args['hugepages'] +\n '\\n intel_iommu=' + derived_kernel_args['intel_iommu'] + \n '\\n iommu=' + derived_kernel_args['iommu'] + '\\n')\n if (derived_kernel_args['intel_iommu'] == deployed_kernel_args['intel_iommu'] and\n derived_kernel_args['default_hugepagesz'] == deployed_kernel_args['default_hugepagesz'] and\n derived_kernel_args['hugepagesz'] == deployed_kernel_args['hugepagesz'] and\n derived_kernel_args['hugepages'] == deployed_kernel_args['hugepages']):\n msg = \"valid.\\n\"\n if not grub_update_status:\n msg += \"node is not restarted.\\n\"\n return msg\n\n# Gets osp parameters name in different osp releases.\ndef get_osp_params_name(client):\n osp_params = {}\n osp_release = get_osp_release(client)\n if ('10' in osp_release or '11' in osp_release):\n osp_params['dpdk_cpus'] = 'NeutronDpdkCoreList'\n osp_params['socket_mem'] = 'NeutronDpdkSocketMemory'\n osp_params['isol_cpus'] = 'HostIsolatedCoreList'\n osp_params['mem_channels'] = 'NeutronDpdkMemoryChannels'\n osp_params['kernel_args'] = 'ComputeKernelArgs'\n else:\n osp_params['dpdk_cpus'] = 'OvsPmdCoreList'\n osp_params['socket_mem'] = 'OvsDpdkSocketMemory'\n osp_params['isol_cpus'] = 'IsolCpusList'\n osp_params['mem_channels'] = 'OvsDpdkMemoryChannels'\n osp_params['kernel_args'] = 'KernelArgs'\n return osp_params\n\n\n# Validates the DPDK parameters\ndef validate_dpdk_parameters(client, deployed, hiera, node_uuid, dpdk_nic_numa_cores_count,\n hugepage_alloc_perc):\n messages = {}\n osp_params = get_osp_params_name(client)\n\n dict_cpus = get_nodes_cores_info(client)\n cpus = list(dict_cpus.values())\n dpdk_nics_numa_info = get_dpdk_nics_info(client)\n display_dpdk_nics_numa_info(cpus, dpdk_nics_numa_info)\n numa_nodes = get_numa_nodes(client)\n dpdk_nics_numa_nodes = get_dpdk_nics_numa_nodes(dpdk_nics_numa_info)\n host_cpus = get_host_cpus_list(cpus)\n messages['host_cpus'] = validate_host_cpus(deployed['HostCpusList'], host_cpus)\n messages['dpdk_cpus'] = validate_dpdk_core_list(dict_cpus, deployed['NeutronDpdkCoreList'], host_cpus,\n numa_nodes, dpdk_nics_numa_nodes, dpdk_nic_numa_cores_count)\n dpdk_socket_memory = get_dpdk_socket_memory(client, dpdk_nics_numa_info, numa_nodes)\n messages['socket_mem'] = validate_dpdk_socket_memory(deployed['NeutronDpdkSocketMemory'],\n dpdk_socket_memory)\n messages['reserved_host_mem'] = validate_nova_reserved_host_memory(deployed['NovaReservedHostMemory'])\n messages['nova_cpus'] = validate_nova_cpus(dict_cpus, deployed['NovaVcpuPinSet'],\n deployed['NeutronDpdkCoreList'], host_cpus, numa_nodes) \n messages['isol_cpus'] = validate_isol_cpus(dict_cpus, deployed['HostIsolatedCoreList'], host_cpus, numa_nodes)\n derived_kernel_args = get_kernel_args(client, hugepage_alloc_perc)\n grub_update_status = get_grub_update_status_from_env(client)\n messages['kernel_args'] = validate_kernel_args(deployed['ComputeKernelArgs'],\n derived_kernel_args,\n grub_update_status)\n messages['tuned'] = validate_tuned_status(deployed['tuned'])\n validation_messages(deployed, hiera, osp_params, messages)\n\n\n# Displays validation messages\ndef validation_messages(deployed, hiera, osp_params, messages):\n t = PrettyTable(['Parameters', 'Deployment Value', 'Hiera Data', 'Validation Messages'])\n t.align[\"Parameters\"] = \"l\"\n t.align[\"Deployment Value\"] = \"l\"\n t.align[\"Hiera Data\"] =\"l\"\n t.align[\"Validation Messages\"] = \"l\"\n t.add_row(['HostCpusList', deployed['HostCpusList'], 'NA', messages['host_cpus']]) \n t.add_row([osp_params['dpdk_cpus'], deployed['NeutronDpdkCoreList'], hiera['NeutronDpdkCoreList'], messages['dpdk_cpus']])\n t.add_row([osp_params['socket_mem'], deployed['NeutronDpdkSocketMemory'], hiera['NeutronDpdkSocketMemory'], messages['socket_mem']])\n t.add_row(['NovaReservedHostMemory', deployed['NovaReservedHostMemory'], hiera['NovaReservedHostMemory'], messages['reserved_host_mem']])\n t.add_row(['NovaVcpuPinSet', deployed['NovaVcpuPinSet'], hiera['NovaVcpuPinSet'], messages['nova_cpus']])\n t.add_row([osp_params['isol_cpus'], deployed['HostIsolatedCoreList'], 'NA', messages['isol_cpus']])\n deployed_kernel_args = deployed['ComputeKernelArgs']\n kernel_args = ('default_hugepagesz=' + deployed_kernel_args['default_hugepagesz'] + '\\n'+\n ' hugepages='+ deployed_kernel_args['hugepagesz'] + '\\n' +\n ' hugepages=' + deployed_kernel_args['hugepages'] + '\\n' +\n ' intel_iommu='+ deployed_kernel_args['intel_iommu'])\n t.add_row([osp_params['kernel_args'], kernel_args, 'NA', messages['kernel_args']])\n mem_channels_msg = 'Recommended value is \"4\" but it should be configured based on hardware spec.\\n'\n t.add_row([osp_params['mem_channels'], deployed['NeutronDpdkMemoryChannels'], hiera['NeutronDpdkMemoryChannels'], mem_channels_msg])\n t.add_row(['tuned', deployed['tuned'], 'NA', messages['tuned']])\n print(t)\n\n\n# Gets environment parameters value and validates.\ndef validate():\n try:\n opts = parse_opts(sys.argv)\n print(\"Validating user inputs..\")\n validate_user_input(opts)\n dpdk_nic_numa_cores_count = int(opts.num_phy_cores_per_numa_node_for_pmd)\n hugepage_alloc_perc = float(opts.huge_page_allocation_percentage)\n flavor = get_flavor_name(opts.role_name)\n node_uuid = get_node_uuid(flavor)\n instance_uuid = get_instance_uuid(node_uuid)\n host_ip = get_host_ip(instance_uuid)\n # SSH access\n client = paramiko.SSHClient()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n client.load_system_host_keys()\n client.connect(host_ip, username='heat-admin')\n client.invoke_shell()\n containers_based_dep = is_containers_based_deployment(client)\n deployed = get_parameters_value_from_env(client,\n containers_based_dep,\n host_ip)\n hiera = get_parameters_value_from_hiera(client,\n containers_based_dep,\n host_ip)\n validate_dpdk_parameters(client, deployed, hiera, node_uuid, \n dpdk_nic_numa_cores_count, hugepage_alloc_perc)\n client.close()\n except Exception as exc:\n print(\"Error: %s\" % exc)\n\n\n# Validates the user inputs\ndef validate_user_input(inputs):\n print(json.dumps({\"role_name\": inputs.role_name,\n \"num_phy_cores_per_numa_node_for_pmd\": int(inputs.num_phy_cores_per_numa_node_for_pmd),\n \"huge_page_allocation_percentage\":int( inputs.huge_page_allocation_percentage)}))\n if not inputs.role_name:\n raise Exception(\"Role name is missing in user input!\");\n\n\n# Gets the user input as dictionary.\ndef parse_opts(argv):\n parser = argparse.ArgumentParser(\n description='Interactive tool')\n parser.add_argument('-r', '--role_name',\n metavar='ROLE NAME',\n help=\"\"\"role name.\"\"\",\n default='')\n parser.add_argument('-n', '--num_phy_cores_per_numa_node_for_pmd',\n metavar='NUMBER OF PHYSICAL CORES PER NUMA FOR PMD',\n help=\"\"\"number of physical cores per numa node for pmd.\"\"\",\n default=1)\n parser.add_argument('-m', '--huge_page_allocation_percentage',\n metavar='HUGEPAGE ALLOCATION PERCENTAGE',\n help=\"\"\"hugepage allocation percentage\"\"\",\n default=50)\n opts = parser.parse_args(argv[1:])\n return opts\n\n\nif __name__ == '__main__':\n validate()\n","sub_path":"post-deployment-validation/DPDK-Parameters/validate_dpdk_params.py","file_name":"validate_dpdk_params.py","file_ext":"py","file_size_in_byte":42570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"254222059","text":"\"\"\"\nLogic for dashboard related routes\n\"\"\"\nfrom flask import Blueprint, render_template\nfrom .forms import LogUserForm, secti,masoform,vstupnitestform\nfrom ..data.database import db\nfrom ..data.models import LogUser\nblueprint = Blueprint('public', __name__)\n\n@blueprint.route('/', methods=['GET'])\ndef index():\n return render_template('public/index.tmpl')\n\n@blueprint.route('/loguserinput',methods=['GET', 'POST'])\ndef InsertLogUser():\n form = LogUserForm()\n if form.validate_on_submit():\n LogUser.create(**form.data)\n return render_template(\"public/LogUser.tmpl\", form=form)\n\n@blueprint.route('/loguserlist',methods=['GET'])\ndef ListuserLog():\n pole = db.session.query(LogUser).all()\n return render_template(\"public/listuser.tmpl\",data = pole)\n\n@blueprint.route('/secti', methods=['GET','POST'])\ndef scitani():\n form = secti()\n if form.validate_on_submit():\n return render_template('public/vystup.tmpl',hod1=form.hodnota1.data,hod2=form.hodnota2.data,suma=form.hodnota1.data+form.hodnota2.data)\n return render_template('public/secti.tmpl', form=form)\n\n@blueprint.route('/maso', methods=['GET','POST'])\ndef masof():\n form = masoform()\n if form.validate_on_submit():\n return render_template('public/masovystup.tmpl',hod1=form.hodnota1.data,hod2=form.hodnota2.data,suma=form.hodnota1.data+form.hodnota2.data)\n return render_template('public/maso.tmpl', form=form)\n\n@blueprint.route('/vstupni_test', methods=['GET','POST'])\ndef vstupnitest():\n from ..data.models import Vysledky\n from flask import flash\n form = vstupnitestform()\n if form.validate_on_submit():\n vysledek=0\n if form.otazka1.data ==2:\n vysledek=vysledek+1\n if form.otazka2.data ==0:\n vysledek=vysledek+1\n if form.otazka3.data.upper() == \"ELEPHANT\":\n vysledek=vysledek+1\n i = Vysledky(username=form.Jmeno.data,hodnoceni=vysledek)\n db.session.add(i)\n db.session.commit()\n flash(\"Vysledek ulozen\", category=\"Error\")\n dotaz = db.session.query(Vysledky.username, Vysledky.hodnoceni).all()\n return render_template('public/vysledekvystup.tmpl',data=dotaz)\n return render_template('public/vstupnitest.tmpl', form=form)\n","sub_path":"src/public/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"79741164","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport json\nimport seaborn as sns\n\n# This function is used to read all the data needed for ploting the indicator data\ndef read_eveything(indicator_path, indicator=True):\n parties = pd.read_csv(\"data/country_party_dataset.csv\", index_col=0)\n positions = pd.read_csv(\"data/positions_scale.csv\")\n\n positions_sorted = ['far-left', 'left-wing to far-left', 'left-wing', 'centre-left to left-wing', 'centre-left', \\\n 'centre to centre-left', 'centre', 'syncretic', 'big tent', 'centre to centre-right', \\\n 'centre-right', 'centre-right to right-wing', 'right-wing', 'right-wing to far-right', \\\n 'far-right']\n\n parties = pd.merge(parties, positions, left_on=[\"Political_position\"], right_on=[\"Position\"])\n\n parties[\"weighted_seats_last\"] = (parties[\"Seats %_last\"]/100)*parties[\"Scale\"]\n parties[\"weighted_seats_previous\"] = (parties[\"Seats %_previous\"]/100)*parties[\"Scale\"]\n\n parties[\"weighted_votes_last\"] = (parties[\"Votes %_last\"]/100)*parties[\"Scale\"]\n parties[\"weighted_votes_previous\"] = (parties[\"Votes %_previous\"]/100)*parties[\"Scale\"]\n\n parties = parties.groupby(\"Country\").sum()\n\n parties[\"difference_seats\"] = parties[\"weighted_seats_last\"] - parties[\"weighted_seats_previous\"]\n parties[\"difference_votes\"] = parties[\"weighted_votes_last\"] - parties[\"weighted_votes_previous\"]\n\n parties = parties.reset_index()\n \n \n election_years = pd.read_csv('data/election_years.csv')\n # because the indicators don't contain data for 2018\n election_years[\"prev_el_year\"] = election_years[\"prev_el_year\"].apply(lambda x: x-1 if x == 2018 else x)\n election_years[\"last_el_year\"] = election_years[\"last_el_year\"].apply(lambda x: x-1 if x == 2018 else x)\n \n \n if indicator:\n indicator = pd.read_csv(indicator_path, header=2, sep=',')\n else:\n indicator = pd.read_csv(indicator_path, sep=',')\n # The indicators don't contain data for 2007, but we don't need it\n indicator[\"2007\"] = indicator[\"2008\"]\n\n indicator[\"Country Name\"] = indicator[\"Country Name\"].replace(\"Slovak Republic\", \"Slovakia\")\n\n # countries and features of interest\n countries = ['Austria','Belgium','Bulgaria','Croatia','Cyprus','Czech Republic','Denmark',\n 'Estonia','Finland','France','Germany','Greece','Hungary','Ireland','Italy','Latvia','Lithuania',\n 'Luxembourg','Malta','Netherlands','Poland','Portugal','Romania','Slovakia','Slovenia','Spain',\n 'Sweden','United Kingdom','Norway','Iceland','Switzerland']\n columns = ['Country Name','Country Code','2007','2008','2009','2010','2011','2012','2013','2014','2015','2016','2017']\n\n # extract only countries of interest\n indicator = indicator.loc[indicator['Country Name'].isin(countries)]\n\n # reset index\n indicator.reset_index(inplace=True)\n\n # extract only features of interest\n indicator = indicator[columns]\n\n indicator = indicator.drop(['Country Code'], axis=1)\n\n indicator = pd.melt(indicator, id_vars=['Country Name'])\n\n indicator[\"variable\"] = indicator[\"variable\"].astype(int)\n indicator[\"value\"] = indicator[\"value\"].astype(float)\n \n \n elections_indicator = pd.merge(election_years, indicator, left_on=['Country', 'prev_el_year'], right_on=['Country Name', 'variable'])\n elections_indicator = elections_indicator.rename(columns={\"value\": \"value_previous\"})\n elections_indicator = pd.merge(elections_indicator, indicator, left_on=['Country', 'last_el_year'], right_on=['Country Name', 'variable'])\n elections_indicator = elections_indicator.rename(columns={\"value\": \"value_last\"})\n elections_indicator = elections_indicator.drop([\"variable_x\", \"variable_y\", \"Country Name_x\", \"Country Name_y\"], axis=1)\n elections_indicator[\"difference_value\"] = elections_indicator['value_last'] - elections_indicator['value_previous']\n \n \n return elections_indicator, parties\n\n# This function plots a regression plot for visualizing the indicator data\ndef plot_everything(elections_indicator, parties, column_x, column_y, hide_germany=False, only_right=False, params={}):\n plt.style.use('seaborn-poster')\n merged = pd.merge(elections_indicator, parties)\n if hide_germany:\n merged = merged[merged['Country'] != 'Germany']\n #merged = merged[merged['Country'] != 'France']\n if only_right:\n merged = merged[merged[column_x] > 0]\n \n plt.subplots(figsize=(10,6)) \n sns.regplot(x=column_x, y=column_y, data=merged)\n if \"x_label\" in params.keys():\n plt.xlabel(params[\"x_label\"])\n if \"y_label\" in params.keys():\n plt.ylabel(params[\"y_label\"])\n if \"title\" in params.keys():\n plt.title(params[\"title\"])\n if \"save_2\" in params.keys():\n plt.savefig(params[\"save_2\"], bbox_inches=\"tight\", dpi=200)\n plt.show()\n \n merged = merged[[column_x, column_y]]\n print(merged.corr('spearman'))\n print(\"\\nData for %s countires\" % merged.dropna().shape[0])\n","sub_path":"processing_indicators.py","file_name":"processing_indicators.py","file_ext":"py","file_size_in_byte":5086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"420147743","text":"\"\"\"Provides interface to CIMAGE.\"\"\"\nimport pathlib\nimport requests\nimport subprocess\nimport shutil\n\n\ndef quantify(name, dta_link, experiment_type, path):\n dta_paths = setup_dta_folders(name, path, dta_link)\n params_path = str(_get_params_path(experiment_type))\n\n normal_search = cimage(params_path, dta_paths['lh'], hl_flag=False)\n inverse_search = cimage(params_path, name, dta_paths['hl'], hl_flag=True)\n\n if normal_search == 0 and inverse_search == 0:\n return (\n combine(path, experiment_type) == 0 and\n combine(path, experiment_type, dta_folder='dta_HL') == 0\n )\n else:\n return False\n\n\ndef cimage(params_path, dta_file_path, name, hl_flag):\n subprocess.Popen([\n 'cimage2',\n params_path,\n name\n ], cwd=dta_file_path).wait()\n\n\ndef combine(path, experiment_type, dta_folder='dta'):\n args = [\n 'cimage_combine',\n 'output_rt_10_sn_2.5.to_excel.txt',\n dta_folder\n ]\n\n if experiment_type is not 'isotop':\n args.insert(1, 'by_protein')\n\n return subprocess.Popen(args, cwd=str(path)).wait()\n\n\ndef setup_dta_folders(name, path, dta_link):\n # download dta results\n # yes, this is a publicly accessible url. lol.\n r = requests.get(dta_link)\n dta_content = r.text\n\n dta_path = path.joinpath('dta')\n dta_path.mkdir()\n\n # duplicate dta file for cimage\n dta_hl_path = path.joinpath('dta_HL')\n dta_hl_path.mkdir()\n\n dta_file_path = dta_path.joinpath('DTASelect-filter_{}_foo.txt'.format(name))\n\n # write data file to disk for regular L/H cimage run\n with dta_file_path.open('w') as f:\n f.write(dta_content)\n\n # copy over for H/L run\n shutil.copy(str(dta_file_path), str(dta_hl_path))\n\n return {\n 'lh': str(dta_path),\n 'hl': str(dta_hl_path)\n }\n\n\ndef _get_params_path(experiment_type):\n return pathlib.Path(\n 'static', 'cimage_params', experiment_type\n ).with_suffix('.params').resolve()\n","sub_path":"cravattdb/auto/quantify.py","file_name":"quantify.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"591084657","text":"import sqlite3\nfrom hashlib import sha256\nfrom urllib.request import urlopen\nimport urllib.parse\nfrom math import floor\n\n\nclass Database(object):\n\tdatabase_uri = None\n\n\tdef __init__(self, database_uri):\n\t\tself.database_uri = database_uri\n\n\tdef account_exists(self, username):\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tc.execute('''\n\t\t\tSELECT * FROM Accounts WHERE username = ?;\n\t\t''', (username,))\n\n\t\tresult = c.fetchone()\n\n\t\tconn.commit()\n\t\tconn.close()\n\n\t\treturn result is not None\n\n\tdef address_is_valid(self, address): # pragma: no cover\n\t\trequest_xml = f'''\n\t\t\t\n\t\t\t\n\t\t\t\t1\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t\t{address[\"street\"]}\n\t\t\t\t\t{address[\"city\"]}\n\t\t\t\t\t{address[\"state\"]}\n\t\t\t\t\t{address[\"zip\"]}\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t
\n\t\t'''\n\n\t\tapi_endpoint = \"http://production.shippingapis.com/ShippingAPI.dll?API=Verify&XML=\"\n\n\t\twith urlopen(api_endpoint + urllib.parse.quote(request_xml)) as response:\n\t\t\tresponse_xml = response.read().decode().upper()\n\n\t\t\tif \"\" in response_xml:\n\t\t\t\treturn False\n\t\t\telif f'{address[\"street\"]}'.upper() not in response_xml:\n\t\t\t\treturn False\n\t\t\telif f'{address[\"city\"]}'.upper() not in response_xml:\n\t\t\t\treturn False\n\t\t\telif f'{address[\"state\"]}'.upper() not in response_xml:\n\t\t\t\treturn False\n\t\t\telif f'{address[\"zip\"]}'.upper() not in response_xml:\n\t\t\t\treturn False\n\t\t\telse:\n\t\t\t\treturn True\n\n\tdef find_credentials(self, credentials):\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tusername = credentials.get(\"username\")\n\t\tpassword = sha256(credentials.get(\"password\").encode()).hexdigest()\n\n\t\tc.execute('''\n\t\t\tSELECT * FROM Accounts WHERE username = ? and password = ?;\n\t\t''', (username, password,))\n\n\t\tresult = c.fetchone()\n\n\t\tconn.commit()\n\t\tconn.close()\n\n\t\treturn result is not None\n\n\tdef get_role(self, username):\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tc.execute('''\n\t\t\tSELECT * FROM Admins\n\t\t\tJOIN Accounts\n\t\t\tON Admins.accountID = Accounts.accountID\n\t\t\tWHERE username = ?;\n\t\t''', (username,))\n\n\t\tif c.fetchone() is not None:\n\t\t\tconn.commit()\n\t\t\tconn.close()\n\t\t\treturn \"admin\"\n\t\telse:\n\t\t\tconn.commit()\n\t\t\tconn.close()\n\t\t\treturn \"customer\"\n\n\tdef get_products(self):\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tc.execute('''\n\t\t\tSELECT * FROM Products;\n\t\t''')\n\n\t\tcolumn_names = next(zip(*c.description))\n\t\tproduct_rows = c.fetchall()\n\n\t\tproducts = [dict(zip(column_names, product_values)) for product_values in product_rows]\n\n\t\tconn.commit()\n\t\tconn.close()\n\n\t\treturn products\n\n\tdef get_categories(self):\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tc.execute('''\n\t\t\tSELECT * FROM Categories;\n\t\t''')\n\n\t\tcolumn_names = next(zip(*c.description))\n\t\tcategory_rows = c.fetchall()\n\n\t\tcategories = [dict(zip(column_names, category_values)) for category_values in category_rows]\n\n\t\tconn.commit()\n\t\tconn.close()\n\n\t\treturn categories\n\n\tdef get_all_orders(self): # pragma: no cover\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tc.execute('''\n\t\t\tSELECT Accounts.username, Orders.*\n\t\t\tFROM Orders, Accounts\n\t\t\tWHERE Orders.accountID == Accounts.accountID;\n\t\t''',)\n\n\t\tcolumn_names = next(zip(*c.description))\n\t\torder_rows = c.fetchall()\n\n\t\torders = [dict(zip(column_names, order_values)) for order_values in order_rows]\n\n\t\torder_ids = [order[\"orderID\"] for order in orders]\n\n\t\tfor index, order_id in enumerate(order_ids):\n\t\t\tc.execute('''\n\t\t\t\tSELECT *\n\t\t\t\tFROM OrderDetails\n\t\t\t\tWHERE orderID = ?;\n\t\t\t''', (order_id,))\n\n\t\t\titem_column_names = next(zip(*c.description))\n\t\t\titem_rows = c.fetchall()\n\n\t\t\titems = [dict(zip(item_column_names, item_values)) for item_values in item_rows]\n\n\t\t\torders[index][\"items\"] = items\n\n\t\tconn.commit()\n\t\tconn.close()\n\t\treturn orders\n\n\tdef get_user_orders(self, username):\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tc.execute('''\n\t\t\tSELECT *\n\t\t\tFROM Orders\n\t\t\tWHERE accountID = (SELECT accountID\n\t\t\t\tFROM Accounts\n\t\t\t\tWHERE username = ?);\n\t\t''', (username,))\n\n\t\tcolumn_names = next(zip(*c.description))\n\t\torder_rows = c.fetchall()\n\n\t\torders = [dict(zip(column_names, order_values)) for order_values in order_rows]\n\n\t\torder_ids = [order[\"orderID\"] for order in orders]\n\n\t\tfor index, order_id in enumerate(order_ids):\n\t\t\tc.execute('''\n\t\t\t\tSELECT *\n\t\t\t\tFROM OrderDetails\n\t\t\t\tWHERE orderID = ?;\n\t\t\t''', (order_id,))\n\n\t\t\titem_column_names = next(zip(*c.description))\n\t\t\titem_rows = c.fetchall()\n\n\t\t\titems = [dict(zip(item_column_names, item_values)) for item_values in item_rows]\n\n\t\t\torders[index][\"items\"] = items\n\n\t\tconn.commit()\n\t\tconn.close()\n\t\treturn orders\n\n\tdef add_category(self, category_name):\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tc.execute('''\n\t\t\tINSERT INTO Categories(categoryName)\n\t\t\tVALUES(?);\n\t\t''', (category_name,))\n\n\t\tconn.commit()\n\t\tconn.close()\n\n\tdef add_product(self, product):\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tproduct_details = [\n\t\t\tproduct.get(\"categoryID\"),\n\t\t\tproduct.get(\"name\"),\n\t\t\tproduct.get(\"description\"),\n\t\t\tproduct.get(\"imageURL\"),\n\t\t\tproduct.get(\"price\"),\n\t\t\tproduct.get(\"quantityAvailable\"),\n\t\t]\n\n\t\t# TODO verify category id exists\n\n\t\tc.execute('''\n\t\t\tINSERT INTO Products(\n\t\t\tcategoryID,\n\t\t\tname,\n\t\t\tdescription,\n\t\t\timageURL,\n\t\t\tprice,\n\t\t\tquantityAvailable\n\t\t\t)\n\t\t\tVALUES(?,?,?,?,?,?);\n\t\t''', product_details)\n\n\t\tconn.commit()\n\t\tconn.close()\n\n\t# TODO this whole function could probably be enhanced/made more efficient using some more advanced sql\n\tdef add_order(self, order):\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tusername = order[\"username\"]\n\n\t\tc.execute('''\n\t\t\tSELECT accountID FROM Accounts WHERE username = ?;\n\t\t''', (username,))\n\n\t\taccount_id = c.fetchone()\n\n\t\tc.execute('''\n\t\t\tSELECT\n\t\t\tbillingAddress,\n\t\t\tbillingCity,\n\t\t\tbillingState,\n\t\t\tbillingPostalCode,\n\t\t\tshippingAddress,\n\t\t\tshippingCity,\n\t\t\tshippingState,\n\t\t\tshippingPostalCode\n\t\t\tFROM Customers WHERE accountID = ?;\n\t\t''', account_id)\n\n\t\taccount_shipping_and_billing = (\n\t\t\torder.get(\"street\"),\n\t\t\torder.get(\"city\"),\n\t\t\torder.get(\"state\"),\n\t\t\torder.get(\"zip\"),\n\t\t\torder.get(\"street\"),\n\t\t\torder.get(\"city\"),\n\t\t\torder.get(\"state\"),\n\t\t\torder.get(\"zip\"),\n\t\t)\n\n\t\taccount_details = (account_id + account_shipping_and_billing)\n\n\t\t# TODO verify user billingAddress and shippingAddress exist\n\n\t\t# TODO verify each product exists and that there is enough to fulfill order\n\n\t\t# create order entry\n\t\tc.execute('''\n\t\t\tINSERT INTO Orders\n\t\t\t(\n\t\t\t\taccountID,\n\t\t\t\tdateOrdered,\n\t\t\t\tbillingAddress,\n\t\t\t\tbillingCity,\n\t\t\t\tbillingState,\n\t\t\t\tbillingPostalCode,\n\t\t\t\tshippingAddress,\n\t\t\t\tshippingCity,\n\t\t\t\tshippingState,\n\t\t\t\tshippingPostalCode,\n\t\t\t\ttaxCost,\n\t\t\t\tshippingCost,\n\t\t\t\ttotalCost\n\t\t\t)\n\t\t\tVALUES (?, DATETIME(\"now\"), ?, ?, ?, ?, ?, ?, ?, ?, 0, 0, 0);\n\t\t''', account_details)\n\n\t\torder_id = c.lastrowid\n\n\t\torderDetails = [\n\t\t\t(order_id, orderDetail[\"quantity\"], orderDetail[\"productID\"])\n\t\t\tfor orderDetail in order[\"orderDetails\"]\n\t\t]\n\n\t\t# add orderlines\n\t\tc.executemany('''\n\t\t\tINSERT INTO OrderDetails\n\t\t\t(\n\t\t\torderID,\n\t\t\tproductID,\n\t\t\tname,\n\t\t\tdescription,\n\t\t\tprice,\n\t\t\tquantity\n\t\t\t)\n\t\t\tSELECT ?, productID, name, description, price, ?\n\t\t\tFROM Products WHERE productID = ?;\n\t\t\t''', orderDetails)\n\n\t\t# update order price info\n\t\t# get sum of price of all products in order\n\t\tc.execute('''\n\t\t\tSELECT SUM(price * quantity)\n\t\t\tFROM OrderDetails\n\t\t\tWHERE orderID = ?;\n\t\t''', (order_id,))\n\n\t\torder_product_sum = c.fetchone()[0]\n\n\t\ttax_rate = 0.0825\n\n\t\ttax_cost = floor(order_product_sum * tax_rate)\n\n\t\ttotal_cost = floor(order_product_sum + tax_cost)\n\n\t\tshipping_cost = 0 # free shipping\n\n\t\tc.execute('''\n\t\t\tUPDATE Orders\n\t\t\tSET\n\t\t\ttaxCost = ?,\n\t\t\tshippingCost = ?,\n\t\t\ttotalCost = ?\n\t\t\tWHERE orderID = ?;\n\t\t''', (tax_cost, shipping_cost, total_cost, order_id,))\n\n\t\tconn.commit()\n\t\tconn.close()\n\n\tdef get_cart(self, username):\n\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tc.execute('''\n\t\t\tSELECT cartID\n\t\t\tFROM Customers\n\t\t\tWHERE accountID = (\n\t\t\t\tSELECT accountID\n\t\t\t\tFROM Accounts\n\t\t\t\tWHERE username = ?\n\t\t\t);\n\t\t''', (username,))\n\n\t\tcart_id = c.fetchone()\n\n\t\tcart_id = cart_id[0] if cart_id is not None else None\n\n\t\tif cart_id is None:\n\t\t\t# create cart\n\t\t\tc.execute('''\n\t\t\t\tINSERT INTO Carts(accountID)\n\t\t\t\tSELECT accountID\n\t\t\t\tFROM Accounts\n\t\t\t\tWHERE username = ?;\n\t\t\t''', (username,))\n\t\t\tcart_id = c.lastrowid\n\n\t\t\t# update customer cart id\n\t\t\tc.execute('''\n\t\t\t\tUPDATE Customers\n\t\t\t\tSET cartID = ?\n\t\t\t\tWHERE accountID = (\n\t\t\t\t\tSELECT accountID\n\t\t\t\t\tFROM Accounts\n\t\t\t\t\tWHERE username = ?\n\t\t\t\t);\n\t\t\t''', (cart_id, username,))\n\n\t\tc.execute('''\n\t\t\tSELECT productID, quantity FROM CartDetails\n\t\t\tWHERE cartID = ?;\n\t\t\t''', (cart_id,))\n\n\t\tcolumn_names = next(zip(*c.description))\n\n\t\tcart_detail_rows = c.fetchall()\n\n\t\tcart = {\"orderDetails\": [dict(zip(column_names, cart_detail)) for cart_detail in cart_detail_rows]}\n\t\tconn.commit()\n\t\tconn.close()\n\t\treturn cart\n\n\tdef update_cart(self, cart):\n\t\t# get account id, and cart id\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tusername = cart[\"username\"]\n\n\t\tc.execute('''\n\t\t\tSELECT accountID FROM Accounts WHERE username = ?;\n\t\t''', (username,))\n\n\t\taccount_id = c.fetchone()\n\n\t\tc.execute('''\n\t\t\tSELECT cartID FROM Customers WHERE accountID = ?;\n\t\t''', account_id)\n\n\t\tcart_id = c.fetchone()[0]\n\n\t\tif cart_id is None:\n\t\t\t# create cart\n\t\t\tc.execute('''\n\t\t\t\tINSERT INTO Carts(accountID)\n\t\t\t\tVALUES(?);\n\t\t\t''', account_id)\n\t\t\tcart_id = c.lastrowid\n\n\t\t\t# update customer cart id\n\t\t\tc.execute('''\n\t\t\t\tUPDATE Customers\n\t\t\t\tSET cartID = ?\n\t\t\t\tWHERE accountID = ?;\n\t\t\t''', (cart_id, account_id[0],))\n\n\t\tcartDetails = [\n\t\t\t(cart_id, cartDetail[\"productID\"], cartDetail[\"quantity\"])\n\t\t\tfor cartDetail in cart[\"orderDetails\"]\n\t\t]\n\n\t\t# delete previous cart details\n\t\tc.execute('''\n\t\t\tDELETE FROM CartDetails\n\t\t\tWHERE cartID = ?;\n\t\t''', (cart_id,))\n\n\t\t# TODO verify cart details exist\n\n\t\t# insert cart details\n\t\tc.executemany('''\n\t\t\tINSERT INTO CartDetails\n\t\t\t(\n\t\t\tcartID,\n\t\t\tproductID,\n\t\t\tquantity\n\t\t\t)\n\t\t\tVALUES(?,?,?);\n\t\t''', cartDetails)\n\n\t\t# insert cart items\n\t\tconn.commit()\n\t\tconn.close()\n\n\tdef add_customer(self, account):\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\taccount_details = [\n\t\t\taccount.get(\"username\"),\n\t\t\tsha256(account.get(\"password\").encode()).hexdigest(),\n\t\t\taccount.get(\"firstName\"),\n\t\t\taccount.get(\"middleInitial\"),\n\t\t\taccount.get(\"lastName\"),\n\t\t\taccount.get(\"phoneNumber\"),\n\t\t\taccount.get(\"email\"),\n\t\t]\n\n\t\tc.execute('''\n\t\t\tINSERT INTO Accounts\n\t\t\t(username, password, firstName, middleInitial, lastName, phoneNumber, email)\n\t\t\tVALUES (?,?,?,?,?,?,?);\n\t\t''', account_details)\n\n\t\tc.execute('''\n\t\t\tINSERT INTO Customers (accountID)\n\t\t\tSELECT accountID FROM Accounts WHERE username = ?;\n\t\t''', (account_details[0],))\n\n\t\tconn.commit()\n\t\tconn.close()\n\n\tdef create_accounts_table(self):\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tc.execute('''\n\t\t\tCREATE TABLE IF NOT EXISTS Accounts (\n\t\t\t\taccountID INTEGER NOT NULL PRIMARY KEY UNIQUE,\n\t\t\t\tusername TEXT NOT NULL UNIQUE,\n\t\t\t\tpassword TEXT NOT NULL,\n\t\t\t\tfirstName TEXT NOT NULL,\n\t\t\t\tmiddleInitial TEXT,\n\t\t\t\tlastName TEXT NOT NULL,\n\t\t\t\tphoneNumber TEXT,\n\t\t\t\temail TEXT NOT NULL\n\t\t\t);\n\t\t''')\n\n\t\tadmin_account = [\n\t\t\t\"admin\",\n\t\t\tsha256(b\"password\").hexdigest(),\n\t\t\t\"admin\",\n\t\t\t\"i\",\n\t\t\t\"strator\",\n\t\t\t\"1234567890\",\n\t\t\t\"admin@ecommerce.com\"\n\t\t]\n\n\t\t# create initial admin account\n\t\tc.execute('''\n\t\t\tINSERT INTO Accounts\n\t\t\t(username, password, firstName, middleInitial, lastName, phoneNumber, email)\n\t\t\tVALUES(?, ?, ?, ?, ?, ?, ?);\n\t\t''', admin_account)\n\t\tconn.commit()\n\t\tconn.close()\n\n\tdef create_admins_table(self):\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tc.execute('''\n\t\t\tCREATE TABLE IF NOT EXISTS Admins (\n\t\t\t\taccountID INTEGER NOT NULL PRIMARY KEY,\n\t\t\t\tFOREIGN KEY(accountID) REFERENCES Accounts(accountID)\n\t\t\t\tON DELETE CASCADE\n\t\t\t);\n\t\t''')\n\n\t\t# insert initial admin account to admin table\n\t\tc.execute('''\n\t\t\tINSERT INTO Admins(accountID)\n\t\t\tSELECT accountID\n\t\t\tFROM Accounts WHERE username = \"admin\";\n\t\t''')\n\t\tconn.commit()\n\t\tconn.close()\n\n\tdef create_customers_table(self):\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tc.execute('''\n\t\t\tCREATE TABLE IF NOT EXISTS Customers (\n\t\t\t\taccountID INTEGER NOT NULL PRIMARY KEY,\n\t\t\t\tbillingAddress TEXT,\n\t\t\t\tbillingCity TEXT,\n\t\t\t\tbillingState TEXT,\n\t\t\t\tbillingPostalCode TEXT,\n\t\t\t\tshippingAddress TEXT,\n\t\t\t\tshippingCity TEXT,\n\t\t\t\tshippingState TEXT,\n\t\t\t\tshippingPostalCode TEXT,\n\t\t\t\taccountCreationDate TEXT,\n\t\t\t\tcartID TEXT,\n\t\t\t\tFOREIGN KEY(accountID) REFERENCES Accounts(accountID)\n\t\t\t\tON DELETE CASCADE\n\t\t\t);\n\t\t''')\n\t\tconn.commit()\n\t\tconn.close()\n\n\tdef create_categories_table(self):\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tc.execute('''\n\t\t\tCREATE TABLE IF NOT EXISTS Categories (\n\t\t\t\tcategoryID INTEGER NOT NULL PRIMARY KEY,\n\t\t\t\tcategoryName TEXT\n\t\t\t);\n\t\t''')\n\t\tconn.commit()\n\t\tconn.close()\n\n\tdef create_products_table(self):\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tc.execute('''\n\t\t\tCREATE TABLE IF NOT EXISTS Products (\n\t\t\t\tproductID INTEGER NOT NULL PRIMARY KEY,\n\t\t\t\tcategoryID INTEGER,\n\t\t\t\tname TEXT,\n\t\t\t\tdescription TEXT,\n\t\t\t\timageURL TEXT,\n\t\t\t\tprice INTEGER,\n\t\t\t\tquantityAvailable INTEGER,\n\t\t\t\tFOREIGN KEY(categoryID) REFERENCES Categories(categoryID)\n\t\t\t\tON DELETE CASCADE\n\t\t\t);\n\t\t''')\n\t\tconn.commit()\n\t\tconn.close()\n\n\tdef create_orders_table(self):\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tc.execute('''\n\t\t\tCREATE TABLE IF NOT EXISTS Orders (\n\t\t\t\torderID INTEGER NOT NULL PRIMARY KEY,\n\t\t\t\taccountID INTEGER,\n\t\t\t\tdateOrdered DATETIME,\n\t\t\t\tbillingAddress TEXT,\n\t\t\t\tbillingCity TEXT,\n\t\t\t\tbillingState TEXT,\n\t\t\t\tbillingPostalCode TEXT,\n\t\t\t\tshippingAddress TEXT,\n\t\t\t\tshippingCity TEXT,\n\t\t\t\tshippingState TEXT,\n\t\t\t\tshippingPostalCode TEXT,\n\t\t\t\ttaxCost INTEGER,\n\t\t\t\tshippingCost INTEGER,\n\t\t\t\ttotalCost INTEGER,\n\t\t\t\tFOREIGN KEY(accountID) REFERENCES Accounts(accountID)\n\t\t\t\tON DELETE CASCADE\n\t\t\t);\n\t\t''')\n\t\tconn.commit()\n\t\tconn.close()\n\n\tdef create_order_details_table(self):\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tc.execute('''\n\t\t\tCREATE TABLE IF NOT EXISTS OrderDetails (\n\t\t\t\torderDetailID INTEGER NOT NULL PRIMARY KEY,\n\t\t\t\torderID INTEGER,\n\t\t\t\tproductID INTEGER,\n\t\t\t\tname TEXT,\n\t\t\t\tdescription TEXT,\n\t\t\t\tprice INTEGER,\n\t\t\t\tquantity INTEGER\n\t\t\t);\n\t\t''')\n\t\tconn.commit()\n\t\tconn.close()\n\n\tdef create_carts_table(self):\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tc.execute('''\n\t\t\tCREATE TABLE IF NOT EXISTS Carts (\n\t\t\t\tcartID INTEGER NOT NULL PRIMARY KEY,\n\t\t\t\taccountID INTEGER,\n\t\t\t\tFOREIGN KEY(accountID) REFERENCES Accounts(accountID)\n\t\t\t\tON DELETE CASCADE\n\t\t\t);\n\t\t''')\n\t\tconn.commit()\n\t\tconn.close()\n\n\tdef create_cart_details_table(self):\n\t\tconn = sqlite3.connect(self.database_uri, check_same_thread=False)\n\t\tc = conn.cursor()\n\n\t\tc.execute('''\n\t\t\tCREATE TABLE IF NOT EXISTS CartDetails (\n\t\t\t\tcartDetailID INTEGER NOT NULL PRIMARY KEY,\n\t\t\t\tcartID INTEGER,\n\t\t\t\tproductID INTEGER,\n\t\t\t\tquantity INTEGER,\n\t\t\t\tFOREIGN KEY(cartID) REFERENCES Carts(cartID)\n\t\t\t\tON DELETE CASCADE,\n\t\t\t\tFOREIGN KEY(productID) REFERENCES Products(productID)\n\t\t\t\tON DELETE CASCADE\n\t\t\t);\n\t\t''')\n\t\tconn.commit()\n\t\tconn.close()\n\n\tdef initialize_database(self):\n\t\tself.create_accounts_table()\n\t\tself.create_admins_table()\n\t\tself.create_customers_table()\n\t\tself.create_categories_table()\n\t\tself.create_products_table()\n\t\tself.create_orders_table()\n\t\tself.create_order_details_table()\n\t\tself.create_carts_table()\n\t\tself.create_cart_details_table()\n","sub_path":"backend/src/main/python/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":16306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"92067879","text":"# -*- coding:utf-8 -*-\n#二叉树\n\nimport sys\n\nclass define(object):\n\t#定义每一个节点的状态\n\tdef __init__(self,data):\n\t\tself.data = data\n\t\tself.leftchild = None\n\t\tself.rightchild = None\n\ndef insertleft(root,nood):\n\t#插入一个左子树\n\tif root:\n\t\tif root.leftchild:\n\t\t\t#如果左边子树已经有的话就继续向左\n\t\t\tinsertleft(root.leftchild,nood)\n\t\telse:\n\t\t\troot.leftchild = nood\n\ndef insertright(root,nood):\n\t#插入一个右子树\n\tif root:\n\t\tif root.rightchild:\n\t\t\tinsertright(root.rightchild,nood)\n\t\telse:\n\t\t\troot.rightchild = nood\n\ndef pre_order(root):\n\tif root:\n\t\tprint(root.data)\n\t\tpre_order(root.rightchild)\n\t\tpre_order(root.leftchild)\n\nnumber = sys.stdin.readline()\nnumber = list(number)\nnumber.pop()\nnumbers = ''\nfor i in number:\n\tnumbers = numbers + i\nnumbers = int(numbers)\n\nfirst_string = sys.stdin.readline()\nfirst_string = list(first_string)\n\nfor i in range(1,numbers):\n\tstring = list(sys.stdin.readline())\n\tstring_root = string[0]\n\tfor i in range(len(first_string)):\n\t\tif string_root == first_string[i]:\n\t\t\tfirst_string.insert(i+1,string[1])\n\t\t\tfirst_string.insert(i+2,string[2])\n\nfirst_string.pop()\nfor i in range(len(first_string)):\n\tfor j in range(len(first_string)):\n\t\tif first_string[j] == '*':\n\t\t\tdel first_string[j]\n\t\t\tbreak\n\nfor i in first_string:\n\tprint(i,end = '')\n\n\n#感觉并没有用到二叉树\n#不过学习了一下递归来表示二叉树\n\n\n\n\n\n","sub_path":"递归/p1305/p1305.py","file_name":"p1305.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"232111968","text":"from flask import Flask, render_template, request, redirect, url_for, session, flash\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom threading import Thread\nfrom time import sleep\nimport datetime\n\nimport math\nimport csv\nimport requests\nimport json\nfrom random import random\nimport numpy as np\n\napp = Flask(__name__)\napp.config[\"SECRET_KEY\"] = \"pLoKmIjNuHbYgVtFcRdXeSzWaQ\"\napp.config['SQLALCHEMY_DATABASE_URI'] = \"sqlite:///project.db\"\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\n\ndb = SQLAlchemy(app)\n\nclass User(db.Model):\n id_ = db.Column(\"id\", db.Integer, primary_key=True)\n uname = db.Column(db.Text, nullable=False)\n email = db.Column(db.Text, nullable=False)\n psw = db.Column(db.Text, nullable=False)\n \n gender = db.Column(db.String(6), default=None)\n height = db.Column(db.Integer, default=None)\n weight = db.Column(db.Integer, default=None)\n age = db.Column(db.Integer, default=None)\n \n day_calories_eaten = db.Column(db.Integer, default=0)\n day_calories_burned = db.Column(db.Integer, default=0)\n week_calories_eaten = db.Column(db.Integer, default=0)\n week_calories_burned = db.Column(db.Integer, default=0)\n month_calories_eaten = db.Column(db.Integer, default=0)\n month_calories_burned = db.Column(db.Integer, default=0)\n year_calories_eaten = db.Column(db.Integer, default=0)\n year_calories_burned = db.Column(db.Integer, default=0)\n \n a = db.Column(db.Integer, default=0) # RMR\n b = db.Column(db.Integer, default=0) # Used to adjust calorie calcoulations\n c = db.Column(db.Integer, default=0) # Used to adjust calorie calcoulations\n d = db.Column(db.Integer, default=0) # Used to adjust calorie calcoulations\n e = db.Column(db.Integer, default=0) #Used for machine learning\n f = db.Column(db.Integer, default=0) #Also used for weight history\n g = db.Column(db.Integer, default=0) #used for activity history\n h = db.Column(db.Integer, default=0) #met average neumerator\n i = db.Column(db.Integer, default=0) #met average denominator\n \n j = db.Column(db.Text, default=\"\") # Excercise history\n k = db.Column(db.Text, default=\"\") # Day Reset\n l = db.Column(db.Text, default=\"\") # Week Reset\n m = db.Column(db.Text, default=\"\") # Month Reset\n n = db.Column(db.Text, default=\"\") # Weight history\n o = db.Column(db.Text, default=\"\") # Cal history\n p = db.Column(db.Text, default=\"\") #Used for weight history\n q = db.Column(db.Text, default=\"\") #Activity history\n r = db.Column(db.Text, default=\"\") #Used for activity history\n\n def __repr__(self):\n return \"{0}: {1} at {2}\".format(self.id_, self.uname, self.email)\n\ndef estimate_coef(x, y): #retrieved from https://www.geeksforgeeks.org/linear-regression-python-implementation/\n # number of observations/points \n n = np.size(x) \n \n # mean of x and y vector \n m_x, m_y = np.mean(x), np.mean(y) \n \n # calculating cross-deviation and deviation about x \n SS_xy = np.sum(y*x) - n*m_y*m_x \n SS_xx = np.sum(x*x) - n*m_x*m_x \n \n # calculating regression coefficients \n b_1 = SS_xy / SS_xx \n b_0 = m_y - b_1*m_x \n \n return(b_0, b_1) \n\n@app.before_first_request\ndef init_db():\n db.create_all()\n\n@app.before_first_request\ndef update_activity_mets():\n global activity_mets\n activity_mets = get_activity_mets()\n\n@app.before_request\ndef day_reset():\n if session.get(\"uname\"):\n match = User.query.filter_by(uname=session[\"uname\"]).first()\n now = datetime.datetime.now()\n reset = False\n if not match.k:\n match.k = now.strftime(\"%m/%d/%Y %H:%M:%S\")\n else:\n reset_dt = datetime.datetime.strptime(match.k, \"%m/%d/%Y %H:%M:%S\")\n while now > reset_dt:\n reset_dt += datetime.timedelta(days=1)\n if not reset:\n match.day_calories_eaten = 0\n match.day_calories_burned = 0\n reset = True\n match.k = reset_dt.strftime(\"%m/%d/%Y %H:%M:%S\")\n db.session.commit()\n\ndef learn(user):\n x = user.o.split(\"|\")\n temp = user.n.split(\"\\n\")\n temp2 = 0.0\n for i in temp:\n i = i.split(\"|\")\n temp2 = max(i[1], float(temp2))\n y = []\n temp3 = int(temp2)\n k = 0\n for i in range(temp3):\n j = 0\n ct = 0\n total = 0\n while(j < i + 1 and k < temp.length):\n total += float(temp[k][0])\n j = float(temp[k][1])\n ct += 1\n k += 1\n y[i] = total / ct\n newVals = estimate_coef(np.array(x), np.array(y))\n return([newVals, x, y])\n\n\n@app.before_request\ndef week_reset():\n if session.get(\"uname\"):\n match = User.query.filter_by(uname=session[\"uname\"]).first()\n now = datetime.datetime.now()\n reset = False\n if not match.l:\n match.l = now.strftime(\"%m/%d/%Y %H:%M:%S\")\n else:\n reset_dt = datetime.datetime.strptime(match.l, \"%m/%d/%Y %H:%M:%S\")\n while now > reset_dt:\n reset_dt += datetime.timedelta(days=7)\n match.o += str(match.week_calories_eaten - match.week_calories_burned) + \"|\"\n match.e += 1\n if match.e > 4:\n nv = learn(match)\n match.o = ''\n match.n = ''\n for i in range(math.floor(match.e ** 0.5), nv[1].length):\n match.o += str(nv[1])\n match.n += str(nv[2]) + \"|\" + str(i - math.floor(match.e ** 0.5)) + \"\\n\"\n match.c -= nv[0][0]\n match.b -= math.e**(1.0 / nv[0][1]) - math.e\n if not reset:\n match.week_calories_eaten = 0\n match.week_calories_burned = 0\n reset = True\n flash(\"DPlease update your weight now! It has been a week since you last updated your weight.\")\n match.l = reset_dt.strftime(\"%m/%d/%Y %H:%M:%S\")\n db.session.commit()\n\n@app.before_request\ndef month_reset():\n if session.get(\"uname\"):\n match = User.query.filter_by(uname=session[\"uname\"]).first()\n now = datetime.datetime.now()\n reset = False\n if not match.m:\n match.m = now.strftime(\"%m/%d/%Y %H:%M:%S\")\n else:\n reset_dt = datetime.datetime.strptime(match.m, \"%m/%d/%Y %H:%M:%S\")\n while now > reset_dt:\n reset_dt += datetime.timedelta(days=30)\n if not reset:\n match.month_calories_eaten = 0\n match.month_calories_burned = 0\n reset = True\n match.m = reset_dt.strftime(\"%m/%d/%Y %H:%M:%S\")\n db.session.commit()\n\nGETPOST = [\"GET\", \"POST\"]\nMS_PER_DAY = 86400000.0\nactivity_mets = []\n\ndef get_activity_mets():\n with open(\"activity_mets.csv\") as file:\n reader = csv.reader(file, delimiter=\"|\", quotechar=\">\")\n activity_mets = []\n for x, sport in enumerate(reader):\n new_sport = [sport[0].strip(), sport[1].strip().title(), float(sport[2]), x]\n activity_mets.append(new_sport)\n return activity_mets\n\ndef get_mets(activity):\n for activity_details in activity_mets:\n if activity_details[1] == activity:\n return activity_details[2]\n return -1.0\n\ndef get_calories(activity, rmr, d=0):\n #print(f\"Getting calories for {activity} for {minutes} with person weighing {weight}\")\n return (get_mets(activity) ** (1 / (d+1)) * float(rmr))\n\ndef calcRMR(gender, weight, height, age, b=0, c=0):\n if gender == \"male\":\n return (66.47 + 13.75 * weight + 5.003 * height - 6.755 * age) * math.log(b + math.e) + c\n elif gender == \"female\":\n return (655.1 + 9.563 * weight + 1.85 * height - 4.676 * age) * math.log(b + math.e) + c\n else:\n return (10.0 * weight + 6.25 * height - 5.0 * age - 78.0) * math.log(b + math.e) + float(c)\n\n@app.route(\"/updateRMR\")\ndef updateRMR(t):\n uname = session.get(\"uname\")\n if not uname:\n return redirect(url_for(\"index\"))\n match = User.query.filter_by(uname=uname).first()\n cals_burned = float(t) * match.a / MS_PER_DAY\n match.day_calories_burned += cals_burned\n match.week_calories_burned += cals_burned\n match.month_calories_burned += cals_burned\n match.year_calories_burned += cals_burned\n db.session.commit()\n\ndef login_db(uname, psw):\n match = User.query.filter_by(uname=uname).first()\n if match and psw == match.psw:\n session[\"logged_in\"] = True\n session[\"uname\"] = match.uname\n session[\"email\"] = match.email\n flash(f\"SSuccessfully logged in as {match.uname}!\")\n return True\n flash(\"DIncorrect Username or Password!\")\n return False\n\ndef register_db(uname, email, psw):\n new_user = User(uname=uname, email=email, psw=psw)\n db.session.add(new_user)\n db.session.commit()\n flash(f\"SSuccessfully Registered as {new_user.uname}!\")\n\n@app.route(\"/\")\ndef index():\n if session.get(\"logged_in\"):\n match = User.query.filter_by(uname=session.get(\"uname\")).first()\n mets = \"\"\n for i in activity_mets:\n mets += \"\\n\"\n for j in i:\n mets += str(j) + \"|\"\n return render_template(\"index.html\", \n uname=session.get(\"uname\"), \n email=match.email, \n gender=match.gender, \n height=match.height, \n weight=match.weight, \n age=match.age,\n history=match.j,\n activity_mets=mets,\n day_calories_eaten=match.day_calories_eaten, \n week_calories_eaten=match.week_calories_eaten, \n month_calories_eaten=match.month_calories_eaten, \n life_calories_eaten=match.year_calories_eaten,\n day_calories_burned=match.day_calories_burned,\n week_calories_burned=match.week_calories_burned,\n month_calories_burned=match.month_calories_burned,\n life_calories_burned=match.year_calories_burned)\n else:\n return render_template(\"index.html\")\n\n@app.route(\"/login\", methods=GETPOST)\ndef login():\n if session.get(\"logged_in\"):\n flash(\"DYou are already logged in!\")\n return redirect(url_for(\"index\"))\n if request.method == \"POST\":\n uname = request.form.get(\"uname\")\n psw = request.form.get(\"psw\")\n remember = request.form.get(\"remember\")\n login_db(uname, psw)\n return redirect(url_for(\"index\"))\n return render_template(\"login.html\", uname=session.get(\"uname\"))\n\n@app.route(\"/register\", methods=GETPOST)\ndef register():\n if session.get(\"logged_in\"):\n flash(\"DYou are already logged in!\")\n return redirect(url_for(\"index\"))\n if request.method == \"POST\":\n uname = request.form.get(\"uname\")\n email = request.form.get(\"email\")\n psw = request.form.get(\"psw\")\n if User.query.filter_by(uname=uname).first():\n flash(\"DUsername is taken!\")\n return redirect(url_for(\"register\"))\n register_db(uname, email, psw)\n return redirect(url_for(\"login\"))\n return render_template(\"register.html\", uname=session.get(\"uname\"))\n\n@app.route(\"/logout\", methods=GETPOST)\ndef logout():\n uname = session.get(\"uname\")\n session.clear()\n flash(f\"SSuccessfully Logged Out from {uname}!\")\n return redirect(url_for(\"login\"))\n\n@app.route(\"/myaccount\", methods=GETPOST)\ndef my_account():\n if not session.get(\"logged_in\"):\n flash(\"DYou muct log in first to access this page!\")\n return redirect(url_for(\"login\"))\n match = User.query.filter_by(uname=session.get(\"uname\")).first()\n if request.method == \"POST\":\n gender = request.form.get(\"gender\")\n height = request.form.get(\"height\")\n weight = request.form.get(\"weight\")\n age = request.form.get(\"age\")\n npsw = request.form.get(\"npsw\")\n opsw = request.form.get(\"opsw\")\n if npsw and opsw:\n if opsw == match.psw:\n match.psw = npsw\n db.session.commit()\n flash(\"SPassword Successfully Changed!\")\n else:\n flash(\"DIncorrect Old Password! Please Try Again or use Forgot Password to reset your password.\")\n else:\n if gender:\n match.gender = gender\n if height:\n height = int(height)\n if request.form.get(\"units\") == \"on\":\n height *= 2.54\n match.height = int(height)\n if weight:\n weight = int(weight)\n if request.form.get(\"units\") == \"on\":\n weight /= 2.20462262\n if match.f != 0:\n match.n += str(weight) + \"|\" + match.p + \"\\n\"\n match.p = str((float(datetime.datetime.now().toordinal()) - float(match.f)) / (MS_PER_DAY * 7.0 / 1000.0) + float(match.p))\n else:\n match.p = \"0.0\"\n match.f = datetime.datetime.now().toordinal()\n if age:\n match.age = int(age)\n #match.a = calcRMR(match.gender, match.weight, match.height, match.age, match.b, match.c)\n match.a = 100\n db.session.commit()\n flash(\"SSuccessfully Updated Biometric Data!\")\n return redirect(url_for(\"my_account\"))\n return render_template(\"myaccount.html\", \n uname=session.get(\"uname\"), \n email=match.email, \n gender=match.gender, \n height=match.height, \n weight=match.weight, \n age=match.age)\n\n@app.route(\"/nutrition\", methods=GETPOST)\ndef nutrition():\n if not session.get(\"logged_in\"):\n flash(\"DYou muct log in first to access this page!\")\n return redirect(url_for(\"login\"))\n if request.method == \"POST\":\n search = request.form.get(\"search\")\n smass = request.form.get(\"smass\")\n upc = request.form.get(\"upc\")\n umass = request.form.get(\"umass\")\n if search and smass:\n response = requests.get(f\"https://api.edamam.com/api/food-database/v2/parser?ingr={search.replace(' ', '%20')}&app_id=88a43868&app_key=e512bec8d5a4570675eec4b47858e83e\").json()[\"hints\"][1][\"food\"]\n label = response[\"label\"]\n cals = (response[\"nutrients\"][\"ENERC_KCAL\"]) * (float(smass) / 100)\n session[\"label\"] = label\n session[\"food_cals\"] = cals\n flash(f\"Sadding {cals} calories from {label}, orO\")\n elif upc and umass:\n response = requests.get(f\"https://api.edamam.com/api/food-database/v2/parser?upc={upc}&app_id=88a43868&app_key=e512bec8d5a4570675eec4b47858e83e\").json()[\"hints\"][0][\"food\"]\n label = response[\"label\"]\n cals = (response[\"nutrients\"][\"ENERC_KCAL\"]) * (float(umass) / 100)\n match = User.query.filter_by(uname=session.get(\"uname\")).first()\n match.day_calories_eaten += cals\n match.week_calories_eaten += cals\n match.month_calories_eaten += cals\n match.year_calories_eaten += cals\n db.session.commit()\n flash(f\"SSuccessfully added {cals} calories from {label}!\")\n else:\n flash(\"DPlease fill out all form fields!\")\n return redirect(url_for(\"nutrition\"))\n match = User.query.filter_by(uname=session.get(\"uname\")).first()\n return render_template(\"nutrition.html\", \n uname=session.get(\"uname\"), \n day_calories_eaten=match.day_calories_eaten, \n week_calories_eaten=match.week_calories_eaten, \n month_calories_eaten=match.month_calories_eaten, \n life_calories_eaten=match.year_calories_eaten)\n\n\n@app.route(\"/add_nutrition\")\ndef add_nutrition():\n if not session.get(\"logged_in\"):\n flash(\"DYou muct log in first to access this page!\")\n return redirect(url_for(\"login\"))\n if session.get(\"food_cals\"):\n match = User.query.filter_by(uname=session.get(\"uname\")).first()\n # if not match.gender or not match.weight or not match.height or not match.age:\n # flash(\"DPlease set your gender, weight, height, and age first!\")\n # return redirect(url_for(\"my_account\"))\n flash(f\"SSuccessfully added {session.get('food_cals')} calories from {session.get('label')}!\")\n match.day_calories_eaten += session[\"food_cals\"]\n match.week_calories_eaten += session[\"food_cals\"]\n match.month_calories_eaten += session[\"food_cals\"]\n match.year_calories_eaten += session[\"food_cals\"]\n db.session.commit()\n del session[\"label\"]\n del session[\"food_cals\"]\n else:\n flash(\"DPlease Choose a Food Item first!\")\n return redirect(url_for(\"nutrition\"))\n\n@app.route(\"/remove_nutrition\")\ndef remove_nutrition():\n if not session.get(\"logged_in\"):\n flash(\"DYou muct log in first to access this page!\")\n return redirect(url_for(\"login\"))\n del session[\"food_cals\"]\n del session[\"label\"]\n return redirect(url_for(\"nutrition\"))\n\n@app.route(\"/activity\", methods=GETPOST)\ndef activity():\n if not session.get(\"logged_in\"):\n flash(\"DYou muct log in first to access this page!\")\n return redirect(url_for(\"login\"))\n match = User.query.filter_by(uname=session.get(\"uname\")).first()\n return render_template(\"activity.html\", uname=session.get(\"uname\"), life_calories_burned=match.year_calories_burned, life_calories_eaten=match.year_calories_eaten, rmr=match.a, age=match.age, weight=match.age, activity_mets=activity_mets)\n\n@app.route(\"/do_activity//\")\ndef do_activity(id, mins):\n if not session.get(\"logged_in\"):\n flash(\"DYou muct log in first to access this page!\")\n return redirect(url_for(\"login\"))\n match = User.query.filter_by(uname=session.get(\"uname\")).first()\n # if not match.gender or not match.weight or not match.height or not match.age:\n # flash(\"DPlease set your gender, weight, height, and age first!\")\n # return redirect(url_for(\"my_account\"))\n activity = activity_mets[id]\n # match.a = calcRMR(match.gender, match.weight, match.height, match.age, match.b, match.c)\n cals = get_calories(activity[1], match.a , match.d)\n match.day_calories_burned += cals\n match.week_calories_burned += cals\n match.month_calories_burned += cals\n match.year_calories_burned += cals\n match.j += str(activity[3]) + \"|\" + str(mins) + \"\\n\"\n if(match.r):\n match.h += int(float(activity[2]))\n match.i += 1\n match.r = str((float(datetime.datetime.now().toordinal()) - float(match.g)) / (MS_PER_DAY * 7.0 / 1000.0) + float(match.r))\n else:\n match.r = \"0.0\"\n match.g = datetime.datetime.now().toordinal()\n db.session.commit()\n flash(f\"SSuccessfully completed {activity[1]} for {mins} minutes!\")\n return redirect(url_for(\"index\"))\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":17987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"558665045","text":"import numpy as np\nimport random\n\n# This class allows the network to draw from a batch of experiences, rather than just one at a time\n# credit - https://medium.com/@awjuliani/simple-reinforcement-learning-with-tensorflow-part-4-deep-q-networks-and-beyond-8438a3e2b8df\nclass experience_buffer():\n # when buffer reaches max capacity, it drops all old experinces\n def __init__(self, buffer_size=10000):\n self.buffer = []\n self.buffer_size = buffer_size\n\n def add(self, experience):\n if len(self.buffer) + 1 >= self.buffer_size:\n self.buffer[0:(1 + len(self.buffer)) - self.buffer_size] = []\n self.buffer.append(experience)\n\n def sample(self, batch_size, trace_length):\n sampled_episodes = random.sample(self.buffer, batch_size)\n sampledTraces = []\n for episode in sampled_episodes:\n point = np.random.randint(0, len(episode) + 1 - trace_length)\n sampledTraces.append(episode[point:point + trace_length])\n sampledTraces = np.array(sampledTraces)\n return np.reshape(sampledTraces, [batch_size * trace_length, 5])\n","sub_path":"Code/NN_AI/experience_buffer.py","file_name":"experience_buffer.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"434939013","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = \"post\"\n\nurlpatterns = [url(r\"^$\", views.home, name=\"home\"),\n url(r\"^create/$\", views.create, name=\"create\"),\n url(r\"^(?P\\d+)/delete/$\", views.delete, name=\"delete\"),\n url(r\"^(?P\\d+)/update/$\", views.update, name=\"update\"),\n url(r\"^(?P\\d+)/new_contract/$\", views.create_contract, name=\"new_contract\"),\n ]\n","sub_path":"post/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"60670683","text":"# Gemma IO demo - analog inputs\n\nfrom digitalio import DigitalInOut, Direction\nfrom analogio import AnalogIn\nimport board\nimport time\n\nled = DigitalInOut(board.L)\nled.direction = Direction.OUTPUT\n\nanalog0in = AnalogIn(board.A0)\nanalog1in = AnalogIn(board.A1)\nanalog2in = AnalogIn(board.A2)\n\ndef getVoltage(pin):\n return (pin.value * 3.3) / 65536\n\nwhile True:\n print(\"A0: %f \\t\\t A1: %f \\t\\t A2: %f\" %\n (getVoltage(analog0in),\n getVoltage(analog1in),\n getVoltage(analog2in)))\n\n time.sleep(0.1)\n","sub_path":"Introducing_Gemma_M0/Gemma_AnalogIn.py","file_name":"Gemma_AnalogIn.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"139650350","text":"import sys\n\nvocab = []\n\n#creates empty list\n\nhs = open('wiki.hist', 'r')\nfor line in hs.readlines():\n\tform = line.strip()\n\trow = form.split(' ')\n\tif len(row) > 1:\n\t\tvocab.append(row[1])\n\n\n\t\nfor line in sys.stdin.readlines():\n\tlines = line.split(\" \")\n\tfor x in lines:\n\t\tif x in vocab:\n\t\t\tprint(x)\n\t\telse:\n\t\t\tprint (\"*\" + x)\n\n\n\n\nhs.close()\n \n\n\n\n\n\n\n\n#for i in ranks:\n\t#print(i)","sub_path":"spellchecker.py","file_name":"spellchecker.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"379946401","text":"#!/usr/bin/env python3\nimport json\nimport os\nimport multiprocessing\nfrom operator import itemgetter\nimport numpy as np\n\nfrom collections import defaultdict\nfrom pysam import AlignmentFile # pylint: disable=no-name-in-module\n\nfrom iggtools.common.argparser import add_subcommand\nfrom iggtools.common.utils import tsprint, num_physical_cores, InputStream, OutputStream, multiprocessing_map, command, cat_files, select_from_tsv, multithreading_map\nfrom iggtools.models.midasdb import MIDAS_DB\nfrom iggtools.common.bowtie2 import build_bowtie2_db, bowtie2_align, samtools_sort, samtools_index, bowtie2_index_exists, _keep_read\nfrom iggtools.params.schemas import snps_profile_schema, snps_pileup_schema, format_data, snps_chunk_summary_schema\nfrom iggtools.models.sample import Sample\nfrom iggtools.models.species import Species, collect_units_per_chunk, parse_species\n\n\nDEFAULT_MARKER_DEPTH = 5.0\nDEFAULT_MARKER_MEDIAN_DEPTH = 0\n\n\nDEFAULT_ALN_MAPID = 94.0\nDEFAULT_ALN_MAPQ = 10\nDEFAULT_ALN_COV = 0.75\nDEFAULT_ALN_READQ = 20\nDEFAULT_ALN_BASEQ = 30\nDEFAULT_ALN_TRIM = 0\n\nDEFAULT_CHUNK_SIZE = 50000\nDEFAULT_MAX_FRAGLEN = 5000\n\n\ndef register_args(main_func):\n subparser = add_subcommand('midas_run_snps', main_func, help='Predict single-nucleotide-polymorphism')\n\n subparser.add_argument('midas_outdir',\n type=str,\n help=\"\"\"Path to directory to store results. Name should correspond to unique sample identifier.\"\"\")\n subparser.add_argument('--sample_name',\n dest='sample_name',\n required=True,\n help=\"Unique sample identifier\")\n subparser.add_argument('-1',\n dest='r1',\n required=True,\n help=\"FASTA/FASTQ file containing 1st mate if using paired-end reads. Otherwise FASTA/FASTQ containing unpaired reads.\")\n subparser.add_argument('-2',\n dest='r2',\n help=\"FASTA/FASTQ file containing 2nd mate if using paired-end reads.\")\n\n # Prebuilt/predownload\n subparser.add_argument('--prebuilt_bowtie2_indexes',\n dest='prebuilt_bowtie2_indexes',\n type=str,\n metavar=\"CHAR\",\n help=f\"Prebuilt bowtie2 database indexes\")\n subparser.add_argument('--prebuilt_bowtie2_species',\n dest='prebuilt_bowtie2_species',\n type=str,\n metavar=\"CHAR\",\n help=f\"List of species used for building the prebuild bowtie2 indexes.\")\n subparser.add_argument('--midas_db',\n dest='midas_db',\n type=str,\n metavar=\"CHAR\",\n help=f\"local MIDAS DB which mirrors the s3 IGG db\")\n\n # Species related\n subparser.add_argument('--species_list',\n dest='species_list',\n type=str,\n metavar=\"CHAR\",\n help=f\"Comma separated list of species ids\")\n subparser.add_argument('--select_by',\n dest='select_by',\n type=str,\n metavar=\"CHAR\",\n default=\"median_marker_coverage\",\n choices=['median_marker_coverage', 'marker_coverage', 'unique_fraction_covered', \"marker_relative_abundance\"],\n help=f\"Column from species_profile based on which to select species.\")\n subparser.add_argument('--select_threshold',\n dest='select_threshold',\n type=float,\n metavar=\"FLOAT\",\n default=DEFAULT_MARKER_MEDIAN_DEPTH,\n help=f\"Include species with > X median SGC (median) marker coverage ({DEFAULT_MARKER_MEDIAN_DEPTH})\")\n\n # Alignment flags (Bowtie2 or postprocessing)\n subparser.add_argument('--aln_speed',\n type=str,\n dest='aln_speed',\n default='very-sensitive',\n choices=['very-fast', 'fast', 'sensitive', 'very-sensitive'],\n help='Alignment speed/sensitivity (very-sensitive). If aln_mode is local (default) this automatically issues the corresponding very-sensitive-local, etc flag to bowtie2.')\n subparser.add_argument('--aln_mode',\n type=str,\n dest='aln_mode',\n default='global',\n choices=['local', 'global'],\n help='Global/local read alignment (local, corresponds to the bowtie2 --local; Default global corresponds to the bowtie2 --end-to-end).')\n subparser.add_argument('--aln_interleaved',\n action='store_true',\n default=False,\n help='FASTA/FASTQ file in -1 are paired and contain forward AND reverse reads')\n subparser.add_argument('--fragment_length',\n type=float,\n dest='fragment_length',\n metavar='FLOAT',\n default=DEFAULT_MAX_FRAGLEN,\n help=f\"Maximum fragment length for paired reads.\")\n\n\n # Pileup flags (samtools, or postprocessing)\n subparser.add_argument('--aln_mapid',\n dest='aln_mapid',\n type=float,\n metavar=\"FLOAT\",\n default=DEFAULT_ALN_MAPID,\n help=f\"Discard reads with alignment identity < MAPID. Values between 0-100 accepted. ({DEFAULT_ALN_MAPID})\")\n subparser.add_argument('--aln_mapq',\n dest='aln_mapq',\n type=int,\n metavar=\"INT\",\n default=DEFAULT_ALN_MAPQ,\n help=f\"Discard reads with mapping quality < MAPQ. ({DEFAULT_ALN_MAPQ})\")\n subparser.add_argument('--aln_readq',\n dest='aln_readq',\n type=int,\n metavar=\"INT\",\n default=DEFAULT_ALN_READQ,\n help=f\"Discard reads with mean quality < READQ ({DEFAULT_ALN_READQ})\")\n subparser.add_argument('--aln_cov',\n dest='aln_cov',\n default=DEFAULT_ALN_COV,\n type=float,\n metavar=\"FLOAT\",\n help=f\"Discard reads with alignment coverage < ALN_COV ({DEFAULT_ALN_COV}). Values between 0-1 accepted.\")\n subparser.add_argument('--aln_baseq',\n dest='aln_baseq',\n default=DEFAULT_ALN_BASEQ,\n type=int,\n metavar=\"INT\",\n help=f\"Discard bases with quality < ALN_BASEQ ({DEFAULT_ALN_BASEQ})\")\n subparser.add_argument('--aln_trim',\n dest='aln_trim',\n default=DEFAULT_ALN_TRIM,\n type=int,\n metavar=\"INT\",\n help=f\"Trim ALN_TRIM base-pairs from 3'right end of read ({DEFAULT_ALN_TRIM})\")\n\n subparser.add_argument('--paired_only',\n action='store_true',\n default=False,\n help=f\"Only recruit properly paired reads for pileup.\")\n\n # File related\n subparser.add_argument('--sparse',\n action='store_true',\n default=True,\n help=f\"Omit zero rows from output.\")\n subparser.add_argument('--chunk_size',\n dest='chunk_size',\n type=int,\n metavar=\"INT\",\n default=DEFAULT_CHUNK_SIZE,\n help=f\"Number of genomic sites for the temporary chunk file ({DEFAULT_CHUNK_SIZE})\")\n subparser.add_argument('--max_reads',\n dest='max_reads',\n type=int,\n metavar=\"INT\",\n help=f\"Number of reads to use from input file(s). (All)\")\n subparser.add_argument('--num_cores',\n dest='num_cores',\n type=int,\n metavar=\"INT\",\n default=num_physical_cores,\n help=f\"Number of physical cores to use ({num_physical_cores})\")\n\n subparser.add_argument('--sim_exp',\n dest='sim_exp',\n action='store_true',\n default=False,\n help=f\"Simulation experiments\")\n return main_func\n\n\ndef reference_overlap(p, q):\n return max(0.0, min(p[1], q[1]) - max(p[0], q[0]) + 1)\n\n\ndef hamming_distance(str1, str2):\n assert len(str1) == len(str2), f\"Two input strings for hamming_distance are different length.\"\n hd = 0\n for i in range(len(str1)):\n if str1[i] != str2[i]:\n hd += 1\n return hd\n\n\ndef position_within_overlap(pos, strand, boundary):\n \"\"\" Check if given position is within the overlap range \"\"\"\n if strand == \"fwd\" and pos is not None and pos >= boundary:\n return True\n if strand == \"rev\" and pos is not None and pos <= boundary:\n return True\n return False\n\n\ndef update_overlap(reads_overlap, aln):\n \"\"\" The actual overlap should substract the number of gaps in the forward read \"\"\"\n aligned_pos = aln.get_aligned_pairs()\n ngaps = 0\n for i in range(0, len(aligned_pos)):\n if aligned_pos[i][1] is not None and aligned_pos[i][1] >= aln.reference_end - reads_overlap and aligned_pos[i][0] is None:\n ngaps += 1\n return reads_overlap - ngaps\n\n\ndef mismatches_within_overlaps(aln, reads_overlap, strand):\n \"\"\" For given alignment, compute NM within and outside overlap with paired read \"\"\"\n\n # reference sequence that is covered by reads alignment\n ref_seq = aln.get_reference_sequence()\n # aligned portion of the read\n qry_seq = aln.query_alignment_sequence\n # a list of aligned read (query) and reference positions\n aligned_pos = aln.get_aligned_pairs()\n\n ngaps_qi = 0\n ngaps_ri = 0\n ngaps_qo = 0\n ngaps_ro = 0\n ro = []\n qo = []\n ri = []\n qi = []\n\n for i in range(0,len(aligned_pos)):\n\n boundary = aln.query_alignment_end - reads_overlap if strand == \"fwd\" else aln.query_alignment_start + reads_overlap - 1\n\n if position_within_overlap(aligned_pos[i][0], strand, boundary):\n # The aligned position is witin the overlap\n if aligned_pos[i][0] is None:\n qi.append(\"-\")\n ngaps_qi += 1\n else:\n qi.append(qry_seq[aligned_pos[i][0] - aln.query_alignment_start])\n\n if aligned_pos[i][1] is None:\n ri.append(\"-\")\n ngaps_ri += 1\n else:\n ri.append(ref_seq[aligned_pos[i][1] - aln.reference_start])\n else:\n # The aligned position is outside the overlap\n if aligned_pos[i][0] is None:\n qo.append(\"-\")\n ngaps_qo += 1\n else:\n qo.append(qry_seq[aligned_pos[i][0] - aln.query_alignment_start])\n\n if aligned_pos[i][1] is None:\n ro.append(\"-\")\n ngaps_ro += 1\n else:\n ro.append(ref_seq[aligned_pos[i][1] - aln.reference_start])\n\n ro = \"\".join(ro)\n qo = \"\".join(qo)\n nm_out = hamming_distance(ro.upper(), qo.upper())\n\n ri = \"\".join(ri)\n qi = \"\".join(qi)\n nm_in = hamming_distance(ri.upper(), qi.upper())\n\n alned_no_gaps = len((ri + ro).replace(\"-\", \"\"))\n\n ngaps_q = ngaps_qi + ngaps_qo\n ngaps_r = ngaps_ri + ngaps_ro\n\n\n row = [\"func::mismatches_within_overlaps\", aln.query_alignment_length, alned_no_gaps, ngaps_r, ngaps_q, aln.query_name,\n aln.reference_name, aln.reference_start, aln.reference_end, aln.query_length,\n aln.get_aligned_pairs()]\n if ngaps_qi > 0:\n print(\"\\t\".join(map(str, row)))\n\n #assert ngaps_qi == 0\n #assert aln.query_alignment_length == len((qi + qo).replace(\"-\", \"\"))\n #assert aln.query_alignment_length + ngaps_q == alned_no_gaps + ngaps_r, \"\\n\".join(map(str, row)) + \"\\n\"\n\n return (nm_out, nm_in, ngaps_ri, ngaps_ro)\n\n\ndef debug_overlap(alns):\n aln = alns[\"fwd\"]\n row = [reads_overlap_raw, reads_overlap, ngaps_ri_rev, ngaps_ro_rev, ngaps_ri_fwd, ngaps_ro_fwd,\n aln.reference_name, aln.reference_start, aln.reference_end,\n aln.query_name, aln.query_alignment_start, aln.query_alignment_end,\n \"R1\" if aln.is_read1 else \"R2\", \"rev\" if aln.is_reverse else \"fwd\",\n dict(aln.tags)['NM'], aln.query_alignment_length, aln.query_length,\n reads_overlap, fragment_length, mismatches]\n print(\"+++++++++++++++++++++++++++++++++++++++++++\")\n print(\"\\t\".join(map(format_data, row)))\n print(aln.get_aligned_pairs())\n aln = alns[\"rev\"]\n row = [reads_overlap_raw, reads_overlap, ngaps_ri_rev, ngaps_ro_rev, ngaps_ri_fwd, ngaps_ro_fwd,\n aln.reference_name, aln.reference_start, aln.reference_end,\n aln.query_name, aln.query_alignment_start, aln.query_alignment_end,\n \"R1\" if aln.is_read1 else \"R2\", \"rev\" if aln.is_reverse else \"fwd\",\n dict(aln.tags)['NM'], aln.query_alignment_length, aln.query_length,\n reads_overlap, fragment_length, mismatches]\n print(\"\\t\".join(map(format_data, row)))\n print(aln.get_aligned_pairs())\n assert False, aln.reference_name\n\n\ndef keep_read(aln):\n global global_args\n args = global_args\n\n if not args.paired_only:\n return _keep_read(aln, args.aln_mapid, args.aln_readq, args.aln_mapq, args.aln_cov)\n return True\n\n\ndef filter_bam_by_single_read(pargs):\n \"\"\" Filter given BAM file with propely paired reads for given species and write to file \"\"\"\n\n global global_args\n global dict_of_species\n global sample\n\n repbamfile, species_id = pargs\n\n tsprint(f\" CZ::filter_bam_by_single_read::{species_id}-0::start filter_bam_by_single_read\")\n\n # List of contigs for given species\n list_of_contig_ids = list(dict_of_species[species_id].contigs.keys())\n\n # Cache *properly* aligned reads-pair\n filtered_alns_dict = defaultdict(dict)\n reads_stats = {\n \"aligned_reads\": dict.fromkeys(list_of_contig_ids, 0),\n \"mapped_reads\": dict.fromkeys(list_of_contig_ids, 0)\n }\n\n with AlignmentFile(repbamfile) as infile:\n for contig_id in list_of_contig_ids:\n # To avoid boundary cliff, we need to read in the whole contig\n aligned_reads = 0\n mapped_reads = 0\n for aln in infile.fetch(contig_id):\n aligned_reads += 1\n if keep_read(aln):\n mapped_reads += 1\n read = \"1\" if aln.is_read1 else \"2\"\n filtered_alns_dict[f\"{aln.query_name}_{read}\"] = aln\n\n reads_stats[\"aligned_reads\"][contig_id] = aligned_reads\n reads_stats[\"mapped_reads\"][contig_id] = mapped_reads\n\n # Write filtered alignments to file\n template_bam = AlignmentFile(repbamfile, \"rb\")\n filtered_bam = AlignmentFile(sample.get_target_layout(\"species_bam\", species_id), \"wb\", template=template_bam)\n for aln in filtered_alns_dict.values():\n filtered_bam.write(aln)\n filtered_bam.close()\n\n tsprint(f\" CZ::filter_bam_by_single_read::{species_id}-0::finish filter_bam_by_single_read\")\n return reads_stats\n\n\ndef filter_bam_by_proper_pair(pargs):\n \"\"\" Filter given BAM file with propely paired reads for given species and write to file \"\"\"\n\n global global_args\n global dict_of_species\n global sample\n\n repbamfile, species_id = pargs\n\n tsprint(f\" CZ::filter_bam_by_proper_pair::{species_id}-0::start filter_bam_by_proper_pair\")\n\n # List of contigs for given species\n list_of_contig_ids = list(dict_of_species[species_id].contigs.keys())\n\n # Cache *properly* aligned reads-pair\n filtered_alns_dict = defaultdict(dict)\n reads_stats = {\n \"aligned_reads\": dict.fromkeys(list_of_contig_ids, 0),\n \"mapped_reads\": dict.fromkeys(list_of_contig_ids, 0)\n }\n\n with AlignmentFile(repbamfile) as infile:\n for contig_id in list_of_contig_ids:\n # To avoid boundary cliff, we need to read in the whole contig\n aligned_reads = 0\n alns_dict = defaultdict(dict) # cache the reads\n for aln in infile.fetch(contig_id):\n aligned_reads += 1\n if aln.is_secondary:\n continue\n if not aln.is_proper_pair:\n continue\n if aln.is_reverse:\n alns_dict[aln.query_name][\"rev\"] = aln\n else:\n alns_dict[aln.query_name][\"fwd\"] = aln\n reads_stats[\"aligned_reads\"][contig_id] = aligned_reads\n\n mapped_reads = 0\n for query_name, alns in alns_dict.items():\n # Ignore orphan reads\n if len(alns) != 2:\n continue\n\n # Common features\n readq = np.mean(alns[\"fwd\"].query_qualities + alns[\"rev\"].query_qualities)\n mapq = max(alns[\"fwd\"].mapping_quality, alns[\"rev\"].mapping_quality)\n\n if readq < global_args.aln_readq:\n continue\n if mapq < global_args.aln_mapq:\n continue\n\n # Template length: number of bases from the left most mapped base to the rightmost mapped base on the reference\n fragment_length = abs(alns[\"fwd\"].template_length)\n\n if fragment_length >= global_args.fragment_length:\n continue\n\n # I think the alignment coverage should not be affected by overlap.\n # However, we should double check whether gaps counted as aligned ..\n align_len = alns[\"fwd\"].query_alignment_length + alns[\"rev\"].query_alignment_length\n query_len = alns[\"fwd\"].query_length + alns[\"rev\"].query_length\n alncov = align_len / float(query_len)\n\n if alncov < global_args.aln_cov:\n continue\n\n # For the compute of sequence identity, we need to specially consider paired-reads overlap\n # Compute the length of the overlapping region along the reference\n reads_overlap = reference_overlap((alns[\"fwd\"].reference_start, alns[\"fwd\"].reference_end - 1), (alns[\"rev\"].reference_start, alns[\"rev\"].reference_end - 1))\n # Compute the query overlap length: substract the gaps in the aligned from the FWD reads to define the overlap boundary\n reads_overlap = update_overlap(reads_overlap, alns[\"fwd\"])\n\n overlap_pass = True\n if reads_overlap:\n # Keep the FWD read, split the REV reads\n (nm_out_rev, nm_in_rev, ngaps_ri_rev, ngaps_ro_rev) = mismatches_within_overlaps(alns[\"rev\"], reads_overlap, \"rev\")\n #assert nm_out_rev + nm_in_rev == dict(alns[\"rev\"].tags)['NM']\n\n # Keep the REV read, split the FWD reads\n (nm_out_fwd, nm_in_fwd, ngaps_ri_fwd, ngaps_ro_fwd) = mismatches_within_overlaps(alns[\"fwd\"], reads_overlap, \"fwd\")\n #assert nm_out_fwd + nm_in_fwd == dict(alns[\"fwd\"].tags)['NM']\n\n # Update the overlap by substracting the number of gaps in the fwd overlap region\n reads_overlap = reads_overlap - ngaps_ri_fwd\n\n # For repeats regions, paired-end reads can be aligned with many gaps, resulting in high mismatches within the overlapping region\n # Only keep aligned pairs indicating from the same DNA fragment\n if abs(nm_in_fwd - nm_in_rev) > 1:\n overlap_pass = False\n continue #<-----------\n\n mismatches = dict(alns[\"fwd\"].tags)['NM'] + nm_out_rev\n\n # Update the aligned_length to compute the mapid\n align_len = alns[\"rev\"].query_alignment_length + alns[\"fwd\"].query_alignment_length - reads_overlap\n align_len_no_gaps = align_len - ngaps_ro_rev - ngaps_ro_fwd - ngaps_ri_fwd\n\n # To avoid overcounting site depth for the overlapping region,\n # \"The higher quality base is used and the lower-quality base is set to BQ=0.\"\n b1 = alns[\"fwd\"].query_alignment_end - reads_overlap\n b2 = alns[\"rev\"].query_alignment_start + reads_overlap - 1\n\n # TODO: loose end => this gives me error using ibd data\n debug_string = \"\\t\".join([str(b1), str(b2), str(reads_overlap), str(len(alns[\"fwd\"].query_alignment_sequence[b1:])), str(len(alns[\"rev\"].query_alignment_sequence[:b2+1])), str(overlap_pass)])\n #assert reads_overlap == len(alns[\"fwd\"].query_alignment_sequence[b1:]), debug_string\n #assert reads_overlap == len(alns[\"rev\"].query_alignment_sequence[:b2+1]), debug_string\n #assert len(alns[\"fwd\"].query_alignment_sequence[b1:]) == len(alns[\"rev\"].query_alignment_sequence[:b2+1])\n # also here\n #if False and reads_overlap != len(alns[\"rev\"].query_alignment_sequence[:b2+1]) and overlap_pass:\n # debug_overlap(alns)\n # print(debug_string)\n\n # Only use the higher quality base in the overlap region for downstream pileup\n f = alns[\"fwd\"].query_qualities[b1:]\n r = alns[\"rev\"].query_qualities[:b2+1]\n for i, _ in enumerate(zip(f, r)):\n (x, y) = _\n if x>=y:\n r[i] = 0\n else:\n f[i] = 0\n alns[\"fwd\"].query_qualities[b1:] = f\n alns[\"rev\"].query_qualities[:b2+1] = r\n\n mapid = 100 * (align_len - mismatches) / float(align_len)\n else:\n mismatches = dict(alns[\"fwd\"].tags)['NM'] + dict(alns[\"rev\"].tags)['NM']\n mapid = 100 * (align_len - mismatches) / float(align_len)\n\n if mapid < global_args.aln_mapid:\n continue\n\n # Compute the mapped reads for the whole contig\n mapped_reads += 2\n filtered_alns_dict[query_name][\"fwd\"] = alns[\"fwd\"]\n filtered_alns_dict[query_name][\"rev\"] = alns[\"rev\"]\n reads_stats[\"mapped_reads\"][contig_id] = mapped_reads\n\n # Write filtered alignments to file\n template_bam = AlignmentFile(repbamfile, \"rb\")\n filtered_bam = AlignmentFile(sample.get_target_layout(\"species_bam\", species_id), \"wb\", template=template_bam)\n for query_name, alns in filtered_alns_dict.items():\n filtered_bam.write(alns[\"fwd\"])\n filtered_bam.write(alns[\"rev\"])\n filtered_bam.close()\n\n tsprint(f\" CZ::filter_bam_by_proper_pair::{species_id}-0::finish filter_bam_by_proper_pair\")\n return reads_stats\n\n\ndef design_chunks_per_species(args):\n sp, midas_db, chunk_size = args\n return sp.design_snps_chunks(midas_db, chunk_size)\n\n\ndef design_chunks(species_ids_of_interest, midas_db, chunk_size):\n \"\"\" Chunks of continuous genomics sites, indexed by species_id, chunk_id \"\"\"\n\n global semaphore_for_species\n global dict_of_species\n\n # Read-only global variables\n semaphore_for_species = dict()\n dict_of_species = {species_id: Species(species_id) for species_id in species_ids_of_interest}\n\n # Design chunks structure per species\n flags = multithreading_map(design_chunks_per_species, [(sp, midas_db, chunk_size) for sp in dict_of_species.values()], 4) #<---\n assert all(flags)\n\n # Sort species by the largest contig length\n sorted_tuples_of_species = sorted(((sp.id, sp.max_contig_length) for sp in dict_of_species.values()), key=itemgetter(1), reverse=True)\n\n arguments_list = []\n for species_id, _ in sorted_tuples_of_species:\n sp = dict_of_species[species_id]\n\n # The structure of the chunks depends on the representative genome sequences\n num_of_sites_chunks = sp.num_of_sites_chunks\n for chunk_id in range(0, num_of_sites_chunks):\n arguments_list.append((species_id, chunk_id))\n\n # Create a semaphore with number_of_chunks of elements\n semaphore_for_species[species_id] = multiprocessing.Semaphore(num_of_sites_chunks)\n for _ in range(num_of_sites_chunks):\n semaphore_for_species[species_id].acquire()\n\n for species_id in dict_of_species.keys():\n arguments_list.append((species_id, -1))\n\n return arguments_list\n\n\ndef process_one_chunk_of_sites(packed_args):\n \"\"\" Process one chunk: either pileup or merge and write results to disk \"\"\"\n\n species_id, chunk_id = packed_args\n\n if chunk_id == -1:\n global semaphore_for_species\n global dict_of_species\n sp = dict_of_species[species_id]\n\n tsprint(f\" CZ::process_one_chunk_of_sites::{species_id}-{chunk_id}::wait merge_chunks_per_species\")\n for _ in range(sp.num_of_sites_chunks):\n semaphore_for_species[species_id].acquire()\n tsprint(f\" CZ::process_one_chunk_of_sites::{species_id}-{chunk_id}::start merge_chunks_per_species\")\n ret = merge_chunks_per_species(species_id)\n tsprint(f\" CZ::process_one_chunk_of_sites::{species_id}-{chunk_id}::finish merge_chunks_per_species\")\n return ret\n\n tsprint(f\" CZ::process_one_chunk_of_sites::{species_id}-{chunk_id}::start compute_pileup_per_chunk\")\n ret = compute_pileup_per_chunk(packed_args)\n tsprint(f\" CZ::process_one_chunk_of_sites::{species_id}-{chunk_id}::finish compute_pileup_per_chunk\")\n\n return ret\n\n\ndef compute_pileup_per_chunk(packed_args):\n \"\"\" Pileup for one chunk, potentially contain multiple contigs \"\"\"\n\n global semaphore_for_species\n global dict_of_species\n global sample\n global global_args\n\n try:\n species_id, chunk_id = packed_args\n sp = dict_of_species[species_id]\n ret = []\n for pargs in sp.chunks_of_sites[chunk_id]:\n ret.append(pileup_per_unit(pargs))\n\n contig_counts_per_chunk = len(sp.chunks_of_sites[chunk_id])\n collect_units_per_chunk(sample, contig_counts_per_chunk, species_id, chunk_id, \"chunk_pileup\")\n\n return ret\n finally:\n semaphore_for_species[species_id].release() # no deadlock\n\n\ndef pileup_per_unit(packed_args):\n \"\"\" Pileup for continuous positions of one contig in one chunk \"\"\"\n\n global global_args\n global dict_of_species\n global sample\n\n # [contig_start, contig_end)\n species_id, chunk_id, contig_id, contig_start, contig_end, count_flag, within_chunk_cid = packed_args\n\n repgenome_bamfile = sample.get_target_layout(\"species_sorted_bam\", species_id)\n headerless_sliced_path = sample.get_target_layout(\"chunk_pileup_perc\", species_id, chunk_id, within_chunk_cid)\n\n zero_rows_allowed = not global_args.sparse\n current_chunk_size = contig_end - contig_start\n contig_seq = dict_of_species[species_id].contigs[contig_id][\"seq\"]\n\n with AlignmentFile(repgenome_bamfile) as bamfile:\n # min_quality_threshold a base has to reach to be counted.\n counts = bamfile.count_coverage(contig_id, contig_start, contig_end, quality_threshold=global_args.aln_baseq)\n\n # aln_stats need to be passed from child process back to parents\n aln_stats = {\n \"species_id\": species_id,\n \"chunk_id\": chunk_id,\n \"contig_id\": contig_id,\n \"chunk_length\": current_chunk_size,\n \"aligned_reads\": 0, #aligned_reads if count_flag and not global_args.paired_only else 0,\n \"mapped_reads\": 0, #mapped_reads if count_flag and not global_args.paired_only else 0,\n \"contig_total_depth\": 0,\n \"contig_covered_bases\": 0,\n }\n\n with OutputStream(headerless_sliced_path) as stream:\n for within_chunk_index in range(0, current_chunk_size):\n depth = sum([counts[nt][within_chunk_index] for nt in range(4)])\n count_a = counts[0][within_chunk_index]\n count_c = counts[1][within_chunk_index]\n count_g = counts[2][within_chunk_index]\n count_t = counts[3][within_chunk_index]\n\n ref_pos = within_chunk_index + contig_start\n ref_allele = contig_seq[ref_pos]\n row = (contig_id, ref_pos + 1, ref_allele, depth, count_a, count_c, count_g, count_t)\n\n aln_stats[\"contig_total_depth\"] += depth\n if depth > 0:\n aln_stats[\"contig_covered_bases\"] += 1\n if depth > 0 or zero_rows_allowed:\n stream.write(\"\\t\".join(map(format_data, row)) + \"\\n\")\n assert within_chunk_index+contig_start == contig_end-1, f\"compute_pileup_per_chunk::index mismatch error for {contig_id}.\"\n\n # Delete temporary bam file <== TODO\n if global_args.paired_only and False:\n command(f\"rm -rf {repgenome_bamfile}\", quiet=False)\n command(f\"rm -rf {repgenome_bamfile}.bai\", quiet=True)\n\n return aln_stats\n\n\ndef merge_chunks_per_species(species_id):\n \"\"\" merge the pileup results from chunks into one file per species \"\"\"\n\n global sample\n global dict_of_species\n\n sp = dict_of_species[species_id]\n number_of_chunks = sp.num_of_sites_chunks\n\n list_of_chunks_pileup = [sample.get_target_layout(\"chunk_pileup\", species_id, chunk_id) for chunk_id in range(0, number_of_chunks)]\n species_snps_pileup_file = sample.get_target_layout(\"snps_pileup\", species_id)\n\n with OutputStream(species_snps_pileup_file) as stream:\n stream.write('\\t'.join(snps_pileup_schema.keys()) + '\\n')\n cat_files(list_of_chunks_pileup, species_snps_pileup_file, 20)\n\n # The chunk_pilup_path will be used in merge_midas_snps.\n if False: #not global_args.debug:\n tsprint(f\"Deleting temporary sliced pileup files for {species_id}.\")\n for s_file in list_of_chunks_pileup:\n command(f\"rm -rf {s_file}\", quiet=True)\n\n # return a status flag\n # the path should be computable somewhere else\n return True\n\n\ndef assign_contig_reads_to_chunks(lalns_stats_by_contig, species_ids_of_interest):\n global dict_of_species\n dchunk_alns_stats = dict()\n for spidx in range(0, len(species_ids_of_interest)):\n species_id = species_ids_of_interest[spidx]\n sp = dict_of_species[species_id]\n\n cc_to_ch = defaultdict(lambda: defaultdict(dict))\n for chunk_id, tchunks_list in sp.chunks_of_sites.items():\n if chunk_id == -1:\n continue\n #[(species_id, chunk_id, contig_id, ci, ci+chunk_size, count_flag, 0)]\n for loc in tchunks_list:\n contig_id = loc[2]\n count_flag = loc[5]\n\n aligned_reads = lalns_stats_by_contig[spidx][\"aligned_reads\"][contig_id]\n mapped_reads = lalns_stats_by_contig[spidx][\"mapped_reads\"][contig_id]\n\n if contig_id not in cc_to_ch[chunk_id]:\n cc_to_ch[chunk_id][contig_id] = {\"aligned_reads\": 0, \"mapped_reads\": 0}\n\n cc_to_ch[chunk_id][contig_id][\"aligned_reads\"] = aligned_reads if count_flag else 0\n cc_to_ch[chunk_id][contig_id][\"mapped_reads\"] = mapped_reads if count_flag else 0\n\n dchunk_alns_stats[species_id] = cc_to_ch\n return dchunk_alns_stats\n\n\ndef write_species_pileup_summary(chunks_pileup_summary, snps_summary_outfile, chunk_output, dchunk_alns_stats):\n \"\"\" Collect species pileup aln stats from all chunks and write to file \"\"\"\n\n species_pileup_summary = defaultdict(dict)\n with OutputStream(chunk_output) as stream:\n stream.write(\"\\t\".join(snps_chunk_summary_schema.keys()) + \"\\n\")\n for records in chunks_pileup_summary:\n if records is True:\n continue\n\n for record in records:\n species_id = record[\"species_id\"]\n chunk_id = record[\"chunk_id\"]\n contig_id = record[\"contig_id\"]\n\n record[\"aligned_reads\"] = dchunk_alns_stats[species_id][chunk_id][contig_id][\"aligned_reads\"]\n record[\"mapped_reads\"] = dchunk_alns_stats[species_id][chunk_id][contig_id][\"mapped_reads\"]\n\n stream.write(\"\\t\".join(map(format_data, record.values())) + \"\\n\")\n\n if species_id not in species_pileup_summary:\n species_pileup_summary[species_id] = {\n \"species_id\": species_id,\n \"genome_length\": 0,\n \"covered_bases\": 0,\n \"total_depth\": 0,\n \"aligned_reads\": 0,\n \"mapped_reads\": 0,\n \"fraction_covered\": 0.0,\n \"mean_coverage\": 0.0\n }\n\n curr_species_pileup = species_pileup_summary.get(species_id)\n curr_species_pileup[\"genome_length\"] += record[\"chunk_length\"]\n curr_species_pileup[\"total_depth\"] += record[\"contig_total_depth\"]\n curr_species_pileup[\"covered_bases\"] += record[\"contig_covered_bases\"]\n curr_species_pileup[\"aligned_reads\"] += record[\"aligned_reads\"]\n curr_species_pileup[\"mapped_reads\"] += record[\"mapped_reads\"]\n\n\n # Secondary round compute: need to loop over species to compute fraction_covered\n for species_id in species_pileup_summary.keys():\n curr_species_pileup = species_pileup_summary.get(species_id)\n if curr_species_pileup[\"genome_length\"] > 0:\n curr_species_pileup[\"fraction_covered\"] = curr_species_pileup[\"covered_bases\"] / curr_species_pileup[\"genome_length\"]\n if curr_species_pileup[\"covered_bases\"] > 0:\n curr_species_pileup[\"mean_coverage\"] = curr_species_pileup[\"total_depth\"] / curr_species_pileup[\"covered_bases\"]\n\n # Write to file\n with OutputStream(snps_summary_outfile) as stream:\n stream.write(\"\\t\".join(snps_profile_schema.keys()) + \"\\n\")\n for record in species_pileup_summary.values():\n stream.write(\"\\t\".join(map(format_data, record.values())) + \"\\n\")\n\n\ndef midas_run_snps(args):\n\n try:\n global global_args\n global_args = args\n\n global sample\n sample = Sample(args.sample_name, args.midas_outdir, \"snps\")\n sample.create_dirs([\"outdir\", \"tempdir\"], args.debug, quiet=True)\n\n species_list = parse_species(args)\n\n # Prepare Bowtie2 genome database path and name, prebuilt or to be built.\n if args.prebuilt_bowtie2_indexes:\n bt2db_dir = os.path.dirname(args.prebuilt_bowtie2_indexes)\n bt2db_name = os.path.basename(args.prebuilt_bowtie2_indexes)\n assert bowtie2_index_exists(bt2db_dir, bt2db_name), f\"Provided {bt2db_dir}/{bt2db_name} don't exist.\"\n\n # Required list of species used to build bowtie2 database to fetch the genome sequences.\n assert (args.prebuilt_bowtie2_species and os.path.exists(args.prebuilt_bowtie2_species)), f\"Need to provide list of speices used to build the provided Bowtie2 indexes.\"\n tsprint(f\"Read in list of species used to build provided bowtie2 indexes {bt2db_dir}/{bt2db_name}\")\n bt2_species_list = []\n with InputStream(args.prebuilt_bowtie2_species) as stream:\n for species_id in select_from_tsv(stream, schema={\"species_id\": str}):\n bt2_species_list.append(species_id[0])\n\n # Update the species list\n species_list = list(set(species_list) & set(bt2_species_list)) if species_list else bt2_species_list\n else:\n sample.create_dirs([\"bt2_indexes_dir\"], args.debug, quiet=True)\n bt2db_dir = sample.get_target_layout(\"bt2_indexes_dir\")\n bt2db_name = \"repgenomes\"\n\n\n # Pileup species: abundant and/or listed species. We don't recommend pileup on too many empty species.\n species_ids_of_interest = species_list if args.select_threshold == -1 else sample.select_species(args, species_list)\n\n species_counts = len(species_ids_of_interest)\n\n sample.create_species_subdirs(species_ids_of_interest, \"temp\", args.debug, quiet=True)\n assert species_counts > 0, f\"No (specified) species pass the marker_depth filter, please adjust the marker_depth or species_list\"\n tsprint(len(species_ids_of_interest))\n\n\n # Fetch representative genome fastas for each species (multiprocessing)\n tsprint(f\"CZ::design_chunks::start\")\n num_cores = min(args.num_cores, species_counts)\n midas_db = MIDAS_DB(args.midas_db if args.midas_db else sample.get_target_layout(\"midas_db_dir\")) #<---- all species\n arguments_list = design_chunks(species_ids_of_interest, midas_db, args.chunk_size)\n tsprint(f\"CZ::design_chunks::finish\")\n\n\n # Build Bowtie indexes for species in the restricted species profile\n contigs_files = midas_db.fetch_files(\"prokka_genome\", species_ids_of_interest)\n tsprint(f\"CZ::build_bowtie2_indexes::start\")\n build_bowtie2_db(bt2db_dir, bt2db_name, contigs_files, args.num_cores)\n tsprint(f\"CZ::build_bowtie2_indexes::finish\")\n\n\n tsprint(f\"CZ::bowtie2_align::start\")\n repgenome_bamfile = sample.get_target_layout(\"snps_repgenomes_bam\")\n bowtie2_align(bt2db_dir, bt2db_name, repgenome_bamfile, args)\n samtools_index(repgenome_bamfile, args.debug, args.num_cores)\n tsprint(f\"CZ::bowtie2_align::finish\")\n\n\n tsprint(f\"CZ::filter_bam_by_proper_pair::start\")\n args_list = [(repgenome_bamfile, species_id) for species_id in species_ids_of_interest]\n if args.paired_only:\n lalns_stats_by_contig = multiprocessing_map(filter_bam_by_proper_pair, args_list, args.num_cores)\n else:\n lalns_stats_by_contig = multiprocessing_map(filter_bam_by_single_read, args_list, args.num_cores)\n\n for species_id in species_ids_of_interest:\n species_bam = sample.get_target_layout(\"species_bam\", species_id)\n species_sorted_bam = sample.get_target_layout(\"species_sorted_bam\", species_id)\n samtools_sort(species_bam, species_sorted_bam, args.debug, args.num_cores)\n samtools_index(species_sorted_bam, args.debug, args.num_cores)\n command(f\"rm -rf {species_bam}\", quiet=True)\n tsprint(f\"CZ::filter_bam_by_proper_pair::finish\")\n\n\n tsprint(f\"CZ::multiprocessing_map::start\")\n chunks_pileup_summary = multiprocessing_map(process_one_chunk_of_sites, arguments_list, args.num_cores)\n tsprint(f\"CZ::multiprocessing_map::finish\")\n\n\n tsprint(f\"CZ::write_species_pileup_summary::start\")\n snps_summary_fp = sample.get_target_layout(\"snps_summary\")\n snps_chunk_summary_fp = sample.get_target_layout(\"snps_chunk_summary\")\n dchunk_alns_stats = assign_contig_reads_to_chunks(lalns_stats_by_contig, species_ids_of_interest)\n write_species_pileup_summary(chunks_pileup_summary, snps_summary_fp, snps_chunk_summary_fp, dchunk_alns_stats)\n tsprint(f\"CZ::write_species_pileup_summary::finish\")\n\n\n except Exception as error:\n if not args.debug:\n tsprint(\"Deleting untrustworthy outputs due to error. Specify --debug flag to keep.\")\n sample.remove_dirs([\"outdir\", \"tempdir\"])\n if not args.prebuilt_bowtie2_indexes:\n sample.remove_dirs([\"bt2_indexes_dir\"])\n raise error\n\n\n@register_args\ndef main(args):\n tsprint(f\"Doing important work in subcommand {args.subcommand} with args\\n{json.dumps(vars(args), indent=4)}\")\n midas_run_snps(args)\n","sub_path":"iggtools/subcommands/midas_run_snps.py","file_name":"midas_run_snps.py","file_ext":"py","file_size_in_byte":40434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"300241679","text":"# -*- coding:utf-8 -*-\nfrom django.conf.urls import patterns, include, url\nfrom mytalk import views\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'myHotel.views.home', name='home'),\n # url(r'^myHotel/', include('myHotel.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n # url(r'^admin/', include(admin.site.urls)),\n #url(r'^site_media/(?P.*)$','django.views.static.serve',{'document_root':settings.STATIC_PATH}),\n url(r'^$',views.index,name='index'),\n url(r'^signIn/$',views.signIn),\n \n url(r'^getStoreMessage/$',views.getStoreMessage),\n url(r'^detectLogin/$',views.detectLogin),\n url(r'^exitOperation/$',views.exitOperation),\n \n url(r'^register/$',views.register),\n\turl(r'^register/doRegister/$',views.doRegister),\n\t\n url(r'^friends/$',views.friends),\n url(r'^friends/message/$',views.message),\n url(r'^friends/deleteFriend/$',views.deleteFriend),\n\t\n url(r'^exchangeUserMessage/$',views.exchangeUserMessage),\n)\n","sub_path":"mytalk/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"266233604","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom bilibili.items import BilibiliItem\n\n\nclass Top100Spider(scrapy.Spider):\n name = 'Top100'\n allowed_domains = ['bilibili.com']\n start_urls = ['https://www.bilibili.com/ranking#!/all/0/0/7/']\n\n def parse(self, response):\n print(response.url)\n lis = response.xpath('//li[@class=\"rank-item\"]')\n print(len(lis))\n\n for li in lis:\n top = li.xpath('.//div[@class=\"num\"]/text()').extract()[0].strip()\n title = li.xpath('.//div[@class=\"info\"]/a/text()').extract()[0].strip()\n author = li.xpath('.//span[@class=\"data-box\"]/text()').extract()[0].strip()\n view = li.xpath('.//span[@class=\"data-box\"]/text()').extract()[1].strip()\n pts = li.xpath('.//div[@class=\"pts\"]/div/text()').extract()[0].strip()\n url = 'https:' + li.xpath('.//div[@class=\"info\"]/a/@href').extract()[0].strip()\n\n item = BilibiliItem()\n item['top'] = top\n item['title'] = title\n item['author'] = author\n item['view'] = view\n item['pts'] = pts\n item['url'] = url\n print(item['top'], item['title'], item['author'], item['view'], item['pts'], item['url'])\n\n yield item\n","sub_path":"pySpider/bilibili/bilibili/spiders/Top100.py","file_name":"Top100.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"429700950","text":"# --coding:utf-8--\nfrom AQ.AQ_pay import Pay\nimport json\nfrom pika.exceptions import AMQPConnectionError\nfrom AQ.pay_queue_center import MsgRpcClient\nfrom aq_log.Journal_class import Journal\nimport traceback\n\n\ndef do_do_pay(data_r, llog=\"\"):\n log = \"\"\n pay = Pay(data=data_r).do_pay()\n if isinstance(pay, dict):\n if pay.get(\"status\") in (500, 404):\n resp = {\n \"请求数据\": data_r,\n \"响应数据\": pay\n }\n Journal().save_journal_pay(massage=json.dumps(resp), level=\"error\")\n return pay\n else:\n resp = {\n \"请求数据\": data_r,\n \"响应数据\": pay\n }\n Journal().save_journal_pay(massage=json.dumps(resp))\n return pay\n print(\"开始发送请求...\", end=\"\")\n param = {\n \"username\": \"ys\",\n \"password\": \"ysmq\",\n \"host\": \"192.168.0.100\",\n \"port\": 5672,\n \"virtual_host\": \"/\",\n \"heart_beat\": 6,\n \"exchange\": \"YS.机票.支付\",\n \"routing_key\": \"YS.机票.支付.支付中心.支付宝\",\n \"queue\": \"YS.机票.支付.支付中心.支付宝\",\n \"socket_timeout\": 10,\n \"time_out\": 120\n }\n _data = {\n 'bankUrl': pay[0],\n 'totalPrice': int(pay[1]),\n 'orderNo': pay[2],\n 'airline': pay[3]\n }\n _data = json.dumps(_data, ensure_ascii=False)\n try:\n response = MsgRpcClient(**param).call(_data)\n print(f\"pass→收到 {response} \")\n res = json.loads(response)\n print(type(res))\n if res.get(\"status\") == 0:\n res[\"payPrice\"] = pay[1]\n resp = {\n \"请求数据\": data_r,\n \"响应数据\": res\n }\n Journal().save_journal_pay(massage=json.dumps(resp))\n return res\n else:\n res[\"user\"] = pay[4]\n res[\"pwd\"] = pay[5]\n resp = {\n \"请求数据\": data_r,\n \"响应数据\": res\n }\n Journal().save_journal_pay(massage=json.dumps(resp), level=\"warn\")\n return res\n except AMQPConnectionError:\n print(\"fail→连接失败\")\n pay = {\n \"status\": 1,\n \"msg\": f\"支付时遇到链接失败,请人工手动登录查看是否支付成功,账号:{pay[4]},密码:{pay[5]}\",\n }\n resp = {\n \"请求数据\": data_r,\n \"响应数据\": pay\n }\n Journal().save_journal_pay(massage=json.dumps(resp), level=\"warn\")\n return pay\n except TimeoutError:\n pay = {\n \"status\": 1,\n \"msg\": f\"支付时遇到请求超时,请人工手动登录查看是否支付成功,账号:{pay[4]},密码:{pay[5]}\",\n }\n resp = {\n \"请求数据\": data_r,\n \"响应数据\": pay\n }\n Journal().save_journal_pay(massage=json.dumps(resp), level=\"warn\")\n return pay\n except Exception as e:\n print(e)\n pay = {\n \"status\": 1,\n \"msg\": f\"支付时遇到异常,请人工手动登录查看是否支付成功,账号:{pay[4]},密码:{pay[5]},\"\n + traceback.format_exc(),\n }\n resp = {\n \"请求数据\": data_r,\n \"响应数据\": pay\n }\n Journal().save_journal_pay(massage=json.dumps(resp), level=\"error\")\n return pay\n","sub_path":"do_pay.py","file_name":"do_pay.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"353070476","text":"import requests\nfrom bs4 import BeautifulSoup\n\ndef get_availablity(url):\n soup = BeautifulSoup(requests.get(url).content, \"html.parser\")\n\n data = soup.find('div', {'id': 'data'}).findAll('td')\n\n all_products = []\n product = {}\n counter = 0\n product_details = ''\n availablility = []\n\n for td in data:\n product_name = td.find('a')\n if not product_name:\n product_details += ' ' + td.text\n else:\n if 'Ebay' not in product_name and counter != 0:\n product[counter] = product_details\n product['link' + str(counter)] = product_name['href']\n all_products.append(product)\n counter += 1\n product_details = product_name.text\n else:\n counter += 1\n product_details = product_name.text\n\n for i in range(len(all_products)):\n product = all_products[i][i+1]\n if 'Available' in product:\n availablility.append({'details': product, 'link' : all_products[i]['link' + str(i + 1)]})\n\n return availablility\n \n\n\n ","sub_path":"checker.py","file_name":"checker.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}