diff --git "a/3181.jsonl" "b/3181.jsonl" new file mode 100644--- /dev/null +++ "b/3181.jsonl" @@ -0,0 +1,643 @@ +{"seq_id":"275041773","text":"from . import *\nfrom app.irsystem.models.search import *\nfrom app.irsystem.models.helpers import *\nfrom app.irsystem.models.helpers import NumpyEncoder as NumpyEncoder\n\nproject_name = \"Melodic Monkeys: Movie Recommendations Based on Music Preferences\"\nnet_id = \"Amber Baez: ab2252, Betsy Vasquez Valerio: blv9, \" \\\n \"Kateryna Romanyuk: kr485, Patrick Neafsey: pmn28, Shilpy Agarwal: sa2229\"\n\n@irsystem.route('/about.html')\ndef go_to_about():\n return render_template('about.html')\n\n@irsystem.route('/', methods=['GET'])\ndef search():\n artist = request.args.get('artist')\n song = request.args.get('song')\n movie = request.args.get('movie')\n quote = request.args.get('quote')\n amazon = request.args.get('amazon')\n disney = request.args.get('disney')\n hbo = request.args.get('hbo')\n hulu = request.args.get('hulu')\n netflix = request.args.get('netflix')\n output_message = 'Please enter a movie to get results!'\n if not movie:\n data = []\n elif find_movie(movie)=='ERROR':\n output_message = 'We did not find the movie you searched for. Did you spell it correctly?'\n data = []\n else:\n data = get_data(artist, song, movie, quote, amazon, disney, hbo, hulu, netflix)\n return render_template('search.html', name=project_name, netid=net_id, output_message=output_message, data=data)\n","sub_path":"app/irsystem/controllers/search_controller.py","file_name":"search_controller.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"41860753","text":"#Programming Project 6 - Lists\r\n#Robert Bayer\r\n#Gets a 7 Digit Number from the user and presents all combinations of characters associated with those numbers\r\n\r\n#Gets a number from the user\r\ndef getnum():\r\n numberlist = []\r\n number = \"00000000\"\r\n #gets the proper length of number\r\n while len(number) != 7:\r\n number = input(\"Enter a seven number digit: \")\r\n #turns the number into a list to make it easier to parse\r\n for i in number:\r\n i = int(i)\r\n numberlist += [i]\r\n return numberlist\r\n\r\n#takes each of the entries in the number's list and cycles through each one present all possible character combinations\r\ndef combos(numberlist):\r\n #list of all letters associated with each number\r\n nums = [[\"A\", \"B\", \"C\"], [\"D\", \"E\", \"F\"], [\"G\", \"H\", \"I\"], [\"J\", \"K\", \"L\"], [\"M\", \"N\", \"O\"],\r\n [\"P\", \"Q\", \"R\", \"S\"], [\"T\", \"U\", \"V\"], [\"W\", \"X\", \"Y\", \"Z\"]]\r\n #list of numbers that will actually return a letter\r\n accept = [2,3,4,5,6,7,8,9]\r\n word = \"\"\r\n result = []\r\n #the loop that cycles through each character at each level\r\n for k in nums[numberlist[0]-2]:\r\n for l in nums[numberlist[1]-2]:\r\n for m in nums[numberlist[2]-2]:\r\n for n in nums[numberlist[3]-2]:\r\n for o in nums[numberlist[4]-2]:\r\n for p in nums[numberlist[5]-2]:\r\n for q in nums[numberlist[6]-2]:\r\n #These if statements replace any 1 or 0 with a blank character spot\r\n if numberlist[0] not in accept:\r\n k = \" \"\r\n if numberlist[1] not in accept:\r\n l = \" \"\r\n if numberlist[2] not in accept:\r\n m = \" \"\r\n if numberlist[3] not in accept:\r\n n = \" \"\r\n if numberlist[4] not in accept:\r\n o = \" \"\r\n if numberlist[5] not in accept:\r\n p = \" \"\r\n if numberlist[6] not in accept:\r\n q = \" \"\r\n #building the \"word\"\r\n word = k + l + m + n + o + p + q\r\n #adding the word to a list\r\n result += [word]\r\n #resetting the word variable\r\n word = \"\"\r\n return result\r\n\r\n#main working function\r\ndef main():\r\n cont = \"y\"\r\n #sets a loop to continue for as any times as wanted\r\n while cont == \"y\":\r\n #gets the numlist and sets it where it can be accessed\r\n numlist = getnum()\r\n #gets the list of results to an accessible level\r\n results = combos(numlist)\r\n #prints the results on their own line\r\n for i in results:\r\n print(i)\r\n #asks if user wants to do it again\r\n cont = input(\"Do you want to continue? (y/n): \")\r\n\r\n\r\n#calling the main working function\r\nmain()","sub_path":"Testing Lists.py","file_name":"Testing Lists.py","file_ext":"py","file_size_in_byte":3222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"116174735","text":"#coding=utf-8\nimport requests\nfrom bs4 import BeautifulSoup\nimport json\n\n\ndic = {\n 'Labelxydm':'SchoolCode', #学院代码\n 'Labelxymc':'School', #学院名称\n 'Labeldsdm': 'IdentifyCode', #导师代码\n 'Labeldsxm': 'Name', #导师姓名\n 'Labelxb': 'Gender', #性别\n 'Labelcsny': 'Birth', #出生年月\n 'Labeltc': 'Special', #特称\n 'Labelzc': 'Title', #职称\n 'Labellb': 'Kind', #类别\n 'Labelxw': 'Degree', #学位\n 'Labelsx': 'Property', #属性\n 'Labelemail': 'Email', #电子邮件\n 'Labelxsjl': 'Experience', #学术经历\n 'Labelgrjj': 'Introduction', #个人简介\n 'lblKyxm': 'Project', #科研项目\n 'lblFbwz': 'Paper', #发表文章\n 'Labelbszydm1':'PhdMajor1Code', #博士招生代码1\n 'Labelbszymc1':'PhdMajor1Name', #博士招生名称1\n 'Labelsszydm1':'MasterMajor1Code', #硕士招生代码1\n 'Labelsszymc1':'MasterMajor1Name', #硕士招生名称1\n 'Labelbszydm2':'PhdMajor2Code', #博士招生代码2\n 'Labelbszymc2':'PhdMajor2Name', #博士招生名称2\n 'Labelsszydm2':'MasterMajor2Code', #硕士招生代码2\n 'Labelsszymc2':'MasterMajor2Name', #硕士招生名称2\n 'Labelbszydm3':'PhdMajor3Code', #博士招生代码3\n 'Labelbszymc3':'PhdMajor3Name', #博士招生名称3\n 'Labelsszydm3':'MasterMajor3Code', #硕士招生代码3\n 'Labelsszymc3':'MasterMajor3Name', #硕士招生名称3\n 'Labelbszydm4':'PhdMajor4Code', #博士招生代码4\n 'Labelbszymc4':'PhdMajor4Name', #博士招生名称4\n 'Labelsszydm4':'MasterMajor4Code', #硕士招生代码4\n 'Labelsszymc4':'MasterMajor4Name', #硕士招生名称4\n 'Labelbszydm5':'PhdMajor5Code', #博士招生名称5\n 'Labelbszymc5':'PhdMajor5Name', #博士招生名称5\n 'Labelsszydm5':'MasterMajor5Code', #硕士招生代码5\n 'Labelsszymc5':'MasterMajor5Name', #硕士招生名称5\n}\n\ndef getHtml(url):\n try:\n res= requests.get(url)\n res.raise_for_status() #若发生错误请求,则抛出异常\n res.encoding = res.apparent_encoding #从内容中分析出的响应内容编码方式\n return res.text\n except:\n return None\n\nif __name__ == \"__main__\":\n JZY_id = 666;\n html = getHtml(\"http://222.197.183.99/TutorDetails.aspx?id=\" + str(JZY_id))\n if(html != None):\n soup = BeautifulSoup(html,'html.parser')\n content = soup.find(id =\"main\")\n items = content.find_all('span')\n prereadydata = {}\n\n ##提取学院代码、学院名称、导师代码、导师姓名等信息\n for i in range(0,len(items)):\n if(items[i].string != None and 'id' in items[i].attrs):\n code = items[i].attrs['id']\n prereadydata[dic[code]] = items[i].string\n prereadydata['University'] = \"电子科技大学\"\n prereadydata['UniversityCode'] = \"10614\"\n\n ##若招生代码存在,则提取招生方向信息\n if 'PhdMajor1Code' or 'MasterMajor1Code' in prereadydata:\n itemMajor = content.select(\"table .l-wrap\")\n detail = {}\n for i in range(0, len(itemMajor)):\n Code = itemMajor[i].select(\".width4em\")\n Name = itemMajor[i].select(\".alignleft\")\n if (i % 2 == 1):\n degree = \"Master\"\n else:\n degree = \"Phd\"\n for j in range(0,len(Code)):\n ##招生方向序号 EX:detail[MasterMajor1Filed1Code] = “01方向:”\n detail[degree + 'Major'+ str(int(i/2)+1) + 'Field'+str(j+1)+'Code'] = Code[j].string.strip()\n ##招生方向名称 EX:detail[PhdMajor1Field1Name] = “软件理论与技术”\n detail[degree + 'Major'+ str(int(i/2)+1) + 'Field'+str(j+1)+'Name'] = Name[j].string.strip()\n if detail != {}:\n prereadydata['MajorFeildDetail']=detail\n try:\n with open('D:/data/ZhanJinYu_Info.json','w') as f:\n json.dump(prereadydata, f, ensure_ascii = False)\n print(\"Success Finish\")\n except:\n print(\"File Write Error\")\n else:\n print(\"Get Html Error\")","sub_path":"get_ZhanJinYu_info_获取詹瑾瑜老师的基本信息.py","file_name":"get_ZhanJinYu_info_获取詹瑾瑜老师的基本信息.py","file_ext":"py","file_size_in_byte":4212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"130462796","text":"__author__ = 'yangchenxing'\nfrom collections import defaultdict\n\n\nclass DefaultDictMaker(object):\n def __call__(self):\n return defaultdict(self)\n\n\nclass LocationSelector(object):\n def __init__(self):\n self._static_path_dict = defaultdict(DefaultDictMaker())\n self._regex_path_list = []\n\n def add_path(self, path, location_pipeline):\n if type(path) is str or type(path) is unicode:\n path_dict = self._static_path_dict\n paths = path.split('/')[1:]\n for path in paths[:-1]:\n path_dict = path_dict[path]\n path_dict[paths[-1]] = location_pipeline\n else:\n self._regex_path_list.append((path, location_pipeline))\n\n def select(self, path):\n paths = path.split('/')[1:]\n path_dict = self._static_path_dict\n for path in paths:\n if path in path_dict:\n path_dict = path_dict[path]\n if type(path_dict) is tuple:\n return path_dict[1]\n for regex, pipeline in self._regex_path_list:\n if regex.match(path):\n return pipeline","sub_path":"src/http/localtion_selector.py","file_name":"localtion_selector.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"161418023","text":"# Density_Function_Theory - KIT v1.0.0 \n# August 2014\n# Implementation for how to construct calculation for doing VASP calculation with DFT_KIT\n\nimport numpy as np\nimport os\nimport sys\nimport pickle\n\nfrom DFT_KIT.core import job, kpoint, element, crystal_3D\nfrom DFT_KIT.calculator import QESPRESSO\nfrom DFT_KIT.apps import crystal_structure\nfrom DFT_KIT.interface import interface_script\nfrom DFT_KIT.apps import bismuth_antimony\n\n[input_parm,opt_parm]=interface_script.init_simulation(0)\nk_min=5\nk_max=20\nall_ks=range(k_min,k_max+1)\n\ndft_job=job.job(subdir=True)\ndft_job.process_opt_parm(opt_parm)\n\n# first round, self-consistent calculation\ndft_kgrid=kpoint.kpoint()\n\n#set the kgrid\ndft_job.sys_info['qes_prefix']='bismuth'\ndft_job.sys_info['qes_fname']='bismuth_kconv'\ndft_crystal=crystal_structure.a7_structure(bismuth_antimony.Bi_exp,length_unit=1.0)\ndft_calc=QESPRESSO.calculator_QESPRESSO(False,dft_job,dft_crystal,dft_kgrid,scheme=1)\ndft_calc.load_parm(False, bismuth_antimony.Bi_qespresso_crystal_scf)\n\noutput_es=[]\nfor ind,k_now in enumerate(all_ks):\n if ind>0:\n dft_job.next_task(True)\n dft_kgrid.set_grid_mode([k_now,k_now,k_now])\n dft_calc.run_calculation()\n output_es.append(dft_calc.output['total_energy'])\n\ndft_job.back_to_root()\npickle.dump(output_es,open('kgrid_conv','wb'))\n\n\n","sub_path":"examples/QESPRESSO_kgrid_convergence_loop.py","file_name":"QESPRESSO_kgrid_convergence_loop.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"70476255","text":"import socket\nimport time\nimport threading\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport os\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-t', '--dir', action=\"store\")\nargs = parser.parse_args()\n\nresult_dir = args.dir\nif not os.path.exists(result_dir):\n os.makedirs(result_dir)\n\ndef Send_Handler(s, addr):\n send_array = np.empty([10000, 2])\n seq_num = 0\n while True:\n stamp = time.time()\n send_array[seq_num] = [seq_num, stamp]\n message = \"{},{}\".format(seq_num, stamp)\n print(\"send,\"+message)\n s.sendto(message.encode('utf-8'), addr)\n pause = stamp+0.02-time.time()\n seq_num += 1\n if pause > 0:\n time.sleep(pause)\n if seq_num == 10000:\n break\n columns = ['seq_no', 'send_time']\n df = pd.DataFrame(send_array, columns=columns)\n df.to_pickle(result_dir + \"/udp_norport_send.pkl\")\n\ndef Recv_Handler(s):\n rec_array = np.empty([10000, 2])\n count = 0\n while True:\n data, addr = s.recvfrom(4096)\n data = data.decode('utf-8')\n count += 1\n stamp = time.time()\n print(data)\n try:\n seq, _ = str(data).split(\",\")\n ind = int(seq)\n rec_array[ind] = [ind, stamp]\n except:\n pass\n if count == 10000:\n break\n columns = ['seq_no', 'rec_time']\n df = pd.DataFrame(rec_array, columns=columns)\n df.to_pickle(result_dir + \"/udp_nodeport_rec.pkl\")\n\ndef Main():\n host = \"130.235.202.199\"\n # host = \"130.235.202.201\"\n # port = 12345\n port = 31234\n s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\n print(\"connect to socket\")\n send = threading.Thread(target=Send_Handler, args=(s, (host, port),))\n recv = threading.Thread(target=Recv_Handler, args=(s, ))\n send.start()\n recv.start()\n send.join()\n recv.join()\n s.close()\n\nif __name__ == '__main__':\n Main()\n","sub_path":"scripts/udp-echo/udp-client.py","file_name":"udp-client.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"332824843","text":"from events import BaseEvent\nfrom events import CustomerEvent\nfrom events import ImageUploadEvent\nfrom events import OrderEvent\nfrom events import SiteVisitEvent\n\nfrom datetime import datetime, timedelta\nimport operator\nimport pprint\nimport time\n\ndef Ingest(e, D):\n if isinstance(e, dict):\n if 'type' in e:\n event = None\n\n if e['type'] == 'CUSTOMER':\n print(e)\n event = CustomerEvent(e)\n\n elif e['type'] == 'SITE_VISIT':\n event = SiteVisitEvent(e)\n elif e['type'] == 'IMAGE_UPLOAD':\n event = ImageUploadEvent(e)\n elif e['type'] == 'ORDER':\n event = OrderEvent(e)\n\n if not event == None:\n event.merge(D)\n\n\"\"\"\nReturns the top x customers by Simple LTV in descending order.\n\"\"\"\ndef TopXSimpleLTVCustomerEvents(x, D):\n if (isinstance(x, int) or isinstance(x, long)):\n if not D.get('ORDER') == None and len(D['ORDER']) > 0:\n all_customers = set()\n min_date = None\n max_date = None\n\n for key, attributes in D['ORDER'].items():\n all_customers.add(attributes['customer_id'].value)\n if (min_date == None or attributes['created_time'].value < min_date):\n min_date = attributes['created_time'].value\n if (max_date == None or attributes['created_time'].value > max_date):\n max_date = attributes['created_time'].value\n\n min_week = __startOfWeek(min_date)\n max_week = __startOfWeek(max_date)\n\n weekly_structure = __generate_weekly_structure(min_week, max_week, all_customers)\n __populate_weekly_structure(weekly_structure, D['ORDER'])\n customer_ltvs = __generate_customer_ltvs(weekly_structure)\n\n return __top_x_ltvs(x, customer_ltvs)\n\n return []\n\n\ndef __startOfWeek(date):\n current_date = date\n\n # While index is not Sunday\n while current_date.weekday() != 6:\n current_date = current_date - timedelta(days=1)\n\n return current_date.date()\n\n\"\"\"\nLooks like:\n {\n '2016-52': {\n 'customer_id_1': {\n num_orders: 0,\n week_average: 0\n },\n 'customer_id_2': {\n num_orders: 0,\n week_average: 0\n }\n },\n '2017-01': {\n 'customer_id_1': {\n num_orders: 0,\n week_average: 0\n },\n 'customer_id_2': {\n num_orders: 0,\n week_average: 0\n }\n }\n }\n\"\"\"\ndef __generate_weekly_structure(min_week, max_week, customers):\n weekly_structure = {}\n current_week = min_week\n\n while current_week <= max_week:\n week_structure = {}\n for customer in customers:\n week_structure[customer] = {\n 'num_orders': 0,\n 'week_average': 0\n }\n weekly_structure[current_week] = week_structure\n\n current_week = current_week + timedelta(weeks=1)\n\n return weekly_structure\n\n\"\"\"\nFills weekly_structure's num_orders and week_average.\n\"\"\"\ndef __populate_weekly_structure(weekly_structure, orders):\n for order_key, order_attributes in orders.items():\n if not order_attributes.get('created_time') == None:\n order_week = __startOfWeek(order_attributes['created_time'].value)\n customer_structure = weekly_structure[order_week][order_attributes['customer_id'].value]\n\n num_orders = customer_structure['num_orders']\n week_average = customer_structure['week_average']\n total_amount = order_attributes['total_amount'].value\n\n customer_structure['week_average'] = (num_orders * week_average + total_amount) / (num_orders + 1)\n customer_structure['num_orders'] += 1\n\n weekly_structure[order_week][order_attributes['customer_id'].value] = customer_structure\n\n\"\"\"\nCalculates ltv (52(a) * 10) for each customer\n\nLooks like:\n {\n 'customer_1': 80,\n 'customer_2': 85\n }\n\"\"\"\ndef __generate_customer_ltvs(weekly_structure):\n \"\"\"\n First calculate total of weekly averages for each customer.\n \"\"\"\n customer_totals = {}\n\n for week, customers in weekly_structure.items():\n for customer, values in customers.items():\n if customer_totals.get(customer) == None:\n customer_totals[customer] = values['week_average']\n else:\n customer_totals[customer] += values['week_average']\n\n \"\"\"\n Now calculate average customer value per week for each customer.\n \"\"\"\n customer_averages = customer_totals\n customer_totals = None\n\n for customer, total in customer_averages.items():\n customer_averages[customer] = total / len(weekly_structure)\n\n \"\"\"\n Now calculate LTVs.\n \"\"\"\n customer_ltvs = customer_averages\n customer_averages = None\n\n for customer, average in customer_ltvs.items():\n customer_ltvs[customer] = 52 * average * 10\n\n return customer_ltvs\n\n\"\"\"\nAs long as x is small, this is O(len(customer_ltvs)).\n\"\"\"\ndef __top_x_ltvs(x, customer_ltvs):\n min_ltv = None\n min_customer = None\n top_dict = {}\n\n for customer, ltv in customer_ltvs.items():\n # check if should add customer\n if (min_ltv == None or len(top_dict) < x or ltv > min_ltv):\n # remove smallest customer in top_dict\n if len(top_dict) == x:\n del top_dict[min_customer]\n # add customer\n top_dict[customer] = ltv\n # (re)calculate min_ltv and min_customer\n if min_ltv == None:\n min_ltv = ltv\n min_customer = customer\n else:\n for c, l in top_dict.items():\n if l < min_ltv:\n min_ltv = l\n min_customer = c\n\n top_dict_sorted = sorted(top_dict.items(), key=operator.itemgetter(1), reverse=True)\n top_dict_sorted_formatted = [{'customer_id': item[0], 'simple_ltv': item[1]} for item in top_dict_sorted]\n\n return top_dict_sorted_formatted\n","sub_path":"src/shutterfly_code_challenge/main/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"191749467","text":"import six\nif six.PY3:\n from io import StringIO\nelse:\n from StringIO import StringIO\n\nfrom .config import COLUMNS_1, is_number\nfrom .base import BaseSmartCSVTestCase\n\nimport smartcsv\nfrom smartcsv.exceptions import InvalidCSVException, InvalidCSVHeaderException\n\n\nclass InvalidCSVTestCase(BaseSmartCSVTestCase):\n def test_invalid_header_fails_creating_the_reader(self):\n \"\"\"Should fail to create the reader if the header is invalid\"\"\"\n # Missing category header column\n csv_data = \"\"\"\ntitle,subcategory,currency,price,url,image_url\niPhone 5c blue,Phones,Smartphones,USD,699,http://apple.com/iphone,http://apple.com/iphone.jpg\n\"\"\"\n self.assertRaises(InvalidCSVHeaderException, lambda: smartcsv.reader(StringIO(csv_data), columns=COLUMNS_1))\n\n def test_if_number_of_fields_is_invalid(self):\n \"\"\"Should fail if the number of fields provided by the CSV is invalid\"\"\"\n # Missing category field\n csv_data = \"\"\"\ntitle,category,subcategory,currency,price,url,image_url\niPhone 5c blue,Smartphones,USD,699,http://apple.com/iphone,http://apple.com/iphone.jpg\n \"\"\"\n reader = smartcsv.reader(StringIO(csv_data), columns=COLUMNS_1)\n try:\n next(reader)\n except InvalidCSVException as e:\n self.assertTrue(e.errors is not None)\n self.assertTrue('row_length' in e.errors)\n\n def test_required_fields_fail_if_no_value_is_provided(self):\n \"\"\"Should fail if a required field is missing\"\"\"\n # Category data is missing (and it's required)\n csv_data = \"\"\"\ntitle,category,subcategory,currency,price,url,image_url\niPhone 5c blue,,Smartphones,USD,699,http://apple.com/iphone,http://apple.com/iphone.jpg\n\"\"\"\n reader = smartcsv.reader(StringIO(csv_data), columns=COLUMNS_1)\n try:\n next(reader)\n except InvalidCSVException as e:\n self.assertTrue(e.errors is not None)\n self.assertTrue('category' in e.errors)\n\n def test_fail_if_choices_doesnt_match(self):\n \"\"\"Should fail if the provided value is not contained in the model choices\"\"\"\n csv_data = \"\"\"\ntitle,category,subcategory,currency,price,url,image_url\niPhone 5c blue,Phones,Smartphones,INVALID,699,http://apple.com/iphone,http://apple.com/iphone.jpg\n \"\"\"\n reader = smartcsv.reader(StringIO(csv_data), columns=COLUMNS_1)\n try:\n next(reader)\n except InvalidCSVException as e:\n self.assertTrue(e.errors is not None)\n self.assertTrue('currency' in e.errors)\n\n def test_fail_if_validator_doesnt_validate(self):\n \"\"\"Should fail if the custom validator doesn't pass\"\"\"\n\n # Preconditions. test if `is_number` works as expected\n self.assertTrue(is_number(699))\n self.assertTrue(is_number(\"699\"))\n self.assertTrue(is_number(699.23))\n self.assertTrue(is_number(\"699.23\"))\n self.assertFalse(is_number(\"ABC\"))\n\n csv_data = \"\"\"\ntitle,category,subcategory,currency,price,url,image_url\niPhone 5c blue,Phones,Smartphones,USD,INVALID,http://apple.com/iphone,http://apple.com/iphone.jpg\n \"\"\"\n reader = smartcsv.reader(StringIO(csv_data), columns=COLUMNS_1)\n\n try:\n next(reader)\n except InvalidCSVException as e:\n self.assertTrue(e.errors is not None)\n self.assertTrue('price' in e.errors)\n\n def test_invalid_validator_in_columns_argument(self):\n columns = COLUMNS_1[:]\n image_url_column = columns.pop(-1).copy()\n image_url_column['validator'] = 3 # Not a callable. Invalid\n columns.append(image_url_column)\n\n csv_data = \"\"\"\ntitle,category,subcategory,currency,price,url,image_url\niPhone 5c blue,Phones,Smartphones,USD,399,http://apple.com/iphone,http://apple.com/iphone.jpg\n \"\"\"\n reader = smartcsv.reader(StringIO(csv_data), columns=columns)\n\n self.assertRaises(AttributeError, lambda: list(next(reader)))\n","sub_path":"tests/test_invalid_csv.py","file_name":"test_invalid_csv.py","file_ext":"py","file_size_in_byte":3969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"567209408","text":"# -*- coding: utf-8 -*-\n\"\"\"Bro/Zeek log data model.\"\"\"\n\nimport abc\nimport collections\nimport types\n\nimport zlogging._typing as typing\nfrom zlogging._aux import expand_typing\nfrom zlogging._exc import ModelTypeError, ModelValueError, ModelFormatError\nfrom zlogging.types import BaseType\n\n__all__ = [\n 'Model', 'new_model',\n]\n\n\nclass Model(metaclass=abc.ABCMeta):\n \"\"\"Log data model.\n\n Attributes:\n __fields__ (:obj:`OrderedDict` mapping :obj:`str` and :class:`~zlogging.types.BaseType`):\n Fields of the data model.\n __record_fields__ (:obj:`OrderedDict` mapping :obj:`str` and :class:`RecordType`):\n Fields of ``record`` data type in the data model.\n __empty_field__ (bytes): Placeholder for empty field.\n __unset_field__ (bytes): Placeholder for unset field.\n __set_separator__ (bytes): Separator for set/vector fields.\n\n Warns:\n BroDeprecationWarning: Use of ``bro_*`` type annotations.\n\n Raises:\n :exc:`ModelValueError`: In case of inconsistency between field\n data types, or values of ``unset_field``, ``empty_field`` and\n ``set_separator``.\n :exc:`ModelTypeError`: Wrong parameters when initialisation.\n\n Note:\n Customise the :meth:`Model.__post_init__ ` method\n in your subclassed data model to implement your own ideas.\n\n Example:\n Define a custom log data model using the prefines Bro/Zeek data types,\n or subclasses of :class:`~zlogging.types.BaseType`::\n\n class MyLog(Model):\n field_one = StringType()\n field_two = SetType(element_type=PortType)\n\n Or you may use type annotations as `PEP 484`_ introduced when declaring\n data models. All available type hints can be found in\n :mod:`zlogging.typing`::\n\n class MyLog(Model):\n field_one: zeek_string\n field_two: zeek_set[zeek_port]\n\n However, when mixing annotations and direct assignments, annotations\n will take proceedings, i.e. the :class:`Model` class shall process first\n annotations then assignments. Should there be any conflicts,\n ``ModelError`` will be raised.\n\n See Also:\n\n See :func:`~zlogging._aux.expand_typing` for more information about\n processing the fields.\n\n .. _PEP 484:\n https://www.python.org/dev/peps/pep-0484/\n\n \"\"\"\n\n @property\n def fields(self) -> typing.OrderedDict[str, BaseType]:\n \"\"\":obj:`OrderedDict` mapping :obj:`str` and :class:`~zlogging.types.BaseType`: fields of the data model\"\"\"\n return self.__fields__\n\n @property\n def unset_field(self) -> bytes:\n \"\"\"bytes: placeholder for empty field\"\"\"\n return self.__unset_field__\n\n @property\n def empty_field(self) -> bytes:\n \"\"\"bytes: placeholder for unset field\"\"\"\n return self.__empty_field__\n\n @property\n def set_separator(self) -> bytes:\n \"\"\"bytes: separator for set/vector fields\"\"\"\n return self.__set_separator__\n\n def __new__(cls, *args, **kwargs): # pylint: disable=unused-argument\n expanded = expand_typing(cls, ModelValueError)\n\n cls.__fields__ = expanded['fields']\n cls.__record_fields__ = expanded['record_fields']\n cls.__doc__ = 'Initialise ``%s`` data model.' % cls.__name__\n\n cls.__unset_field__ = expanded['unset_field']\n cls.__empty_field__ = expanded['empty_field']\n cls.__set_separator__ = expanded['set_separator']\n\n return super().__new__(cls)\n\n def __init__(self, *args, **kwargs):\n init_args = collections.OrderedDict()\n\n field_names = list(self.__fields__)\n if len(args) > len(field_names):\n raise ModelTypeError('__init__() takes %d positional arguments but %d were given' % (len(field_names), len(args))) # pylint: disable=line-too-long\n for index, arg in enumerate(args):\n name = field_names[index]\n init_args[name] = self.__fields__[name](arg)\n for arg, val in kwargs.items():\n if arg in init_args:\n raise ModelTypeError('__init__() got multiple values for argument %r' % arg)\n if arg not in field_names:\n if arg in self.__record_fields__ and isinstance(val, dict):\n for arg_nam, arg_val in val.items():\n name = '%s.%s' % (arg, arg_nam)\n if name not in self.__fields__:\n raise ModelTypeError('__init__() got an unexpected keyword argument %r' % name)\n init_args[name] = self.__fields__[name](arg_val)\n continue\n raise ModelTypeError('__init__() got an unexpected keyword argument %r' % arg)\n init_args[arg] = self.__fields__[arg](val)\n\n diff = list()\n for field in field_names:\n if field in init_args:\n continue\n diff.append(field)\n if diff:\n length = len(diff)\n if length == 1:\n diff_args = repr(diff[0])\n elif length == 2:\n diff_args = '%r and %r' % tuple(diff)\n else:\n diff_args = '%s, and %r' % (', '.join(map(repr, diff_args[:-1])), diff_args[-1])\n raise ModelTypeError('missing %d required positional arguments: %s' % (length, diff_args))\n\n for key, val in init_args.items():\n setattr(self, key, val)\n self.__post_init__()\n\n def __post_init__(self):\n \"\"\"Post-processing customisation.\"\"\"\n\n def __str__(self) -> str:\n fields = list()\n for field in self.__fields__:\n value = getattr(self, field)\n fields.append('%s=%s' % (field, value))\n return '%s(%s)' % (type(self).__name__, ', '.join(fields))\n\n def __repr__(self) -> str:\n fields = list()\n for field in self.__fields__:\n value = getattr(self, field)\n fields.append('%s=%s' % (field, value))\n return '%s(%s)' % (type(self).__name__, ', '.join(fields))\n\n def __call__(self, format: str) -> typing.Any: # pylint: disable=redefined-builtin\n \"\"\"Serialise data model with given format.\n\n Args:\n format: Serialisation format.\n\n Returns:\n The serialised data.\n\n Raises:\n :exc:`ModelFormatError`: If ``format`` is not\n supproted, i.e. :meth:`Mode.to{format}` does not\n exist.\n\n \"\"\"\n func = 'to%s' % format\n if hasattr(self, func):\n return getattr(self, func)()\n raise ModelFormatError('unsupported format: %s' % format)\n\n def tojson(self) -> typing.OrderedDict[str, typing.Any]:\n \"\"\"Serialise data model as JSON log format.\n\n Returns:\n An :obj:`OrderedDict` mapping each field and serialised JSON\n serialisable data.\n\n \"\"\"\n fields = collections.OrderedDict()\n for field, type_cls in self.__fields__.items():\n value = getattr(self, field)\n fields[field] = type_cls.tojson(value)\n return fields\n\n def toascii(self) -> typing.OrderedDict[str, str]:\n \"\"\"Serialise data model as ASCII log format.\n\n Returns:\n An :obj:`OrderedDict` mapping each field and serialised text data.\n\n \"\"\"\n fields = collections.OrderedDict()\n for field, type_cls in self.__fields__.items():\n value = getattr(self, field)\n fields[field] = type_cls.toascii(value)\n return fields\n\n def asdict(self, dict_factory: typing.Optional[type] = None) -> typing.Dict[str, typing.Any]:\n \"\"\"Convert data model as a dictionary mapping field names to field values.\n\n Args:\n dict_factory: If given, ``dict_factory`` will be used instead of\n built-in :obj:`dict`.\n\n Returns:\n A dictionary mapping field names to field values.\n\n \"\"\"\n if dict_factory is None:\n dict_factory = dict\n fields = dict_factory()\n\n for field in self.__fields__:\n value = getattr(self, field)\n fields[field] = value\n return fields\n\n def astuple(self, tuple_factory: typing.Optional[type] = None) -> typing.Tuple[typing.Any]:\n \"\"\"Convert data model as a tuple of field values.\n\n Args:\n tuple_factory: If given, ``tuple_factory`` will be used instead of\n built-in :obj:`tuple`.\n\n Returns:\n A tuple of field values.\n\n \"\"\"\n fields = list()\n for field in self.__fields__:\n value = getattr(self, field)\n fields.append(value)\n\n if tuple_factory is None:\n tuple_factory = tuple\n return tuple_factory(fields)\n\n\ndef new_model(name: str, **fields: typing.Kwargs) -> Model:\n \"\"\"Create a data model dynamically with the appropriate fields.\n\n Args:\n name: data model name\n **fields: defined fields of the data model\n\n Returns:\n :class:`Model`: created data model\n\n Examples:\n Typically, we define a data model by subclassing the :obj:`Model`\n class, as following::\n\n class MyLog(Model):\n field_one = StringType()\n field_two = SetType(element_type=PortType)\n\n when defining dynamically with :func:`new_model`, the definition above\n can be rewrote to::\n\n MyLog = new_model('MyLog', field_one=StringType(), field_two=SetType(element_type=PortType))\n\n \"\"\"\n def gen_body(ns: typing.Dict[str, typing.Any]) -> typing.Dict[str, typing.Any]:\n \"\"\"Generate ``exec_body``.\"\"\"\n for name, type_cls in fields.items():\n ns[name] = type_cls\n return types.new_class(name, (Model,), exec_body=gen_body)\n","sub_path":"zlogging/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":9869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"113053238","text":"import requests\r\nimport xlwt\r\nimport xlrd\r\nfrom lxml import etree\r\nimport requests\r\nimport pymysql\r\nimport json\r\nimport datetime\r\nimport time\r\narg1 = \"两室一厅\"\r\narg2 = \"大竹林\"\r\narg3 = \"鸳鸯\"\r\narg4 = \"华岩\"\r\narg5 = \"茶园\"\r\narg6 = \"龙州湾\"\r\narg7 = \"井口-美丽阳光家园\"\r\narg8 = \"南岸区-江南水岸\"\r\narg9 = \"蔡家\"\r\narg10 = \"钓鱼嘴-半岛逸景●乐园\"\r\narg11 = \"碚都佳园\"\r\narg12 = \"龙洲南苑\"\r\narg13 = \"西永\"\r\narg14 = \"木耳\"\r\narg15 = \"界石\"\r\narg16 = \"陈家桥-学府悦园\"\r\narg17 = \"缙云新居\"\r\nheaders1 = {\r\n 'Referer' : 'http://www.cqgzfglj.gov.cn:9090/site/cqgzf/queryresultpublic/applicationresultdetail/24'\r\n}\r\n\r\n\r\nclass gongZuData(object):\r\n\r\n def __init__(self):\r\n self.f = xlwt.Workbook() #创建工作薄\r\n self.sheet1 = self.f.add_sheet(u'图书列表',cell_overwrite_ok=True)#命名table\r\n self.rowsTitle = [u'申请编号',u'姓名',u'性别',u'工作单位',u'个人收入',u'家庭收入',u'申请方式',u'有无住房',u'住房面积',u'申请片区',u'状态',u'申请时间','申请户型']#创建标题\r\n for i in range(0, len(self.rowsTitle)):\r\n #最后一个参数设置样式\r\n self.sheet1.write(0, i, self.rowsTitle[i], self.set_style('Times new Roman', 220, True))\r\n #Excel保存位置\r\n self.f.save('C:/Users/Administrator/Desktop/gongzu.xlsx')\r\n #该函数设置字体样式\r\n def set_style(self,name, height, bold=False):\r\n style = xlwt.XFStyle() # 初始化样式\r\n font = xlwt.Font() # 为样式创建字体\r\n font.name = name\r\n font.bold = bold\r\n font.colour_index = 2\r\n font.height = height\r\n style.font = font\r\n return style\r\n\r\n # def getUrl(self):\r\n # for i in range(10):\r\n # url = 'https://book.douban.com/top250?start={}'.format(i*25)\r\n # self.spiderPage(url)\r\n\r\n def gongzu(self):\r\n count = 1\r\n while (count < 3):\r\n request1 = requests.request(\"POST\",\r\n url=\"http://www.cqgzfglj.gov.cn:9090/site/cqgzf/queryresultpublic/getSqshjgAction\"\r\n \"?isInit=true&prefix=&pageNumber=\" + str(\r\n count) + \"&xm=&cnumber=&sqpq=&code=&tableName=QUERY25\", headers=headers1)\r\n # print(request1.url)\r\n print(\"第\" + str(count) + \"页:\" + request1.text)\r\n # i = 0\r\n # self.assertIn(arg1, request1.text, msg = \"no\")\r\n time.sleep(1)\r\n count = count + 1\r\n\r\n def spiderPage(self,url):\r\n if url is None:\r\n return None\r\n\r\n try:\r\n data = xlrd.open_workbook('C:/Users/Administrator/Desktop/gongzu.xlsx')#打开Excel文件\r\n table = data.sheets()[0] #通过索引顺序获取table,因为初始化时只创建了一个table,因此索引值为0\r\n rowCount = table.nrows #获取行数 ,下次从这一行开始\r\n proxies = {#使用代理IP,获取IP的方式在上一篇文章爬虫打卡4中有叙述\r\n 'http':'http://110.73.1.47:8123'}\r\n user_agent='Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'\r\n headers = {'User-Agent': user_agent}\r\n respon=requests.get(url, headers=headers,proxies=proxies)#获得响应\r\n htmlText=respon.text#打印html内容\r\n s = etree.HTML(htmlText)#将源码转化为能被XPath匹配的格式\r\n trs = s.xpath('//*[@id=\"content\"]/div/div[1]/div/table/tr')#提取相同的前缀\r\n m = 0\r\n for tr in trs:\r\n data = []\r\n bookHref=tr.xpath('./td[2]/div[1]/a/@href')\r\n bookTitle=tr.xpath('./td[2]/div[1]/a/text()')\r\n bookScore=tr.xpath('./td[2]/div[2]/span[2]/text()')\r\n bookPeople=tr.xpath('./td[2]/div[2]/span[3]/text()')\r\n bookImg=tr.xpath('./td[1]/a/img/@src')\r\n bookHref = bookHref[0] if bookHref else '' # python的三目运算 :为真时的结果 if 判定条件 else 为假时的结果\r\n bookTitle = bookTitle[0] if bookTitle else ''\r\n bookScore = bookScore[0] if bookScore else ''\r\n bookPeople =bookPeople[0] if bookPeople else ''\r\n bookImg = bookImg[0] if bookImg else ''\r\n\r\n #拼装成一个列表\r\n data.append(rowCount+m) #为每条书添加序号\r\n data.append(bookHref)\r\n data.append(bookTitle)\r\n data.append(bookScore)\r\n data.append(bookPeople)\r\n data.append(bookImg)\r\n\r\n for i in range(len(data)):\r\n self.sheet1.write(rowCount+m,i,data[i]) #写入数据到execl中\r\n\r\n m+=1 #记录行数增量\r\n print(m)\r\n print (bookHref,bookTitle,bookScore,bookPeople,bookImg)\r\n\r\n except Exception as e:\r\n print ('出错',type(e),e)\r\n\r\n finally:\r\n self.f.save('C:/Users/Administrator/Desktop/gongzu.xlsx')\r\n\r\n\r\nif '_main_':\r\n dbBook = gongZuData()\r\n dbBook.gongzu()","sub_path":"SaaSFlowTest/FlowTestCase/公租房2.py","file_name":"公租房2.py","file_ext":"py","file_size_in_byte":5245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"452587589","text":"import spacy\nfrom spacy.lang.en import English\nfrom spacy.pipeline import EntityRuler\nfrom spacy.matcher import Matcher\nfrom spacy.matcher import PhraseMatcher\n\nfrom .EntityPatterns import EntityPatterns as ep\nfrom .utils import get_text_doc, sanitize_tuples, format_double_quotes\nimport en_core_web_lg\nimport en_core_web_sm\n\nnlp_web_lg = en_core_web_lg.load()\nnlp_web_sm = en_core_web_sm.load()\n\n\ndef get_birthdays(doc):\n \"\"\"Identifies date of births in a document and\n returns a tuple containing the birthday, start and end of index, entity type, and segment\n\n Input:\n nlp document\n Results:\n tuple (token.text, token.idx, token.idx + len(token.text), token.ent_type_, token.sent)\n\n \"\"\"\n\n for ent in doc.ents:\n ent.merge()\n\n for token in doc:\n if token.ent_type_ == 'DATE' and token.head.text == 'born':\n yield (token.text, token.idx, token.idx + len(token.text), token.ent_type_, token.sent)\n\n\ndef get_names(doc):\n \"\"\"Returns a tuple of text, begging and ending position and label for PERSON named entities\"\"\"\n for item in doc.ents:\n if item.label_ == 'PERSON':\n yield (item.text, item.start_char, item.end_char, item.label_)\n\n\ndef get_credit_cards(content):\n \"\"\"Extracts credit cards from text based on the Entity Ruler by using Regular Expressions\"\"\"\n nlp_english = English()\n ruler = EntityRuler(nlp_english)\n\n patterns = [\n {\"label\": \"CREDIT_CARD\", \"pattern\": ep.american_express_pattern},\n {\"label\": \"CREDIT_CARD\", \"pattern\": ep.diners_club_pattern},\n {\"label\": \"CREDIT_CARD\", \"pattern\": ep.discover_pattern},\n {\"label\": \"CREDIT_CARD\", \"pattern\": ep.jcb_pattern},\n {\"label\": \"CREDIT_CARD\", \"pattern\": ep.maestro_pattern},\n {\"label\": \"CREDIT_CARD\", \"pattern\": ep.mastercard_pattern},\n {\"label\": \"CREDIT_CARD\", \"pattern\": ep.visa_pattern}\n ]\n\n ruler.add_patterns(patterns)\n nlp_english.add_pipe(ruler)\n\n doc = nlp_english(content)\n for token in doc.ents:\n yield (token.text, token.start_char, token.end_char, token.label_)\n\n\ndef get_phone_numbers(content):\n \"\"\"\n Uses the spacy Matcher to create matching pattern for extracting\n phone numbers. In addition, use the PhraseMatcher to extract phone numbers that\n don't fit the numbers only pattern\n\n :param content: cleaned text from emails, articles, etc\n :return phones: a list of phone numbers extracted from the content\n \"\"\"\n\n label = \"PHONE\"\n\n # Round 1: Using spacy's Matcher\n nlp_web_sm = spacy.load(\"en_core_web_sm\")\n matcher = Matcher(nlp_web_sm.vocab)\n\n matcher.add(label, None, ep.phone_pattern_1)\n matcher.add(label, None, ep.phone_pattern_2)\n matcher.add(label, None, ep.phone_pattern_3)\n\n doc = nlp_web_sm(content)\n matches = matcher(doc)\n\n for match_id, start, end in matches:\n span = doc[start:end]\n yield (span, start, end, label) # phones.append((span, start, end, label))\n\n # Round 2: Using spacy's PhraseMatcher\n nlp_en = English()\n matcher = PhraseMatcher(nlp_en.vocab, attr=\"SHAPE\")\n matcher.add(label, None, nlp_en(u\"235-423-2356(h)\"), nlp_en(u\"563-456-1785(w)\"), nlp_en(u\"713.463.8626\"))\n\n doc = nlp_en(content)\n for match_id, start, end in matcher(doc):\n span = doc[start:end]\n yield (span, start, end, label) # phones.append((span, start, end, label)) #return phones\n\n\ndef get_emails(content):\n \"\"\"\n Uses the EntityRuler to extract emails by using a RegEX email pattern as defined in the\n EntityPattern class\n\n :param content:\n :return emails:\n \"\"\"\n\n nlp_english = English()\n ruler = EntityRuler(nlp_english)\n\n patterns = [\n {\"label\": \"EMAIL\", \"pattern\": ep.email_address_pattern}\n ]\n\n ruler.add_patterns(patterns)\n nlp_english.add_pipe(ruler)\n\n doc = nlp_english(content)\n\n for token in doc.ents:\n yield (token.text, token.start_char, token.end_char, token.label_)\n\n\ndef get_pii(file, args):\n \"\"\"Collect desired/chosen personal information identifiers in the args,\n sorts according to appearance in the document and\n formats the list as required.\n\n :param file text file:\n :param args arguments with type of of identifiable information to be extracted\n\n :return\n formatted_pii: list of formatted piis in a given file\n \"\"\"\n\n pii = []\n\n birthdays =[]\n names = []\n phones = []\n cards = []\n emails = []\n\n text = get_text_doc(file)\n\n doc = nlp_web_lg(text)\n\n # extract personal identifiable information as chosen\n if args.names:\n names = [name for name in get_names(doc)]\n\n if args.birthdays:\n birthdays = [ent for ent in get_birthdays(doc)]\n\n if args.phones:\n phones = [ent for ent in get_phone_numbers(text)]\n\n if args.cards:\n cards = [ent for ent in get_credit_cards(text)]\n\n if args.emails:\n emails = [ent for ent in get_emails(text)]\n\n # collect all chosen personal information identifiers\n pii += birthdays\n pii += names\n pii += emails\n pii += phones\n pii += cards\n\n # sort them as they appear in the file\n pii_sorted = sorted(pii, key=lambda tup: tup[1])\n result_pii = [item for item in sanitize_tuples(pii_sorted)]\n\n # format as required\n formatted_pii = format_double_quotes(result_pii)\n\n return formatted_pii\n","sub_path":"src/identifier.py","file_name":"identifier.py","file_ext":"py","file_size_in_byte":5357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"22419209","text":"from source import Commands as Cmd\nfrom source import TextSnippets as GlobalTxt\n\nCHECKLIST_LOAD_WRONG_DEAL_STAGE = 'Заказ должен находиться в стадии \\'Согласовано\\' для перевода в стадию \\'В ' \\\n 'доставке\\'\\\\.\\n' + GlobalTxt.SUGGEST_CANCEL_TEXT\n\nCOURIER_TEMPLATE = '*{}*\\n*{}*\\n\\n'\nCOURIER_UNKNOWN_ID_TEXT = 'Неизвестный курьер\\\\. Попробуйте снова\\\\.\\n' + GlobalTxt.SUGGEST_CANCEL_TEXT\nCOURIER_EXISTS_TEXT = 'Курьер *{}* уже назначен для этого заказа\\\\.\\n' \\\n 'Используйте {}, чтобы продолжить без изменения, или назначьте нового курьера\\\\.\\n' \\\n + GlobalTxt.SUGGEST_CANCEL_TEXT + '\\n\\n'\nCOURIER_SUGGESTION_TEXT = 'Назначьте курьера\\\\.\\n' + GlobalTxt.SUGGEST_CANCEL_TEXT + '\\n\\n'\n\nCOURIER_SETTING_COMMAND_PATTERN = '^/' + Cmd.SET_COURIER_PREFIX + '\\\\' + Cmd.CMD_DELIMETER + r'(\\d+)$'\nCOURIER_SKIPPING_COMMAND_PATTERN = '^/' + Cmd.SKIP_COURIER_SETTING + '$'\n\nCHECKLIST_PHOTO_REQUIRE_TEMPLATE = 'Загрузите фото чек\\\\-листа\\\\.\\n' + GlobalTxt.SUGGEST_CANCEL_TEXT + '\\n\\n' \\\n '*Заказ №*: {}\\n' \\\n '*Что заказано*: {}\\n' \\\n '*Контакт*: {}\\n' \\\n '*Флорист*: {}\\n' \\\n '*Кто принял заказ*: {}\\n' \\\n '*Инкогнито*: {}\\n' \\\n '*Комментарий к товару*: {}\\n' \\\n '*Комментарий по доставке*: {}\\n' \\\n '*Сумма заказа общая\\\\(итоговая\\\\):* {}\\n\\n' \\\n '*Тип оплаты*: {}\\n' \\\n '*Способ оплаты*: {}\\n' \\\n '*Статус оплаты*: {}\\n' \\\n '*Предоплата*: {}\\n' \\\n '*К оплате*: {}\\n' \\\n '*Тип заказа*: {}'\n","sub_path":"source/cmd_handlers/Checklist2/TextSnippets.py","file_name":"TextSnippets.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"364886870","text":"#!/usr/local/bin/python3\n\n#@author\t\tBrandon Tarney\n#@date\t\t\t9/30/2018\n#@description\tCondensedKNearestNeighbor class\n\nimport numpy as np\nimport pandas as pd\nimport argparse\nimport operator\nimport random\nimport copy\nfrom k_nearest_neighbor import KNearestNeighbor\n\n#=============================\n# CondensedKNearestNeighbor\n#\n# - Class to encapsulate a condensed K-NN model for testing\n#=============================\nclass CondensedKNearestNeighbor(KNearestNeighbor) :\n\n\t#Assumes data is numpy 2d array of points\n\tdef __init__(self, data, k_number):\n\t\tKNearestNeighbor.__init__(self, data, k_number)\n\n\t#=============================\n\t# train()\n\t#\t- Condense data into subset representing @ least every class\n\t#=============================\n\tdef train(self, new_data):\n\t\t#print('data before condense')\n\t\t#print(self.data)\n\t\t#Initialize with an empty set\n\t\tfinal_chosen_points = np.array([])\n\n\t\tshuffled_data = np.array(new_data, copy=True)\n\n\t\t#For each point Xt point in new_data, find point X' where\n\t\t#\tD(Xt, X') = min for all X' in chosen points\n\t\twhile True:\n\t\t\t#Randomize your data\n\t\t\tnp.random.shuffle(shuffled_data)\n\t\t\t#print('shuffled data')\n\t\t\t#print(shuffled_data)\n\n\t\t\t#initialize values to empty for each run\n\t\t\t#iterative_chosen_points = np.array([])\n\t\t\titerative_chosen_idx = []\n\n\t\t\t#randomly grab a starting point\n\t\t\tif final_chosen_points.size == 0:\n\t\t\t\t#print('first row shuffled data')\n\t\t\t\t#print(shuffled_data[0])\n\t\t\t\tfinal_chosen_points = np.array([shuffled_data[0]])\n\t\t\t\t#print('final_chosen_points')\n\t\t\t\t#print(final_chosen_points)\n\n\t\t\tfor point_idx in range(len(shuffled_data)):\n\t\t\t\t#print('point under consideration')\n\t\t\t\t#print(shuffled_data[point_idx])\n\t\t\t\t#find closest point in Z X' to 'point'\n\t\t\t\tpoint = shuffled_data[point_idx]\n\t\t\t\tdistances_to_point = self._get_all_data_distances_to_point(\n\t\t\t\t\t\tfinal_chosen_points, point)\n\t\t\t\t#print('distances_to_point')\n\t\t\t\t#print(distances_to_point)\n\t\t\t\tnum_close_points = 1\n\t\t\t\tclosest_points = self._get_closest_k_points(\n\t\t\t\t\t\tfinal_chosen_points, \n\t\t\t\t\t\tdistances_to_point, \n\t\t\t\t\t\tnum_close_points)\n\n\t\t\t\t#if class of 'point' != class of X', add point to Z\n\t\t\t\tclosest_point_class = closest_points[0,-1]\n\t\t\t\tpoint_class = point[-1]\n\t\t\t\tif closest_point_class != point_class:\n\t\t\t\t\t#print('chosen points')\n\t\t\t\t\t#print(final_chosen_points)\n\t\t\t\t\t#print('point in consideration')\n\t\t\t\t\t#print(point)\n\t\t\t\t\t#print('closest point in final_chosen_points')\n\t\t\t\t\t#print(closest_points)\n\t\t\t\t\titerative_chosen_idx.append(point_idx)\n\t\t\t\t\tfinal_chosen_points = np.vstack(\n\t\t\t\t\t\t\t[final_chosen_points, point])\n\n\t\t\t\t#End of for loop\n\n\t\t\tif (len(iterative_chosen_idx) == 0):\n\t\t\t\tbreak # chosen set will be unchanged\n\n\t\t\t#print('final_chosen_points')\n\t\t\t#print(final_chosen_points)\n\t\t\tbreak\n\n\t\t\t#End of while loop\n\n\t\tself.data = np.copy(final_chosen_points)\n\t\t#print('data after condense')\n\t\t#print(self.data)\n\t\treturn\n\n#=============================\n# MAIN PROGRAM\n#=============================\ndef main():\n\tprint('Main() - testing condensed knn model')\n\tparser = argparse.ArgumentParser(description='test condensed knn model')\n\tparser.add_argument('k_number', type=int, default=1, nargs='?', help='number of total neighbors')\n\targs = parser.parse_args()\n\n\t#Mode is always majority...this is not used for regression\n\tmode = \"majority\"\n\n\tprint()\n\tprint('TEST 1: dummy data')\n\tprint('train data (final col is class):')\n\ttrain_data = pd.DataFrame([\n\t\t[0,0,0,0], [2,0,0,0], [0,2,0,0], [0,0,2,0],\n\t\t[4,4,4,4], [3,4,4,4], [4,3,4,4], [4,4,3,4],\n\t\t[8,8,8,8], [6,8,8,8], [8,6,8,8], [8,8,6,8]])\n\tprint(train_data)\n\tprint('test data1 (final col class):')\n\ttest_data1 = pd.DataFrame([[0,0,0,0]])\n\tprint(test_data1)\n\tprint('test data2 (final col class):')\n\ttest_data2 = pd.DataFrame([\n\t\t[1,3,0,0], [4,5,6,4], [7,8,7,8]])\n\tprint(test_data2)\n\tprint()\n\n\tcondensed_knn = CondensedKNearestNeighbor(train_data.values, args.k_number)\n\tcondensed_knn.train(train_data.values)\n\tprint('condensed train data')\n\tprint(condensed_knn.data)\n\tresult1 = condensed_knn.test(test_data1.values, mode)\n\tprint('Result1 Accuracy (%):') \n\tprint(result1, '%')\n\tresult2 = condensed_knn.test(test_data2.values, mode)\n\tprint('Result2 Accuracy (%):') \n\tprint(result2, '%')\n\n\n''' COMMENTED OUT FOR SUBMITTAL\nif __name__ == '__main__':\n\tmain()\n\t'''\n","sub_path":"algorithms/condensed_k_nearest_neighbor.py","file_name":"condensed_k_nearest_neighbor.py","file_ext":"py","file_size_in_byte":4256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"359292506","text":"\"\"\"diplom URL Configuration\r\n\r\nThe `urlpatterns` list routes URLs to views. For more information please see:\r\n https://docs.djangoproject.com/en/2.0/topics/http/urls/\r\nExamples:\r\nFunction views\r\n 1. Add an import: from my_app import views\r\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\r\nClass-based views\r\n 1. Add an import: from other_app.views import Home\r\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\r\nIncluding another URLconf\r\n 1. Import the include() function: from django.urls import include, path\r\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\r\n\"\"\"\r\nfrom django.contrib import admin\r\nfrom django.urls import path\r\nfrom shop.views import index, cart, empty_section, item_page, category_view, signup, add_to_cart, make_order\r\nfrom django.contrib.auth import views as auth_views\r\n\r\nurlpatterns = [\r\n path('', index, name='index'),\r\n path('item//', item_page, name='item_page'),\r\n path('cart/add/', add_to_cart, name='add_to_cart'),\r\n path('cart/', cart, name='cart'),\r\n path('empty_section/', empty_section, name='empty_section'),\r\n path('login/', auth_views.LoginView.as_view(), name='login'),\r\n path('logout/', auth_views.LogoutView.as_view(), name=\"logged_out\"),\r\n path('signup/', signup, name=\"signup\"),\r\n path('category//', category_view, name='category'),\r\n path('admin/', admin.site.urls),\r\n path('make_order', make_order, name='make_order'),\r\n]\r\n","sub_path":"diplom/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"167336438","text":"import numpy\n\n\nclass User():\n def __init__(self):\n self.user_data = {\n 'record_stamp': numpy.datetime64, # UTC 'Zulu' time (default for Json)\n 'user_id': int,\n 'username': str,\n 'level': int,\n 'points': int,\n 'developer': bool,\n 'moderator': bool,\n 'admin': bool,\n 'gender': bool,\n 'age': int,\n 'friends': [int],\n 'muted_users': [int],\n 'fav_game_ids': [int],\n 'highly_rated_game_ids': [int],\n 'badges': [{'badge_id': int, 'timestamp': numpy.datetime64}],\n 'timezone': int\n }\n\n\nclass Game():\n \"\"\"\n {\n 'record_stamp': datetime,\n 'url': str,\n 'title': str,\n 'developer': user_id,\n 'publish_date': datetime,\n 'avg_rating': int,\n 'no_of_ratings': int,\n 'no_of_plays': int,\n 'tags': [{tag, score}]\n }\n \"\"\"\n\n\nclass Badge():\n \"\"\"\n {\n 'record_stamp': datetime,\n 'id': int,\n 'game_url': str,\n 'created_at': datetime,\n 'points': int,\n 'difficulty': str\n }\n \"\"\"\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"511923492","text":"#1 . medium\r\n\r\n#join([\"oven\", \"envier\", \"erase\", \"serious\"]) ➞ [\"ovenvieraserious\", 2]\r\n#join([\"move\", \"over\", \"very\"]) ➞ [\"movery\", 3]\r\n#join([\"to\", \"ops\", \"psy\", \"syllable\"]) ➞ [\"topsyllable\", 1]\r\n\r\n# \"to\" and \"ops\" share \"o\" (1)\r\n# \"ops\" and \"psy\" share \"ps\" (2)\r\n# \"psy\" and \"syllable\" share \"sy\" (2)\r\n# the minimum overlap is 1\r\n#join([\"aaa\", \"bbb\", \"ccc\", \"ddd\"]) ➞ [\"aaabbbcccddd\", 0]\r\n\r\nx = [\"ovenen\", \"enenvier\", \"erase\", \"serious\"]\r\nx = [\"move\", \"over\", \"very\"]\r\nx = [\"to\", \"ops\", \"psy\", \"syllable\"]\r\nx = [\"aasfeded\", \"eded12312\", \"cswe\", \"cswe2314\"]\r\ndef join(x) :\r\n try:\r\n if isinstance(x,list):\r\n nums = [] # 초기값\r\n words = x[0]\r\n for i in range(len(x) - 1): #리스트 내의 단계들에 대해서 함. 리스트항목이 4개있으면 3번을 수행해야함.\r\n count = min(len(x[i]), len(x[i + 1])) # 초기값. 위에서 내려감\r\n while True: #계속실행.\r\n\r\n if x[i][-count:] == x[i + 1][:count]: #만약 뒤의값이 같으면 나옴.\r\n words += x[i + 1][count :] #words에 단어를 잇고\r\n nums.append(count) #연결된 count를 출력\r\n break #그리고 루프나옴.\r\n elif count == 0: #만약 count==0이될때까지 안되다가 0이되면\r\n words += x[i+1] #그냥이어버리고\r\n nums.append(count) #그때의 카운트를 출력.\r\n break #그리고 나옴.\r\n\r\n count -= 1 #하나씩 줄이면서 살펴볼것\r\n\r\n num = min(nums) #그렇게 얻어진 모든 count들 중에서 가장 작은 값.\r\n return print([words, num]) #그리고 출력\r\n else:\r\n raise Exception\r\n except Exception:\r\n print('주의! 리스트를 입력해주세요.')\r\njoin(x)\r\n\r\n\r\n#2 . very hard\r\n\r\n#sexagenary(1971) ➞ \"Metal Pig\"\r\n#sexagenary(1927) ➞ \"Fire Rabbit\"\r\n#sexagenary(1974) ➞ \"Wood Tiger\"\r\n\r\ndef sexagenary(year) :\r\n try:\r\n if isinstance(year,int) :\r\n stem = ['Wood', 'Fire', 'Earth', 'Metal', 'Water']\r\n branch = ['Rat','Ox','Tiger','Rabbit','Dragon','Snake','Horse',\r\n 'Sheep','Monkey','Rooster','Dog','Pig']\r\n stem2 = sum([[i]*2 for i in stem],[]) #stem을 각각 2번씩 출력.\r\n branches = branch *5 #branch 60개짜리\r\n\r\n import operator #요소별 덧셈을 위한 모듈\r\n items_sub = [i + ' ' for i in stem2] *6 #두번씩 나눠서 해야한다.\r\n items = list(map(operator.add,items_sub,branches)) #역시 같은이유.\r\n\r\n init = year-1984 #초기치를 0으로 만드는 작업. (1984년의 순서를 0으로만듦.)\r\n if init >= 60 or init < 0 : #60사이클이므로 60보다 클경우와, 작은경우로 나눈다. (2044년 이후, 1984년 전)\r\n init = init % 60 #나머지를 다뤄주면 된다.\r\n\r\n zodiac = items[init]\r\n\r\n return zodiac\r\n\r\n else :\r\n raise Exception\r\n except Exception:\r\n print(\"주의! 연도를 넣어주세요.\")\r\n\r\n\r\ndef sexagenary2(year) :\r\n try:\r\n if isinstance(year,int) :\r\n\r\n stem = ['Wood', 'Fire', 'Earth', 'Metal', 'Water']\r\n branch = ['Rat', 'Ox', 'Tiger', 'Rabbit', 'Dragon', 'Snake', 'Horse',\r\n 'Sheep', 'Monkey', 'Rooster', 'Dog', 'Pig']\r\n\r\n stem2 = sum([[i]*2 for i in stem ],[])\r\n init = year - 1984\r\n\r\n first = init % 10\r\n end = init % 12\r\n\r\n return print(stem2[first],branch[end])\r\n else :\r\n raise Exception\r\n except Exception:\r\n print(\"주의! 연도를 넣어주세요.\")\r\n\r\n\r\nsexagenary(4400)\r\nsexagenary(1984)\r\nsexagenary(32)\r\n#3. expert\r\n\r\n# XO(\"ooxx\") ➞ true\r\n# XO(\"xooxx\") ➞ false\r\n# XO(\"ooxXm\") ➞ true\r\n# // Case insensitive.\r\n# XO(\"zpzpzpp\") ➞ true\r\n# // Returns true if no x and o.\r\n# XO(\"zzoo\") ➞ false\r\n\r\ndef XO(x) :\r\n try:\r\n if isinstance(x , str):\r\n ox=list(x) #그냥 바로 x가 str이면 list(x.lower())로 내리고 시작해도됨. 그러면 아래 if문에서 제대로 걸러짐.\r\n o_num = 0\r\n x_num = 0\r\n for i in ox :\r\n if i.lower() == \"o\":\r\n o_num += 1\r\n elif i.lower() == 'x' :\r\n x_num += 1\r\n\r\n if o_num == x_num :\r\n return True\r\n else:\r\n return False\r\n else:\r\n raise Exception\r\n\r\n except Exception:\r\n print(\"문자열을 입력하세요\")\r\n\r\n","sub_path":"Self_study/2019_Summer/Python Basics/Module, examples/HW Zodiac and.. .py","file_name":"HW Zodiac and.. .py","file_ext":"py","file_size_in_byte":4728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"346467472","text":"from implementation.Parameters import Parameters\nfrom numpy.lib.scimath import power, sqrt\n\ndef getCenterOfGravity(genotypes):\n centerOfGravity = []\n for i in xrange(Parameters.genotypeLength):\n centerOfGravity.append(0)\n count = 0\n for genotype in genotypes:\n for i in xrange(len(genotype)):\n centerOfGravity[i] += genotype[i]\n count += 1\n for i in xrange(len(centerOfGravity)):\n centerOfGravity[i] = centerOfGravity[i]/count\n return centerOfGravity\n \ndef getDist(point1, point2):\n sumVal = 0\n for i in xrange(len(point1)):\n sumVal += power(point1[i]+point2[i],2)\n return sqrt(sumVal)","sub_path":"src/monitor/MonitorHelper.py","file_name":"MonitorHelper.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"106375902","text":"\n\ndef interpolation_search(slist, num):\n Sindex = 0\n Eindex = len(slist)-1\n\n while Sindex <= Eindex and num >= slist[Sindex] and num <= slist[Eindex]:\n\n pos = Sindex + int(((float(Eindex - Sindex) /\n ( slist[Eindex] - slist[Sindex])) * ( num - slist[Sindex])))\n\n if slist[pos] == num:\n return pos\n\n if slist[pos] < num:\n Sindex = pos + 1\n else:\n Eindex = pos - 1\n \n return False\n\n\nwantedNum = 4\nslist = [1, 2, 3, 4, 5, 6, 7, 8]\n\nsearch = interpolation_search(slist,wantedNum)\n\nif search != False:\n print(search)\nelse:\n print(None)\n\n","sub_path":"Algorithms/Search Algorithms/Interpolation Search.py","file_name":"Interpolation Search.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"430062842","text":"import numpy as np\nfrom sklearn import preprocessing\nfrom sklearn import datasets\n\ninputData = np.array([[5.1, -2.9, 3.3],\n [-1.2, 7.8, -6.1],\n [3.9, 0.4, 2.1],\n [7.3, -9.9, -4.5]])\n\n##평균제거 -> 마이너스는 0으로, 평균 제거\ndataBinarized = preprocessing.Binarizer(threshold=2.1).transform(inputData)\nprint(\"\\nBinarized data: \\n\", dataBinarized)\n\nprint(\"\\nBEFORE:\")\nprint(\"Mean = \", inputData.mean(axis=0))\nprint(\"Std deviation =\", inputData.std(axis=0))\n\ndataScaled = preprocessing.scale(inputData)\nprint(\"\\nAFTER: \")\nprint(\"Mean = \", dataScaled.mean(axis=0))\nprint(\"Std deviation = \", dataScaled.std(axis=0))\n\n##크기조정 -> 값이 너무 터무니없이 크게하지 않기 위해 0~1 사이로 바꿈\ndataScalerMinMax = preprocessing.MinMaxScaler(feature_range=(0, 1))\ndataScaledMinMax = dataScalerMinMax.fit_transform(inputData)\nprint(\"\\nMin max scaled data: \\n\", dataScaledMinMax)\n\n# 정규화 (데이터의 총 합을 1로 만드는 방법이 대표적임)\ndataNormalized11 = preprocessing.normalize(inputData, norm=\"l1\")\ndataNormalized12 = preprocessing.normalize(inputData, norm=\"l2\")\nprint(\"\\nL1 normalized data : \\n\", dataNormalized11)\nprint(\"\\nL2 normalized data : \\n\", dataNormalized12)\n\n# 레이블 인코딩\ninputLabels = ['red', 'black', 'red', 'green', 'black', 'yellow', 'white']\nencoder = preprocessing.LabelEncoder()\nencoder.fit(inputLabels)\n\nprint(\"\\nLabel mapping:\")\nfor i, item in enumerate(encoder.classes_):\n print(item, '-->', i)\n\ntest_labels = ['green', 'red', 'black']\nencodedValues = encoder.transform(test_labels)\nprint(\"\\nLabels =\", test_labels)\nprint(\"Encoded values=\", list(encodedValues))\n\n##로지스틱 회귀\nfrom sklearn import linear_model\nimport matplotlib.pyplot as plt\n\nX = np.array([[3.1, 7.2], [4, 6.7], [2.9, 8], [5.1, 4.5],\n [6,5], [5.6,5], [3.3,0.4], [3.9,0.9],\n [2.8,1], [0.5,3.4], [1,4], [0.6,4.9]])\ny = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3])\n\n\nclassifier = linear_model.LogisticRegression(solver='liblinear', C=1)\nclassifier.fit(X, y)\n\n#\n# list_data = [1,2,3]\n# array = np.array(list_data)\n#\n# print(array.size)\n# print(array.dtype)\n# print(array[2])\n#\n# array1 = np.arange(4)\n# print(array1)\n#\n# array2 = np.zeros((4,4), dtype=float)\n# print(array2)\n#\n# # array3 = np.ones((3,3)\n#\n#\n# array4 = np.random.randint(0, 10, (3,3))\n# print(array4)\n#\n# #평균이 0이고, 표준편차가 1인 표준정규를 띄는 배열\n# array5 = np.random.normal(0,1,(3,3))\n# print(array5)\n#\n# array6 = np.concatenate([array1, array2])\n# print(array6.size)\n# print(array6)\n# array = np.array([1,2,3,4])\n# array = np.arange(8).reshape(2,4)\n# left, right = np.split(array, [2], axis=1)\n# print(array)\n# print (left.shape)\n# print (right.shape)\n# print (right[1][1])\n#\n# cv2.imread(file_name, flag)","sub_path":"numpy_test1.py","file_name":"numpy_test1.py","file_ext":"py","file_size_in_byte":2844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"461347546","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2018/8/31 16:08\n@author: gzp\nFunc: \n\"\"\"\nimport os\nimport shutil\nimport cv2\nimport json\nimport numpy as np\nimport re\n\"\"\"\nFor objection detection\n1.Load data from json file, just focus on the label and points;\n2.No need to annotate object with 4 points, but it is necessary to annotate clockwise (some algorithms are sensitive to annotation direction), we use minimum circumscribed rectangle to get 8coordinates by 4 corners;\n3.Save the result into text file with the same name of json file.\n\"\"\"\nfrom functools import reduce\ndef get_min_circumscribed_rectangle_from_coordinates(coordinate_list, mode=1):\n \"\"\"\n calculate the rectangle with minimum area.\n :param coordinate_list: [[x1, y1], [x2, y2], [x3, y3]]\n :param mode: 0, ((xc, yc), (w, h)); 1, ((x1,y1),(x2,y2),(x3,y3),(x4,y4)) clock wise\n :return:list of the result, float\n \"\"\"\n cnt = np.array(coordinate_list) # change to numpy array\n rect = cv2.minAreaRect(cnt) # get the ((xc,yc),(w,h), theta)\n if mode == 1:\n box = cv2.boxPoints(rect) # get four coordinates\n box = box.astype(np.int).tolist()\n return box\n else:\n rect = [rect[0][0], rect[0][1], rect[1][0], rect[1][1], rect[2]]\n return rect\ndef map_label_name(label, label_name_dict):\n \"\"\"\n Convert instance label in json into a category.\n :param label: instance label in json file\n :param label_name_dict: dictionary made by label_id and category name.\n :return: category name.\n \"\"\"\n for name in label_name_dict.values():\n pattern = re.compile(r'{}[0-9]'.format(name))\n if re.match(pattern, label):\n return name\n assert False, \"instance label in json file is not recommended, please check the annotation.\"\ndef convert_json_to_txt(json_path, txt_path, label_name_dict):\n data = json.load(open(json_path, 'r'))\n shapes = data['shapes']\n with open(txt_path, 'w') as f:\n for shape in shapes:\n label = shape['label']\n points = shape['points']\n category_name = map_label_name(label, label_name_dict)\n coords = get_min_circumscribed_rectangle_from_coordinates(points)\n coords = reduce(lambda x, y:x+y,coords)\n coords = [str(v) for v in coords]\n line = ','.join(coords + [category_name]) + '\\n'\n f.write(line)\n\n\"\"\"\n1.Make sure that, you've installed the labelme;\nhttps://github.com/wkentaro/labelme\n2.Use the package sys to call labelme_json_to_dataset\n3.Two new files generate, yaml file and mask file\n\"\"\"\ndef generate_mask_and_yamls(rgb_dir, json_dir, mask_dir, yaml_dir):\n \"\"\"\n Generage mask and yaml files from json file\n :param rgb_dir: rgb image dir\n :param json_dir: json file dir\n :param mask_dir: mask save dir\n :param yaml_dir: yaml sace dir\n :return:\n \"\"\"\n print(\"--+\"*30)\n print(\"generate mask and yaml files from annotation (json files)...\")\n files = [file for file in os.listdir(rgb_dir) if file.endswith('png') or file.endswith('jpg')]\n for i, file in enumerate(files):\n json_path = os.path.join(json_dir, file.replace('png', 'json'))\n os.system('labelme_json_to_dataset {}'.format(json_path))\n new_generated_dir = os.path.join(json_dir, file.replace('.png', '_json'))\n yaml_path = os.path.join(new_generated_dir, 'info.yaml')\n mask_path = os.path.join(new_generated_dir, 'label.png')\n shutil.copyfile(yaml_path, os.path.join(yaml_dir, file.replace('png', 'yaml')))\n shutil.copyfile(mask_path, os.path.join(mask_dir, file))\n # delete new_generated_dir\n tmpfiles = os.listdir(new_generated_dir)\n for tmpfile in tmpfiles:\n file_path = os.path.join(new_generated_dir, tmpfile)\n os.remove(file_path)\n shutil.rmtree(new_generated_dir)\n print(\"Done.\")\n\n","sub_path":"annotation.py","file_name":"annotation.py","file_ext":"py","file_size_in_byte":3875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"336731305","text":"import sys\r\nimport socket\r\nfrom struct import unpack\r\nfrom zlib import crc32\r\n\r\nif len(sys.argv) != 2:\r\n print(f\"Usage: {sys.argv[0]} \")\r\n exit(-1)\r\n\r\n# Create a socket\r\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\nsock.bind(('', int(sys.argv[1])))\r\n\r\nwhile True:\r\n try:\r\n data, addr = sock.recvfrom(1000)\r\n if (len(data) < 8):\r\n print(\"Pkt too short\")\r\n continue\r\n\r\n my_checksum = crc32(data[4:])\r\n\r\n # Debug print\r\n print(f\"Received CRC:{my_checksum} Data:{data}\")\r\n\r\n your_checksum, num = unpack(\"Ii\", data)\r\n if (your_checksum != my_checksum):\r\n print(\"Pkt corrupt\")\r\n else:\r\n print(f\"Pkt {num}\")\r\n\r\n # send ack\r\n sock.sendto(b\"A\", addr)\r\n except:\r\n print(\"Client disconnected\") \r\n","sub_path":"Assignment/ass2/ass02_files/python files/SimpleUDPReceiver.py","file_name":"SimpleUDPReceiver.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"593201766","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport json\n\nfrom django.http import JsonResponse\nfrom events.calender_utils import CalenderEventsUtil\nfrom.models import Club, Event, Subscription\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom datetime import datetime, timedelta\nimport pytz\nfrom .forms import EventForm\nfrom allauth.socialaccount.models import SocialToken\n\nLOGIN_WITH_SCOPE = '/accounts/google/login/?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar&access_type=offline'\nLOGIN_URL = '/accounts/google/login/'\n\ndef change_list(request):\n utc_time = datetime.utcnow()\n gmt_timezone = pytz.timezone(\"GMT\")\n timezone = pytz.timezone(\"Asia/Kolkata\")\n utc_time = gmt_timezone.localize(utc_time)\n curr_time=utc_time.astimezone(timezone).time()\n curr_date=utc_time.astimezone(timezone).date()\n evs=Event.objects.filter(day__gte=curr_date)\n evs=sorted(evs,key=lambda x: (x.day,x.start_time))\n evs_with_changes=[]\n i=0\n prev=0\n nextday= datetime.today() + timedelta(days=1)\n nextday=nextday.date()\n for e in evs:\n if (e.day > curr_date or e.end_time > curr_time):\n d={}\n d[\"club\"]=e.club\n d[\"end_time\"]=e.end_time\n d[\"start_time\"]=e.start_time\n d[\"day\"]=e.day\n d[\"name\"]=e.name\n d[\"venue\"]=e.venue\n d[\"event_link\"]=e.event_link\n b=False\n if i==0:\n b=True\n elif prev!=e.day :\n b=True\n if prev > nextday:\n b=False\n d[\"change\"]=b\n d[\"pk\"] = e.pk\n evs_with_changes.append(d)\n prev=d[\"day\"]\n i+=1\n try:\n usr = request.user.first_name + \" \" + request.user.last_name\n except:\n usr = request.user\n return render(request, 'events/change_list.html', {\n 'events': evs_with_changes,\n 'time': curr_time,\n 'date': curr_date,\n 'tomorrow': nextday,\n 'user':usr })\n\ndef is_club(user):\n try:\n club = Club.objects.get(email=user.email)\n return True\n except Club.DoesNotExist:\n return False\n \n return True\n\ndef has_calender_access(user):\n result = SocialToken.objects.filter(account__user=user, account__provider='google')\n\n # TODO - Add a check if calender scope is available or not\n\n if len(result) == 0:\n return False, None, None\n\n result = result.get()\n refresh_token = result.__dict__.get('token_secret')\n access_token = result.__dict__.get('token')\n expires_at = result.__dict__.get('expires_at')\n\n if refresh_token is None:\n # Check if access token is valid or not\n if access_token is None:\n return False, None, None\n else:\n now = datetime.now()\n if now + timedelta(minutes=30) > expires_at:\n print(\"Access token expired!\")\n return False, access_token, None\n \n return True, access_token, refresh_token\n\ndef handle_calender_event(user, event, access_token, refresh_token, method='create'):\n ''' Creates the calender event and returns the values\n @params method : 'create', 'update'\n '''\n\n google_calender = CalenderEventsUtil(\n access_token=access_token,\n refresh_token=refresh_token\n )\n\n calender_response = None\n if method == 'delete':\n calender_response = google_calender.delete_calender_event(event.id)\n else:\n event.club = user.first_name + \" \" + user.last_name\n event.created_by_email = user.email\n\n start_date_time = event.day.isoformat() + \"T\" + event.start_time.isoformat()\n end_date_time = event.day.isoformat() + \"T\" + event.end_time.isoformat()\n\n subscriptions = Subscription.objects.filter(club_email=user.email)\n attendees_emails = list(subscriptions.values_list('student_email', flat=True))\n\n # Now use the above google_calender object to create a new event\n # TODO - Allow invites to be added\n event_data = google_calender.create_event_data(\n str(event.name),\n str(event.venue) + ', IIT Mandi',\n str(event.description),\n start_date_time,\n end_date_time,\n attendees_emails,\n )\n\n if method == 'update':\n calender_response = google_calender.update_calender_event(event.id, event_data)\n else:\n calender_response = google_calender.create_calender_event(event_data)\n\n if calender_response.get('success'):\n event.id = calender_response.get('event_id')\n event.event_link = calender_response.get('event_link')\n\n if method == 'delete':\n event.delete()\n else:\n event.save()\n\n return redirect('change_list') \n else:\n resp = \"Event \" + str(method) + \" failed on Google Calender\" + str(calender_response)\n print(resp)\n return JsonResponse({\"error\": resp})\n\ndef event_new(request):\n if not request.user.is_authenticated:\n return redirect(LOGIN_WITH_SCOPE)\n\n if not is_club(request.user):\n return JsonResponse({\"error\": \"Events can only be created by clubs\"})\n\n has_access, access_token, refresh_token = has_calender_access(request.user)\n if not has_access:\n return redirect(LOGIN_WITH_SCOPE)\n\n # We have refresh token, so we are good to go to create calender event\n if request.method == \"POST\":\n form = EventForm(request.POST)\n if form.is_valid():\n event = form.save(commit=False)\n return handle_calender_event(request.user, event, access_token, refresh_token, method='create')\n else:\n form = EventForm()\n return render(request, 'events/event_edit.html', {'form': form})\n\ndef event_edit(request, pk):\n event = get_object_or_404(Event, pk=pk)\n if not request.user.is_authenticated or request.user.first_name not in event.club:\n return redirect(LOGIN_WITH_SCOPE)\n\n if not is_club(request.user):\n return JsonResponse({\"error\": \"Events can only be created by clubs\"})\n\n has_access, access_token, refresh_token = has_calender_access(request.user)\n if not has_access:\n return redirect(LOGIN_WITH_SCOPE)\n\n if request.method == \"POST\":\n form = EventForm(request.POST, instance=event)\n if form.is_valid():\n event = form.save(commit=False)\n return handle_calender_event(request.user, event, access_token, refresh_token, method='update')\n else:\n form = EventForm(instance=event)\n return render(request, 'events/event_edit.html', {'form': form})\n\ndef event_delete(request, pk):\n event = get_object_or_404(Event, pk=pk)\n if not request.user.is_authenticated or request.user.first_name not in event.club:\n return redirect(LOGIN_WITH_SCOPE)\n\n if not is_club(request.user):\n return JsonResponse({\"error\": \"Events can only be created by clubs\"})\n\n has_access, access_token, refresh_token = has_calender_access(request.user)\n if not has_access:\n return redirect(LOGIN_WITH_SCOPE)\n\n event = Event.objects.filter(pk=pk)\n event.id = pk\n return handle_calender_event(request.user, event, access_token, refresh_token, method='delete')\n\ndef subscription_list(request):\n if not request.user.is_authenticated:\n return redirect(LOGIN_URL + '?next=/subscription/')\n\n if request.method == \"POST\":\n body = json.loads(request.body)\n\n if body.get('checked'):\n sub = Subscription(club_email=body.get('club'), student_email=request.user.email)\n sub.save()\n\n return JsonResponse({\"success\": True,\n \"student_email\": request.user.email,\n \"club_email\": body.get('club')\n })\n else:\n sub = Subscription.objects.filter(club_email=body.get('club'))\n sub = sub.filter(student_email=request.user.email)\n sub.delete()\n\n return JsonResponse({\"success\": True,\n \"student_email\": request.user.email,\n \"club_email\": body.get('club')\n })\n\n\n all_clubs = Club.objects.values_list('email', flat=True)\n\n sub = Subscription.objects.filter(student_email=request.user.email)\n user_clubs = list(sub.values_list('club_email', flat=True))\n\n clubs = []\n for x in all_clubs:\n clubs.append({\"email\": x, \"checked\": (x in user_clubs)})\n\n return render(request, 'events/subscriptions.html',\n {'clubs': clubs})\n","sub_path":"events/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"140595358","text":"from src.base import BaseHandler\nfrom tornado.gen import coroutine\nfrom tornado.web import RequestHandler\nfrom twilio.rest import TwilioRestClient\n \nclass MessageHandler(BaseHandler):\n @coroutine\n def post(self, *args, **kwargs):\n print(\"MESSAGEHANDLER\")\n data=self.parse_request_body()\n ACCOUNT_SID = 'AC7a04c2569f0d4c1bb1209fc24958f0a9'\n AUTH_TOKEN = '8a9796aeec4b5cdeb09da5febd5afee9'\n client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)\n client.messages.create(\n to = data['to_number'],\n from_ = '+18022430203',\n body = data['body'],\n )\n self.respond('Message Sent','200')\n \n","sub_path":"src/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"36604045","text":"import os\nimport yaml\n\nfrom .system import SYSTEM\n\n__CACHE__ = None\n\ndef _filename(filename=None):\n if filename is None:\n if SYSTEM == 'win':\n filename = os.path.join(os.environ.get(\"USERPROFILE\"), \"_devopsrc\")\n else:\n filename = os.path.join(os.environ.get(\"HOME\"), \".devopsrc\")\n return filename\n\ndef load(filename=None):\n global __CACHE__\n if __CACHE__ is None or filename is not None:\n filename = _filename(filename=filename)\n try:\n with open(filename, \"r\") as filehandler:\n __CACHE__ = yaml.load(filehandler.read())\n except Exception as e:\n __CACHE__ = dict()\n\ndef register(filename=None):\n global __CACHE__\n load()\n filename = _filename(filename=filename)\n with open(filename, \"w\") as filehandler:\n filehandler.write(yaml.dump(__CACHE__, default_flow_style=False))\n\ndef set_active_branch(branch):\n global __CACHE__\n load()\n if not active_branch is None:\n __CACHE__[\"active_branch\"] = branch\n register()\n \ndef unset_active_branch():\n global __CACHE__\n load()\n __CACHE__.pop(\"active_branch\", None)\n register()\n\ndef set_netrc_update(update=False):\n global __CACHE__\n load()\n if update is not None:\n __CACHE__[\"netrc_update\"] = update\n register()\n\n","sub_path":"src/py/devops_tools/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"581950921","text":"from copy import deepcopy\nfrom enum import Enum, auto\n\n\nclass DiversificationStrategy(Enum):\n RESTART = auto()\n CONTINUOUS = auto()\n\n def move(self, hidden_list, pick_number=3):\n if self.value == self.RESTART.value:\n return self.move_to_restart()\n elif self.value == self.CONTINUOUS.value:\n return self.move_to_the_smallest_values(hidden_list, pick_number)\n\n def move_to_smallest_values(self, hidden_list, pick_number=3):\n pass\n\n def move_to_the_smallest_values(self, hidden_list, pick_number=3):\n smallest_dict = deepcopy(hidden_list)\n smallest_dict = self.pick_all_zeros(smallest_dict)\n smallest_dict = dict(sorted(smallest_dict.items(), key=lambda item: item[1][1])[:pick_number])\n # print(\"Picked values by the diversification run:\", smallest_dict)\n return deepcopy(smallest_dict)\n\n def pick_all_zeros(self, dict):\n for i in range(0, len(self.matrix) - 1):\n for j in range(i, len(self.matrix) - 1):\n if self.matrix[i][j] == 0:\n dict[i] = (j, 0)\n break\n return dict\n","sub_path":"tabu-search-algorithm/strategies/diversification_strategies.py","file_name":"diversification_strategies.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"83148028","text":"import os\nimport sys\nimport re\nimport subprocess\nimport argparse\nimport logging\nimport json\nimport time\n\nlogging.getLogger().setLevel(logging.INFO)\nlogging.basicConfig(format='%(asctime)s %(message)s')\n\nclass jobexecutor:\n def __init__(self):\n self.command=\"echo please set command\"\n self.outdir=os.path.abspath('.')\n self.input=\"state.json\"\n self.output=self.input\n self.vf=1\n self.cpu=1\n self.queue=\"st.q\"\n self.project=None\n self.lineSplit=100\n self.partAll=[]\n \n def runclusterjob(self,commandshell=None,jobname=None):\n #self.input=self.outdir+\"/state/\"+self.input\n self.output=self.input\n useCommand=commandshell\n if commandshell is None:\n useCommand=self.command\n takecommand,part=self.makeRunCommand(useCommand)\n self.partAll=[]\n for i in range(1,part+1,1):\n self.partAll.append(str(i))\n usedjobname=jobname\n os.makedirs(\"%s/state\" % (self.outdir),mode=0o755,exist_ok=True)\n \n if jobname is None:\n usedjobname=\"test\"\n statedict=self.loadjson()\n if statedict['control'] == 'run':\n globalcode=1\n if usedjobname in statedict:\n prejobidPart=statedict[usedjobname]\n if prejobidPart == 'completed':\n globalcode=0\n else:\n prejobid,partRecord=prejobidPart.split('-')\n partRecordCheck=partRecord.split(',')\n shellcode=self.checkshell(takecommand,\"%s/shell/%s/%s.sh\" % (self.outdir,jobname,jobname))\n #check previous shell and current shell if different,then kill job and run new shell\n #if shell code is not the same then need to rerun de job anyway\n if shellcode==1:\n self.killjob(prejobid)\n if prejobid != 'completed':\n logging.info(\"kill previous %s\" % (usedjobname))\n else:\n if prejobid == 'completed':\n globalcode=0\n else:\n palivecode=self.checkalive(prejobid)\n if palivecode==0:\n globalcode,unfinishPart=self.checkcomplete(prejobid,partRecordCheck,usedjobname)\n if unfinishPart:\n uniquePart={}\n for pp in unfinishPart:\n uniquePart[pp]=1\n self.partAll=uniquePart.keys()\n \n \n while(globalcode > 0):\n recode,submitid=self.submitjob(takecommand,usedjobname)\n timecap=30\n if recode == 0:\n statedict[usedjobname]=submitid+\"-\"+\",\".join(self.partAll)\n elif recode > 0:\n logging.info(\"resubmit job because the first submit fail\")\n resubmitid=self.rerunjob(recode,timecap,takecommand,usedjobname)\n statedict[usedjobname]=resubmitid+\"-\"+\",\".join(self.partAll)\n else:\n globalcode=-1\n statedict[usedjobname]=submitid\n\n self.dumpjson(statedict)\n time.sleep(30)\n if globalcode > 0:\n jobid=statedict[usedjobname].split('-')[0]\n alivecode=self.checkalive(jobid)\n if alivecode==0:\n globalcode,unfinishParta=self.checkcomplete(jobid,self.partAll,usedjobname)\n if unfinishParta:\n uniqueParta={}\n for ppp in unfinishParta:\n uniqueParta[ppp]=1\n self.partAll=uniqueParta.keys()\n else:\n self.killjob(jobid)\n if globalcode==0:\n statedict[usedjobname]='completed-'\n self.dumpjson(statedict)\n elif statedict['control'] == 'hold':\n self.hodljob()\n elif statedict['control'] == 'stop':\n pass\n else:\n pass\n \n\n\n def submitjob(self,commandshell,jobname):\n shelldir=\"%s/shell/%s\" % (self.outdir,jobname)\n os.makedirs(shelldir,mode=0o755,exist_ok=True)\n out=open(shelldir+\"/\"+jobname+\".sh\",mode='w')\n out.write(commandshell)\n out.close()\n part=\",\".join(self.partAll)\n qsubcommand=\"qsub -clear -terse -N %s.sh -t %s -wd %s -l vf=%sG,num_proc=%d -binding linear:%d -q %s \" % (jobname,part,shelldir,self.vf,self.cpu,self.cpu,self.queue)\n if self.project is not None:\n qsubcommand+=\"-P %s\" % (self.project)\n qsubcommand+=\" %s/%s.sh\" % (shelldir,jobname)\n logging.info(qsubcommand)\n submit=subprocess.Popen(qsubcommand,shell=True,stderr=subprocess.PIPE,stdout=subprocess.PIPE,universal_newlines=True)\n returncode=submit.wait(timeout=120)\n if returncode == 0:\n stdout=submit.stdout.read()\n stderr=submit.stderr.read()\n #print(stdout+\"\\n\"+stderr)\n if stderr is not '':\n return -1,stderr\n else:\n return returncode,re.sub(r'\\..*',r'',stdout.replace('\\n',''))\n else:\n return 1,None\n \n def rerunjob(self,code,timecap,commandshell,jobname):\n tmpcode=code\n tmpsid=''\n totaltime=0\n while(tmpcode != 0):\n time.sleep(timecap)\n tmpcode,tmpsid=self.submitjob(commandshell,jobname)\n totaltime+=30\n if totaltime > 7200:\n tmpcode=0\n tmpsid='fail to resubmit job for two hours.'\n\n return tmpsid\n\n def killjob(self,sgejobid):\n if sgejobid=='completed':\n pass\n else:\n cmd='qdel %s' % (sgejobid)\n subprocess.Popen(cmd,shell=True,universal_newlines=True)\n\n def makeRunCommand(self, command):\n commandLine=re.sub(r'\\s+$',r'',command).split('\\n')\n commandLineNum=len(commandLine)\n modifiedCmd=[]\n jobcu=1\n if commandLineNum > 1:\n partNum=1\n if commandLineNum >self.lineSplit:\n partNum=int(commandLineNum/self.lineSplit)+1\n elif commandLineNum= partNum:\n cu=0\n jobcu+=1\n else:\n bsline=re.sub(r'\\s+$',r'',commandLine[0])\n btline=re.sub(r';+$',r'',bsline)\n lineM=\"if [ $SGE_TASK_ID -eq 1 ];then { %s ; } && echo JobFinished $SGE_TASK_ID;fi\" % (btline)\n modifiedCmd.append(lineM)\n jobcu+=1\n spart=jobcu-1\n logging.info(\"%d line(s) in this step\" % (spart))\n return \"\\n\".join(modifiedCmd),spart\n\n\n def checkshell(self, newshell,oldshellfile):\n #logging.info(oldshellfile)\n oldshell=open(oldshellfile,mode='r').readlines()\n totalshell=''\n for line in oldshell:\n #logging.info(line)\n totalshell+=re.sub(r'\\s+',r'',line)\n tnewshell=re.sub(r'\\s+',r'',newshell)\n if tnewshell != totalshell:\n logging.info(\"%s\\nNOT EUQAL%s\\n\" % (tnewshell,totalshell))\n return 1\n else:\n return 0\n\n def hodljob(self):\n pass\n def checkalive(self, sgejobid):\n cplcode=-1\n counttime={}\n tcount=0\n logging.info(\"checkalive \"+sgejobid)\n while(cplcode<0):\n time.sleep(120)\n qstatuser=\"qstat\"\n statall=subprocess.Popen(qstatuser,shell=True,stderr=subprocess.PIPE,stdout=subprocess.PIPE,universal_newlines=True)\n returncode=-1\n try:\n returncode=statall.wait(timeout=120)\n except:\n pass\n if returncode >=0:\n stdoutall=statall.stdout.readlines()\n stderrall=statall.stderr.read()\n if stderrall is not '':\n pass\n else:\n jobrecord=[x for x in stdoutall if re.match(re.escape(sgejobid),re.sub(r'^\\s+',r'',x))]\n if jobrecord:\n jobrecordarray=jobrecord[0].split()\n print(jobrecordarray[4])\n if jobrecordarray[4] == 'qw':\n pass\n elif jobrecordarray[4] == 'Eqw':\n self.killjob(sgejobid)\n cplcode=1\n elif jobrecordarray[4] == 'T':\n self.killjob(sgejobid)\n cplcode=1\n elif jobrecordarray[4] == 'dr':\n cplcode=1\n elif jobrecordarray[4] == 't':\n tcount+=1\n if tcount > 5:\n cplcode=1\n elif jobrecordarray[4] == 'r':\n qstatcmd=\"qstat -j %s\" % sgejobid\n stat=subprocess.Popen(qstatcmd,shell=True,stderr=subprocess.PIPE,stdout=subprocess.PIPE,universal_newlines=True)\n returncode=-1\n try:\n returncode=stat.wait(timeout=120)\n except:\n pass\n if returncode >=0:\n stdout=stat.stdout.readlines()\n stderr=stat.stderr.read()\n if re.match(r'Following',stderr):\n cplcode=0\n elif stderr:\n #some kind of sge error\n pass\n else:\n usageAll=[x for x in stdout if re.match(r'usage',x)]\n for line in usageAll:\n aa=line.split()\n livevf=re.findall(r'vmem=\\d+\\.\\d+.',line)\n if livevf:\n livevfs=livevf[0].replace('vmem=','')\n vmem=float(livevfs[0:-1])\n if livevfs[-1] == 'M':\n vmem/=1024\n if vmem >self.vf*1.5 or vmem >self.vf+5:\n try:\n counttime[aa[1]]+=120\n except:\n counttime[aa[1]]=120\n else:\n counttime[aa[1]]=0\n if counttime[aa[1]] >= 1200:\n newvf=vmem*1.5\n logging.info(\"jobid %s have break memory for 20min : set %d G used %d G; kill and reqsub new vf %s G\" % (sgejobid,self.vf,vmem,newvf))\n self.vf=newvf\n cplcode=1\n break\n else:\n pass\n else:\n cplcode=0\n print(\"checkalive code %d\" % (cplcode))\n return cplcode\n\n def checkcomplete(self,jobid,jobpart,jobname):\n if re.match(r'fail',jobid):\n return 1\n else:\n cplcode=-1\n uncpPart=[]\n while(cplcode<0):\n cmd=\"qstat -j %s\" % jobid\n stat=subprocess.Popen(cmd,shell=True,stderr=subprocess.PIPE,stdout=subprocess.PIPE,universal_newlines=True)\n returncode=-1\n try:\n returncode=stat.wait(timeout=120)\n except:\n pass\n if returncode >=0:\n stdout=stat.stdout.readlines()\n stderr=stat.stderr.read()\n if re.match(r'Following',stderr):\n for part in jobpart:\n shelldir=\"%s/shell/%s/%s.sh.o%s.%s\" % (self.outdir,jobname,jobname,jobid,part)\n shellerr=\"%s/shell/%s/%s.sh.e%s.%s\" % (self.outdir,jobname,jobname,jobid,part)\n try:\n alllog=open(shelldir,mode='r').readlines()\n if re.match(r'JobFinished',alllog[-1]):\n if cplcode<0:\n cplcode=0\n else:\n uncpPart.append(part)\n cplcode=1\n except:\n uncpPart.append(part)\n cplcode=1\n try:\n allerr=open(shellerr,mode='r').readlines()\n for x in allerr:\n if re.search(r'Segmentation fault',x):\n cplcode=-1\n logging.info(\"Job %s with Jobid %s in fatal error;check %s for detail\" % (jobname,jobid,shellerr))\n except:\n pass\n elif re.match(r'========',stdout[0]):\n pass\n else:\n pass\n print(cplcode)\n time.sleep(60)\n return cplcode,uncpPart\n\n def dumpjson(self,statedict,outputfile=None):\n self.output=self.input\n outputjson=outputfile\n if outputfile is None:\n outputjson=self.output\n try:\n oldjsondict=self.loadjson(outputjson)\n out=open(outputjson,mode='w')\n oldjsondict.update(statedict) \n json.dump(statedict,out,indent=4)#when step run parrallel, this file will be in wrong format. need to load the file first and then write the other in the same file\n out.close()\n except IOError as e:\n raise e\n \n def loadjson(self, inputfile=None):\n inputjson=inputfile\n if inputfile is None:\n inputjson=self.input\n try:\n jsondict=json.load(open(inputjson,mode='r'))\n except:\n jsondict={'control':'run'}\n return jsondict\n\n\nif __name__ == '__main__':\n if len(sys.argv) == 1:\n print(\"use -h to check more parameter\")\n sys.exit()\n parser=argparse.ArgumentParser(description=\"pipeline annotator help\")\n parser.add_argument('--shellfile',dest=\"shellFile\",type=str,help=\"the shell file would be submit\")\n parser.add_argument('--line',dest=\"lineSplit\",type=int,help=\"the line number contain in each split part. default split in 100 part. if you wish to run the whole shell in one job,set this to a number larger than the line number of the shell file and not equal 100\")\n parser.add_argument('--vf',dest=\"vf\",type=int,help=\"memory used in each job [ only support GB ]\")\n parser.add_argument('--cpu',dest=\"cpu\",type=int,help=\"cpu number set for each job\")\n parser.add_argument('--queue',dest=\"queue\",type=str,help=\"the queue use to run the job\")\n parser.add_argument('--project',dest=\"project\",type=str,help=\"the project code use to run the job. if the queue didn't need, don't set\")\n parser.add_argument('--outdir',dest=\"outdir\",type=str,help=\"the output dir used to output the log and job state, default current directory\")\n\n localeArg=parser.parse_args()\n pwd=os.path.abspath('.')\n\n if localeArg.shellFile is None or localeArg.outdir is None or localeArg.queue is None:\n print(\"shellFile or outdir or queue not set\")\n sys.exit()\n startw=jobexecutor()\n startw.outdir=localeArg.outdir\n try:\n command=open(localeArg.shellFile,mode='r').read()\n startw.command=command\n except IOError as e:\n raise e\n jobnamea=os.path.basename(localeArg.shellFile)\n jobname=re.sub(r'\\..*',r'',jobnamea)\n if localeArg.vf is not None:\n startw.vf=localeArg.vf\n if localeArg.cpu is not None:\n startw.cpu=localeArg.cpu\n if localeArg.project is not None:\n startw.project=localeArg.project\n if localeArg.lineSplit is not None:\n startw.lineSplit=localeArg.lineSplit\n startw.runclusterjob(jobname=jobname)\n\n\n","sub_path":"jobexcutor.py","file_name":"jobexcutor.py","file_ext":"py","file_size_in_byte":17431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"646817058","text":"import math\ndef czytajWspolczynniki():\n wspolczynniki = []\n while len(wspolczynniki) < 3:\n wspolczynniki.append(int(input(\"Podaj współczynnik \"+ str(len(wspolczynniki))+\": \")))\n return wspolczynniki\n\ndef obliczDelte(wspolczynniki):\n return wspolczynniki[1]**2 - 4*wspolczynniki[0]*wspolczynniki[2]\n\ndef obliczPierwiastki(wspolczynniki, delta):\n if delta < 0:\n print(\"Delta mniejsza od 0\")\n return []\n elif delta == 0:\n return [(-wspolczynniki[0])/(2*wspolczynniki[1])]\n elif delta > 0:\n a = (-wspolczynniki[1]-math.sqrt(delta))/(wspolczynniki[0]*2)\n b = (-wspolczynniki[1]+math.sqrt(delta))/(wspolczynniki[0]*2)\n return [a,b]\n \ndef wyswietlPierwiastki(pierwiastki):\n print(\"Pierwiastki kwadratowe: \")\n for i in pierwiastki:\n print(i)","sub_path":"05-ModularProgramming/zadania/QuadraticEquation.py","file_name":"QuadraticEquation.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"153504032","text":"import uproot\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport scipy.stats\nfrom matplotlib.ticker import (MultipleLocator, FormatStrFormatter, AutoMinorLocator)\nfrom overloads import ROOT, SinglePadCanvas, niceTLegend\nfrom helpers import ATLASInternal, EnergyAndLumi, DrawText, ATLASPre\nimport re\nlegend_title = {\n \"r1\": \"1 #font[52]{b}-tag, resolved\",\n \"r2\": \"2 #font[52]{b}-tags, resolved\",\n \"r3\": \"3+ #font[52]{b}-tags, resolved\",\n \"m1\": \"1 #font[52]{b}-tag, 0 add., merged\",\n \"m2\": \"2 #font[52]{b}-tags, 0 add., merged\",\n \"m1a\": \"1 #font[52]{b}-tag, 1+ add., merged\",\n \"m2a\": \"2 #font[52]{b}-tags, 1+ add., merged\",\n \"m12a\": \"1+2 #font[52]{b}-tags, 1+ add., merged\",\n \"sum\": \"All signal regions\",\n}\ngraph_style = {\n \"r1\": {\"color\": ROOT.kTeal - 8, \"markerstyle\": 8, \"markersize\": 0.75, \"linestyle\": 1, \"linewidth\": 2},\n \"r2\": {\"color\": ROOT.kTeal - 8, \"markerstyle\": 8, \"markersize\": 0.75, \"linestyle\": 2, \"linewidth\": 2},\n \"r3\": {\"color\": ROOT.kTeal - 8, \"markerstyle\": 8, \"markersize\": 0.75, \"linestyle\": 3, \"linewidth\": 2},\n \"m1\": {\n \"color\": ROOT.kAzure - 8,\n \"markerstyle\": 8,\n \"markersize\": 0.75,\n \"linestyle\": 1,\n \"linewidth\": 2,\n },\n \"m2\": {\n \"color\": ROOT.kAzure - 8,\n \"markerstyle\": 8,\n \"markersize\": 0.75,\n \"linestyle\": 2,\n \"linewidth\": 2,\n },\n \"m12a\": {\n \"color\": ROOT.kAzure - 8,\n \"markerstyle\": 8,\n \"markersize\": 0.75,\n \"linestyle\": 3,\n \"linewidth\": 2,\n },\n \"m1a\": {\n \"color\": ROOT.kAzure - 8,\n \"markerstyle\": 8,\n \"markersize\": 0.75,\n \"linestyle\": 3,\n \"linewidth\": 2,\n },\n \"m2a\": {\n \"color\": ROOT.kAzure - 8,\n \"markerstyle\": 8,\n \"markersize\": 0.75,\n \"linestyle\": 4,\n \"linewidth\": 2,\n },\n \"sum\": {\"color\": ROOT.kBlack, \"markerstyle\": 8, \"markersize\": 1.2, \"linestyle\": 1, \"linewidth\": 3},\n}\ntext = {\n \"HVTZHllqq\": {\"title\": \"2L channel, HVT Z' #rightarrow Zh #rightarrow llbb, llcc\", \"xtitle\": r\"#font[52]{m_{Z'}} [GeV]\"},\n \"AZhllbb\": {\n \"title\": \"2L channel, gg #rightarrow A #rightarrow Zh #rightarrow llbb\",\n \"xtitle\": r\"#font[52]{A} resonance mass [GeV]\",\n },\n \"bbAZhllbb\": {\n \"title\": \"2L channel, gg #rightarrow b#bar{b}A, A #rightarrow Zh\",\n \"xtitle\": r\"#font[52]{A} resonance mass [GeV]\",\n },\n}\ndef apply_style(graph, region):\n graph.SetLineStyle(graph_style[region][\"linestyle\"])\n graph.SetLineWidth(graph_style[region][\"linewidth\"])\n graph.SetLineColor(graph_style[region][\"color\"])\n\n graph.SetMarkerStyle(graph_style[region][\"markerstyle\"])\n graph.SetMarkerSize(graph_style[region][\"markersize\"])\n graph.SetMarkerColor(graph_style[region][\"color\"])\n \ndef main():\n # samplenameinhist = \"AZhllbb\"\n # samplenameininfo = \"ggA\"\n # signalname = \"AZhllbb\"\n\n # samplenameinhist = \"HVTZHllqq\"\n # samplenameininfo = \"HVT\"\n # signalname = \"HVTZHllqq\"\n \n samplenameinhist = \"bbAZhllbb\"\n samplenameininfo = \"bbA\"\n signalname = \"bbAZhllbb\"\n ids = []\n masses = []\n yields = {}\n selected = {}\n selectedr1 = {}\n selectedr2 = {}\n selectedr3 = {}\n selectedm1 = {}\n selectedm2 = {}\n selectedm1a = {}\n selectedm2a = {}\n selectedm12a = {}\n\n with open(\"sample_info.txt\") as f:\n for eachline in f:\n sample_tem = eachline.split(\" \")\n sample = []\n for each in sample_tem:\n if each != \"\" and each != \"\\n\":\n sample.append(each)\n if samplenameininfo in sample[1]:\n ids.append(int(sample[0]))\n else:\n continue\n if samplenameininfo == \"ggA\" or samplenameininfo == \"bbA\":\n for each in sample[2].split(\"_\"):\n if samplenameininfo in each:\n masses.append(int(each.replace(samplenameininfo, \"\")))\n break\n elif samplenameininfo == \"HVT\":\n masses.append(int(re.findall(\"\\d+\", sample[2].split(\"_\")[-1])[0]))\n\n \n yieldfiles = [\"a.txt\", \"d.txt\", \"e.txt\"]\n for eachfile in yieldfiles:\n with open(eachfile) as f:\n for eachline in f:\n sample_tem = eachline.split(\" \")\n sample = []\n for each in sample_tem:\n if each != \"\" and each != \"\\n\":\n sample.append(each)\n if int(sample[0]) in ids:\n i = ids.index(int(sample[0]))\n if masses[i] not in yields:\n yields[masses[i]] = int(sample[1])\n else:\n yields[masses[i]] += int(sample[1])\n \n f = uproot.open(\"run2dbl_bbA.root\")\n # for each_histname in f.keys():\n # if \"bbA\" in each_histname.decode(\"utf-8\") and \"300_\" in each_histname.decode(\"utf-8\") and \"_SR_\" in each_histname.decode(\"utf-8\"):\n # print(each_histname)\n # exit(1)\n print(masses)\n for each_histname in f.keys():\n each_histname_b = each_histname\n each_histname = each_histname.decode(\"utf-8\")\n for each_mass in masses:\n if samplenameinhist + str(each_mass) + \"_\" in each_histname and \"_SR_\" in each_histname:\n # if each_mass == 400:\n # print(\" \" + each_histname)\n if \"0tag\" in each_histname:\n continue\n if \"bbA\" not in each_histname:\n continue\n if samplenameininfo != \"bbA\":\n if \"topaddbjetcr\" in each_histname or \"4ptag2pjet\" in each_histname or \"3tag2pjet\" in each_histname or \"3ptag2pjet\" in each_histname:\n continue\n if each_mass not in selected:\n selected[each_mass] = f[each_histname_b]._fEntries\n else:\n selected[each_mass] += f[each_histname_b]._fEntries\n if \"1tag2pjet\" in each_histname:\n if each_mass not in selectedr1:\n selectedr1[each_mass] = f[each_histname_b]._fEntries\n else:\n print(\"error1\")\n exit(1)\n if \"2tag2pjet\" in each_histname:\n if each_mass not in selectedr2:\n selectedr2[each_mass] = f[each_histname_b]._fEntries\n else:\n print(\"error2\")\n exit(1)\n if \"3ptag2pjet\" in each_histname:\n if each_mass not in selectedr3:\n selectedr3[each_mass] = f[each_histname_b]._fEntries\n else:\n print(\"error3\")\n exit(1)\n if \"1tag1pfat0pjet_0ptv_SR_noaddbjetsr\" in each_histname:\n if each_mass not in selectedm1:\n selectedm1[each_mass] = f[each_histname_b]._fEntries\n else:\n print(\"error4\")\n exit(1)\n if \"2tag1pfat0pjet_0ptv_SR_noaddbjetsr_mVH\" in each_histname:\n if each_mass not in selectedm2:\n selectedm2[each_mass] = f[each_histname_b]._fEntries\n else:\n print(\"error5\")\n exit(1)\n if \"1tag1pfat0pjet_0ptv_SR_topaddbjetcr\" in each_histname:\n if each_mass not in selectedm1a:\n selectedm1a[each_mass] = f[each_histname_b]._fEntries\n else:\n print(\"error6\")\n exit(1)\n if \"2tag1pfat0pjet_0ptv_SR_topaddbjetcr_mVH\" in each_histname:\n if each_mass not in selectedm2a:\n selectedm2a[each_mass] = f[each_histname_b]._fEntries\n else:\n print(\"error4\")\n exit(1)\n if \"2tag1pfat0pjet_0ptv_SR_topaddbjetcr_mVH\" in each_histname or \"1tag1pfat0pjet_0ptv_SR_topaddbjetcr\" in each_histname:\n if each_mass not in selectedm12a:\n selectedm12a[each_mass] = f[each_histname_b]._fEntries\n else:\n selectedm12a[each_mass] += f[each_histname_b]._fEntries\n print(selected)\n masses_tem = sorted(masses)\n masses = []\n for each in masses_tem:\n if each < 5010:\n masses.append(each)\n\n acceptance = []\n for each in masses:\n if each in selected:\n acceptance.append(selected[each]/yields[each])\n print(each, selected[each], yields[each], selected[each]/yields[each])\n\n acceptancer1 = []\n for each in masses:\n if each in selectedr1:\n acceptancer1.append(selectedr1[each]/yields[each])\n else:\n acceptancer1.append(0)\n \n acceptancer2 = []\n for each in masses:\n if each in selectedr2:\n acceptancer2.append(selectedr2[each]/yields[each])\n else:\n acceptancer2.append(0)\n\n acceptancer3 = []\n for each in masses:\n if each in selectedr3:\n acceptancer3.append(selectedr3[each]/yields[each])\n else:\n acceptancer3.append(0)\n\n acceptancem1 = []\n for each in masses:\n if each in selectedm1:\n acceptancem1.append(selectedm1[each]/yields[each])\n else:\n acceptancem1.append(0)\n\n acceptancem2 = []\n for each in masses:\n if each in selectedm2:\n acceptancem2.append(selectedm2[each]/yields[each])\n else:\n acceptancem2.append(0)\n\n\n acceptancem1a = []\n for each in masses:\n if each in selectedm1a:\n acceptancem1a.append(selectedm1a[each]/yields[each])\n else:\n acceptancem1a.append(0)\n\n acceptancem2a = []\n for each in masses:\n if each in selectedm2a:\n acceptancem2a.append(selectedm2a[each]/yields[each])\n else:\n acceptancem2a.append(0)\n\n acceptancem12a = []\n for each in masses:\n if each in selectedm12a:\n acceptancem12a.append(selectedm12a[each]/yields[each])\n else:\n acceptancem12a.append(0)\n\n efficiencies = {}\n efficiencies[\"r1\"] = acceptancer1\n efficiencies[\"r2\"] = acceptancer2\n efficiencies[\"r3\"] = acceptancer3\n efficiencies[\"m1\"] = acceptancem1\n efficiencies[\"m2\"] = acceptancem2\n efficiencies[\"m1a\"] = acceptancem1a\n efficiencies[\"m2a\"] = acceptancem2a\n efficiencies[\"m12a\"] = acceptancem12a\n efficiencies[\"sum\"] = acceptance\n \n canv = SinglePadCanvas()\n canv.cd()\n xax, yax = None, None\n legend = niceTLegend()\n __root_objects = []\n __root_objects.append(legend)\n sumlist = [\"sum\"] + [\"r1\", \"r2\", \"m1\", \"m2\"]\n if samplenameininfo == \"bbA\":\n sumlist = [\"sum\"] + [\"r1\", \"r2\", \"r3\", \"m1\", \"m2\", \"m12a\"]\n for region in sumlist:\n graph = ROOT.TGraph()\n __root_objects.append(graph)\n graph.SetTitle(region)\n for idx, (mass, eff) in enumerate(zip(masses, efficiencies[region])):\n graph.SetPoint(idx, mass, eff)\n if xax is None:\n graph.Draw(\"APL\")\n xax = graph.GetXaxis()\n yax = graph.GetYaxis()\n graph.SetMinimum(0)\n graph.SetMaximum(1.8 * np.max(efficiencies[\"sum\"]))\n else:\n graph.Draw(\"PLsame\")\n apply_style(graph, region)\n legend.AddEntry(graph, legend_title[region], \"PL\")\n\n canv.paper_style()\n canv.xtitle = text[signalname][\"xtitle\"]\n canv.ytitle = \"Acceptance #times efficiency\"\n canv.title = \"\"\n canv.xrange = (100, 5100)\n if \"HVT\" not in signalname:\n canv.xrange = (200, 2100)\n\n yax.SetNdivisions(505)\n\n legend.UpdateCoords(0.52, 0.65, 0.9, 0.93)\n legend.Draw()\n\n ATLASInternal(x=0.15, y=0.88)\n #ATLASPre(x=0.15, y=0.88)\n EnergyAndLumi(x=0.15, y=0.82, lumi=139, size=0.035)\n DrawText(text[signalname][\"title\"], x=0.15, y=0.78, size=0.035)\n\n canv.save(f\"signal_efficiency_{signalname}\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"acceptance/yieldplot_root_bba.py","file_name":"yieldplot_root_bba.py","file_ext":"py","file_size_in_byte":12256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"576122197","text":"import matplotlib.pyplot as plt\nimport scipy.stats as stats\nimport numpy as np\n\nimport json\n\n\nplt.style.use('plotstyle.mplstyle')\nplt.rcParams['legend.title_fontsize'] = 'xx-small'\n\n\nfig = plt.figure(constrained_layout=True)\ngs = fig.add_gridspec(11,3)\nax = [fig.add_subplot(gs[i*6:(i+1)*6-2, j]) \n for j in [0,1,2] for i in [0,1]]\n\nlg = [fig.add_subplot(gs[i*6+4:(i+1)*6, j]) \n for j in [0,1,2] for i in [0,1] ]\n[l.axis('off') for l in lg]\n\n\ndists = [\n 'Normal',\n 'Lognormal',\n 'Beta',\n 'Uniform',\n 'Weibull',\n 'Gumbel']\n\n\nwith open('rvplot.json') as file: dat = json.load(file)\n\n##############################################################################\n# Add missing distributions\n\ndist = 'Normal'\nparams = [[6.0, 0.5], [5.0, 1.0], ]\nx = np.linspace(0.,10,100)\n\ndat[dist] = {\n 'l':['$\\\\mu={}$,\\n $\\\\sigma={}$'.format(a[0],a[1]) for a in params],\n 'x':x,\n 'y':[],\n}\nfor a in params: dat[dist]['y'].append(stats.norm.pdf(x,a[0],a[1]))\n\n\ndist = 'Beta'\nparams = [[0.5, 0.5], [5.0, 1.0], [1.0, 3.0], [2.0, 2.0],[2.0, 5.0]]\nx = np.linspace(0.,1.,100)\n\ndat[dist] = {\n 'l':['$a={}$,\\n $b={}$'.format(a[0],a[1]) for a in params],\n 'x':x,\n 'y':[],\n}\nfor a in params: dat[dist]['y'].append(stats.beta.pdf(x,a[0],a[1]))\n\n##############################################################################\n\nfor i, dist in enumerate(dists):\n lines = []\n l, x, y = dat[dist].values()\n if len(y) < len(x):\n for yi,li in zip(y,l): lines += ax[i].plot(x, yi, label=li,linewidth=0.7)\n else: lines += ax[i].plot(x,y,label=l,linewidth=1.)\n\n ax[i].set_title(dist)\n # ax[i].xaxis.set_ticklabels([])\n # ax[i].yaxis.set_ticklabels([])\n leg = lg[i].legend(lines,l,loc='center',ncol=2, handlelength=0.7,labelspacing=0.3)\n plt.setp(leg.get_texts(), fontsize='6')\n\npath = '..\\\\docs\\\\common\\\\user_manual\\\\usage\\\\desktop\\\\figures\\\\'\n\nfig.savefig(path+'rvplot.png')\n","sub_path":"rvPlots/rvplot.py","file_name":"rvplot.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"554725821","text":"from jupyterhub.mmcauth import MMCAuthenticator\nimport os\nimport sys\n\n\n# c.JupyterHub.authenticator_class = DummyAuthenticator\nc.JupyterHub.authenticator_class = MMCAuthenticator\n\n# launch with docker\nc.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner'\n\n# we need the hub to listen on all ips when it is in a container\nc.JupyterHub.hub_ip = '0.0.0.0'\n# the hostname/ip that should be used to connect to the hub\n# this is usually the hub container's name\nc.JupyterHub.hub_connect_ip = 'jupyterhub'\n\n# pick a docker image. This should have the same version of jupyterhub\n# in it as our Hub.\nc.DockerSpawner.image = 'jupyter/base-notebook'\n\n# tell the user containers to connect to our docker network\nc.DockerSpawner.network_name = 'jupyterhub'\n\n# delete containers when the stop\nc.DockerSpawner.remove = True\n\nc.MMCAuthenticator.mmc_userinfo_url = 'https://newton-dev-samwell.micromooc.com/samwell/api/v1/user/current'\n\n# Explicitly set notebook directory because we'll be mounting a host volume to\n# it. Most jupyter/docker-stacks *-notebook images run the Notebook server as\n# user `jovyan`, and set the notebook directory to `/home/jovyan/work`.\n# We follow the same convention.\nnotebook_dir = os.environ.get('DOCKER_NOTEBOOK_DIR') or '/home/jovyan/work'\nc.DockerSpawner.notebook_dir = notebook_dir\n\n# Mount the real user's Docker volume on the host to the notebook user's\n# notebook directory in the container\nc.DockerSpawner.volumes = { 'jupyterhub-user-{username}': notebook_dir }\n\nc.Spawner.mem_limit = '128M'\n\n# run cull-idle as a service\nc.JupyterHub.services = [\n {\n 'name': 'cull-idle',\n 'admin': True,\n 'command': [sys.executable, '/src/jupyterhub/cull_idle_servers.py', '--timeout=900'],\n }\n]","sub_path":"mmc/jupyterhub_config.py","file_name":"jupyterhub_config.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"544987208","text":"#\n# coding: utf-8\n# Copyright (c) 2018 DATADVANCE\n#\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 persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\"\"\"Tests GraphQL over WebSockets with subscriptions.\n\nHere we test `Subscription` and `GraphqlWsConsumer` classes.\n\"\"\"\n\n# NOTE: Tests use the GraphQL over WebSockets setup. All the necessary\n# items (schema, query, subscriptions, mutations, Channels\n# consumer & application) are defined at the end on this file.\n\nimport json\nimport textwrap\nimport uuid\n\nimport channels\nimport channels.testing as ch_testing\nimport django.urls\nimport graphene\nimport pytest\n\nfrom channels_graphql_ws.graphql_ws import GraphqlWsConsumer, Subscription\n\n\n# Default timeout. Increased to avoid TimeoutErrors on slow machines.\nTIMEOUT = 5\n\n\n@pytest.mark.asyncio\nasync def test_main_usecase():\n \"\"\"Test main use-case with the GraphQL over WebSocket.\"\"\"\n\n # Channels communicator to test WebSocket consumers.\n comm = ch_testing.WebsocketCommunicator(\n application=my_app, path=\"graphql/\", subprotocols=[\"graphql-ws\"]\n )\n\n print(\"Establish WebSocket connection and check a subprotocol.\")\n connected, subprotocol = await comm.connect(timeout=TIMEOUT)\n assert connected, \"Could not connect to the GraphQL subscriptions WebSocket!\"\n assert subprotocol == \"graphql-ws\", \"Wrong subprotocol received!\"\n\n print(\"Initialize GraphQL connection.\")\n await comm.send_json_to({\"type\": \"connection_init\", \"payload\": \"\"})\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"type\"] == \"connection_ack\"\n\n print(\"Make simple GraphQL query and check the response.\")\n uniq_id = str(uuid.uuid4().hex)\n await comm.send_json_to(\n {\n \"id\": uniq_id,\n \"type\": \"start\",\n \"payload\": {\n \"query\": textwrap.dedent(\n \"\"\"\n query MyOperationName {\n value\n }\n \"\"\"\n ),\n \"variables\": {},\n \"operationName\": \"MyOperationName\",\n },\n }\n )\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"id\"] == uniq_id, \"Response id != request id!\"\n assert resp[\"type\"] == \"data\", \"Type `data` expected!\"\n assert \"errors\" not in resp[\"payload\"]\n assert resp[\"payload\"][\"data\"][\"value\"] == MyQuery.VALUE\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"id\"] == uniq_id, \"Response id != request id!\"\n assert resp[\"type\"] == \"complete\", \"Type `complete` expected!\"\n\n print(\"Subscribe to GraphQL subscription.\")\n subscription_id = str(uuid.uuid4().hex)\n\n await comm.send_json_to(\n {\n \"id\": subscription_id,\n \"type\": \"start\",\n \"payload\": {\n \"query\": textwrap.dedent(\n \"\"\"\n subscription MyOperationName {\n on_chat_message_sent(userId: ALICE) {\n event\n }\n }\n \"\"\"\n ),\n \"variables\": {},\n \"operationName\": \"MyOperationName\",\n },\n }\n )\n\n print(\"Trigger the subscription by mutation to receive notification.\")\n uniq_id = str(uuid.uuid4().hex)\n message = \"Hi!\"\n await comm.send_json_to(\n {\n \"id\": uniq_id,\n \"type\": \"start\",\n \"payload\": {\n \"query\": textwrap.dedent(\n \"\"\"\n mutation MyOperationName($message: String!) {\n send_chat_message(message: $message) {\n message\n }\n }\n \"\"\"\n ),\n \"variables\": {\"message\": message},\n \"operationName\": \"MyOperationName\",\n },\n }\n )\n\n # Mutation response.\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"id\"] == uniq_id, \"Response id != request id!\"\n assert resp[\"type\"] == \"data\", \"Type `data` expected!\"\n assert \"errors\" not in resp[\"payload\"]\n assert resp[\"payload\"][\"data\"] == {\"send_chat_message\": {\"message\": message}}\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"id\"] == uniq_id, \"Response id != request id!\"\n assert resp[\"type\"] == \"complete\", \"Type `complete` expected!\"\n\n # Subscription notification.\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"id\"] == subscription_id, \"Notification id != subscription id!\"\n assert resp[\"type\"] == \"data\", \"Type `data` expected!\"\n assert \"errors\" not in resp[\"payload\"]\n event = resp[\"payload\"][\"data\"][\"on_chat_message_sent\"][\"event\"]\n assert json.loads(event) == {\n \"userId\": UserId.ALICE,\n \"payload\": message,\n }, \"Subscription notification contains wrong data!\"\n\n print(\"Disconnect and wait the application to finish gracefully.\")\n await comm.disconnect(timeout=TIMEOUT)\n await comm.wait(timeout=TIMEOUT)\n\n\n@pytest.mark.asyncio\nasync def test_error_cases():\n \"\"\"Test that server responds correctly when errors happen.\n\n Check that server responds with message of type `data` when there\n is a syntax error in the request or the exception in a resolver\n was raised. Check that server responds with message of type `error`\n when there was an exceptional situation, for example, field `query`\n of `payload` is missing or field `type` has a wrong value.\n \"\"\"\n\n # Channels communicator to test WebSocket consumers.\n comm = ch_testing.WebsocketCommunicator(\n application=my_app, path=\"graphql/\", subprotocols=[\"graphql-ws\"]\n )\n\n print(\"Establish & initialize the connection.\")\n await comm.connect(timeout=TIMEOUT)\n await comm.send_json_to({\"type\": \"connection_init\", \"payload\": \"\"})\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"type\"] == \"connection_ack\"\n\n print(\"Check that query syntax error leads to the `error` response.\")\n uniq_id = str(uuid.uuid4().hex)\n await comm.send_json_to(\n {\n \"id\": uniq_id,\n \"type\": \"wrong_type__(ツ)_/¯\",\n \"payload\": {\"variables\": {}, \"operationName\": \"MyOperationName\"},\n }\n )\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"id\"] == uniq_id, \"Response id != request id!\"\n assert resp[\"type\"] == \"error\", \"Type `error` expected!\"\n assert len(resp[\"payload\"]) == 1, \"Single error expected!\"\n assert isinstance(\n resp[\"payload\"][\"errors\"][0], str\n ), \"Error must be of string type!\"\n\n print(\n \"Check that query syntax error leads to the `data` response \"\n \"with `errors` array.\"\n )\n uniq_id = str(uuid.uuid4().hex)\n await comm.send_json_to(\n {\n \"id\": uniq_id,\n \"type\": \"start\",\n \"payload\": {\n \"query\": textwrap.dedent(\n \"\"\"\n This list produces a syntax error!\n \"\"\"\n ),\n \"variables\": {},\n \"operationName\": \"MyOperationName\",\n },\n }\n )\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"id\"] == uniq_id, \"Response id != request id!\"\n assert resp[\"type\"] == \"data\", \"Type `data` expected!\"\n payload = resp[\"payload\"]\n assert payload[\"data\"] is None\n errors = payload[\"errors\"]\n assert len(errors) == 1, \"Single error expected!\"\n assert (\n \"message\" in errors[0] and \"locations\" in errors[0]\n ), \"Response missing mandatory fields!\"\n assert errors[0][\"locations\"] == [{\"line\": 1, \"column\": 1}]\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"id\"] == uniq_id, \"Response id != request id!\"\n assert resp[\"type\"] == \"complete\", \"Type `complete` expected!\"\n\n print(\n \"Check that query syntax error leads to the `data` response \"\n \"with `errors` array.\"\n )\n uniq_id = str(uuid.uuid4().hex)\n await comm.send_json_to(\n {\n \"id\": uniq_id,\n \"type\": \"start\",\n \"payload\": {\n \"query\": textwrap.dedent(\n \"\"\"\n query MyOperationName {\n value(issue_error: true)\n }\n \"\"\"\n ),\n \"variables\": {},\n \"operationName\": \"MyOperationName\",\n },\n }\n )\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"id\"] == uniq_id, \"Response id != request id!\"\n assert resp[\"type\"] == \"data\", \"Type `data` expected!\"\n payload = resp[\"payload\"]\n assert payload[\"data\"][\"value\"] is None\n errors = payload[\"errors\"]\n assert len(errors) == 1, \"Single error expected!\"\n assert errors[0][\"message\"] == MyQuery.VALUE\n assert \"locations\" in errors[0]\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"id\"] == uniq_id, \"Response id != request id!\"\n assert resp[\"type\"] == \"complete\", \"Type `complete` expected!\"\n\n print(\"Check multiple errors in the `data` message.\")\n uniq_id = str(uuid.uuid4().hex)\n await comm.send_json_to(\n {\n \"id\": uniq_id,\n \"type\": \"start\",\n \"payload\": {\n \"query\": textwrap.dedent(\n \"\"\"\n query {\n projects {\n path\n wrong_filed\n }\n }\n\n query a {\n projects\n }\n\n { wrong_name }\n \"\"\"\n ),\n \"variables\": {},\n \"operationName\": \"MyOperationName\",\n },\n }\n )\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"id\"] == uniq_id, \"Response id != request id!\"\n assert resp[\"type\"] == \"data\", \"Type `data` expected!\"\n payload = resp[\"payload\"]\n assert payload[\"data\"] is None\n errors = payload[\"errors\"]\n assert len(errors) == 5, \"Five errors expected!\"\n # Message is here: `This anonymous operation must be\n # the only defined operation`.\n assert errors[0][\"message\"] == errors[3][\"message\"]\n assert \"locations\" in errors[2], \"The `locations` field expected\"\n assert \"locations\" in errors[4], \"The `locations` field expected\"\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"id\"] == uniq_id, \"Response id != request id!\"\n assert resp[\"type\"] == \"complete\", \"Type `complete` expected!\"\n\n print(\"Disconnect and wait the application to finish gracefully.\")\n await comm.disconnect(timeout=TIMEOUT)\n await comm.wait(timeout=TIMEOUT)\n\n\n@pytest.mark.asyncio\nasync def test_connection_error():\n \"\"\"Test that server responds correctly when connection errors happen.\n\n Check that server responds with message of type `connection_error`\n when there was an exception in `on_connect` method.\n \"\"\"\n\n print(\"Prepare application.\")\n\n class MyGraphqlWsConsumerConnectionError(GraphqlWsConsumer):\n \"\"\"Channels WebSocket consumer which provides GraphQL API.\"\"\"\n\n schema = \"\"\n\n async def on_connect(self, payload):\n from graphql.error import GraphQLError\n\n # Always close the connection.\n raise GraphQLError(\"Reject connection\")\n\n application = channels.routing.ProtocolTypeRouter(\n {\n \"websocket\": channels.routing.URLRouter(\n [\n django.urls.path(\n \"graphql-connection-error/\", MyGraphqlWsConsumerConnectionError\n )\n ]\n )\n }\n )\n\n # Channels communicator to test WebSocket consumers.\n comm = ch_testing.WebsocketCommunicator(\n application=application,\n path=\"graphql-connection-error/\",\n subprotocols=[\"graphql-ws\"],\n )\n\n print(\"Try to initialize the connection.\")\n await comm.connect(timeout=TIMEOUT)\n await comm.send_json_to({\"type\": \"connection_init\", \"payload\": \"\"})\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"type\"] == \"connection_error\"\n assert resp[\"payload\"][\"message\"] == \"Reject connection\"\n resp = await comm.receive_output(timeout=TIMEOUT)\n assert resp[\"type\"] == \"websocket.close\"\n assert resp[\"code\"] == 4000\n\n print(\"Disconnect and wait the application to finish gracefully.\")\n await comm.disconnect(timeout=TIMEOUT)\n await comm.wait(timeout=TIMEOUT)\n\n\n@pytest.mark.asyncio\nasync def test_subscribe_unsubscribe():\n \"\"\"Test subscribe-unsubscribe behavior with the GraphQL over WebSocket.\n\n 0. Subscribe to GraphQL subscription: messages for Alice.\n 1. Send STOP message and unsubscribe.\n 2. Subscribe to GraphQL subscription: messages for Tom.\n 3. Call unsubscribe method of the Subscription instance\n (via `kick_out_user` mutation).\n 4. Execute some mutation.\n 5. Check subscription notifications: there are no notifications.\n \"\"\"\n\n # Channels communicator to test WebSocket consumers.\n comm = ch_testing.WebsocketCommunicator(\n application=my_app, path=\"graphql/\", subprotocols=[\"graphql-ws\"]\n )\n\n print(\"Establish and initialize WebSocket GraphQL connection.\")\n await comm.connect(timeout=TIMEOUT)\n await comm.send_json_to({\"type\": \"connection_init\", \"payload\": \"\"})\n await comm.receive_json_from(timeout=TIMEOUT)\n\n print(\"Subscribe to GraphQL subscription.\")\n sub_id = str(uuid.uuid4().hex)\n await comm.send_json_to(\n {\n \"id\": sub_id,\n \"type\": \"start\",\n \"payload\": {\n \"query\": textwrap.dedent(\n \"\"\"\n subscription MyOperationName {\n on_chat_message_sent(userId: ALICE) { event }\n }\n \"\"\"\n ),\n \"variables\": {},\n \"operationName\": \"MyOperationName\",\n },\n }\n )\n\n print(\"Stop subscription by id.\")\n await comm.send_json_to({\"id\": sub_id, \"type\": \"stop\"})\n # Subscription notification with unsubscribe information.\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"id\"] == sub_id, \"Response id != request id!\"\n assert resp[\"type\"] == \"complete\", \"Type `complete` expected!\"\n\n print(\"Subscribe to GraphQL subscription.\")\n sub_id = str(uuid.uuid4().hex)\n await comm.send_json_to(\n {\n \"id\": sub_id,\n \"type\": \"start\",\n \"payload\": {\n \"query\": textwrap.dedent(\n \"\"\"\n subscription MyOperationName {\n on_chat_message_sent(userId: TOM) { event }\n }\n \"\"\"\n ),\n \"variables\": {},\n \"operationName\": \"MyOperationName\",\n },\n }\n )\n\n print(\"Stop all subscriptions for TOM.\")\n uniq_id = str(uuid.uuid4().hex)\n await comm.send_json_to(\n {\n \"id\": uniq_id,\n \"type\": \"start\",\n \"payload\": {\n \"query\": textwrap.dedent(\n \"\"\"\n mutation MyOperationName {\n kick_out_user(userId: TOM) { success }\n }\n \"\"\"\n ),\n \"variables\": {},\n \"operationName\": \"MyOperationName\",\n },\n }\n )\n # Mutation response.\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"id\"] == uniq_id, \"Response id != request id!\"\n assert resp[\"type\"] == \"data\", \"Type `data` expected!\"\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"id\"] == uniq_id, \"Response id != request id!\"\n assert resp[\"type\"] == \"complete\", \"Type `complete` expected!\"\n # Subscription notification with unsubscribe information.\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"id\"] == sub_id, \"Response id != request id!\"\n assert resp[\"type\"] == \"complete\", \"Type `complete` expected!\"\n\n print(\"Trigger the subscription by mutation to receive notification.\")\n uniq_id = str(uuid.uuid4().hex)\n message = \"Is anybody here?\"\n await comm.send_json_to(\n {\n \"id\": uniq_id,\n \"type\": \"start\",\n \"payload\": {\n \"query\": textwrap.dedent(\n \"\"\"\n mutation MyOperationName($message: String!) {\n send_chat_message(message: $message) {\n message\n }\n }\n \"\"\"\n ),\n \"variables\": {\"message\": message},\n \"operationName\": \"MyOperationName\",\n },\n }\n )\n # Mutation response.\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"id\"] == uniq_id, \"Response id != request id!\"\n assert resp[\"type\"] == \"data\", \"Type `data` expected!\"\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"id\"] == uniq_id, \"Response id != request id!\"\n assert resp[\"type\"] == \"complete\", \"Type `complete` expected!\"\n\n # Check notifications: there are no notifications! Previously,\n # we have unsubscribed from all subscriptions.\n assert await comm.receive_nothing() is True, \"No notifications expected!\"\n\n print(\"Disconnect and wait the application to finish gracefully.\")\n await comm.disconnect(timeout=TIMEOUT)\n await comm.wait(timeout=TIMEOUT)\n\n\n@pytest.mark.asyncio\nasync def test_groups():\n \"\"\"Test notifications and subscriptions behavior depending on the\n different subscription groups.\n\n 0. Subscribe to the group1: messages for Alice.\n 1. Subscribe to the group2: messages for Tom.\n 2. Trigger group1 (send message to Alice) and check subscribed\n recipients: Alice.\n 3. Trigger group2 (send message to Tom) and check subscribed\n recipients: Tom.\n 4. Trigger all groups (send messages for all users) and check\n subscribed recipients: Alice, Tom.\n \"\"\"\n\n async def create_and_subscribe(userId):\n \"\"\"Establish and initialize WebSocket GraphQL connection.\n\n Subscribe to GraphQL subscription by userId.\n\n Args:\n userId: User ID for `on_chat_message_sent` subscription.\n\n Returns:\n sub_id: Subscription uid.\n comm: Client, instance of the `WebsocketCommunicator`.\n \"\"\"\n comm = ch_testing.WebsocketCommunicator(\n application=my_app, path=\"graphql/\", subprotocols=[\"graphql-ws\"]\n )\n\n await comm.connect(timeout=TIMEOUT)\n await comm.send_json_to({\"type\": \"connection_init\", \"payload\": \"\"})\n await comm.receive_json_from(timeout=TIMEOUT)\n\n sub_id = str(uuid.uuid4().hex)\n await comm.send_json_to(\n {\n \"id\": sub_id,\n \"type\": \"start\",\n \"payload\": {\n \"query\": textwrap.dedent(\n \"\"\"\n subscription MyOperationName($userId: UserId) {\n on_chat_message_sent(userId: $userId) { event }\n }\n \"\"\"\n ),\n \"variables\": {\"userId\": userId},\n \"operationName\": \"MyOperationName\",\n },\n }\n )\n return sub_id, comm\n\n async def trigger_subscription(comm, userId, message):\n \"\"\"Send a message to user using `send_chat_message` mutation.\n\n Args:\n comm: Client, instance of WebsocketCommunicator.\n userId: User ID for `send_chat_message` mutation.\n message: Any string message.\n \"\"\"\n uniq_id = str(uuid.uuid4().hex)\n await comm.send_json_to(\n {\n \"id\": uniq_id,\n \"type\": \"start\",\n \"payload\": {\n \"query\": textwrap.dedent(\n \"\"\"\n mutation MyOperationName($message: String!,\n $userId: UserId) {\n send_chat_message(message: $message,\n userId: $userId) { message }\n }\n \"\"\"\n ),\n \"variables\": {\"message\": message, \"userId\": userId},\n \"operationName\": \"MyOperationName\",\n },\n }\n )\n # Mutation response.\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"id\"] == uniq_id, \"Response id != request id!\"\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"id\"] == uniq_id, \"Response id != request id!\"\n\n def check_resp(resp, uid, user_id, message):\n \"\"\"Check the responce from `on_chat_message_sent` subscription.\n\n Args:\n uid: Expected value of field `id` of responce.\n userId: Expected user ID.\n message: Expected message string.\n \"\"\"\n assert resp[\"id\"] == uid, \"Notification id != subscription id!\"\n assert resp[\"type\"] == \"data\", \"Type `data` expected!\"\n assert \"errors\" not in resp[\"payload\"]\n event = resp[\"payload\"][\"data\"][\"on_chat_message_sent\"][\"event\"]\n assert json.loads(event) == {\n \"userId\": user_id,\n \"payload\": message,\n }, \"Subscription notification contains wrong data!\"\n\n async def disconnect(comm):\n \"\"\"Disconnect and wait the application to finish gracefully.\"\"\"\n await comm.disconnect(timeout=TIMEOUT)\n await comm.wait(timeout=TIMEOUT)\n\n print(\"Initialize the connection, create subscriptions.\")\n alice_id = \"ALICE\"\n tom_id = \"TOM\"\n # Subscribe to messages for TOM.\n uid_tom, comm_tom = await create_and_subscribe(tom_id)\n # Subscribe to messages for Alice.\n uid_alice, comm_alice = await create_and_subscribe(alice_id)\n\n print(\"Trigger subscription: send message to Tom.\")\n message = \"Hi, Tom!\"\n # Note: Strictly speaking, we do not have confidence that `comm_tom`\n # had enough time to subscribe. So Tom may not be able to receive\n # a message from Alice. But in this simple test, we performed the\n # Tom's subscription before the Alice's subscription and\n # that should be enough.\n await trigger_subscription(comm_alice, tom_id, message)\n # Check Tom's notifications.\n resp = await comm_tom.receive_json_from(timeout=TIMEOUT)\n check_resp(resp, uid_tom, UserId[tom_id].value, message)\n # Any other did not receive any notifications.\n assert await comm_alice.receive_nothing() is True, \"No notifications expected!\"\n\n print(\"Trigger subscription: send message to Alice.\")\n message = \"Hi, Alice!\"\n await trigger_subscription(comm_tom, alice_id, message)\n # Check Tom's notifications.\n resp = await comm_alice.receive_json_from(timeout=TIMEOUT)\n check_resp(resp, uid_alice, UserId[alice_id].value, message)\n # Any other did not receive any notifications.\n assert await comm_tom.receive_nothing() is True, \"No notifications expected!\"\n\n print(\"Trigger subscription: send message to all groups.\")\n message = \"test... ping...\"\n await trigger_subscription(comm_tom, None, message)\n # Check Tom's and Alice's notifications.\n resp = await comm_tom.receive_json_from(timeout=TIMEOUT)\n check_resp(resp, uid_tom, UserId[tom_id].value, message)\n resp = await comm_alice.receive_json_from(timeout=TIMEOUT)\n check_resp(resp, uid_alice, UserId[alice_id].value, message)\n\n # Disconnect.\n await disconnect(comm_tom)\n await disconnect(comm_alice)\n\n\n@pytest.mark.asyncio\nasync def test_keepalive():\n \"\"\"Test that server sends keepalive messages.\"\"\"\n\n print(\"Prepare application.\")\n\n class MyGraphqlWsConsumerKeepalive(GraphqlWsConsumer):\n \"\"\"Channels WebSocket consumer which provides GraphQL API.\"\"\"\n\n schema = \"\"\n # Period to send keepalive mesages. Just some reasonable number.\n send_keepalive_every = 0.05\n\n application = channels.routing.ProtocolTypeRouter(\n {\n \"websocket\": channels.routing.URLRouter(\n [django.urls.path(\"graphql-keepalive/\", MyGraphqlWsConsumerKeepalive)]\n )\n }\n )\n\n # Channels communicator to test WebSocket consumers.\n comm = ch_testing.WebsocketCommunicator(\n application=application, path=\"graphql-keepalive/\", subprotocols=[\"graphql-ws\"]\n )\n\n print(\"Establish & initialize the connection.\")\n await comm.connect(timeout=TIMEOUT)\n await comm.send_json_to({\"type\": \"connection_init\", \"payload\": \"\"})\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert resp[\"type\"] == \"connection_ack\"\n resp = await comm.receive_json_from(timeout=TIMEOUT)\n assert (\n resp[\"type\"] == \"ka\"\n ), \"Keepalive message expected right after `connection_ack`!\"\n\n print(\"Receive several keepalive messages.\")\n pings = []\n for _ in range(3):\n pings.append(await comm.receive_json_from(timeout=TIMEOUT))\n assert all([ping[\"type\"] == \"ka\" for ping in pings])\n\n print(\"Send connection termination message.\")\n await comm.send_json_to({\"type\": \"connection_terminate\"})\n\n print(\"Disconnect and wait the application to finish gracefully.\")\n await comm.disconnect(timeout=TIMEOUT)\n await comm.wait(timeout=TIMEOUT)\n\n\n# --------------------------------------------------------- GRAPHQL OVER WEBSOCKET SETUP\n\n\nclass UserId(graphene.Enum):\n \"\"\"User IDs for sending messages.\"\"\"\n\n TOM = 0\n ALICE = 1\n\n\nclass OnChatMessageSent(Subscription):\n \"\"\"Test GraphQL subscription.\n\n Subscribe to receive messages by user ID.\n \"\"\"\n\n event = graphene.JSONString()\n\n class Arguments:\n \"\"\"That is how subscription arguments are defined.\"\"\"\n\n userId = UserId()\n\n def subscribe(\n self, info, userId\n ): # pylint: disable=unused-argument,arguments-differ\n \"\"\"Specify subscription groups when client subscribes.\"\"\"\n assert self is None, \"Root `self` expected to be `None`!\"\n # Subscribe to the group corresponding to the user.\n if not userId is None:\n return [f\"user_{userId}\"]\n # Subscribe to default group.\n return []\n\n def publish(self, info, userId): # pylint: disable=unused-argument,arguments-differ\n \"\"\"Publish query result to the subscribers.\"\"\"\n event = {\"userId\": userId, \"payload\": self}\n\n return OnChatMessageSent(event=event)\n\n @classmethod\n def notify(cls, userId, message): # pylint: disable=arguments-differ\n \"\"\"Example of the `notify` classmethod usage.\"\"\"\n # Find the subscription group for user.\n group = None if userId is None else f\"user_{userId}\"\n super().broadcast(group=group, payload=message)\n\n\nclass SendChatMessage(graphene.Mutation):\n \"\"\"Test GraphQL mutation.\n\n Send message to the user or all users.\n \"\"\"\n\n class Output(graphene.ObjectType):\n \"\"\"Mutation result.\"\"\"\n\n message = graphene.String()\n userId = UserId()\n\n class Arguments:\n \"\"\"That is how mutation arguments are defined.\"\"\"\n\n message = graphene.String(required=True)\n userId = graphene.Argument(UserId, required=False)\n\n def mutate(self, info, message, userId=None): # pylint: disable=unused-argument\n \"\"\"Send message to the user or all users.\"\"\"\n assert self is None, \"Root `self` expected to be `None`!\"\n\n # Notify subscribers.\n OnChatMessageSent.notify(message=message, userId=userId)\n\n return SendChatMessage.Output(message=message, userId=userId)\n\n\nclass KickOutUser(graphene.Mutation):\n \"\"\"Test GraphQL mutation.\n\n Stop all subscriptions associated with the user.\n \"\"\"\n\n class Arguments:\n \"\"\"That is how mutation arguments are defined.\"\"\"\n\n userId = UserId()\n\n success = graphene.Boolean()\n\n def mutate(self, info, userId): # pylint: disable=unused-argument\n \"\"\"Unsubscribe everyone associated with the userId.\"\"\"\n assert self is None, \"Root `self` expected to be `None`!\"\n\n OnChatMessageSent.unsubscribe(group=f\"user_{userId}\")\n\n return KickOutUser(success=True)\n\n\nclass MySubscription(graphene.ObjectType):\n \"\"\"GraphQL subscriptions.\"\"\"\n\n on_chat_message_sent = OnChatMessageSent.Field()\n\n\nclass MyMutation(graphene.ObjectType):\n \"\"\"GraphQL mutations.\"\"\"\n\n send_chat_message = SendChatMessage.Field()\n kick_out_user = KickOutUser.Field()\n\n\nclass MyQuery(graphene.ObjectType):\n \"\"\"Root GraphQL query.\"\"\"\n\n VALUE = str(uuid.uuid4().hex)\n value = graphene.String(args={\"issue_error\": graphene.Boolean(default_value=False)})\n\n def resolve_value(self, info, issue_error): # pylint: disable=unused-argument\n \"\"\"Resolver to return predefined value which can be tested.\"\"\"\n assert self is None, \"Root `self` expected to be `None`!\"\n if issue_error:\n raise RuntimeError(MyQuery.VALUE)\n return MyQuery.VALUE\n\n\nmy_schema = graphene.Schema(\n query=MyQuery,\n subscription=MySubscription,\n mutation=MyMutation,\n auto_camelcase=False,\n)\n\n\nclass MyGraphqlWsConsumer(GraphqlWsConsumer):\n \"\"\"Channels WebSocket consumer which provides GraphQL API.\"\"\"\n\n schema = my_schema\n\n\nmy_app = channels.routing.ProtocolTypeRouter(\n {\n \"websocket\": channels.routing.URLRouter(\n [django.urls.path(\"graphql/\", MyGraphqlWsConsumer)]\n )\n }\n)\n","sub_path":"tests/test_graphql_ws.py","file_name":"test_graphql_ws.py","file_ext":"py","file_size_in_byte":30729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"189610723","text":"from datetime import datetime\nfrom typing import Dict\n\nclass Currency(object):\n \"\"\"stores info about currencies codes, name and rss URL\"\"\"\n def __init__(self, code: str, name: str, url: str) -> None:\n self.code = code\n self.name = name\n self.url = url\n\n @classmethod\n def from_dict(cls, dict_):\n currency = Currency(\n code=dict_['code'],\n name=dict_['name'],\n url=dict_['url']\n )\n return currency\n\n\nclass EurRate(object):\n \"\"\"to single daily exchange rate\"\"\"\n def __init__(self, datestr: str, rate: str) -> None:\n self.date = datetime.strptime(datestr,'%Y-%m-%dT%H%M%S%z')\n self.rate = float(rate)\n\n @classmethod\n def from_dict(cls, dict_ : Dict) -> EurRate:\n rate = EurRate(\n datestr=dict_['date'],\n rate=dict_['rate']\n )\n return rate\n\n def get_str_date(self) -> str:\n return datetime.strftime(self.date, '%Y-%m-%dT%H%M%S%z')\n","sub_path":"scrapper/core/domain.py","file_name":"domain.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"21031027","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\":Mod: evaluate.py\n\n:Synopsis:\n\n:Author:\n ide\n\n:Created:\n 6/20/20\n\"\"\"\n\nimport collections\nfrom enum import Enum\n\nfrom flask import (\n Blueprint, Flask, url_for, render_template, session, app\n)\n\nfrom metapype.eml import names\nimport metapype.eml.validate as validate\nfrom metapype.eml.validation_errors import ValidationError\nimport metapype.eml.evaluate as evaluate\nfrom metapype.eml.evaluation_warnings import EvaluationWarning\nfrom metapype.model.node import Node\nimport webapp.home.metapype_client as metapype_client\nfrom webapp.pages import *\nimport webapp.auth.user_data as user_data\nimport webapp.home.load_data_table as load_data_table\n\napp = Flask(__name__)\nhome = Blueprint('home', __name__, template_folder='templates')\n\n\nclass EvalSeverity(Enum):\n ERROR = 1\n WARNING = 2\n INFO = 3\n\n\nclass EvalType(Enum):\n REQUIRED = 1\n RECOMMENDED = 2\n BEST_PRACTICE = 3\n OPTIONAL = 4\n\n\nscopes = [\n 'ecotrends',\n 'edi',\n 'knb-lter-and',\n 'knb-lter-arc',\n 'knb-lter-bes',\n 'knb-lter-ble',\n 'knb-lter-bnz',\n 'knb-lter-cap',\n 'knb-lter-cce',\n 'knb-lter-cdr',\n 'knb-lter-cwt',\n 'knb-lter-fce',\n 'knb-lter-gce',\n 'knb-lter-hbr',\n 'knb-lter-hfr',\n 'knb-lter-jrn',\n 'knb-lter-kbs',\n 'knb-lter-knz',\n 'knb-lter-luq',\n 'knb-lter-mcm',\n 'knb-lter-mcr',\n 'knb-lter-nes',\n 'knb-lter-nin',\n 'knb-lter-ntl',\n 'knb-lter-nwk',\n 'knb-lter-nwt',\n 'knb-lter-pal',\n 'knb-lter-pie',\n 'knb-lter-sbc',\n 'knb-lter-sev',\n 'knb-lter-sgs',\n 'knb-lter-vcr',\n 'lter-landsat',\n 'lter-landsat-ledaps',\n 'msb-cap',\n 'msb-paleon',\n 'msb-tempbiodev'\n]\n\n\ndef get_eval_entry(id, link=None, section=None, item=None):\n try:\n vals = session[f'__eval__{id}']\n if section:\n vals[0] = section\n if item:\n vals[1] = item\n return Eval_Entry(section=vals[0], item=vals[1], severity=EvalSeverity[vals[2]], type=EvalType[vals[3]],\n explanation=vals[4], link=link)\n except:\n return None\n\n\ndef add_to_evaluation(id, link=None, section=None, item=None):\n entry = get_eval_entry(id, link, section, item)\n if entry:\n evaluation.append(entry)\n\n\nEval_Entry = collections.namedtuple(\n 'Evaluate_Entry', [\"section\", \"item\", \"severity\", \"type\", \"explanation\", \"link\"])\nevaluation = []\n\n\ndef find_min_unmet(errs, node_name, child_name):\n for err_code, msg, node, *args in errs:\n if err_code == ValidationError.MIN_OCCURRENCE_UNMET:\n err_cause, min = args\n if node.name == node_name and err_cause == child_name:\n return True\n return False\n\n\ndef find_min_unmet_for_choice(errs, node_name):\n for err_code, msg, node, *args in errs:\n if err_code == ValidationError.MIN_CHOICE_UNMET and node.name == node_name:\n return True\n return False\n\n\ndef find_content_empty(errs, node_name):\n found = []\n for err in errs:\n err_code, _, node, *_ = err\n if err_code == ValidationError.CONTENT_EXPECTED_NONEMPTY and node.name == node_name:\n found.append(err)\n return found\n\n\ndef find_content_enum(errs, node_name):\n found = []\n for err in errs:\n err_code, _, node, *_ = err\n if err_code == ValidationError.CONTENT_EXPECTED_ENUM and node.name == node_name:\n found.append(err)\n return found\n\n\ndef find_err_code(errs, err_code_to_find, node_name):\n found = []\n for err in errs:\n err_code, _, node, *_ = err\n if err_code == err_code_to_find and node.name == node_name:\n found.append(err)\n return found\n\n\ndef find_missing_attribute(errs, node_name, attribute_name):\n errs_found = find_err_code(errs, ValidationError.ATTRIBUTE_REQUIRED, node_name)\n for err in errs_found:\n errcode, msg, node, attribute = err\n if attribute == attribute_name:\n return err\n return None\n\n\ndef check_dataset_title(eml_node, filename):\n link = url_for(PAGE_TITLE, filename=filename)\n dataset_node = eml_node.find_child(names.DATASET)\n validation_errs = validate_via_metapype(dataset_node)\n # Is title node missing?\n if find_min_unmet(validation_errs, names.DATASET, names.TITLE):\n add_to_evaluation('title_01', link)\n return\n # Is title node content empty?\n title_node = eml_node.find_single_node_by_path([names.DATASET, names.TITLE])\n if title_node:\n validation_errs = validate_via_metapype(title_node)\n if not title_node or find_content_empty(validation_errs, names.TITLE):\n add_to_evaluation('title_01', link)\n return\n\n evaluation_warnings = evaluate_via_metapype(title_node)\n # Is the title too short?\n if find_err_code(evaluation_warnings, EvaluationWarning.TITLE_TOO_SHORT, names.TITLE):\n add_to_evaluation('title_02', link)\n\n\ndef check_id_for_EDI(package_id):\n try:\n scope, identifier, revision = package_id.split('.')\n if scope not in scopes:\n raise ValueError\n identifier = int(identifier)\n revision = int(revision)\n except ValueError:\n return False\n return True\n\n\ndef check_data_package_id(eml_node, filename):\n link = url_for(PAGE_DATA_PACKAGE_ID, filename=filename)\n validation_errs = validate_via_metapype(eml_node)\n if find_missing_attribute(validation_errs, 'eml', 'packageId'):\n add_to_evaluation('data_package_id_01', link)\n else:\n # check if data package ID has correct form for EDI data repository\n data_package_id = eml_node.attribute_value(\"packageId\")\n if not check_id_for_EDI(data_package_id):\n add_to_evaluation('data_package_id_02', link)\n\n\ndef check_responsible_party(rp_node:Node, section:str=None, item:str=None,\n page:str=None, filename:str=None, node_id:str=None,\n related_project_node_id:str=None):\n if not related_project_node_id:\n link = url_for(page, filename=filename, node_id=node_id)\n else:\n link = url_for(page, filename=filename, node_id=node_id, project_node_id=related_project_node_id)\n validation_errs = validate_via_metapype(rp_node)\n\n # Last name is required if other parts of name are given\n if find_min_unmet(validation_errs, names.INDIVIDUALNAME, names.SURNAME):\n add_to_evaluation('responsible_party_04', link, section, item)\n\n # At least one of surname, organization name, or position name is required\n if find_min_unmet_for_choice(validation_errs, rp_node.name):\n add_to_evaluation('responsible_party_01', link, section, item)\n\n # Organization ID requires a directory attribute\n if find_missing_attribute(validation_errs, 'userId', 'directory'):\n add_to_evaluation('responsible_party_06', link, section, item)\n\n # Role, if required\n if find_min_unmet(validation_errs, rp_node.name, names.ROLE) or find_content_empty(validation_errs, names.ROLE):\n add_to_evaluation('responsible_party_03', link, section, item)\n\n evaluation_warnings = evaluate_via_metapype(rp_node)\n # User ID is recommended\n if find_err_code(evaluation_warnings, EvaluationWarning.ORCID_ID_MISSING, rp_node.name):\n add_to_evaluation('responsible_party_02', link, section, item)\n\n # Email is recommended\n if find_err_code(evaluation_warnings, EvaluationWarning.EMAIL_MISSING, rp_node.name):\n add_to_evaluation('responsible_party_05', link, section, item)\n\ndef check_creators(eml_node, filename):\n link = url_for(PAGE_CREATOR_SELECT, filename=filename)\n dataset_node = eml_node.find_child(names.DATASET)\n validation_errs = validate_via_metapype(dataset_node)\n\n if find_min_unmet(validation_errs, names.DATASET, names.CREATOR):\n add_to_evaluation('creators_01', link)\n else:\n creator_nodes = eml_node.find_all_nodes_by_path([names.DATASET, names.CREATOR])\n for creator_node in creator_nodes:\n check_responsible_party(creator_node, 'Creators', 'Creator', PAGE_CREATOR, filename, creator_node.id)\n\n\ndef check_metadata_providers(eml_node, filename):\n link = url_for(PAGE_METADATA_PROVIDER_SELECT, filename=filename)\n metadata_provider_nodes = eml_node.find_all_nodes_by_path([names.DATASET, names.METADATAPROVIDER])\n if metadata_provider_nodes and len(metadata_provider_nodes) > 0:\n for metadata_provider_node in metadata_provider_nodes:\n check_responsible_party(metadata_provider_node, 'Metadata Providers', 'Metadata Provider',\n PAGE_METADATA_PROVIDER, filename, metadata_provider_node.id)\n\n\ndef check_associated_parties(eml_node, filename):\n link = url_for(PAGE_ASSOCIATED_PARTY_SELECT, filename=filename)\n associated_party_nodes = eml_node.find_all_nodes_by_path([names.DATASET, names.ASSOCIATEDPARTY])\n if associated_party_nodes and len(associated_party_nodes) > 0:\n for associated_party_node in associated_party_nodes:\n check_responsible_party(associated_party_node, 'Associated Parties', 'Associated Party',\n PAGE_ASSOCIATED_PARTY, filename, associated_party_node.id)\n\n\ndef check_dataset_abstract(eml_node, filename):\n link = url_for(PAGE_ABSTRACT, filename=filename)\n dataset_node = eml_node.find_child(names.DATASET)\n evaluation_warnings = evaluate_via_metapype(dataset_node)\n\n if find_err_code(evaluation_warnings, EvaluationWarning.DATASET_ABSTRACT_MISSING, names.DATASET):\n add_to_evaluation('abstract_01', link)\n return\n\n if find_err_code(evaluation_warnings, EvaluationWarning.DATASET_ABSTRACT_TOO_SHORT, names.DATASET):\n add_to_evaluation('abstract_02', link)\n return\n\n\ndef check_keywords(eml_node, filename):\n link = url_for(PAGE_KEYWORD_SELECT, filename=filename)\n dataset_node = eml_node.find_child(names.DATASET)\n evaluation_warnings = evaluate_via_metapype(dataset_node)\n\n if find_err_code(evaluation_warnings, EvaluationWarning.KEYWORDS_MISSING, names.DATASET):\n add_to_evaluation('keywords_01', link)\n return\n\n if find_err_code(evaluation_warnings, EvaluationWarning.KEYWORDS_INSUFFICIENT, names.DATASET):\n add_to_evaluation('keywords_02', link)\n return\n\n\ndef check_intellectual_rights(eml_node, filename):\n link = url_for(PAGE_INTELLECTUAL_RIGHTS, filename=filename)\n dataset_node = eml_node.find_child(names.DATASET)\n evaluation_warnings = evaluate_via_metapype(dataset_node)\n\n if find_err_code(evaluation_warnings, EvaluationWarning.INTELLECTUAL_RIGHTS_MISSING, names.DATASET):\n add_to_evaluation('intellectual_rights_01', link)\n return\n\n\ndef check_taxonomic_coverage(node, filename):\n\n link = url_for(PAGE_TAXONOMIC_COVERAGE, filename=filename, node_id=node.id)\n\n validation_errs = validate_via_metapype(node)\n if find_content_empty(validation_errs, names.TAXONRANKNAME):\n add_to_evaluation('taxonomic_coverage_01', link)\n if find_content_empty(validation_errs, names.TAXONRANKVALUE):\n add_to_evaluation('taxonomic_coverage_02', link)\n\n\ndef check_coverage(eml_node, filename):\n dataset_node = eml_node.find_child(names.DATASET)\n\n link = url_for(PAGE_GEOGRAPHIC_COVERAGE_SELECT, filename=filename)\n\n evaluation_warnings = evaluate_via_metapype(dataset_node)\n\n if find_err_code(evaluation_warnings, EvaluationWarning.DATASET_COVERAGE_MISSING, names.DATASET):\n add_to_evaluation('coverage_01', link)\n\n taxonomic_classification_nodes = []\n dataset_node.find_all_descendants(names.TAXONOMICCOVERAGE, taxonomic_classification_nodes)\n for taxonomic_classification_node in taxonomic_classification_nodes:\n check_taxonomic_coverage(taxonomic_classification_node, filename)\n\n\ndef check_geographic_coverage(eml_node, filename):\n link = url_for(PAGE_GEOGRAPHIC_COVERAGE_SELECT, filename=filename)\n geographic_coverage_nodes = eml_node.find_all_nodes_by_path([names.DATASET, names.COVERAGE, names.GEOGRAPHICCOVERAGE])\n for geographic_coverage_node in geographic_coverage_nodes:\n link = url_for(PAGE_GEOGRAPHIC_COVERAGE, filename=filename, node_id=geographic_coverage_node.id)\n validation_errs = validate_via_metapype(geographic_coverage_node)\n if find_content_empty(validation_errs, names.GEOGRAPHICDESCRIPTION):\n add_to_evaluation('geographic_coverage_01', link)\n if find_err_code(validation_errs, ValidationError.CONTENT_EXPECTED_RANGE, names.WESTBOUNDINGCOORDINATE):\n add_to_evaluation('geographic_coverage_03', link)\n if find_err_code(validation_errs, ValidationError.CONTENT_EXPECTED_RANGE, names.EASTBOUNDINGCOORDINATE):\n add_to_evaluation('geographic_coverage_04', link)\n if find_err_code(validation_errs, ValidationError.CONTENT_EXPECTED_RANGE, names.NORTHBOUNDINGCOORDINATE):\n add_to_evaluation('geographic_coverage_05', link)\n if find_err_code(validation_errs, ValidationError.CONTENT_EXPECTED_RANGE, names.SOUTHBOUNDINGCOORDINATE):\n add_to_evaluation('geographic_coverage_06', link)\n if find_content_enum(validation_errs, names.ALTITUDEUNITS):\n add_to_evaluation('geographic_coverage_08', link)\n # special case to combine missing bounding coordinates into a single error\n if find_min_unmet(validation_errs, names.BOUNDINGCOORDINATES, names.WESTBOUNDINGCOORDINATE) or \\\n find_min_unmet(validation_errs, names.BOUNDINGCOORDINATES, names.EASTBOUNDINGCOORDINATE) or \\\n find_min_unmet(validation_errs, names.BOUNDINGCOORDINATES, names.NORTHBOUNDINGCOORDINATE) or \\\n find_min_unmet(validation_errs, names.BOUNDINGCOORDINATES, names.SOUTHBOUNDINGCOORDINATE):\n add_to_evaluation('geographic_coverage_02', link)\n # special case to cover the three bounding altitudes fields\n if find_min_unmet(validation_errs, names.BOUNDINGALTITUDES, names.ALTITUDEMINIMUM) or \\\n find_min_unmet(validation_errs, names.BOUNDINGALTITUDES, names.ALTITUDEMAXIMUM) or \\\n find_min_unmet(validation_errs, names.BOUNDINGALTITUDES, names.ALTITUDEUNITS) or \\\n find_content_empty(validation_errs, names.ALTITUDEMINIMUM) or \\\n find_content_empty(validation_errs, names.ALTITUDEMAXIMUM) or \\\n find_content_empty(validation_errs, names.ALTITUDEUNITS):\n add_to_evaluation('geographic_coverage_07', link)\n\ndef get_attribute_type(attrib_node:Node):\n mscale_node = attrib_node.find_child(names.MEASUREMENTSCALE)\n nominal_node = mscale_node.find_child(names.NOMINAL)\n if nominal_node:\n enumerated_domain_node = nominal_node.find_single_node_by_path([names.NONNUMERICDOMAIN, names.ENUMERATEDDOMAIN])\n if enumerated_domain_node:\n return metapype_client.VariableType.CATEGORICAL\n text_domain_node = nominal_node.find_single_node_by_path([names.NONNUMERICDOMAIN, names.TEXTDOMAIN])\n if text_domain_node:\n return metapype_client.VariableType.TEXT\n ratio_node = mscale_node.find_child(names.RATIO)\n if ratio_node:\n return metapype_client.VariableType.NUMERICAL\n datetime_node = mscale_node.find_child(names.DATETIME)\n if datetime_node:\n return metapype_client.VariableType.DATETIME\n return None\n\n\ndef generate_code_definition_errs(eml_node, filename, err_code, errs_found):\n mscale = metapype_client.VariableType.CATEGORICAL\n for err in errs_found:\n err_node = err[2]\n code_definition_node = err_node.parent\n enumerated_domain_node = code_definition_node.parent\n non_numeric_domain_node = enumerated_domain_node.parent\n nominal_node = non_numeric_domain_node.parent\n mscale_node = nominal_node.parent\n attribute_node = mscale_node.parent\n attribute_list_node = attribute_node.parent\n data_table_node = attribute_list_node.parent\n link = url_for(PAGE_CODE_DEFINITION, filename=filename, dt_node_id=data_table_node.id, att_node_id=attribute_node.id,\n nom_ord_node_id=nominal_node.id, node_id=code_definition_node.id, mscale=mscale)\n add_to_evaluation(err_code, link)\n\n\ndef check_attribute(eml_node, filename, data_table_node:Node, attrib_node:Node):\n attr_type = get_attribute_type(attrib_node)\n mscale = None\n if attr_type == metapype_client.VariableType.CATEGORICAL:\n page = PAGE_ATTRIBUTE_CATEGORICAL\n mscale = metapype_client.VariableType.CATEGORICAL.name\n elif attr_type == metapype_client.VariableType.NUMERICAL:\n page = PAGE_ATTRIBUTE_NUMERICAL\n mscale = metapype_client.VariableType.NUMERICAL.name\n elif attr_type == metapype_client.VariableType.TEXT:\n page = PAGE_ATTRIBUTE_TEXT\n mscale = metapype_client.VariableType.TEXT.name\n elif attr_type == metapype_client.VariableType.DATETIME:\n page = PAGE_ATTRIBUTE_DATETIME\n mscale = metapype_client.VariableType.DATETIME.name\n link = url_for(page, filename=filename, dt_node_id=data_table_node.id, node_id=attrib_node.id, mscale=mscale)\n\n validation_errs = validate_via_metapype(attrib_node)\n if find_content_empty(validation_errs, names.ATTRIBUTEDEFINITION):\n add_to_evaluation('attributes_01', link)\n if find_min_unmet(validation_errs, names.MISSINGVALUECODE, names.CODEEXPLANATION):\n add_to_evaluation('attributes_07', link)\n\n # Categorical\n if attr_type == metapype_client.VariableType.CATEGORICAL:\n if find_min_unmet(validation_errs, names.ENUMERATEDDOMAIN, names.CODEDEFINITION):\n add_to_evaluation('attributes_04', link)\n found = find_content_empty(validation_errs, names.CODE)\n if found:\n generate_code_definition_errs(eml_node, filename, 'attributes_05', found)\n found = find_content_empty(validation_errs, names.DEFINITION)\n if found:\n generate_code_definition_errs(eml_node, filename, 'attributes_06', found)\n\n # Numerical\n if attr_type == metapype_client.VariableType.NUMERICAL:\n if find_min_unmet(validation_errs, names.RATIO, names.UNIT):\n add_to_evaluation('attributes_02', link)\n if find_min_unmet_for_choice(validation_errs, names.UNIT):\n add_to_evaluation('attributes_02', link)\n\n # DateTime\n if attr_type == metapype_client.VariableType.DATETIME:\n if find_content_empty(validation_errs, names.FORMATSTRING):\n add_to_evaluation('attributes_03', link)\n\n\ndef check_data_table_md5_checksum(data_table_node, link):\n object_name_node = data_table_node.find_descendant(names.OBJECTNAME)\n data_file = object_name_node.content\n uploads_folder = user_data.get_document_uploads_folder_name()\n full_path = f'{uploads_folder}/{data_file}'\n try:\n computed_md5_hash = load_data_table.get_md5_hash(full_path)\n except FileNotFoundError:\n add_to_evaluation('data_table_07', link)\n return\n authentication_node = data_table_node.find_descendant(names.AUTHENTICATION)\n if authentication_node:\n found_md5_hash = authentication_node.content\n if found_md5_hash != computed_md5_hash:\n add_to_evaluation('data_table_06', link)\n\n\ndef check_data_table(eml_node, filename, data_table_node:Node):\n link = url_for(PAGE_DATA_TABLE, filename=filename, dt_node_id=data_table_node.id)\n validation_errs = validate_via_metapype(data_table_node)\n\n check_data_table_md5_checksum(data_table_node, link)\n\n if find_min_unmet(validation_errs, names.DATATABLE, names.ENTITYNAME):\n add_to_evaluation('data_table_01', link)\n if find_min_unmet(validation_errs, names.DATATABLE, names.ENTITYDESCRIPTION):\n add_to_evaluation('data_table_02', link)\n if find_min_unmet(validation_errs, names.PHYSICAL, names.OBJECTNAME):\n add_to_evaluation('data_table_03', link)\n if find_min_unmet(validation_errs, names.DATATABLE, names.ATTRIBUTELIST):\n add_to_evaluation('data_table_04', link)\n\n evaluation_warnings = evaluate_via_metapype(data_table_node)\n if find_err_code(evaluation_warnings, EvaluationWarning.DATATABLE_DESCRIPTION_MISSING, names.DATATABLE):\n add_to_evaluation('data_table_02', link)\n\n attribute_list_node = data_table_node.find_child(names.ATTRIBUTELIST)\n if attribute_list_node:\n attribute_nodes = attribute_list_node.find_all_children(names.ATTRIBUTE)\n for attribute_node in attribute_nodes:\n check_attribute(eml_node, filename, data_table_node, attribute_node)\n\n\ndef check_data_tables(eml_node, filename):\n link = url_for(PAGE_DATA_TABLE_SELECT, filename=filename)\n dataset_node = eml_node.find_child(names.DATASET)\n evaluation_warnings = evaluate_via_metapype(dataset_node)\n if find_err_code(evaluation_warnings, EvaluationWarning.DATATABLE_MISSING, names.DATASET):\n add_to_evaluation('data_table_05', link)\n\n data_table_nodes = eml_node.find_all_nodes_by_path([names.DATASET, names.DATATABLE])\n for data_table_node in data_table_nodes:\n check_data_table(eml_node, filename, data_table_node)\n\n\ndef check_maintenance(eml_node, filename):\n link = url_for(PAGE_MAINTENANCE, filename=filename)\n dataset_node = eml_node.find_child(names.DATASET)\n evaluation_warnings = evaluate_via_metapype(dataset_node)\n if find_err_code(evaluation_warnings, EvaluationWarning.MAINTENANCE_DESCRIPTION_MISSING, names.DESCRIPTION):\n add_to_evaluation('maintenance_01', link)\n\n\ndef check_contacts(eml_node, filename):\n link = url_for(PAGE_CONTACT_SELECT, filename=filename)\n dataset_node = eml_node.find_child(names.DATASET)\n validation_errs = validate_via_metapype(dataset_node)\n if find_min_unmet(validation_errs, names.DATASET, names.CONTACT):\n add_to_evaluation('contacts_01', link=link)\n contact_nodes = eml_node.find_all_nodes_by_path([\n names.DATASET,\n names.CONTACT\n ])\n for contact_node in contact_nodes:\n check_responsible_party(contact_node, 'Contacts', 'Contact', PAGE_CONTACT,\n filename, contact_node.id)\n\n\ndef check_method_step(method_step_node, filename, node_id):\n link = url_for(PAGE_METHOD_STEP, filename=filename, node_id=node_id)\n evaluation_warnings = evaluate_via_metapype(method_step_node)\n if find_err_code(evaluation_warnings, EvaluationWarning.METHOD_STEP_DESCRIPTION_MISSING, names.DESCRIPTION):\n add_to_evaluation('methods_02', link)\n\n\ndef check_method_steps(eml_node, filename):\n link = url_for(PAGE_METHOD_STEP_SELECT, filename=filename)\n dataset_node = eml_node.find_child(names.DATASET)\n evaluation_warnings = evaluate_via_metapype(dataset_node)\n if find_err_code(evaluation_warnings, EvaluationWarning.DATASET_METHOD_STEPS_MISSING, names.DATASET):\n add_to_evaluation('methods_01', link)\n\n method_step_nodes = eml_node.find_all_nodes_by_path([\n names.DATASET,\n names.METHODS,\n names.METHODSTEP\n ])\n for method_step_node in method_step_nodes:\n check_method_step(method_step_node, filename, method_step_node.id)\n\n\ndef check_project_award(award_node, filename, related_project_id=None):\n if not related_project_id:\n link = url_for(PAGE_FUNDING_AWARD, filename=filename, node_id=award_node.id)\n else:\n link = url_for(PAGE_FUNDING_AWARD, filename=filename, node_id=award_node.id, project_node_id=related_project_id)\n validation_errors = validate_via_metapype(award_node)\n if find_min_unmet(validation_errors, names.AWARD, names.FUNDERNAME) or \\\n find_content_empty(validation_errors, names.FUNDERNAME):\n add_to_evaluation('project_04', link)\n if find_min_unmet(validation_errors, names.AWARD, names.TITLE) or \\\n find_content_empty(validation_errors, names.TITLE):\n add_to_evaluation('project_05', link)\n\n\ndef check_project_node(project_node, filename, related_project_id=None):\n if not related_project_id:\n link = url_for(PAGE_PROJECT, filename=filename)\n else:\n link = url_for(PAGE_PROJECT, filename=filename, node_id=related_project_id)\n validation_errors = validate_via_metapype(project_node)\n name = project_node.name\n if find_min_unmet(validation_errors, name, names.TITLE):\n add_to_evaluation('project_01', link)\n if find_content_empty(validation_errors, names.TITLE):\n # We need to distinguish between a missing title for the project itself or one of its related projects\n found = find_content_empty(validation_errors, names.TITLE)\n for err_code, msg, node, *args in found:\n if node.parent.name == name:\n add_to_evaluation('project_01', link)\n if find_min_unmet(validation_errors, name, names.PERSONNEL):\n add_to_evaluation('project_02', link)\n\n project_personnel_nodes = project_node.find_all_children(names.PERSONNEL)\n for project_personnel_node in project_personnel_nodes:\n check_responsible_party(project_personnel_node, \"Project\", \"Project Personnel\",\n PAGE_PROJECT_PERSONNEL, filename, project_personnel_node.id,\n related_project_id)\n\n project_award_nodes = project_node.find_all_children(names.AWARD)\n for project_award_node in project_award_nodes:\n check_project_award(project_award_node, filename, related_project_id)\n\n related_project_nodes = project_node.find_all_children(names.RELATED_PROJECT)\n for related_project_node in related_project_nodes:\n check_project_node(related_project_node, filename, related_project_node.id)\n\n\ndef check_project(eml_node, filename):\n link = url_for(PAGE_PROJECT, filename=filename)\n project_node = eml_node.find_single_node_by_path([names.DATASET, names.PROJECT])\n if project_node:\n check_project_node(project_node, filename)\n else:\n dataset_node = eml_node.find_child(names.DATASET)\n evaluation_warnings = evaluate_via_metapype(dataset_node)\n if find_err_code(evaluation_warnings, EvaluationWarning.DATASET_PROJECT_MISSING, names.DATASET):\n add_to_evaluation('project_03', link)\n\n\ndef check_other_entity(entity_node, filename):\n link = url_for(PAGE_OTHER_ENTITY, filename=filename, node_id=entity_node.id)\n\n validation_errors = validate_via_metapype(entity_node)\n if find_min_unmet(validation_errors, names.OTHERENTITY, names.ENTITYNAME):\n add_to_evaluation('other_entity_01', link)\n if find_min_unmet(validation_errors, names.OTHERENTITY, names.ENTITYTYPE):\n add_to_evaluation('other_entity_02', link)\n\n evaluation_warnings = evaluate_via_metapype(entity_node)\n if find_err_code(evaluation_warnings, EvaluationWarning.OTHER_ENTITY_DESCRIPTION_MISSING, names.OTHERENTITY):\n add_to_evaluation('other_entity_03', link)\n\n\ndef check_other_entities(eml_node, filename):\n other_entity_nodes = eml_node.find_all_nodes_by_path([names.DATASET, names.OTHERENTITY])\n for other_entity_node in other_entity_nodes:\n check_other_entity(other_entity_node, filename)\n\n\ndef eval_entry_to_string(eval_entry):\n return f'Section: {eval_entry.section}
Item: {eval_entry.item}
Severity: {eval_entry.severity.name}
Type: {eval_entry.type.name}
Explanation: {eval_entry.explanation}
Link'\n\n\ndef to_string(evaluation):\n if evaluation and len(evaluation) > 0:\n s = ''\n for eval_entry in evaluation:\n s += eval_entry_to_string(eval_entry) + '

'\n return s\n else:\n return \"OK!\"\n\n\ndef collect_entries(evaluation, section):\n return [entry for entry in evaluation if entry.section == section]\n\n\ndef format_entry(entry:Eval_Entry):\n output = ''\n output += f'{entry.item}'\n output += f'{entry.severity.name.title()}'\n output += f'{entry.type.name.title()}'\n output += f'{entry.explanation}'\n output += ''\n return output\n\n\ndef format_output(evaluation):\n sections = ['Title', 'Data Tables', 'Creators', 'Contacts', 'Associated Parties', 'Metadata Providers', 'Abstract',\n 'Keywords', 'Intellectual Rights', 'Coverage', 'Geographic Coverage', 'Temporal Coverage',\n 'Taxonomic Coverage', 'Maintenance', 'Methods', 'Project', 'Other Entities', 'Data Package ID']\n\n severities = [EvalSeverity.ERROR, EvalSeverity.WARNING, EvalSeverity.INFO]\n\n all_ok = True\n output = ''\n for section in sections:\n entries = collect_entries(evaluation, section)\n if not entries:\n continue\n all_ok = False\n output += f'

{section}

' \\\n f''\n for severity in severities:\n for entry in entries:\n if entry.severity == severity:\n output += format_entry(entry)\n output += '
ItemSeverityReasonExplanation

'\n if all_ok:\n output += '

Everything looks good!

'\n output += ''\n return output\n\n\ndef perform_evaluation(eml_node, filename):\n global evaluation\n evaluation = []\n\n check_dataset_title(eml_node, filename)\n check_data_tables(eml_node, filename)\n check_creators(eml_node, filename)\n check_contacts(eml_node, filename)\n check_associated_parties(eml_node, filename)\n check_metadata_providers(eml_node, filename)\n check_dataset_abstract(eml_node, filename)\n check_keywords(eml_node, filename)\n check_intellectual_rights(eml_node, filename)\n check_coverage(eml_node, filename)\n check_geographic_coverage(eml_node, filename)\n check_maintenance(eml_node, filename)\n check_method_steps(eml_node, filename)\n check_project(eml_node, filename)\n check_other_entities(eml_node, filename)\n check_data_package_id(eml_node, filename)\n \n return evaluation\n\n\ndef check_metadata_status(eml_node, filename):\n evaluations = perform_evaluation(eml_node, filename)\n errors = 0\n warnings = 0\n for entry in evaluations:\n _, _, severity, _, _, _ = entry\n if severity == EvalSeverity.ERROR:\n errors += 1\n if severity == EvalSeverity.WARNING:\n warnings += 1\n return errors, warnings\n\n\ndef check_eml(eml_node, filename):\n evaluations = perform_evaluation(eml_node, filename)\n return format_output(evaluations)\n\n\ndef validate_via_metapype(node):\n errs = []\n try:\n validate.tree(node, errs)\n except Exception as e:\n print(f'validate_via_metapype: node={node.name} exception={e}')\n return errs\n\n\ndef evaluate_via_metapype(node):\n eval = []\n try:\n evaluate.tree(node, eval)\n except Exception as e:\n print(f'evaluate_via_metapype: node={node.name} exception={e}')\n return eval\n\n\n\n\n\n","sub_path":"webapp/home/check_metadata.py","file_name":"check_metadata.py","file_ext":"py","file_size_in_byte":31207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"207425556","text":"# # Find Nearest Neighbors of Tabular Data\n# In this notebook, we compute the nearest neighbors of different row items in a tabular dataset (loaded as a `pd.DataFrame`) using K-Nearest Neighbors and FAISS trees.\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.neighbors import NearestNeighbors\nimport faiss\n\n# Parameters\nK_NEIGHBORS = 2\n\n# \"Read file\" (dummy data)\ndf = pd.DataFrame({c: np.random.randint(low=1, high=190, size=10000) for c in ['a', 'b']})\ndf #pd.read_csv(FILE)\n\n\n# Weight Features With User Input\n# Get size of data to provide user with weights\nn_cols = df.values.shape[1] # Get number of columns\nprint(\"Please enter {} weights, one for each column:\".format(n_cols))\nquery = input(\"Please enter {} numbers in list format, e.g. {} \\n -->\".format(n_cols, [i for i in range(n_cols)]))\nweights = np.array(eval(query)) # Reads as list, and converts to NumPy array\nprint(\"Weights are: {}\".format(weights))\n\n\n# Now \"weight the features\"\nX = df.values # Creates a NumPy array\nX_norm = X * weights # Scales values by weights\n\n\n# Find Neighbors Using [K-Nearest Neighbor Objects](https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.NearestNeighbors.html)\n# KNN objects can be used to compute nearest neighbors using a variety of distance metrics, which can be helpful for instances where data has different scales (e.g. Mahalanobis distance), is gridded (Manhattan distance), or has other unique constraints. Below, we will implement KNN objects with the `sklearn` Python libary.\n\n# Create K-Nearest Neighbors object\nknn = NearestNeighbors(n_neighbors=K_NEIGHBORS, metric=\"minkowski\", p=2)\nknn.fit(X_norm) # Fit the knn object to the data\nneighbor_idx = knn.kneighbors(X_norm, K_NEIGHBORS+1, return_distance=False)[:, 1:] # Can't take yourself\nneighbor_dict = {i: k for i, k in enumerate(neighbor_idx)} # Indexed by X_norm\n\n# Find Neighbors Using [FAISS Trees](https://github.com/facebookresearch/faiss)\n# FAISS trees are especially helpful for running large queries. These operations are run in C in order to improve runtime, and can result in signicantly faster queries for large datasets/high dimensions. Below, we'll show how to query neighbors using L2-norms (Euclidean distance), implemented with the `faiss` Python libary.\n\nclass FaissKNeighbors:\n \"\"\"An implementation of FAISS trees.\n\n Parameters:\n k (int): The number of neighbors we consider for the FAISS tree.\n \"\"\"\n def __init__(self, k=50):\n self.index = None\n self.k = k\n\n def fit(self, X):\n \"\"\"Function to fit the FAISS tree.\n\n Parameters:\n X (np.array): Array of shape (N, d), where N is the number of\n samples and d is the dimension of hte data. Note that the\n array must be of type np.float32.\n \"\"\"\n self.index = faiss.IndexFlatL2(X.shape[1])\n self.index.add(X.astype(np.float32))\n\n def query(self, X, k=None):\n \"\"\"Function to query the neighbors of the FAISS tree.\n\n Parameters:\n X (np.array): Array of shape (N, D), where N is the number of\n samples, and D is the dimension of the features.\n k (int): If provided, the number of neighbors to compute. Defaults\n to None, in which case self.k is used as the number of neighbors.\n\n Returns:\n indices (np.array): Array of shape (N, K), where N is the number of\n samples, and K is the number of nearest neighbors to be computed.\n The ith row corresponds to the k-nearest neighbors of the ith\n sample.\n \"\"\"\n # Set number of neighbors\n if k is None: # Use default number of neighbors\n k = self.k\n\n # Query and return nearest neighbors\n _, indices = self.index.search(X.astype(np.float32), k=k)\n return indices\n\n# Need to convert array to C-order\nX_norm = X_norm.copy(order=\"C\")\n\n# Fit the FAISS tree\nfaiss_tree = FaissKNeighbors(k=K_NEIGHBORS+1) # Creates the FAISS tree\nfaiss_tree.fit(X_norm) # Fits using L2 norm (Euclidean distance)\n\n# Now query neighbors of the FAISS tree\nneighbor_idx = faiss_tree.query(X_norm)[:, 1:]\nneighbor_dict = {i: k for i, k in enumerate(neighbor_idx)} # Indexed by X_norm\n\ndef find_k_nearest(f_csv, kneighbors=5, use_faiss=False, metric=\"minkowski\", p=2):\n \n # Read csv file into pandas DataFrame\n df = pd.read_csv(f_csv) \n \n # Get size of data to provide user with weights\n n_cols = df.values.shape[1] # Get number of columns\n print(\"Please enter {} weights, one for each column:\".format(n_cols))\n query = input(\"Please enter {} numbers in list format, e.g. {} \\n -->\".format(n_cols, [i for i in range(n_cols)]))\n weights = np.array(eval(query)) # Reads as list, and converts to NumPy array\n print(\"Weights are: {}\".format(weights))\n \n # Now \"weight the features\"\n X = df.values # Creates a NumPy array\n X_norm = X * weights # Scales values by weights\n \n # Use KNN\n if not use_faiss:\n # Create K-Nearest Neighbors object\n knn = NearestNeighbors(n_neighbors=kneighbors, metric=metric, p=p)\n knn.fit(X_norm) # Fit the knn object to the data\n \n # Now query neighbors of the KNN tree (NOTE: closest neighbor may be point itself)\n neighbor_idx = knn.kneighbors(X_norm, kneighbors+1, return_distance=False)[:, 1:]\n neighbor_dict = {i: k for i, k in enumerate(neighbor_idx)} # Indexed by X_norm\n \n # Use FAISS tree\n else:\n # Need to convert array to C-order\n X_norm = X_norm.copy(order=\"C\")\n\n # Fit the FAISS tree\n faiss_tree = FaissKNeighbors(k=kneighbors+1) # Creates the FAISS tree\n faiss_tree.fit(X_norm) # Fits using L2 norm (Euclidean distance)\n\n # Now query neighbors of the FAISS trees\n neighbor_idx = faiss_tree.query(X_norm)[:, 1:]\n neighbor_dict = {i: k for i, k in enumerate(neighbor_idx)} # Indexed by X_norm\n \n return neighbor_dict\n","sub_path":"python/python_package_tutorials/pandas/pandas_exercises/knn_df.py","file_name":"knn_df.py","file_ext":"py","file_size_in_byte":6009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"612570079","text":"import glob\nimport os\nimport sys\n# import pathlib\nimport shutil\n\ndef findFilesInFolder(path, pathList, extension, subFolders = True):\n \"\"\"\n Recursive function to find all files of an extension type in a folder (and optionally in all subfolders too)\n path: Base directory to find files\n pathList: A list that stores all paths\n extension: File extension to find\n subFolders: Bool. If True, find files in all subfolders under path. If False, only searches files in the specified folder\n \"\"\"\n try: # Trapping a OSError: File permissions problem I believe\n for entry in os.scandir(path):\n if entry.is_file() and entry.path.endswith(extension): # if it is a file\n pathList.append(entry.path)\n print(entry.path)\n elif entry.is_dir() and subFolders: # if it is a directory, then repeat process as a nested function\n pathList = findFilesInFolder(entry.path, pathList, extension, subFolders)\n except:\n print('Cannot access ' + path +'. Probably a permissions error')\n return pathList\n\nscandir=\"dstdir\"\nextension = \".pyc\"\ndstpyc=\"pycfiles\"\nfailpyc=\"failfiles\"\ncommand_prefix='uncompyle6 -o'\npathlist=[]\n\ndirs=os.listdir(scandir)\nlogfile=open('processlog/fail.txt',\"a\")\ncount=0\nnumall=0\nsuc_count=7151\n# logfile.write(\"----------------------------------------------------------------------------------------------------------------------\")\n\nfor folder in dirs:\n try:\n count=count+1 #count the number of dictiaonary\n print(count)\n workingdir=os.path.join(scandir,folder,\"\") #file path\n if(folder==\"arena-0.0.5.tar\"):\n continue\n pathlist=findFilesInFolder(workingdir,pathlist,extension,True)\n print(pathlist)\n numall = numall + len(pathlist)\n if(count>247342):\n if (len(pathlist) > 0):\n dstpycdir = os.path.join(dstpyc, folder, \"\")\n if (not os.path.isdir(dstpycdir)):\n os.mkdir(dstpycdir)\n for pycfile in pathlist:\n fullcommand = command_prefix + ' ' + dstpycdir + ' ' + pycfile\n print(pycfile)\n try:\n stream = os.popen(fullcommand)\n output = stream.read()\n # logfile.write(output)\n if (\"Successfully\" not in output):\n suc_count = suc_count + 1\n print(\"error: \" + str(suc_count))\n failpycdir = os.path.join(failpyc, folder, \"\")\n logfile.write(str(suc_count) + \": \" + pycfile + \"\\n\")\n if (not os.path.isdir(failpycdir)):\n os.mkdir(failpycdir)\n shutil.copy(pycfile, failpycdir)\n print(\"Copy success!!!\")\n stream.close()\n except:\n suc_count = suc_count + 1\n print(\"error: \" + str(suc_count))\n failpycdir = os.path.join(failpyc, folder, \"\")\n logfile.write(str(suc_count) + \": \" + pycfile + \"\\n\")\n if (not os.path.isdir(failpycdir)):\n os.mkdir(failpycdir)\n shutil.copy(pycfile, failpycdir)\n print(\"Copy success!!!\")\n logfile.flush()\n pathlist=[]\n except:\n print(\"unknown error: \"+folder+\"\\n\")\n\nlogfile.write(\"Sum: \" + str(numall)+ \" pyc files\" +\"\\n\"+ \"Failed decompile: \"+str(suc_count))\nlogfile.close()\n","sub_path":"analyze_code/fail_decompile.py","file_name":"fail_decompile.py","file_ext":"py","file_size_in_byte":3565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"242164539","text":"\nclass BSTNode(object):\n def __init__(self,key):\n self.key = key\n self.left = None\n self.right = None\n\ndef insert(root, key):\n if not root:\n return\n elif root.key == key:\n return\n elif key < root.key:\n if root.left:\n insert(root.left,key)\n else:\n root.left = BSTNode(key)\n else:\n if root.right:\n insert(root.right,key)\n else:\n root.right = BSTNode(key)\n\n\ndef search(root,key):\n if not root:\n return\n if root.key == key:\n return root\n elif key < root.key:\n return search(root.left, key)\n else:\n return search(root.right,key)\n\ndef searchparent(root,key):\n if not root:\n return\n if root.key == key:\n return # need to go up a level\n elif key < root.key:\n if root.left.key == key:\n return (root, root.left)\n else:\n return searchparent(root.left,key)\n else:\n if root.right.key == key:\n return (root, root.right)\n else:\n return searchparent(root.right,key)\n\ndef delete(root,key):\n\n def rightmostchildkey(root):\n if not root.right:\n return root.key\n\n p,node = searchparent(root, key)\n if not node.left and not node.right: # no child\n c = None\n elif node.left and node.right: # both child\n rmk = rightmostchildkey(node.left)\n delete(node.left, rmk)\n else: # 1 child\n if not node.left:\n c = node.left\n elif not node.right:\n c = node.right\n if p.right is node:\n p.right = c\n else:\n p.left = c\n\ndef inorder(root):\n if not root:\n yield '#'\n return\n\n for n in inorder(root.left):\n yield n\n yield root\n\n for n in inorder(root.right):\n yield n\n\ndef buildatree(xs):\n if not xs:\n return\n root = BSTNode(xs[0])\n for x in xs:\n insert(root, x)\n return root\n\ndef rotate(p, node):\n if node is p.left:\n p.left = node.right\n node.right = p\n elif node is p.right:\n p.right = node.left\n node.left = p\n return node\n\n\n# order has to be right\ndef copyatree_dfs(xs):\n if not xs:\n return\n root = BSTNode(xs[0])\n cur = root\n ix = [1]\n\n def _dfs(root):\n if ix[0] < len(xs) or xs[ix[0]] == '#':\n ix[0] += 1\n return\n if ix[0] < len(xs):\n root.left = BSTNode(xs[ix[0]])\n ix[0] += 1\n _dfs(root.left)\n root.right = BSTNode(xs[ix[0]])\n ix[0] += 1\n _dfs(root.right)\n\n _dfs(root)\n return root\n\n# root = buildatree([1,3,2,4,8])\n# print [n.key if n!='#' else n for n in inorder(root)]","sub_path":"binary_tree/bst_wo_parent.py","file_name":"bst_wo_parent.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"90487147","text":"#!/usr/local/bin/python3\n#MacOSX\n\nimport math\nguess = 0\nguesses = []\nnum_of_guesses = 0\nprint(\"*\" * 40)\nprint(\"*\" * 8, \"Computer Guessing Game\", \"*\" * 8, )\nprint(\"*\" * 40)\nhigh_low = '-'\n\nlow = int(input(\"Enter low number: \"))\nhigh = int(input(\"Enter high number: \"))\nif (low == high):\n print(\"Too easy, its {}!\".format(low))\n exit(0)\nelif (low > high):\n print(\"Can't trick me, low is now {} and high is now {}\".format(high, low))\n temp = low\n low = high\n high = temp\nmax_of_guesses = int(math.log(high - low,2) + 1)\nprint(\"Write your number down, I will guess the number in {0} guesses.\\n\".format(max_of_guesses))\n\ndef guess_a_number(lo, hi):\n return lo + ((hi - lo) // 2)\n\nwhile (high_low != 'c') and (high != low):\n guess = guess_a_number(low, high)\n guesses.append(guess)\n num_of_guesses += 1\n high_low = input(\"I guess {0}. Enter c (correct), h (higher), l (lower)\".format(guess))\n if (high_low == 'h'):\n low = guess + 1\n elif (high_low == 'l'):\n high = guess - 1\nelse:\n print(\"See! I told you I can guess the number in {} guesses!\".format(max_of_guesses))\n print(\"Number of guesses: \", num_of_guesses)\n print(\"Computer guesses were: \", guesses)","sub_path":"programming/python/binary_search-high_low_game.py","file_name":"binary_search-high_low_game.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"41670700","text":"\"\"\"\n1. Create a permutation of the indices.\n2. Shuffle a text file according to the permutation.\n\"\"\"\n\nfrom __future__ import unicode_literals\n\nimport sys\nimport codecs\nimport re\nimport copy\nimport argparse\nimport random\nimport pickle\n\n# hack for python2/3 compatibility\nfrom io import open\nargparse.open = open\n\n\ndef create_parser():\n parser = argparse.ArgumentParser(\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=\"Parse an OpenNMT-py log.\")\n\n parser.add_argument(\n '--input', '-i', type=argparse.FileType('r'), default=sys.stdin,\n metavar='PATH',\n help=\"Input text file.\")\n\n parser.add_argument(\n '--output', '-o', type=argparse.FileType('w'), default=sys.stdout,\n metavar='PATH',\n help=\"Output text file.\")\n \n parser.add_argument(\n '--create_permutation', '-p', type=int, default=0,\n help=\"Create a permutation or shuffle files.\")\n \n return parser\n\ndef create_permutation(infile):\n print(\"Reading file...\\n\")\n i = 0\n permutation = []\n for line in infile:\n permutation.append(i)\n i += 1\n print(\"Shuffling...\\n\")\n random.shuffle(permutation)\n pickle.dump(permutation, open(\"permutation.pickle\", \"wb\"))\n print(\"Done\")\n\ndef shuffle_file(infile, outfile):\n permutation = pickle.load(open(\"permutation.pickle\", \"rb\" ))\n print(\"Reading file...\\n\")\n lines = []\n for line in infile:\n lines.append(line)\n print(\"Writing output file...\\n\")\n for index in permutation:\n outfile.write(lines[index])\n print(\"Done\")\n \ndef main(infile, outfile, int_create_permutation):\n if int_create_permutation != 0:\n create_permutation(infile)\n else:\n shuffle_file(infile, outfile)\n \nif __name__ == '__main__':\n\n # python 2/3 compatibility\n if sys.version_info < (3, 0):\n sys.stderr = codecs.getwriter('UTF-8')(sys.stderr)\n sys.stdout = codecs.getwriter('UTF-8')(sys.stdout)\n sys.stdin = codecs.getreader('UTF-8')(sys.stdin)\n else:\n sys.stderr = codecs.getwriter('UTF-8')(sys.stderr.buffer)\n sys.stdout = codecs.getwriter('UTF-8')(sys.stdout.buffer)\n sys.stdin = codecs.getreader('UTF-8')(sys.stdin.buffer)\n \n parser = create_parser()\n args = parser.parse_args()\n\n # read/write files as UTF-8\n if args.input.name != '':\n args.input = codecs.open(args.input.name, encoding='utf-8')\n if args.output.name != '':\n args.output = codecs.open(args.output.name, 'w', encoding='utf-8')\n\n main(args.input, args.output, args.create_permutation)\n","sub_path":"opennmt_scripts/shuffle.py","file_name":"shuffle.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"554355128","text":"\"\"\"1.7 Rotate Matrix\n\nProblem:\n\n Given an image represented by an N x N matrix, where each pixel in the image\n is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this\n in-place?\n\nApproach:\n\n Multidimensional operation can be tricky to think about, especially how do\n we index them in such that we iterate in correct order?\n\n Instead of spending much time finding the correct way to index in a way that\n we can reverse any arbitary N x N matrix, we can do one of two:\n\n One, we can actually use rotation matrix R to perform a rotation in\n Euclidean space. However, this involve matrix multiplication and trig so the\n computation time may not be optimal.\n\n Then, the second approach is noticing that we can first reverse the rows of\n the matrix, then invert it diagnolly.\n\n\"\"\"\n\nclass Solution:\n def reverseMatrix(self, mat):\n i, j = 0, len(mat) - 1\n while i <= j:\n mat[i], mat[j] = mat[j], mat[i]\n i += 1\n j -= 1\n\n def invertDiagMatrix(self, mat):\n for row in range(len(mat) - 1):\n for col in range(row + 1, len(mat)):\n if row != col:\n mat[row][col], mat[col][row] = mat[col][row], mat[row][col]\n\n def rotateMatrixClockwise(self, mat):\n self.reverseMatrix(mat)\n self.invertDiagMatrix(mat)\n\ndef printMatrix(mat):\n for row in mat:\n print(row)\n print()\n\ndef main():\n mat = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n ]\n printMatrix(mat)\n Solution().rotateMatrixClockwise(mat)\n printMatrix(mat)\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"Coding_Question/CCI/01_Arrays_and_Strings/1.7_rotateMatrix.py","file_name":"1.7_rotateMatrix.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"329743936","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'polls'\nurlpatterns = [\n url(r'^$', views.IndexView.as_view(), name='index'),\n url(r'^(?P\\d+)/$', views.DetailView.as_view(), name='detail'),\n url(r'^(?P\\d+)/resules/$', views.ResultView.as_view(), name='results'),\n url(r'^(?P\\d+)/vote/$', views.vote, name='vote'),\n url(r'^(?P\\d+)/createchoice/$', views.createchoice, name='createchoice'),\n url(r'^home/$', views.home, name='home')\n]","sub_path":"first_django_tut/mysite/polls/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"346541853","text":"'''\r\nCreated on Aug 13, 2015\r\n\r\n@author: spatel2\r\n'''\r\nx= int(input(\"Enter 1st Number: \"))\r\ny= int(input(\"Enter 2nd Number: \"))\r\na =x;b =y\r\nwhile b != 0 :\r\n t = b;\r\n b = a % b;\r\n a = t;\r\n\r\nHcf = a\r\n \r\nLcm = (x*y)//Hcf\r\n\r\nprint(\"Greatest common divisor of \",x,\" and \",y,\" = \",Hcf);\r\nprint(\"Least common multiple of \",x,\" and \",y,\" = \", Lcm);","sub_path":"Python_Training/MyPythonPrograms/src/HcfAndLcm.py","file_name":"HcfAndLcm.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"451552200","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3351)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/wodby/models/request_app_create_services.py\n# Compiled at: 2020-04-12 05:03:52\n# Size of source mod 2**32: 4654 bytes\n\"\"\"\n Wodby API Client\n\n Wodby Developer Documentation https://wodby.com/docs/dev # noqa: E501\n\n OpenAPI spec version: 3.0.13\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\nimport pprint, re, six\n\nclass RequestAppCreateServices(object):\n __doc__ = 'NOTE: This class is auto generated by the swagger code generator program.\\n\\n Do not edit the class manually.\\n '\n swagger_types = {'enable': 'bool', \n 'implementation': 'str', \n 'name': 'str'}\n attribute_map = {'enable': 'enable', \n 'implementation': 'implementation', \n 'name': 'name'}\n\n def __init__(self, enable=None, implementation=None, name=None):\n \"\"\"RequestAppCreateServices - a model defined in Swagger\"\"\"\n self._enable = None\n self._implementation = None\n self._name = None\n self.discriminator = None\n if enable is not None:\n self.enable = enable\n if implementation is not None:\n self.implementation = implementation\n self.name = name\n\n @property\n def enable(self):\n \"\"\"Gets the enable of this RequestAppCreateServices. # noqa: E501\n\n :return: The enable of this RequestAppCreateServices. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._enable\n\n @enable.setter\n def enable(self, enable):\n \"\"\"Sets the enable of this RequestAppCreateServices.\n\n :param enable: The enable of this RequestAppCreateServices. # noqa: E501\n :type: bool\n \"\"\"\n self._enable = enable\n\n @property\n def implementation(self):\n \"\"\"Gets the implementation of this RequestAppCreateServices. # noqa: E501\n\n :return: The implementation of this RequestAppCreateServices. # noqa: E501\n :rtype: str\n \"\"\"\n return self._implementation\n\n @implementation.setter\n def implementation(self, implementation):\n \"\"\"Sets the implementation of this RequestAppCreateServices.\n\n :param implementation: The implementation of this RequestAppCreateServices. # noqa: E501\n :type: str\n \"\"\"\n self._implementation = implementation\n\n @property\n def name(self):\n \"\"\"Gets the name of this RequestAppCreateServices. # noqa: E501\n\n :return: The name of this RequestAppCreateServices. # noqa: E501\n :rtype: str\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, name):\n \"\"\"Sets the name of this RequestAppCreateServices.\n\n :param name: The name of this RequestAppCreateServices. # noqa: E501\n :type: str\n \"\"\"\n if name is None:\n raise ValueError('Invalid value for `name`, must not be `None`')\n self._name = name\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(lambda x: x.to_dict() if hasattr(x, 'to_dict') else x, value))\n else:\n if hasattr(value, 'to_dict'):\n result[attr] = value.to_dict()\n else:\n if isinstance(value, dict):\n result[attr] = dict(map(lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item, value.items()))\n else:\n result[attr] = value\n\n if issubclass(RequestAppCreateServices, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, RequestAppCreateServices):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other","sub_path":"pycfiles/wodby-3.0.13-py3.5/request_app_create_services.cpython-35.py","file_name":"request_app_create_services.cpython-35.py","file_ext":"py","file_size_in_byte":4498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"354706528","text":"import tvm\nfrom tvm import te\nimport topi\nfrom tvm import autotvm\nimport numpy as np\nimport logging\nimport sys\n\nn, c, h, w = 16, 256, 28, 28\nf, r, s = 512, 3, 3\nstride = (1, 1)\npadding = (1, 1)\ndilate = (1, 1)\ngroups = 4\ndtype = 'float32'\nc_perg = int(c/groups)\n\ninput_shape = (n, c, h, w)\nweight_shape = (f, c_perg, r, s)\nap = tvm.te.placeholder(shape=input_shape, dtype=dtype, name=\"A\")\nwp = tvm.te.placeholder(shape=weight_shape, dtype=dtype, name=\"W\")\n\nlogging.getLogger('autotvm').setLevel(logging.DEBUG)\nlogging.getLogger('autotvm').addHandler(logging.StreamHandler(sys.stdout))\n\ntask = autotvm.task.create('group_conv2d_nchw.cuda', args=(ap, wp, stride, padding, dilate, groups, dtype), target='cuda')\n\nmeasure_option = autotvm.measure_option(\n builder = autotvm.LocalBuilder(),\n runner = autotvm.LocalRunner(repeat=3, min_repeat_ms=100, timeout=4)\n)\ntuner = autotvm.tuner.XGBTuner(task, feature_type='knob')\n\ntuner.tune(n_trial = 2000,\n measure_option = measure_option,\n callbacks = [autotvm.callback.log_to_file('conv-grouped.log')]\n)\n\ndispatch_context = autotvm.apply_history_best('conv-grouped.log')\nbest_config = dispatch_context.query(task.target, task.workload)\nprint(best_config)\n\nwith autotvm.apply_history_best('conv-grouped.log') as best:\n with tvm.target.create('cuda'):\n outs = topi.cuda.group_conv2d_nchw(ap, wp, stride, padding, dilate, groups, dtype)\n s = topi.cuda.schedule_group_conv2d_nchw([outs])\n func = tvm.build(s, [ap, wp])\n\nctx = tvm.gpu(0)\na_np = np.random.uniform(size=input_shape).astype(dtype)\nw_np = np.random.uniform(size=weight_shape).astype(dtype)\na = tvm.nd.array(a_np, ctx)\nw = tvm.nd.array(w_np, ctx)\n\nevaluator = func.time_evaluator(func.entry_name, ctx, number = 1, repeat = 10)\ntimer = evaluator(a, w).mean*1e3\nprint(\"time: %.2fms\" % (timer))\n\n# dev_module = func.imported_modules[0]\n# print(dev_module)\n# print(\"-------GPU code-------\")\n# print(dev_module.get_source())\n","sub_path":"benchmark/tvm/conv-grouped.py","file_name":"conv-grouped.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"134578563","text":"import sys,os\nimport subprocess\n\nindex_file = sys.argv[1]\nscript = 'python2 extractFeatures_by_index_07jan_load_dicts.py '\ndata = 'data/all_events_parsed_sorted_old_tweets_no_doubles.txt '\n\nmax_processes = 18\nprocesses = set()\ncount = 0\ndiff = 500\n\nfor idx in range(700,93200,diff):\n\tidx2 = idx + diff\n\trun_system = script + data + index_file + ' ' + str(idx) + ' ' + str(idx2)\n\tprocesses.add(subprocess.Popen(run_system, shell=True))\n\tcount += 1\n\tprint(count,'range:', idx,idx2)\n\tif len(processes) >= max_processes:\n\t\tos.wait()\n\t\tprocesses.difference_update([p for p in processes if p.poll() is not None])\n\t\n#Check if all the child processes were closed\nfor p in processes:\n if p.poll() is None:\n p.wait()\n","sub_path":"run_extract_features_parallel.py","file_name":"run_extract_features_parallel.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"413122565","text":"#\n\ndosya=open(\"p067_triangle.txt\")\nucgen = []\n\nfor line in dosya.readlines(): #dosyanın içindeki her satır için bu işlemleri yap\n line = line.rstrip('\\n').split(' ') #satır sonu karakterini çıkardım ve elemanları boşlukla ayırdım\n ucgen.append(line) #her bir satırı üçgen listesine ekledim\ndosya.close() #dosyayı okudum kapatıyorum\n\nfor n in range(len(ucgen)-2,-1,-1):\n for m in range(len(ucgen[n])):\n ucgen[n][m] = int(ucgen[n][m]) + max(int(ucgen[n+1][m]),int(ucgen[n+1][m+1]))\n\nprint(ucgen[0][0])\n","sub_path":"PYTHON/DERS13-54.py","file_name":"DERS13-54.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"342559641","text":"from django.urls import path\nfrom . import views\n\napp_name = 'payroll'\n\nurlpatterns = [\n # /payroll/\n path('', views.IndexView.as_view(), name='index'),\n\n # /payroll/string/\n path('create/', views.PaymentCreateView.as_view(), name='create_payment'),\n path('detail//', views.PaymentDetailView.as_view(),\n name='detail_payment'),\n path('update//', views.PaymentUpdateView.as_view(),\n name='update_payment'),\n path('last/create/', views.LastPaymentCreateView.as_view(),\n name='create_last_payment'),\n path('last/update//', views.LastPaymentUpdateView.as_view(),\n name='update_last_payment'),\n path('last/detail//', views.LastPaymentDetailView.as_view(),\n name='detail_last_payment'),\n\n # Method\n path('ajax/payment_calculation/', views.payment_calculation),\n path('last/ajax/payment_calculation/', views.payment_calculation),\n\n path('payslipPDF//', views.PaymentPDFView.as_view(), name='payslip_pdf'),\n path('last/payslipPDF//',\n views.LastPaymentPDFView.as_view(), name='last_payslip_pdf'),\n]\n","sub_path":"payroll/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"166509845","text":"import tkinter\nimport configparser\nfrom app import Application\n\n# init config\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\ndef main():\n root = tkinter.Tk()\n root.title('人生如遊戲')\n\n # check does the window need fixed size\n if config['window']['fixed_size'] == 'yes':\n root.resizable(width=False, height=False)\n\n application = Application(root)\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"168434054","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n\tdef isValidBST1(self, root):\n\t\treturn self.helper(root, None, None)\n\n\tdef helper1(self, root, minVal, maxVal):\n\t\tif root == None:\n\t\t\treturn True\n\t\tif minVal != None and root.val <= minVal:\n\t\t\treturn False\n\t\tif maxVal != None and root.val >= maxVal:\n\t\t\treturn False\n\t\treturn self.helper(root.left, minVal, root.val) and self.helper(root.right, root.val, maxVal)\n\n\tdef isValidBST2(self, root):\n\t\tif root == None:\n\t\t\treturn True\n\t\tprev = None\n\t\tstack = []\n\t\twhile(root != None or len(stack) > 0):\n\t\t\twhile(root != None):\n\t\t\t\tstack.append(root)\n\t\t\t\troot = root.left\n\t\t\troot = stack.pop()\n\t\t\tif prev != None and root.val <= prev.val:\n\t\t\t\treturn False\n\t\t\tprev = root\n\t\t\troot = root.right\n\t\treturn True\n\n\tprev = None\n\tdef isValidBST3(self, root):\n\t\tself.prev = None\n\t\treturn self.helper(root)\n\n\tdef helper3(self, root):\n\t\tif root == None:\n\t\t\treturn True\n\t\tif not self.helper3(root.left):\n\t\t\treturn False\n\t\tif self.prev != None and root.val <= self.prev.val:\n\t\t\treturn False\n\t\tself.prev = root\n\t\treturn self.helper3(root.right)","sub_path":"Problem1.py","file_name":"Problem1.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"369589334","text":"class Func(object):\n\tdef __init__(self):\n\t\tself.name = None\n\t\tself.retType = None\n\t\tself.retDerive = None\n\t\tself.paramList = None\n\t\tself.ASTList = None\n\t\tself.returnSTMT = None\n\n\tdef __init__(self, name, retType, retDerive, paramList, ASTList, returnSTMT):\n\t\tself.name = name\n\t\tself.retType = retType\n\t\tself.retDerive = retDerive\n\t\tself.paramList = paramList\n\t\tself.ASTList = ASTList\n\t\tself.returnSTMT = returnSTMT\n","sub_path":"assignment5/func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"194026245","text":"from bcg_dist import find_peak, rotate, np, fits\nfrom scipy.interpolate import interp2d\nfrom read import init, calibrate\n\ndef angle(pt1, pt2):\n\trelative_pos = (pt2 - pt1)\n\tif len(relative_pos) == 1:\n\t\trelative_pos = (pt2 - pt1)[0]\n\treturn np.angle(relative_pos[0] + 1j*relative_pos[1]) #output in radians\n\ndef rotate_image(image, angle):\n\timage[np.isnan(image)] = 0 #otherwise rotation gets fucked\n\trotimage = rotate(image, angle = angle)\n\tdatasize = image.shape[0]\n\trotsize = rotimage.shape[0]\n\n\tif rotsize != datasize:\n\t\txstart = (rotsize - datasize)//2\n\t\trotimage = rotimage[xstart:xstart+datasize, xstart:xstart+datasize]\n\t\trotimage[rotimage == 0] = np.nan\n\treturn rotimage\n\ndef align_bcgs(obsfile, errfile, potfile, xrayfile, bcg1_pix=None, bcg2_pix=None, xmin=300, xmax=1200, ymin = 300, ymax = 1200):\n\tpeaks = find_peak(potfile, ret_peaks=True, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax)\n\tpotential = fits.getdata(potfile)\n\tminima1 = potential[peaks[0][0]][peaks[0][1]] \n\tminima2 = potential[peaks[1][0]][peaks[1][1]] \n\n\t#this is centered on xray peak\n\tobsdata, errorsq, x, y, xp = init(obsfile, errfile)\n\n\tdata = fits.getdata(xrayfile)\n\theader = fits.getheader(xrayfile)\n\tdx = header['CDELT1']\n\tsx = calibrate(data.shape[1],header,axis=1)\n\tsy = calibrate(data.shape[1],header,axis=2)\n\n\tif minima1 < minima2:\n\t\tpeak1 = peaks[0]\n\t\tpeak2 = peaks[1]\n\telse:\n\t\tpeak1 = peaks[1]\n\t\tpeak2 = peaks[0]\n\n\tpos_peak1 = (sx[peak1[0]], sy[peak1[1]])\n\n\t#peak1 should = xp = center\n\tsx -= pos_peak1[0]\n\tsy -= pos_peak1[1]\n\n\tf = interp2d(sx, sy, data)\n\tbinned_data = f(x,y)\n\n\t#rotate each about xp counterclockwise by angle \n\tif bcg1_pix:\n\t\tbcg_angle_obs = np.degrees(angle(bcg2_pix - xp, bcg1_pix - xp))\n\t\tbcg_angle_sim = np.degrees(angle(peak2, peak1))\n\n\t\trot_image = rotate(binned_data, bcg_angle_sim-bcg_angle_obs, reshape=False)\n\t\n\t\t#good! now output this shifted and rotated array\n\t\treturn rot_image #because obs RA are decreasing, while sim is increasing\n\telse:\n\t\treturn binned_data\n\n#testing in app editing","sub_path":"gcmerge/align_BCGs.py","file_name":"align_BCGs.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"645051007","text":"\"\"\"myblog URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom django.conf.urls import include , re_path\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom mainsite import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('',views.homepage),\n path('accounts/', include('allauth.urls')),\n re_path(r'^filer/', include('filer.urls')),\n re_path(r'^(\\d*)/$',views.index),\n path('post//',views.showpost),\n path('delete_message/',views.delete_message),\n path('like/',views.like),\n re_path(r'^market/(\\d*)/$',views.market),\n re_path(r'^product/(\\d+)$',views.product,name='product-url'),\n re_path(r'^cart/$', views.cart),\n re_path(r'^additem/(\\d+)/(\\d+)/$', views.add_to_cart,name='additem-url'),\n re_path(r'^removeitem/(\\d+)/$', views.remove_from_cart,name='removeitem-url'),\n re_path(r'^order/$',views.order),\n re_path(r'^myorders/$',views.my_orders),\n re_path(r'^paypal/', include('paypal.standard.ipn.urls')),\n re_path(r'^payment/(\\d+)/$',views.payment),\n re_path(r'^done/(\\d+)/$',views.payment_done),\n re_path(r'^canceled/(\\d+)/$',views.payment_canceled),\n]\nurlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)","sub_path":"myblog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"295430574","text":"class Scene(object):\n def __init__(self, title, urlname, description):\n self.title = title\n self.urlname = urlname\n self.description = description\n self.paths = {}\n\n def go(self, direction):\n default_direction = None\n if '*' in self.paths.keys():\n default_direction = self.paths.get('*')\n return self.paths.get(direction, default_direction)\n\n def add_paths(self, paths):\n self.paths.update(paths)\n\n# Create the scenes of the game\ndeath = Scene(\"Death\", \"death\",\n\"\"\"\nYou are dead. Now the entire 'Tribe of the Last Mediahicans' is\nabout to be erased by the 'Big Python' because of your destitue.\nMay Manitou torture your soul in the happy hunting ground for\neternity. Howgh!\n\"\"\")\n\nsaloon = Scene(\"Saloon\", \"saloon\",\n\"\"\"\nYou wake up in a Saloon with a really bad hangover.\nOn the table in front of you a huge bottle of firewater is\nprovided. The bottle is empty. At the table sits a bunch of\npalefaces. They are all asleep after binge drinking!\nYour plan to knock them out in a boozy session has worked out.\nYou can leave the Saloon now to get you a palefaces' horse and\nride to your village.\nBe riding carefully you are still a little drunk!\n\"\"\")\n\nplains = Scene(\"Plains\", \"plains\",\n\"\"\"\nYou arrive at the creek. Remember that it is a long-ass way back\nto your village. Get some fresh water for you and your horse.\nBut try to drink not too much water because then you will have\nto pee in the plains later.\nAs a true 'Mediahican' you should know that peeing in the plains\nis deadly! This is S3RIOUS!\nTry to guess how many drinks of water are appropriate now.\n\"\"\")\n\nshaman_tent = Scene(\"shaman_tent\", \"Shaman_Tent\",\n\"\"\"\nYou arrive at your village and head directly to the tent of\nthe'Mediahicans' Shaman Jonathanou. You enter his tent and hear\nthe wise voice of the Shaman saying:\n'Young Mediahican did you not listen to the old legends of the\n'Big Python'?! It is about time, that you face the battle.\nYou are no beginner no more.\nTake a puff of the 'Python Pipe' and you will envision what it\ntakes to conquer the 'Big Python'!'\nHe hands you the Shaman pipe. What are going to do?\nTake a puff or pass?\n\"\"\")\n\nsnake_pit = Scene(\"Snake_Pit\", \"snake_pit\",\n\"\"\"\nYou stand at the Snake Pit.\nAcid fumes and a a fetid, choking odour, the smell of a\ncharnel house, grabbs you by the throat!\nThe 'Big Python' wriggles out of the Snake Pit\nand stands in attack position.\nNow you have to show what you have learned from all them 'Python'\ndrills since you have been become a 'Mediahican'.\nThe 'Big Python' tries to snag your head, but you duck down.\nYou jump to the left side and spit out the command to destroy\nthe 'Big Python' forever:\nDef destroy_python(eternity):\npython.destroy\nThe mighty words of Jonathanou echo in your head: Never forget\nto attach 'Parenthesis' to the 'Dot Operator'!\nWhat do you attach?\n\"\"\")\n\nsleepy_loser = Scene(\"Sleep\", \"sleep\",\n\"\"\"\nYou are such a lazy 'Mediahican'! Your whole Tribe is about to be\nerased by the Big Python because you are such an idle bastard!\nWith this kinda attitude you never gonna conquer the Big Python!\nWhen you will wake up the palefaces probably gonna lynch you\nanyway.\n\"\"\")\n\ndrunk_loser = Scene( \"Drunk_Loser\", \"drunk_loser\",\n\"\"\"\nYou crock! Your whole Tribe is about to be erased by the 'Big\nPython'. And you keep on drinking firewater?!\nYou are a disgrace for the 'Tribe of the last Mediahicans'!\nAlthough 'Mediahicans' are notorious for boozing too much.\nBy the time you'll wake up, the palefaces probably gonna lynch you anyway.\nCheers loser!\n\"\"\")\n\nfinished = Scene(\"Finished\", \"You won\",\n\"\"\"\nThe 'Big Python' fizzles a last SssssDamned!\nThe monster curls to the left and then to the right.\nSuddenly you hear a big bang and the 'Big Python' explodes\nand slime covers the whole plas plus your face.\nBut nevermind! You have mastered the 'Big Python' and saved\nthe entire 'Class of the Last Mediahicans'.\nEverlasting glory is all but certain for you.\n'Big Python' is destroyed and your Tribe will forever be grateful.\nManitous sympathy will be for certain from now on...\nYou've won young Mediahican! Great Job, Howgh!\n\"\"\")\n\n#Define the action commands available in each scene\nsaloon.add_paths({\n 'sleep': sleepy_loser,\n 'drink': drunk_loser,\n 'ride': plains\n})\n\nplains.add_paths({\n '3': shaman_tent,\n '*': death\n})\n\nshaman_tent.add_paths({\n 'take a puff': snake_pit,\n 'pass': death\n})\n\nsnake_pit.add_paths({\n '()': finished,\n '*': death\n})\n# Make some useful variables to be used in the web application\nSCENES = {\n death.urlname: death,\n saloon.urlname: saloon,\n plains.urlname: plains,\n shaman_tent.urlname: shaman_tent,\n snake_pit.urlname: snake_pit,\n sleepy_loser.urlname: sleepy_loser,\n drunk_loser.urlname: drunk_loser,\n finished.urlname: finished\n}\nSTART = saloon\n","sub_path":"EX52/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":4838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"584030618","text":"#!/usr/bin/python3\n\nimport tempfile as _tempfile\nfrom libkyt import time as _time\n\ndef timed_mkdtemp(prefix=\"\", suffix=\"\", dir=\"./\"):\n timestamp = _time.path_friendly_time()\n prefix = prefix + timestamp + \"-\"\n return _tempfile.mkdtemp(suffix=suffix,\n prefix=prefix,\n dir=dir)\n","sub_path":"libkyt/fs.py","file_name":"fs.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"535989037","text":"import json\r\nfrom os import path\r\nimport os\r\nimport csv\r\n\r\ndef jsonToCSV (infile, outfile):\r\n\r\n\twriter = csv.writer(outfile)\r\n\r\n\twith infile as json_data:\r\n\t\td = json.load(json_data)\r\n\r\n\t\tfor r in d[\"results\"]:\r\n\t\t\tfor a in r[\"alternatives\"]:\r\n\t\t\t\tc = a[\"word_confidence\"]\r\n\t\t\t\tt = a[\"timestamps\"]\r\n\t\t\t\tfor i in range(0, len(t)):\r\n\t\t\t\t\tword = t[i][0]\r\n\t\t\t\t\tconf = c[i][1]\r\n\t\t\t\t\tstart = t[i][1]\r\n\t\t\t\t\tend = t[i][2]\r\n\r\n\t\t\t\t\tvals = [word, conf, start, end]\r\n\r\n\t\t\t\t\twriter.writerow(vals)\r\n\r\nfiles = os.listdir('ts_watson')\r\n\r\nfor file in files:\r\n\tinfile = open('ts_watson/' + file, 'rb')\r\n\toutfile = open('csv_watson/' + file.replace('.json', '_watson.csv'), 'w', newline='')\r\n\tjsonToCSV(infile, outfile)\r\n\tinfile.close()\r\n\toutfile.close()\r\n","sub_path":"Utils/watsonToCSV.py","file_name":"watsonToCSV.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"595628418","text":"class Installation():\r\n\r\n \"\"\"docstring for Installation\"\"\"\r\n\r\n def __init__(self, equActiviteSalleSpe, equActivitePratique, equActivitePraticable, comLib, actCode, actNivLib, comInsee, actLib, equNbEquIdentique):\r\n super(Installation, self).__init__()\r\n self.equipementId = equipementId\r\n self.equActiviteSalleSpe = equActiviteSalleSpe\r\n self.equActivitePratique = equActivitePratique\r\n self.equActivitePraticable = equActivitePraticable\r\n self.comLib = comLib\r\n self.actCode = actCode\r\n self.actNivLib = actNivLib\r\n self.comInsee = comInsee\r\n self.actLib = actLib\r\n self.equNbEquIdentique = equNbEquIdentique\r\n","sub_path":"Class/installationsClass.py","file_name":"installationsClass.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"376383424","text":"#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport datetime\nimport sys\nimport time\n\nimport pytest\n\nfrom airflow.jobs.triggerer_job import TriggererJob\nfrom airflow.models import Trigger\nfrom airflow.operators.dummy import DummyOperator\nfrom airflow.triggers.base import TriggerEvent\nfrom airflow.triggers.temporal import TimeDeltaTrigger\nfrom airflow.triggers.testing import FailureTrigger, SuccessTrigger\nfrom airflow.utils import timezone\nfrom airflow.utils.session import create_session\nfrom airflow.utils.state import State, TaskInstanceState\nfrom tests.test_utils.db import clear_db_runs\n\n\n@pytest.fixture(autouse=True)\ndef clean_database():\n \"\"\"Fixture that cleans the database before and after every test.\"\"\"\n clear_db_runs()\n yield # Test runs here\n clear_db_runs()\n\n\n@pytest.fixture\ndef session():\n \"\"\"Fixture that provides a SQLAlchemy session\"\"\"\n with create_session() as session:\n yield session\n\n\n@pytest.mark.skipif(sys.version_info.minor <= 6 and sys.version_info.major <= 3, reason=\"No triggerer on 3.6\")\ndef test_is_alive():\n \"\"\"Checks the heartbeat logic\"\"\"\n # Current time\n triggerer_job = TriggererJob(None, heartrate=10, state=State.RUNNING)\n assert triggerer_job.is_alive()\n\n # Slightly old, but still fresh\n triggerer_job.latest_heartbeat = timezone.utcnow() - datetime.timedelta(seconds=20)\n assert triggerer_job.is_alive()\n\n # Old enough to fail\n triggerer_job.latest_heartbeat = timezone.utcnow() - datetime.timedelta(seconds=31)\n assert not triggerer_job.is_alive()\n\n # Completed state should not be alive\n triggerer_job.state = State.SUCCESS\n triggerer_job.latest_heartbeat = timezone.utcnow() - datetime.timedelta(seconds=10)\n assert not triggerer_job.is_alive(), \"Completed jobs even with recent heartbeat should not be alive\"\n\n\n@pytest.mark.skipif(sys.version_info.minor <= 6 and sys.version_info.major <= 3, reason=\"No triggerer on 3.6\")\ndef test_is_needed(session):\n \"\"\"Checks the triggerer-is-needed logic\"\"\"\n # No triggers, no need\n triggerer_job = TriggererJob(None, heartrate=10, state=State.RUNNING)\n assert triggerer_job.is_needed() is False\n # Add a trigger, it's needed\n trigger = TimeDeltaTrigger(datetime.timedelta(days=7))\n trigger_orm = Trigger.from_object(trigger)\n trigger_orm.id = 1\n session.add(trigger_orm)\n session.commit()\n assert triggerer_job.is_needed() is True\n\n\n@pytest.mark.skipif(sys.version_info.minor <= 6 and sys.version_info.major <= 3, reason=\"No triggerer on 3.6\")\ndef test_capacity_decode():\n \"\"\"\n Tests that TriggererJob correctly sets capacity to a valid value passed in as a CLI arg,\n handles invalid args, or sets it to a default value if no arg is passed.\n \"\"\"\n # Positive cases\n variants = [\n 42,\n None,\n ]\n for input_str in variants:\n job = TriggererJob(capacity=input_str)\n assert job.capacity == input_str or 1000\n\n # Negative cases\n variants = [\n \"NAN\",\n 0.5,\n -42,\n 4 / 2, # Resolves to a float, in addition to being just plain weird\n ]\n for input_str in variants:\n with pytest.raises(ValueError):\n TriggererJob(capacity=input_str)\n\n\n@pytest.mark.skipif(sys.version_info.minor <= 6 and sys.version_info.major <= 3, reason=\"No triggerer on 3.6\")\ndef test_trigger_lifecycle(session):\n \"\"\"\n Checks that the triggerer will correctly see a new Trigger in the database\n and send it to the trigger runner, and then delete it when it vanishes.\n \"\"\"\n # Use a trigger that will not fire for the lifetime of the test\n # (we want to avoid it firing and deleting itself)\n trigger = TimeDeltaTrigger(datetime.timedelta(days=7))\n trigger_orm = Trigger.from_object(trigger)\n trigger_orm.id = 1\n session.add(trigger_orm)\n session.commit()\n # Make a TriggererJob and have it retrieve DB tasks\n job = TriggererJob()\n job.load_triggers()\n # Make sure it turned up in TriggerRunner's queue\n assert [x for x, y in job.runner.to_create] == [1]\n # Now, start TriggerRunner up (and set it as a daemon thread during tests)\n job.runner.daemon = True\n job.runner.start()\n try:\n # Wait for up to 3 seconds for it to appear in the TriggerRunner's storage\n for _ in range(30):\n if job.runner.triggers:\n assert list(job.runner.triggers.keys()) == [1]\n break\n time.sleep(0.1)\n else:\n pytest.fail(\"TriggerRunner never created trigger\")\n # OK, now remove it from the DB\n session.delete(trigger_orm)\n session.commit()\n # Re-load the triggers\n job.load_triggers()\n # Wait for up to 3 seconds for it to vanish from the TriggerRunner's storage\n for _ in range(30):\n if not job.runner.triggers:\n break\n time.sleep(0.1)\n else:\n pytest.fail(\"TriggerRunner never deleted trigger\")\n finally:\n # We always have to stop the runner\n job.runner.stop = True\n\n\n@pytest.mark.skipif(sys.version_info.minor <= 6 and sys.version_info.major <= 3, reason=\"No triggerer on 3.6\")\ndef test_trigger_from_dead_triggerer(session):\n \"\"\"\n Checks that the triggerer will correctly claim a Trigger that is assigned to a\n triggerer that does not exist.\n \"\"\"\n # Use a trigger that has an invalid triggerer_id\n trigger = TimeDeltaTrigger(datetime.timedelta(days=7))\n trigger_orm = Trigger.from_object(trigger)\n trigger_orm.id = 1\n trigger_orm.triggerer_id = 999 # Non-existent triggerer\n session.add(trigger_orm)\n session.commit()\n # Make a TriggererJob and have it retrieve DB tasks\n job = TriggererJob()\n job.load_triggers()\n # Make sure it turned up in TriggerRunner's queue\n assert [x for x, y in job.runner.to_create] == [1]\n\n\n@pytest.mark.skipif(sys.version_info.minor <= 6 and sys.version_info.major <= 3, reason=\"No triggerer on 3.6\")\ndef test_trigger_from_expired_triggerer(session):\n \"\"\"\n Checks that the triggerer will correctly claim a Trigger that is assigned to a\n triggerer that has an expired heartbeat.\n \"\"\"\n # Use a trigger assigned to the expired triggerer\n trigger = TimeDeltaTrigger(datetime.timedelta(days=7))\n trigger_orm = Trigger.from_object(trigger)\n trigger_orm.id = 1\n trigger_orm.triggerer_id = 42\n session.add(trigger_orm)\n # Use a TriggererJob with an expired heartbeat\n triggerer_job_orm = TriggererJob()\n triggerer_job_orm.id = 42\n triggerer_job_orm.start_date = timezone.utcnow() - datetime.timedelta(hours=1)\n triggerer_job_orm.end_date = None\n triggerer_job_orm.latest_heartbeat = timezone.utcnow() - datetime.timedelta(hours=1)\n session.add(triggerer_job_orm)\n session.commit()\n # Make a TriggererJob and have it retrieve DB tasks\n job = TriggererJob()\n job.load_triggers()\n # Make sure it turned up in TriggerRunner's queue\n assert [x for x, y in job.runner.to_create] == [1]\n\n\n@pytest.mark.skipif(sys.version_info.minor <= 6 and sys.version_info.major <= 3, reason=\"No triggerer on 3.6\")\ndef test_trigger_firing(session):\n \"\"\"\n Checks that when a trigger fires, it correctly makes it into the\n event queue.\n \"\"\"\n # Use a trigger that will immediately succeed\n trigger = SuccessTrigger()\n trigger_orm = Trigger.from_object(trigger)\n trigger_orm.id = 1\n session.add(trigger_orm)\n session.commit()\n # Make a TriggererJob and have it retrieve DB tasks\n job = TriggererJob()\n job.load_triggers()\n # Now, start TriggerRunner up (and set it as a daemon thread during tests)\n job.runner.daemon = True\n job.runner.start()\n try:\n # Wait for up to 3 seconds for it to fire and appear in the event queue\n for _ in range(30):\n if job.runner.events:\n assert list(job.runner.events) == [(1, TriggerEvent(True))]\n break\n time.sleep(0.1)\n else:\n pytest.fail(\"TriggerRunner never sent the trigger event out\")\n finally:\n # We always have to stop the runner\n job.runner.stop = True\n\n\n@pytest.mark.skipif(sys.version_info.minor <= 6 and sys.version_info.major <= 3, reason=\"No triggerer on 3.6\")\ndef test_trigger_failing(session):\n \"\"\"\n Checks that when a trigger fails, it correctly makes it into the\n failure queue.\n \"\"\"\n # Use a trigger that will immediately fail\n trigger = FailureTrigger()\n trigger_orm = Trigger.from_object(trigger)\n trigger_orm.id = 1\n session.add(trigger_orm)\n session.commit()\n # Make a TriggererJob and have it retrieve DB tasks\n job = TriggererJob()\n job.load_triggers()\n # Now, start TriggerRunner up (and set it as a daemon thread during tests)\n job.runner.daemon = True\n job.runner.start()\n try:\n # Wait for up to 3 seconds for it to fire and appear in the event queue\n for _ in range(30):\n if job.runner.failed_triggers:\n assert list(job.runner.failed_triggers) == [1]\n break\n time.sleep(0.1)\n else:\n pytest.fail(\"TriggerRunner never marked the trigger as failed\")\n finally:\n # We always have to stop the runner\n job.runner.stop = True\n\n\n@pytest.mark.skipif(sys.version_info.minor <= 6 and sys.version_info.major <= 3, reason=\"No triggerer on 3.6\")\ndef test_trigger_cleanup(session):\n \"\"\"\n Checks that the triggerer will correctly clean up triggers that do not\n have any task instances depending on them.\n \"\"\"\n # Use a trigger that will not fire for the lifetime of the test\n # (we want to avoid it firing and deleting itself)\n trigger = TimeDeltaTrigger(datetime.timedelta(days=7))\n trigger_orm = Trigger.from_object(trigger)\n trigger_orm.id = 1\n session.add(trigger_orm)\n session.commit()\n # Trigger the cleanup code\n Trigger.clean_unused(session=session)\n session.commit()\n # Make sure it's gone\n assert session.query(Trigger).count() == 0\n\n\n@pytest.mark.skipif(sys.version_info.minor <= 6 and sys.version_info.major <= 3, reason=\"No triggerer on 3.6\")\ndef test_invalid_trigger(session, dag_maker):\n \"\"\"\n Checks that the triggerer will correctly fail task instances that depend on\n triggers that can't even be loaded.\n \"\"\"\n # Create a totally invalid trigger\n trigger_orm = Trigger(classpath=\"fake.classpath\", kwargs={})\n trigger_orm.id = 1\n session.add(trigger_orm)\n session.commit()\n\n # Create the test DAG and task\n with dag_maker(dag_id='test_invalid_trigger', session=session):\n DummyOperator(task_id='dummy1')\n\n dr = dag_maker.create_dagrun()\n task_instance = dr.task_instances[0]\n # Make a task instance based on that and tie it to the trigger\n task_instance.state = TaskInstanceState.DEFERRED\n task_instance.trigger_id = 1\n session.commit()\n\n # Make a TriggererJob and have it retrieve DB tasks\n job = TriggererJob()\n job.load_triggers()\n\n # Make sure it turned up in the failed queue\n assert list(job.runner.failed_triggers) == [1]\n\n # Run the failed trigger handler\n job.handle_failed_triggers()\n\n # Make sure it marked the task instance as failed (which is actually the\n # scheduled state with a payload to make it fail)\n task_instance.refresh_from_db()\n assert task_instance.state == TaskInstanceState.SCHEDULED\n assert task_instance.next_method == \"__fail__\"\n assert task_instance.next_kwargs == {'error': 'Trigger failure'}\n","sub_path":"tests/jobs/test_triggerer_job.py","file_name":"test_triggerer_job.py","file_ext":"py","file_size_in_byte":12286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"134396460","text":"import pyautogui\nimport time\nimport pyscreenshot as ImageGrab\nimport subprocess\nfrom datetime import datetime\n\n\ncreate_dc=\"mkdir DC\"\ncreate_drc=\"mkdir DRC\"\nroute = \"/home/fakhril/Documents/PEMOGRAMAN/PYTHON/cursor_move/\"\n\nsubprocess.run([\"mkdir\", datetime.today().strftime(\"%d %h %y\")])\nsubprocess.Popen(create_dc.split(), stdout=subprocess.PIPE,cwd= route + datetime.today().strftime(\"%d %h %y\"))\nsubprocess.Popen(create_drc.split(), stdout=subprocess.PIPE,cwd= route + datetime.today().strftime(\"%d %h %y\"))\n\narray_Host = [158,193,227,261,290,329,364,398,433,467,503,538,570,607,639,675,712,746,779,814]\n# array_get1 = [498,590,450,438,490,383,378,376,391,382,553,529,552,556,553,570,588,628,637,650]\n# array_get2 = [327,403,473,480,423,460,479,481,440,444,460,459,454,459,484,449,464,478,464,444]\n\n\ndelay = 5\ntime.sleep(5)\nn = 0\nfor i in range(len(array_Host)):\n # klik host\n pyautogui.click(454, array_Host[i]) \n time.sleep(delay)\n\n ##tambahkan kordinat tiap host\n #scrol ambil helth\n # pyautogui.click(1596,670)\n # time.sleep(delay)\n\n #helth\n n+=1\n pyautogui.click(1059,345)\n time.sleep(delay)\n im = ImageGrab.grab(bbox=(90, 270, 1500, 700))\n im.save(datetime.today().strftime(\"%d %h %y\")+\"/DRC\"+\"/\"+ str(n) +\".png\")\n time.sleep(delay)\n # pyautogui.click(109,228)\n # time.sleep(delay)\n pyautogui.click(1480,240)\n time.sleep(delay)\n\n\n # pyautogui.click(1596,130)\n # time.sleep(delay)\n #memory usage\n # pyautogui.click(727,515) #crome\n n+=1\n pyautogui.click(1338,662) #2\n time.sleep(delay)\n im = ImageGrab.grab(bbox=(90, 270, 1500, 700))\n im.save(datetime.today().strftime(\"%d %h %y\")+\"/DRC\"+\"/\"+ str(n) +\".png\")\n time.sleep(delay)\n # pyautogui.click(109,228)\n # time.sleep(delay)\n pyautogui.click(1480,240)\n time.sleep(delay)\n\n #cpu usage\n n+=1\n pyautogui.click(1338,822) #2\n time.sleep(delay)\n im = ImageGrab.grab(bbox=(90, 270, 1500, 700))\n im.save(datetime.today().strftime(\"%d %h %y\")+\"/DRC\"+\"/\"+ str(n) +\".png\")\n time.sleep(delay)\n # pyautogui.click(109,228)\n # time.sleep(delay)\n pyautogui.click(1480,240)\n time.sleep(delay)\n\n #network\n n+=1\n pyautogui.click(1341,503)\n time.sleep(delay)\n im = ImageGrab.grab(bbox=(90, 270, 1500, 700))\n im.save(datetime.today().strftime(\"%d %h %y\")+\"/DRC\"+\"/\"+ str(n) +\".png\")\n time.sleep(delay)\n # pyautogui.click(109,228)\n # time.sleep(delay)\n pyautogui.click(1480,240)\n time.sleep(delay)\n\n #disklatecy\n n+=1\n pyautogui.click(1060,501)\n time.sleep(delay)\n im = ImageGrab.grab(bbox=(90, 270, 1500, 700))\n im.save(datetime.today().strftime(\"%d %h %y\")+\"/DRC\"+\"/\"+ str(n) +\".png\")\n time.sleep(delay)\n # pyautogui.click(109,228)\n # time.sleep(delay)\n pyautogui.click(1478,242)\n time.sleep(delay)\n\n # klik back\n pyautogui.click(21, 83)\n time.sleep(delay)\n # klik scroll\n pyautogui.click(1593, 877)\n pyautogui.click(1593, 877)\n pyautogui.click(1593, 877)\n time.sleep(delay)\nimport DRC","sub_path":"LAPORAN_DRC.py","file_name":"LAPORAN_DRC.py","file_ext":"py","file_size_in_byte":3050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"423126728","text":"#!/usr/bin/env python\n\n# Copyright (c) 2001-2004 Twisted Matrix Laboratories.\n# See LICENSE for details.\n\n\"\"\"\nDistutils-launcher for Twisted projects.\n\"\"\"\n\nimport sys, os, glob\n\nsubprojects = ('core', 'conch', 'flow', 'lore', 'mail', 'names', 'pair',\n 'runner', 'web', 'words', 'news')\n\n\ndef runInDir(dir, f, *args, **kw):\n origdir = os.path.abspath('.')\n os.chdir(dir)\n try:\n return f(*args, **kw)\n finally:\n os.chdir(origdir)\n\ndef runSetup(project, args):\n dir = getProjDir(project)\n\n setupPy = os.path.join(dir, 'setup.py')\n if not os.path.exists(setupPy):\n sys.stderr.write(\"Error: No such project '%s'.\\n\" % (project,))\n sys.stderr.write(\" (File '%s' not found)\\n\" % (setupPy,))\n sys.exit(1)\n\n result = runInDir(dir, os.spawnv,\n os.P_WAIT, sys.executable,\n [sys.executable, 'setup.py'] + args)\n if result != 0:\n sys.stderr.write(\"Error: Subprocess exited with result %d for project %s\\n\" %\n (result, project))\n sys.exit(1)\n\n\ndef getProjDir(proj):\n globst = 'Twisted%s-*' % (proj != 'core'\n and proj.capitalize() or '')\n gl = glob.glob(globst)\n assert len(gl) == 1, 'Wrong number of %s found!?' % proj\n dir = gl[0]\n return dir\n \ndef printProjectInfo(out=sys.stdout):\n out.write(\n\"\"\"Twisted: The Framework Of Your Internet.\nUsage: setup.py \n setup.py all \n\nE.g. setup.py all install\nor setup.py core --help\n\n\"\"\")\n out.write(\"%-10s %-10s\\n\" % (\"Project\", \"Version\"))\n\n for project in subprojects:\n dir = getProjDir(project)\n ver = dir.split('-')[-1]\n out.write(\" %-10s %-10s\\n\" % (project, ver))\n\n\ndef main(args):\n os.putenv(\"PYTHONPATH\", \".\"+os.pathsep+os.getenv(\"PYTHONPATH\", \"\"))\n if len(args) == 0 or args[0] in ('-h', '--help'):\n printProjectInfo()\n sys.exit(0)\n \n # special case common options\n if args[0] in ('install','build'):\n project = 'all'\n else:\n project = args[0]\n args = args[1:]\n \n if project == 'all':\n for project in subprojects:\n runSetup(project, args)\n else:\n runSetup(project, args)\n \nif __name__ == \"__main__\":\n try:\n main(sys.argv[1:])\n except KeyboardInterrupt:\n sys.exit(1)\n\n \n","sub_path":"admin/sumo-setup.py","file_name":"sumo-setup.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"17780397","text":"# coding=utf-8\n\nimport os\nimport tensorflow as tf\n\nslim = tf.contrib.slim\nfrom lib.data_load.data_loader import read_inputs\nfrom lib.utils.utils import g_parameter\nimport config\nfrom lib.train.train import train\n\n# os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\nsample_dir = config.sample_dir\nnum_classes = config.num_classes\nbatch_size = config.batch_size\narch_model = config.arch_model\ncheckpoint_exclude_scopes = config.checkpoint_exclude_scopes\ndropout_prob = config.dropout_prob\ntrain_rate = config.train_rate\nepoch = config.epoch\nlearning_r_decay = config.learning_r_decay\nlearning_rate_base = config.learning_rate_base\ndecay_rate = config.decay_rate\nheight, width = config.height, config.width\ntrain_dir = config.train_dir\nfine_tune = config.fine_tune\ntrain_all_layers = config.train_all_layers\ncheckpoint_path = config.checkpoint_path\n\ntrain_data, train_label, valid_data, valid_label, train_n, valid_n = read_inputs(sample_dir, train_rate, batch_size)\n\nprint(train_data, train_label, valid_data, valid_label)\n\nif not os.path.isdir(train_dir):\n os.makedirs(train_dir)\n\ntrain(train_data, train_label, valid_data, valid_label, train_n, train_dir, num_classes, batch_size,\n arch_model, learning_r_decay, learning_rate_base, decay_rate, dropout_prob, epoch,\n checkpoint_exclude_scopes, fine_tune, train_all_layers, checkpoint_path, g_parameter)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"340483977","text":"class Solution:\n def searchMatrix(self, matrix, target):\n if sum(matrix, []) == []:\n \treturn False\n row = len(matrix)\n col = len(matrix[0])\n\n # Find row\n if matrix[row//2][0] > target:\n \trowend = row // 2\n \trowstart = 0\n elif matrix[row//2][0] < target:\n \trowstart = row // 2\n \trowend = row - 1\n else:\n \treturn True\n while rowend - rowstart > 1:\n \trowmid = (rowstart + rowend) // 2\n \tif matrix[rowmid][0] > target:\n \t\trowend = rowmid\n \telif matrix[rowmid][0] < target:\n \t\trowstart = rowmid\n \telse:\n \t\treturn True\n # rowend - rowstart == 1\n if matrix[rowend][0] == target:\n \treturn True\n elif matrix[rowend][0] < target:\n \trowstart = rowend\n # Find col\n colstart = 0\n colend = col - 1\n while colstart <= colend:\n \tcolmid = (colstart + colend) // 2\n \tif matrix[rowstart][colmid] < target:\n \t\tcolstart = colmid + 1\n \telif matrix[rowstart][colmid] > target:\n \t\tcolend = colmid - 1\n \telse:\n \t\treturn True\n\n return False","sub_path":"Leetcode/leetcode74 搜索二维矩阵.py","file_name":"leetcode74 搜索二维矩阵.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"321160194","text":"import dataCreate\nimport numpy as np\nimport model\nimport matplotlib.pyplot as plt\nimport datetime\n\nmarket_info = dataCreate.createDataSet()\n\nfor coins in ['_x', '_y']:\n kwargs = {'close_off_high' + coins: lambda x: 2 * (x['High' + coins] - x['Close**' + coins]) / (x['High' + coins] - x['Low' + coins]) - 1,\n 'volatility' + coins: lambda x: (x['High' + coins] - x['Low' + coins]) / (x['Open*' + coins])}\n market_info = market_info.assign(**kwargs)\n\nmodel_data = market_info[['Date'] + [metric + coin for metric in ['Close**', 'Volume', 'close_off_high', 'volatility'] for coin in ['_x', '_y']]]\n# 時間順になるようにソートする\nmodel_data = model_data.sort_values(by='Date')\nprint(\"**********model_dataのヘッダ情報**********\")\nprint(model_data.head())\n\n# dateの列を削除\nsplit_date = '2017-10-01'\n# split_dateを定義して、それ未満の場合はtraining_set, それ以上の場合はtest_setに代入する\ntraining_set, test_set = model_data[model_data['Date'] < split_date], model_data[model_data['Date'] >= split_date]\n# dropは指定の行or列を削除するdrop(labels, axis)\n# axis=0は行, axis=1は列\ntraining_set = training_set.drop('Date', 1)\ntest_set = test_set.drop('Date', 1)\n\n# データのまとまりを10日に設定\nwindow_len = 10\nnorm_cols = [metric + coin for metric in ['Close**', 'Volume'] for coin in ['_x', '_y']]\n\n# training_set, test_setをwindow_lenで分ける\nLSTM_training_inputs = []\nfor i in range(len(training_set) - window_len):\n temp_set = training_set[i:(i + window_len)].copy()\n for col in norm_cols:\n temp_set.loc[:, col] = temp_set[col] / temp_set[col].iloc[0] - 1\n LSTM_training_inputs.append(temp_set)\nLSTM_training_outputs = (training_set['Close**_y'][window_len:].values / training_set['Close**_y'][:-window_len].values) - 1\n\nLSTM_test_inputs = []\nfor i in range(len(test_set) - window_len):\n temp_set = test_set[i:(i + window_len)].copy()\n for col in norm_cols:\n temp_set.loc[:, col] = temp_set[col] / temp_set[col].iloc[0] - 1\n LSTM_test_inputs.append(temp_set)\nLSTM_test_outputs = (test_set['Close**_y'][window_len:].values / test_set['Close**_y'][:-window_len].values) - 1\n\n# trainint_dataのインプットデータを確認\nprint(\"**********LSTM_training_inputs確認(データフレーム)**********\")\nprint(LSTM_training_inputs[0])\n\n# PandasのdataFrameからNumpy配列へ変換\nLSTM_training_inputs = [np.array(LSTM_training_input) for LSTM_training_input in LSTM_training_inputs]\nLSTM_training_inputs = np.array(LSTM_training_inputs)\nLSTM_test_inputs = [np.array(LSTM_test_input) for LSTM_test_input in LSTM_test_inputs]\nLSTM_test_inputs = np.array(LSTM_test_inputs)\n\n# ランダムシードの設定(randomで生成される数値の固定)\nnp.random.seed(202)\n\n# モデルの構築\neth_model = model.createModel(LSTM_training_inputs, output_size=1, neurons = 20)\n\n# モデルのアウトプットは次の窓の10番目の価格(正規化されている)\nLSTM_training_outputs = (training_set['Close**_y'][window_len:].values / training_set['Close**_y'][:-window_len].values) - 1\n# データを流してフィッティング\neth_history = eth_model.fit(LSTM_training_inputs, LSTM_training_outputs, epochs=50, batch_size=1, verbose=2, shuffle=True)\n\n# lossの変化をプロットして確認\nfig, ax1 = plt.subplots(1, 1)\nprint(\"eth_history.epoch\\n\" + str(eth_history.epoch))\nprint(type(eth_history))\nprint(eth_history.history)\nax1.plot(eth_history.epoch, eth_history.history['loss'])\nax1.set_title(\"TrainingError\")\nax1.set_ylabel('Mean Absolute Error(MAE)', fontsize=12)\nax1.set_xlabel(\"# Epochs\", fontsize=12)\nplt.show()\n\n\n# プロッティングと予測の処理を一緒に行う\nfrom mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes\nfrom mpl_toolkits.axes_grid1.inset_locator import mark_inset\n\nfig, ax1 = plt.subplots(1, 1)\nax1.set_xticks([datetime.date(i, j, 1) for i in range(2013, 2019) for j in [1, 5, 9]])\nax1.set_xticklabels([datetime.date(i, j, 1).strftime('%d %y') for i in range(2013, 2019) for j in [1, 5, 9]])\nax1.plot(model_data[model_data['Date'] < split_date]['Date'][window_len:].astype(datetime.datetime),\n training_set['Close**_y'][window_len:], label='Actual')\nax1.plot(model_data[model_data['Date']< split_date]['Date'][window_len:].astype(datetime.datetime),\n ((np.transpose(eth_model.predict(LSTM_training_inputs))+1) * training_set['Close**_y'].values[:-window_len])[0],\n label='Predicted')\nax1.set_title('Training Set: Single Timepoint Prediction')\nax1.set_ylabel('Ethereum Price ($)',fontsize=12)\nax1.legend(bbox_to_anchor=(0.15, 1), loc=2, borderaxespad=0., prop={'size': 14})\nax1.annotate('MAE: %.4f'%np.mean(np.abs((np.transpose(eth_model.predict(LSTM_training_inputs))+1)-\\\n (training_set['Close**_y'].values[window_len:])/(training_set['Close**_y'].values[:-window_len]))),\n xy=(0.75, 0.9), xycoords='axes fraction',\n xytext=(0.75, 0.9), textcoords='axes fraction')\n# 下記コードはこちらのURL参照しました:http://akuederle.com/matplotlib-zoomed-up-inset\naxins = zoomed_inset_axes(ax1, 3.35, loc=10)\naxins.set_xticks([datetime.date(i,j,1) for i in range(2013,2019) for j in [1, 5, 9]])\naxins.plot(model_data[model_data['Date']< split_date]['Date'][window_len:].astype(datetime.datetime),\n training_set['Close**_y'][window_len:], label='Actual')\naxins.plot(model_data[model_data['Date']< split_date]['Date'][window_len:].astype(datetime.datetime),\n ((np.transpose(eth_model.predict(LSTM_training_inputs))+1) * training_set['Close**_y'].values[:-window_len])[0],\n label='Predicted')\naxins.set_xlim([datetime.date(2017, 3, 1), datetime.date(2017, 5, 1)])\naxins.set_ylim([10, 60])\naxins.set_xticklabels('')\nmark_inset(ax1, axins, loc1=1, loc2=3, fc=\"none\", ec=\"0.5\")\nplt.show()\n\n# LSTMモデルがみたことの無い時期の予測\nfig, ax1 = plt.subplots(1, 1)\nax1.set_xticks([datetime.date(2017, i + 1, 1) for i in range(12)])\nax1.set_xticklabels([datetime.date(2017,i+1,1).strftime('%b %d %Y') for i in range(12)])\nax1.plot(model_data[model_data['Date'] >= split_date]['Date'][window_len:].astype(datetime.datetime),\n test_set['Close**_y'][window_len:], label='Actual')\nax1.plot(model_data[model_data['Date'] >= split_date]['Date'][window_len:].astype(datetime.datetime),\n ((np.transpose(eth_model.predict(LSTM_test_inputs))+1) * test_set['Close**_y'].values[:-window_len])[0],\n label='Predicted')\nax1.annotate('MAE: %.4f'%np.mean(np.abs((np.transpose(eth_model.predict(LSTM_test_inputs))+1)-\\\n (test_set['Close**_y'].values[window_len:])/(test_set['Close**_y'].values[:-window_len]))),\n xy=(0.75, 0.9), xycoords='axes fraction',\n xytext=(0.75, 0.9), textcoords='axes fraction')\nax1.set_title('Test Set: Single Timepoint Prediction', fontsize=13)\nax1.set_ylabel('Ethereum Price ($)',fontsize=12)\nax1.legend(bbox_to_anchor=(0.1, 1), loc=2, borderaxespad=0., prop={'size': 14})\nplt.show()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"390479545","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/jsonstore/client.py\n# Compiled at: 2013-03-01 05:08:36\nimport sys\nfrom urlparse import urljoin\nfrom urllib import quote\nfrom datetime import datetime\nfrom hashlib import sha1\nimport requests\nfrom simplejson import dumps, loads\nfrom uuid import uuid4\nimport iso8601\nfrom jsonstore.rest import OpEncoder\nfrom jsonstore.exceptions import ConflictError\n\nclass EntryManager(object):\n\n def __init__(self, url, auth=None):\n if not url.endswith('/'):\n url += '/'\n self.store = url\n self.auth = auth\n\n def create(self, entry=None, **kwargs):\n \"\"\"\n Add a new entry to the store.\n\n \"\"\"\n if entry is None:\n entry = kwargs\n else:\n assert isinstance(entry, dict), 'Entry must be instance of ``dict``!'\n entry.update(kwargs)\n id_ = entry.setdefault('__id__', str(uuid4()))\n url = urljoin(self.store, str(id_))\n r = requests.post(url, data=dumps(entry, cls=OpEncoder), auth=self.auth)\n if r.status_code == 409:\n raise ConflictError('Conflict, the id \"%s\" already exists!' % id_)\n else:\n r.raise_for_status()\n entry = loads(r.content)\n entry['__updated__'] = iso8601.parse_date(entry['__updated__'])\n return entry\n\n def delete(self, id_):\n \"\"\"\n Delete a single entry from the store.\n\n \"\"\"\n url = urljoin(self.store, str(id_))\n r = requests.delete(url, auth=self.auth)\n\n def update(self, entry=None, old=None, **kwargs):\n \"\"\"\n Conditionally update an entry.\n\n \"\"\"\n if entry is None:\n entry = kwargs\n else:\n assert isinstance(entry, dict), 'Entry must be instance of ``dict``!'\n entry.update(kwargs)\n id_ = entry['__id__']\n url = urljoin(self.store, str(id_))\n headers = {}\n if old is not None:\n headers['If-Match'] = '%s' % sha1(dumps(old, cls=OpEncoder, indent=4)).hexdigest()\n r = requests.put(url, data=dumps(entry, cls=OpEncoder), headers=headers, auth=self.auth)\n if r.status_code == 412:\n raise ConflictError('Pre-condition failed!')\n else:\n r.raise_for_status()\n entry = loads(r.content)\n entry['__updated__'] = iso8601.parse_date(entry['__updated__'])\n return entry\n\n def search(self, obj=None, size=None, offset=0, count=False, **kwargs):\n \"\"\"\n Search database using a JSON object.\n\n \"\"\"\n if obj is None:\n obj = kwargs\n else:\n assert isinstance(obj, dict), 'Search key must be instance of ``dict``!'\n obj.update(kwargs)\n params = {}\n if size is not None:\n params['size'] = size\n if offset:\n params['offset'] = offset\n url = urljoin(self.store, quote(dumps(obj, cls=OpEncoder)))\n if count:\n r = requests.head(url, params=params, auth=self.auth)\n return int(r.headers['X-ITEMS'])\n else:\n r = requests.get(url, params=params, auth=self.auth)\n entries = r.json()\n for entry in entries:\n entry['__updated__'] = iso8601.parse_date(entry['__updated__'])\n\n return entries\n return","sub_path":"pycfiles/jsonstore-1.3.1-py2.7/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"135812310","text":"import ticker as yf\r\nfrom typing import Optional, Tuple, List\r\n\r\ndef get_price_change(\r\n ticker: str,\r\n lookback: Optional[str] = \"2d\"\r\n) -> Tuple[float, List]:\r\n \"\"\"Gets price change for a particular ticker\r\n Args:\r\n ticker (str): Ticker of interest. E.g., BABA or Y92.SI\r\n lookback (str, optional): Price change period to evaluate on.\r\n Defaults to \"2d\".\r\n Returns:\r\n Tuple[float, List]: Percentage change in float.\r\n \"\"\"\r\n stock = yf.Ticker(ticker)\r\n hist = stock.history(period=lookback).Close.values.tolist()\r\n if len(hist) != int(lookback[0]):\r\n lookback = f\"{int(lookback[0])+1}d\"\r\n hist = stock.history(period=lookback).Close.values.tolist()\r\n\r\n if not hist:\r\n return f\"Couldn't find history for ticker {ticker}\", None\r\n pct_chng = ((hist[-1] - hist[0]) / hist[0]) * 100\r\n return np.round(pct_chng, 2), hist\r\n","sub_path":"ticker.py","file_name":"ticker.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"81843246","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport geom_fcns as geo\nimport render_fcns as ren\nimport os \nimport sys\n##########################################################################################\n# investigation #4 -- messier example with asynchronous contraction \n##########################################################################################\nfolder_name = 'synthetic_data_S4'\nif not os.path.exists(folder_name):\n\tos.makedirs(folder_name)\n\n##########################################################################################\n# . -- .\n# * *\n# * _ *\n# * | \\ | | *\n#\t * | | | | *\n# * | / | | *\n#\t * | \\ | | *\n# * | | | | *\n# * |_/ \\____/ *\n# * *\n# ' -- '\n##########################################################################################\n\n##########################################################################################\n# ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ #\n# create geometry \n# ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ #\n##########################################################################################\n\n##########################################################################################\n# define undeformed geometry \n##########################################################################################\n# seg 1 -- ellipse -- outer ring\nx_cent = 15; y_cent = 3; z_cent = .1\nellipse_a = 20; ellipse_b = 25; th_min = .1; th_max = np.pi*2.0\nnum_sarc = 40\nsl_1 = geo.sarc_list_ellipse_seg(x_cent, y_cent, z_cent, ellipse_a, ellipse_b, th_min, th_max, num_sarc)\n\n# seg 2 -- inner\nx_cent = 10; y_cent = -10; z_cent = 0\nellipse_a = 5; ellipse_b = 9; th_min = .2; th_max = np.pi - .1\nnum_sarc = 10\nsl_2 = geo.sarc_list_ellipse_seg(x_cent, y_cent, z_cent, ellipse_a, ellipse_b, th_min, th_max, num_sarc)\n\n# seg 3 -- inner\nx_cent = 20; y_cent = -10; z_cent = 0\nellipse_a = 5; ellipse_b = 9; th_min = .2; th_max = np.pi - .1\nnum_sarc = 10\nsl_3 = geo.sarc_list_ellipse_seg(x_cent, y_cent, z_cent, ellipse_a, ellipse_b, th_min, th_max, num_sarc)\n\n# seg 4 -- inner\nx_end_1 = 5; y_end_1 = -10; z_end_1 = .1\nx_end_2 = 25; y_end_2 = -10; z_end_2 = -.1\nnum_sarc = 10\nsl_4 = geo.sarc_list_line_seg(x_end_1,y_end_1,z_end_1,x_end_2,y_end_2,z_end_2,num_sarc)\n\n# seg 5 -- inner\nx_cent = 3; y_cent = 10.5; z_cent = 0\nellipse_a = 20; ellipse_b = 7; th_min = .1; th_max = np.pi/2.0 \nnum_sarc = 10\nsl_5 = geo.sarc_list_ellipse_seg(x_cent, y_cent, z_cent, ellipse_a, ellipse_b, th_min, th_max, num_sarc)\n\n# seg 6 -- inner\nx_cent = 3; y_cent = 10; z_cent = 0\nellipse_a = 20; ellipse_b = 7; th_min = -.1; th_max = -np.pi/2.0 \nnum_sarc = 10\nsl_6 = geo.sarc_list_ellipse_seg(x_cent, y_cent, z_cent, ellipse_a, ellipse_b, th_min, th_max, num_sarc)\n\nsarc_list_A = sl_1\n\nsarc_list_B = sl_2 + sl_3 + sl_4 + sl_5 + sl_6 \n\nsarc_list = sarc_list_A + sarc_list_B\n\n##########################################################################################\n# define and apply the deformation gradient F_homog_iso\n##########################################################################################\nval_list_A = []\nv = .003\nv2 = 40\nfor kk in range(0,15): val_list_A.append(kk*v)\nfor kk in range(0,5): val_list_A.append(15*v) \nfor kk in range(0,15): val_list_A.append(15*v - kk*v)\nfor kk in range(0,15): val_list_A.append(kk*v)\nfor kk in range(0,5): val_list_A.append(15*v) \nfor kk in range(0,15): val_list_A.append(15*v - kk*v)\nfor kk in range(0,5): val_list_A.append(15*v) \nfor kk in range(0,5): val_list_A.append(kk*v)\n\nx0 = 15; y0 = 0; z0 = 0\nx_zone_1 = 10; x_zone_2 = 20\nF_fcn = geo.transform_helper_F_homog_iso\nsarc_list_ALL_A = geo.sarc_list_ALL_transform_F( sarc_list_A, val_list_A, x0, y0, z0, x_zone_1, x_zone_2, F_fcn)\n\nval_list_B = [] \nfor kk in range(0,int(v2*2)): val_list_B.append(np.sin(kk/20)*.1)\n\nF_fcn = geo.transform_helper_F_nonhomog_aniso\nsarc_list_ALL_B = geo.sarc_list_ALL_transform_F( sarc_list_B, val_list_B, x0, y0, z0, x_zone_1, x_zone_2, F_fcn)\n\nsarc_list_ALL = []\nfor kk in range(0,len(val_list_A)):\n\tSL = sarc_list_ALL_A[kk] + sarc_list_ALL_B[kk]\n\tsarc_list_ALL.append(SL)\n\n##########################################################################################\n# save geometry \n##########################################################################################\ngeo.plot_3D_geom(folder_name,sarc_list,'k','r-')\ngeo.pickle_sarc_list_ALL(folder_name,sarc_list_ALL)\nsarc_array, sarc_array_normalized, x_pos_array, y_pos_array = geo.get_ground_truth(sarc_list_ALL)\ngeo.plot_ground_truth_timeseries(sarc_array_normalized, folder_name)\n\n##########################################################################################\n# ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ #\n# render\n# ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ # ~ #\n##########################################################################################\n\nis_normal_radius = True; is_normal_height = True\navg_radius = 2.0; avg_height = 1\nparameter_radius = 0.25; parameter_height = 0.1\nradius_list_A, height_list_A = ren.z_disk_props( sarc_list_A, is_normal_radius, is_normal_height, avg_radius, avg_height, parameter_radius, parameter_height)\n\nis_normal_radius = True; is_normal_height = True\navg_radius = 2.0 / 3.0; avg_height = .5\nparameter_radius = 0.005; parameter_height = 0.002\nradius_list_B, height_list_B = ren.z_disk_props( sarc_list_B, is_normal_radius, is_normal_height, avg_radius, avg_height, parameter_radius, parameter_height)\n\nradius_list = radius_list_A + radius_list_B\nheight_list = height_list_A + height_list_B \n\nnum_frames = len(val_list_A)\n\nimg_list = []\n\nfor frame in range(0,num_frames):\n\tsarc_list = sarc_list_ALL[frame]\n\t# only keep sarcomeres that are within the frame\n\tz_lower = -10; z_upper = 10 \n\tsarc_list_in_slice, radius_list_in_slice, height_list_in_slice = ren.sarc_list_in_slice_fcn(sarc_list, radius_list, height_list, z_lower, z_upper)\n\t# turn into a 3D matrix of points\n\tx_lower = -15; x_upper = 40\n\ty_lower = -30; y_upper = 40\n\tz_lower = -5; z_upper = 5\n\tdim_x = int((x_upper-x_lower)/2.0*6); dim_y = int((y_upper-y_lower)/2.0*6)\n\tdim_z = int(4)\n\tmean_rad = radius_list_in_slice; mean_hei = height_list_in_slice\n\tbound_x = 10; bound_y = 10; bound_z = 10; val = 100\n\tmatrix = ren.slice_to_matrix(sarc_list_in_slice,dim_x,dim_y,dim_z,x_lower,x_upper,y_lower,y_upper,z_lower,z_upper, mean_rad, mean_hei, bound_x, bound_y, bound_z,val)\n\t# add random \n\tmean = 10; std = 1\n\tmatrix = ren.random_val(matrix,mean,std)\n\t# add blur\n\tsig = 1\n\tmatrix_blur = ren.matrix_gaussian_blur_fcn(matrix,sig)\n\t# convert matrix to image \n\tslice_lower = 0; slice_upper = 4\n\timage = ren.matrix_to_image(matrix_blur,slice_lower,slice_upper)\n\t# image list \n\timg_list.append(image)\n\n\nren.save_img_stills(img_list,folder_name)\nren.still_to_avi(folder_name,num_frames,False)\nren.ground_truth_movie(folder_name,num_frames,img_list,sarc_array_normalized, x_pos_array, y_pos_array,x_lower,x_upper,y_lower,y_upper,dim_x,dim_y)\n#ren.still_to_avi(folder_name_render,num_frames,True)\n\nnp.savetxt(folder_name + '/' + folder_name + '_GT_sarc_array_normalized.txt',sarc_array_normalized)\nnp.savetxt(folder_name + '/' + folder_name + '_GT_x_pos_array.txt',(x_pos_array - x_lower)/(x_upper-x_lower)*dim_x)\nnp.savetxt(folder_name + '/' + folder_name + '_GT_y_pos_array.txt',(y_pos_array - y_lower)/(y_upper-y_lower)*dim_y)\n\n\n","sub_path":"Generate_Synthetic_Data/generate_synthetic_data_S4.py","file_name":"generate_synthetic_data_S4.py","file_ext":"py","file_size_in_byte":7669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"550523118","text":"import networkx as nx\nfrom dbt.logger import GLOBAL_LOGGER as logger\n\nfrom dbt.utils import is_enabled, get_materialization, coalesce\nfrom dbt.node_types import NodeType\nfrom dbt.contracts.graph.parsed import ParsedNode\nimport dbt.exceptions\n\nSELECTOR_PARENTS = '+'\nSELECTOR_CHILDREN = '+'\nSELECTOR_GLOB = '*'\nSELECTOR_CHILDREN_AND_ANCESTORS = '@'\nSELECTOR_DELIMITER = ':'\n\n\nclass SelectionCriteria(object):\n def __init__(self, node_spec):\n self.raw = node_spec\n self.select_children = False\n self.select_parents = False\n self.select_childrens_parents = False\n self.selector_type = SELECTOR_FILTERS.FQN\n\n if node_spec.startswith(SELECTOR_CHILDREN_AND_ANCESTORS):\n self.select_childrens_parents = True\n node_spec = node_spec[1:]\n\n if node_spec.startswith(SELECTOR_PARENTS):\n self.select_parents = True\n node_spec = node_spec[1:]\n\n if node_spec.endswith(SELECTOR_CHILDREN):\n self.select_children = True\n node_spec = node_spec[:-1]\n\n if self.select_children and self.select_childrens_parents:\n raise dbt.exceptions.RuntimeException(\n 'Invalid node spec {} - \"@\" prefix and \"+\" suffix are '\n 'incompatible'.format(self.raw)\n )\n\n if SELECTOR_DELIMITER in node_spec:\n selector_parts = node_spec.split(SELECTOR_DELIMITER, 1)\n self.selector_type, self.selector_value = selector_parts\n else:\n self.selector_value = node_spec\n\n\nclass SELECTOR_FILTERS(object):\n FQN = 'fqn'\n TAG = 'tag'\n SOURCE = 'source'\n\n\ndef split_specs(node_specs):\n specs = set()\n for spec in node_specs:\n parts = spec.split(\" \")\n specs.update(parts)\n\n return specs\n\n\ndef get_package_names(graph):\n return set([node.split(\".\")[1] for node in graph.nodes()])\n\n\ndef is_selected_node(real_node, node_selector):\n for i, selector_part in enumerate(node_selector):\n\n is_last = (i == len(node_selector) - 1)\n\n # if we hit a GLOB, then this node is selected\n if selector_part == SELECTOR_GLOB:\n return True\n\n # match package.node_name or package.dir.node_name\n elif is_last and selector_part == real_node[-1]:\n return True\n\n elif len(real_node) <= i:\n return False\n\n elif real_node[i] == selector_part:\n continue\n\n else:\n return False\n\n # if we get all the way down here, then the node is a match\n return True\n\n\ndef _node_is_match(qualified_name, package_names, fqn):\n \"\"\"Determine if a qualfied name matches an fqn, given the set of package\n names in the graph.\n\n :param List[str] qualified_name: The components of the selector or node\n name, split on '.'.\n :param Set[str] package_names: The set of pacakge names in the graph.\n :param List[str] fqn: The node's fully qualified name in the graph.\n \"\"\"\n if len(qualified_name) == 1 and fqn[-1] == qualified_name[0]:\n return True\n\n if qualified_name[0] in package_names:\n if is_selected_node(fqn, qualified_name):\n return True\n\n for package_name in package_names:\n local_qualified_node_name = [package_name] + qualified_name\n if is_selected_node(fqn, local_qualified_node_name):\n return True\n\n return False\n\n\ndef warn_if_useless_spec(spec, nodes):\n if len(nodes) > 0:\n return\n\n msg = (\n \"* Spec='{}' does not identify any models\"\n .format(spec['raw'])\n )\n dbt.exceptions.warn_or_error(msg, log_fmt='{} and was ignored\\n')\n\n\nclass NodeSelector(object):\n def __init__(self, linker, manifest):\n self.linker = linker\n self.manifest = manifest\n\n def _node_iterator(self, graph, exclude, include):\n for node in graph.nodes():\n real_node = self.manifest.nodes[node]\n if include is not None and real_node.resource_type not in include:\n continue\n if exclude is not None and real_node.resource_type in exclude:\n continue\n yield node, real_node\n\n def parsed_nodes(self, graph):\n return self._node_iterator(\n graph,\n exclude=(NodeType.Source,),\n include=None)\n\n def source_nodes(self, graph):\n return self._node_iterator(\n graph,\n exclude=None,\n include=(NodeType.Source,))\n\n def get_nodes_by_qualified_name(self, graph, qualified_name_selector):\n \"\"\"Yield all nodes in the graph that match the qualified_name_selector.\n\n :param str qualified_name_selector: The selector or node name\n \"\"\"\n qualified_name = qualified_name_selector.split(\".\")\n package_names = get_package_names(graph)\n for node, real_node in self.parsed_nodes(graph):\n if _node_is_match(qualified_name, package_names, real_node.fqn):\n yield node\n\n def get_nodes_by_tag(self, graph, tag_name):\n \"\"\" yields nodes from graph that have the specified tag \"\"\"\n for node, real_node in self.parsed_nodes(graph):\n if tag_name in real_node.tags:\n yield node\n\n def get_nodes_by_source(self, graph, source_full_name):\n \"\"\"yields nodes from graph are the specified source.\"\"\"\n parts = source_full_name.split('.')\n if len(parts) == 1:\n target_source, target_table = parts[0], None\n elif len(parts) == 2:\n target_source, target_table = parts\n else: # len(parts) > 2 or len(parts) == 0\n msg = (\n 'Invalid source selector value \"{}\". Sources must be of the '\n 'form `${{source_name}}` or '\n '`${{source_name}}.${{target_name}}`'\n ).format(source_full_name)\n raise dbt.exceptions.RuntimeException(msg)\n\n for node, real_node in self.source_nodes(graph):\n if target_source not in (real_node.source_name, SELECTOR_GLOB):\n continue\n if target_table in (None, real_node.name, SELECTOR_GLOB):\n yield node\n\n def select_childrens_parents(self, graph, selected):\n ancestors_for = self.select_children(graph, selected) | selected\n return self.select_parents(graph, ancestors_for) | ancestors_for\n\n def select_children(self, graph, selected):\n descendants = set()\n for node in selected:\n descendants.update(nx.descendants(graph, node))\n return descendants\n\n def select_parents(self, graph, selected):\n ancestors = set()\n for node in selected:\n ancestors.update(nx.ancestors(graph, node))\n return ancestors\n\n def collect_models(self, graph, selected, spec):\n additional = set()\n if spec.select_childrens_parents:\n additional.update(self.select_childrens_parents(graph, selected))\n if spec.select_parents:\n additional.update(self.select_parents(graph, selected))\n if spec.select_children:\n additional.update(self.select_children(graph, selected))\n return additional\n\n def collect_tests(self, graph, model_nodes):\n test_nodes = set()\n for node in model_nodes:\n # include tests that depend on this node. if we aren't running\n # tests, they'll be filtered out later.\n child_tests = [n for n in graph.successors(node)\n if self.manifest.nodes[n].resource_type ==\n NodeType.Test]\n test_nodes.update(child_tests)\n return test_nodes\n\n def get_nodes_from_spec(self, graph, spec):\n filter_map = {\n SELECTOR_FILTERS.FQN: self.get_nodes_by_qualified_name,\n SELECTOR_FILTERS.TAG: self.get_nodes_by_tag,\n SELECTOR_FILTERS.SOURCE: self.get_nodes_by_source,\n }\n\n filter_method = filter_map.get(spec.selector_type)\n\n if filter_method is None:\n valid_selectors = \", \".join(filter_map.keys())\n logger.info(\"The '{}' selector specified in {} is invalid. Must \"\n \"be one of [{}]\".format(\n spec.selector_type,\n spec.raw,\n valid_selectors))\n\n return set()\n\n collected = set(filter_method(graph, spec.selector_value))\n collected.update(self.collect_models(graph, collected, spec))\n collected.update(self.collect_tests(graph, collected))\n\n return collected\n\n def select_nodes(self, graph, raw_include_specs, raw_exclude_specs):\n selected_nodes = set()\n\n for raw_spec in split_specs(raw_include_specs):\n spec = SelectionCriteria(raw_spec)\n included_nodes = self.get_nodes_from_spec(graph, spec)\n selected_nodes.update(included_nodes)\n\n for raw_spec in split_specs(raw_exclude_specs):\n spec = SelectionCriteria(raw_spec)\n excluded_nodes = self.get_nodes_from_spec(graph, spec)\n selected_nodes.difference_update(excluded_nodes)\n\n return selected_nodes\n\n def _is_graph_member(self, node_name):\n node = self.manifest.nodes[node_name]\n if node.resource_type == NodeType.Source:\n return True\n return not node.get('empty') and is_enabled(node)\n\n def get_valid_nodes(self, graph):\n return [\n node_name for node_name in graph.nodes()\n if self._is_graph_member(node_name)\n ]\n\n def _is_match(self, node_name, resource_types, tags, required):\n node = self.manifest.nodes[node_name]\n if node.resource_type not in resource_types:\n return False\n tags = set(tags)\n if tags and not bool(set(node.tags) & tags):\n # there are tags specified but none match\n return False\n for attr in required:\n if not getattr(node, attr):\n return False\n return True\n\n def get_selected(self, include, exclude, resource_types, tags, required):\n graph = self.linker.graph\n\n include = coalesce(include, ['*'])\n exclude = coalesce(exclude, [])\n tags = coalesce(tags, [])\n\n to_run = self.get_valid_nodes(graph)\n filtered_graph = graph.subgraph(to_run)\n selected_nodes = self.select_nodes(filtered_graph, include, exclude)\n\n filtered_nodes = set()\n for node_name in selected_nodes:\n if self._is_match(node_name, resource_types, tags, required):\n filtered_nodes.add(node_name)\n\n return filtered_nodes\n\n def is_ephemeral_model(self, node):\n is_model = node.get('resource_type') == NodeType.Model\n is_ephemeral = get_materialization(node) == 'ephemeral'\n return is_model and is_ephemeral\n\n def get_ancestor_ephemeral_nodes(self, selected_nodes):\n node_names = {}\n for node_id in selected_nodes:\n if node_id not in self.manifest.nodes:\n continue\n node = self.manifest.nodes[node_id]\n # sources don't have ancestors and this results in a silly select()\n if node.resource_type == NodeType.Source:\n continue\n node_names[node_id] = node.name\n\n include_spec = [\n '+{}'.format(node_names[node])\n for node in selected_nodes if node in node_names\n ]\n if not include_spec:\n return set()\n\n all_ancestors = self.select_nodes(self.linker.graph, include_spec, [])\n\n res = []\n for ancestor in all_ancestors:\n ancestor_node = self.manifest.nodes.get(ancestor, None)\n\n if ancestor_node and self.is_ephemeral_model(ancestor_node):\n res.append(ancestor)\n\n return set(res)\n\n def select(self, query):\n include = query.get('include')\n exclude = query.get('exclude')\n resource_types = query.get('resource_types')\n tags = query.get('tags')\n required = query.get('required', ())\n\n selected = self.get_selected(include, exclude, resource_types, tags,\n required)\n\n addins = self.get_ancestor_ephemeral_nodes(selected)\n\n return selected | addins\n","sub_path":"core/dbt/graph/selector.py","file_name":"selector.py","file_ext":"py","file_size_in_byte":12297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"546372842","text":"\n\nfrom django.core.management.base import BaseCommand, CommandError\nfrom stations.models import Station, Line, StationConnection, StationCode\nfrom trains.models import Train\nfrom wmata import api\nfrom pprint import pprint\nfrom django.db import transaction\nimport sys\n\n\nclass Command(BaseCommand):\n help = 'Imports stations data'\n\n def add_arguments(self, parser):\n \"\"\"\n File to read in\n \"\"\"\n pass\n\n def handle(self, *args, **options):\n \"\"\"\n Import the station data\n \"\"\"\n\n with transaction.atomic():\n\n # Delete old trains\n # TODO: update old trains with new locations\n Train.objects.all()\n\n trains_data = api.get_trains_prediction()\n for train_data in trains_data['Trains']:\n\n line_code = train_data['Line']\n\n try:\n # get line by code\n line = Line.objects.get(code=line_code)\n except Line.DoesNotExist:\n continue\n\n # determine which direction the train is going\n destination_station = StationCode.get_station_by_code(train_data['DestinationCode'])\n traveling_forward = line.end_station == destination_station\n\n # station the train is traveling to\n target_station = StationCode.get_station_by_code(train_data['LocationCode'])\n\n # number of cars on train\n num_cars = train_data['Car']\n\n # current eta\n eta_min = train_data['Min']\n\n # get the connection the train is on\n try:\n if traveling_forward:\n connection = StationConnection.objects.get(next_station=target_station, line=line)\n else:\n connection = StationConnection.objects.get(prev_station=target_station, line=line)\n except StationConnection.DoesNotExist:\n\n # TODO: Currently skipping trains coming to the start of an end node\n continue \n\n # reached destination\n if eta_min == 'BRD' or eta_min == 'ARR':\n connection_progress = 1.0\n else:\n try:\n # interpolate based on eta\n connection_progress = float(eta_min) / float(connection.rail_time_min)\n except ValueError:\n connection_progress = 0.0\n\n # make sure train is in the connection\n if connection_progress <= 1.0:\n train = Train(line=line, final_station=destination_station, next_station_eta_min=eta_min,\n current_connection=connection, num_cars=num_cars, connection_progress=connection_progress,\n traveling_forward=traveling_forward)\n train.save()\n\n\n \"\"\"\n # is traveling along connection towards next station\n # as opposed to towards prev station\n traveling_forward = models.BooleanField()\n\n # 0.0 to 1.0 value along StationConnection based on next_station_eta\n connection_progress = FloatField()\n\n # traveling line\n line = models.ForeignKey(Line, on_delete=models.CASCADE, related_name='trains')\n\n # number of cars\n num_cars = models.PositiveIntegerField()\n\n # final destination\n final_station = models.ForeignKey(Station, on_delete=models.CASCADE, related_name='ending_trains')\n\n # next station\n current_connection = models.ForeignKey(StationConnection, on_delete=models.CASCADE)\n next_station_eta_min = models.CharField(max_length=10)\n\n class Meta:\n ordering = ('line', 'current_connection', 'name', )\n \"\"\"","sub_path":"trains/management/commands/update_trains.py","file_name":"update_trains.py","file_ext":"py","file_size_in_byte":3873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"138189644","text":"from rosalind.core.rosalindsolution import RosalindSolution\nfrom rosalind.solutions import problem_order\nfrom rosalind.utils.iterators.translator import Translator\nfrom rosalind.utils.parsers.fastaparser import FastaParser\n\n\nclass RosalindImplementation(RosalindSolution):\n def __init__(self):\n super().__init__()\n self.problem_name = self.get_pname(__file__)\n self.problem_number = problem_order.index(self.problem_name)\n\n def solve(self, instream, outstream):\n parser = FastaParser(instream)\n transcript = next(parser).read\n for fa in parser:\n transcript = transcript.replace(fa.read, '')\n print(*Translator(transcript.replace('T', 'U')), sep='',\n file=outstream)\n","sub_path":"rosalind/solutions/splc.py","file_name":"splc.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"542442293","text":"\"\"\"\nMIT License\n\nCopyright (c) 2010, Ben Ogle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\n\nimport subprocess\nimport StringIO\nimport common\nfrom common import p\n\nYUICOMPRESSOR_PATH = 'YUICOMPRESSOR_PATH'\n\nTYPE_SWITCH = '--type'\nTYPE_JS = 'js'\nTYPE_CSS = 'css'\n\ndef compress(data, type=TYPE_JS, level=None):\n \"\"\"\n Compresses a wad of data and gives it back to you.\n \"\"\"\n COMPRESSOR_COMMAND = common.java_command(YUICOMPRESSOR_PATH)\n \n proc = subprocess.Popen(COMPRESSOR_COMMAND + [TYPE_SWITCH, type], stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n compressed_data, error = proc.communicate(data)\n return compressed_data\n\ndef compress_local(out_file, input_fnames, type=TYPE_JS, verbose=False, level=None):\n \"\"\"\n \"\"\"\n \n out_file = out_file or ('compressed.'+TYPE_JS)\n p('Compressing %s ...' % out_file, verbose)\n \n s = common.concat(input_fnames)\n s = compress(s, type)\n out = open(out_file, 'w')\n out.write(s)\n out.close()","sub_path":"yuicompressor.py","file_name":"yuicompressor.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"66713256","text":"import json\n\nfrom datetime import datetime, timedelta\n\nimport os\n\nfrom ajaxuploader.views import AjaxFileUploader, csrf_exempt\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.core.files import File\nfrom django.core.urlresolvers import reverse\nfrom django.http.response import HttpResponse, HttpResponseRedirect, Http404\nfrom django.shortcuts import render\nfrom django.template import Context\nfrom django.template.defaultfilters import slugify\nfrom django.template.loader import get_template\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic import TemplateView, DetailView\nfrom django.utils.translation import ugettext as _\n\nfrom ikwen.conf import settings as ikwen_settings\nfrom ikwen.core.models import Service\nfrom ikwen.core.utils import get_service_instance, get_model_admin_instance, DefaultUploadBackend\nfrom ikwen.accesscontrol.backends import UMBRELLA\nfrom ikwen.core.views import ChangeObjectBase\nfrom ikwen.revival.models import Revival, ProfileTag\nfrom ikwen.rewarding.models import Coupon, JoinRewardPack, PaymentRewardPack, CRBillingPlan, CROperatorProfile, \\\n CouponWinner, Reward, ReferralRewardPack, WELCOME_REWARD_OFFERED, FREE_REWARD_OFFERED, REFERRAL_REWARD_OFFERED\nfrom ikwen.rewarding.admin import CouponAdmin\n\nfrom ikwen.rewarding.utils import REFERRAL\n\nCONTINUOUS_REWARDING = 'Continuous Rewarding'\n\n\nclass Dashboard(TemplateView):\n template_name = 'rewarding/dashboard.html'\n\n\nclass Configuration(TemplateView):\n template_name = 'rewarding/configuration.html'\n\n def get_context_data(self, **kwargs):\n context = super(Configuration, self).get_context_data(**kwargs)\n service = get_service_instance()\n dc_coupon_list = Coupon.objects.using(UMBRELLA).filter(service=service, type=Coupon.DISCOUNT, deleted=False)\n po_coupon_list = Coupon.objects.using(UMBRELLA).filter(service=service, type=Coupon.PURCHASE_ORDER, deleted=False)\n gift_coupon_list = Coupon.objects.using(UMBRELLA).filter(service=service, type=Coupon.GIFT, deleted=False)\n context['plan_list'] = CRBillingPlan.objects.using(UMBRELLA).filter(is_active=True)\n payment_interval_list = []\n bound_list = set()\n for reward in PaymentRewardPack.objects.using(UMBRELLA).filter(service=service).order_by('floor'):\n bound_list.add((reward.floor, reward.ceiling))\n for item in bound_list:\n floor, ceiling = item[0], item[1]\n interval = {'floor': floor, 'ceiling': ceiling}\n\n coupon_list = []\n for coupon in Coupon.objects.using(UMBRELLA).filter(service=service, type=Coupon.DISCOUNT, deleted=False):\n coupon.payment_reward = coupon.get_payment_reward_pack(floor, ceiling)\n coupon_list.append(coupon)\n interval['dc_coupon_list'] = coupon_list\n\n coupon_list = []\n for coupon in Coupon.objects.using(UMBRELLA).filter(service=service, type=Coupon.PURCHASE_ORDER, deleted=False):\n coupon.payment_reward = coupon.get_payment_reward_pack(floor, ceiling)\n coupon_list.append(coupon)\n interval['po_coupon_list'] = coupon_list\n\n coupon_list = []\n for coupon in Coupon.objects.using(UMBRELLA).filter(service=service, type=Coupon.GIFT, deleted=False):\n coupon.payment_reward = coupon.get_payment_reward_pack(floor, ceiling)\n coupon_list.append(coupon)\n interval['gift_coupon_list'] = coupon_list\n\n payment_interval_list.append(interval)\n\n context['dc_coupon_list'] = dc_coupon_list\n context['po_coupon_list'] = po_coupon_list\n context['gift_coupon_list'] = gift_coupon_list\n context['payment_interval_list'] = payment_interval_list\n try:\n context['cr_profile'] = CROperatorProfile.objects.using(UMBRELLA).get(service=service)\n except CROperatorProfile.DoesNotExist:\n pass\n return context\n\n def get(self, request, *args, **kwargs):\n action = request.GET.get('action')\n if action == 'activate':\n return self.activate()\n elif action == 'delete':\n return self.delete_coupon(request)\n return super(Configuration, self).get(request, *args, **kwargs)\n\n @method_decorator(csrf_exempt)\n def dispatch(self, request, *args, **kwargs):\n return super(Configuration, self).dispatch(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n action = request.GET.get('action')\n if action == 'save_billing':\n return self.save_billing(request)\n elif action == 'save_rewards_packs':\n return self.save_rewards_packs(request)\n context = self.get_context_data(**kwargs)\n return render(request, self.template_name, context)\n\n def activate(self):\n service_id = getattr(settings, 'IKWEN_SERVICE_ID')\n service = Service.objects.using(UMBRELLA).get(pk=service_id)\n plan = CRBillingPlan.objects.using(UMBRELLA).get(slug=CRBillingPlan.FREE_TEST)\n expiry = datetime.now() + timedelta(days=90)\n CROperatorProfile.objects.using(UMBRELLA).get_or_create(service=service, plan=plan, expiry=expiry)\n notice = _(\"Your Continuous Rewarding program is now active.\")\n messages.success(self.request, notice)\n next_url = reverse('rewarding:configuration')\n return HttpResponseRedirect(next_url)\n\n def save_billing(self, request):\n plan_id = request.POST['plan_id']\n sms = request.POST.get('sms_push')\n auto_renew = request.POST.get('auto_renew')\n plan = CRBillingPlan.objects.using(UMBRELLA).get(pk=plan_id)\n service = get_service_instance()\n cr_profile = CROperatorProfile.objects.using(UMBRELLA).get(service=service)\n if cr_profile.plan != plan:\n cr_profile.plan = plan\n cr_profile.sms = True if sms else False\n cr_profile.auto_renew = True if auto_renew else False\n cr_profile.save()\n notice = _(\"Your Billing Plan was changed to %s.\" % plan.name)\n messages.success(self.request, notice)\n next_url = reverse('rewarding:configuration')\n return HttpResponseRedirect(next_url)\n\n def save_rewards_packs(self, request):\n rewards = json.loads(request.body)\n service = get_service_instance()\n service_umbrella = Service.objects.using(UMBRELLA).get(pk=service.id)\n # Delete all previous set JoinRewards ...\n JoinRewardPack.objects.using(UMBRELLA).filter(service=service_umbrella).delete()\n\n # ... And set new ones\n for reward in rewards['join']:\n coupon_id = reward['coupon_id']\n try:\n coupon = Coupon.objects.using(UMBRELLA).get(pk=coupon_id)\n except Coupon.DoesNotExist:\n continue\n count = int(reward['count'])\n JoinRewardPack.objects.using(UMBRELLA).create(service=service_umbrella, coupon=coupon, count=count)\n\n # Delete all previous set ReferralRewards ...\n ReferralRewardPack.objects.using(UMBRELLA).filter(service=service_umbrella).delete()\n\n # ... And set new ones\n for reward in rewards['referral']:\n coupon_id = reward['coupon_id']\n try:\n coupon = Coupon.objects.using(UMBRELLA).get(pk=coupon_id)\n except Coupon.DoesNotExist:\n continue\n count = int(reward['count'])\n ReferralRewardPack.objects.using(UMBRELLA).create(service=service_umbrella, coupon=coupon, count=count)\n\n ref_tag, update = ProfileTag.objects.get_or_create(name=REFERRAL, slug=REFERRAL, is_auto=True)\n if len(rewards['referral']) > 0:\n revival, update = Revival.objects.\\\n get_or_create(service=service, model_name='core.Service', object_id=service.id,\n profile_tag_id=ref_tag.id, mail_renderer='ikwen.revival.utils.render_suggest_referral_mail')\n revival_umbrella, update = Revival.objects.using(UMBRELLA)\\\n .get_or_create(id=revival.id, service=service_umbrella, model_name='core.Service', object_id=service_umbrella.id,\n mail_renderer='ikwen.revival.utils.render_suggest_referral_mail',\n profile_tag_id=ref_tag.id, get_kwargs='ikwen.rewarding.utils.get_referral_reward_pack_list')\n revival_umbrella.is_active = True\n revival_umbrella.save()\n else:\n Revival.objects\\\n .filter(service=service, model_name='core.Service', object_id=service.id, profile_tag_id=ref_tag.id,\n mail_renderer='ikwen.revival.utils.render_suggest_referral_mail').update(is_active=False)\n Revival.objects.using(UMBRELLA)\\\n .filter(service=service_umbrella, model_name='core.Service',\n object_id=service_umbrella.id, profile_tag_id=ref_tag.id,\n mail_renderer='ikwen.revival.utils.render_suggest_referral_mail').update(is_active=False)\n\n # Delete all previous set PurchaseRewards ...\n PaymentRewardPack.objects.using(UMBRELLA).filter(service=service_umbrella).delete()\n\n # Check to make sure intervals do not overlap\n intervals = rewards['payment']\n _cmp = lambda x, y: 1 if x['floor'] > y['floor'] else -1\n intervals.sort(_cmp)\n overlap = False\n for i in range(len(intervals) - 1):\n if int(intervals[i]['ceiling']) >= int(intervals[i+1]['floor']):\n overlap = True\n break\n if overlap:\n i00, i01 = intervals[i]['floor'], intervals[i]['ceiling']\n i10, i11 = intervals[i+1]['floor'], intervals[i+1]['ceiling']\n response = {'error': 'Intervals %s-%s and %s-%s overlap' % (i00, i01, i10, i11)}\n return HttpResponse(json.dumps(response))\n\n # ... And set new ones\n for interval in intervals:\n floor = int(interval['floor'])\n ceiling = int(interval['ceiling'])\n for reward in interval['reward_list']:\n coupon_id = reward['coupon_id']\n try:\n coupon = Coupon.objects.using(UMBRELLA).get(pk=coupon_id)\n except Coupon.DoesNotExist:\n continue\n count = int(reward['count'])\n PaymentRewardPack.objects.using(UMBRELLA).create(service=service_umbrella, coupon=coupon,\n floor=floor, ceiling=ceiling, count=count)\n return HttpResponse(json.dumps({'success': True}))\n\n def delete_coupon(self, request):\n object_id = request.GET['selection']\n coupon = Coupon.objects.using(UMBRELLA).get(pk=object_id)\n response = {\n 'message': \"Coupon %s deleted.\" % coupon.name,\n 'deleted': [coupon.id]\n }\n # ikwen_media_root = ikwen_settings.MEDIA_ROOT\n # if coupon.image.name:\n # try:\n # os.unlink(ikwen_media_root + coupon.image.name)\n # except:\n # pass\n coupon.deleted = True\n coupon.is_active = False\n coupon.save()\n return HttpResponse(\n json.dumps(response),\n content_type='application/json'\n )\n\n\nclass ChangeCoupon(ChangeObjectBase):\n model = Coupon\n model_admin = CouponAdmin\n object_list_url = 'rewarding:configuration'\n template_name = 'rewarding/change_coupon.html'\n\n def get_object(self, **kwargs):\n object_id = kwargs.get('object_id')\n if object_id:\n try:\n return Coupon.objects.using(UMBRELLA).get(pk=object_id)\n except Coupon.DoesNotExist:\n raise Http404('No Coupon matches the given ID.')\n\n def get_context_data(self, **kwargs):\n context = super(ChangeCoupon, self).get_context_data(**kwargs)\n context['verbose_name_plural'] = CONTINUOUS_REWARDING\n service = get_service_instance()\n coupon_list = list(Coupon.objects.using(UMBRELLA).filter(service=service))\n winner_list = set([obj.member\n for obj in CouponWinner.objects.using(UMBRELLA).filter(coupon__in=coupon_list, collected=False)])\n context['winner_list'] = winner_list\n return context\n\n def get(self, request, *args, **kwargs):\n action = request.GET.get('action')\n if action == 'delete_image':\n object_id = kwargs.get('object_id')\n obj = Coupon.objects.using(UMBRELLA).get(pk=object_id)\n image_field_name = request.GET.get('image_field_name', 'image')\n image_field = obj.__getattribute__(image_field_name)\n if image_field.name:\n image_path = ikwen_settings.MEDIA_ROOT + image_field.name\n os.unlink(image_path)\n try:\n os.unlink(image_field.small_path)\n os.unlink(image_field.thumb_path)\n except:\n pass\n obj.__setattr__(image_field_name, None)\n obj.save()\n return HttpResponse(\n json.dumps({'success': True}),\n content_type='application/json'\n )\n return super(ChangeCoupon, self).get(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n object_admin = get_model_admin_instance(self.model, self.model_admin)\n object_id = kwargs.get('object_id')\n qs = Coupon.objects.using(UMBRELLA)\n if object_id:\n obj = self.get_object(**kwargs)\n qs = qs.exclude(pk=obj.id)\n else:\n obj = self.model()\n name_field_name = request.POST.get('name_field_name', 'name')\n slug_field_name = request.POST.get('slug_field_name', 'slug')\n name = request.POST.get(name_field_name)\n slug = slugify(name)\n found = qs.filter(**{slug_field_name: slug}).count()\n if found:\n context = self.get_context_data(**kwargs)\n context['errors'] = _(\"A coupon with name %s already exists.\" % name)\n return render(request, self.template_name, context)\n model_form = object_admin.get_form(request)\n form = model_form(request.POST, instance=obj)\n if form.is_valid():\n form.save()\n try:\n obj.__getattribute__(slug_field_name)\n try:\n name_field = obj.__getattribute__(name_field_name)\n obj.__setattr__(slug_field_name, slugify(name_field))\n obj.save()\n except:\n pass\n except:\n pass\n image_url = request.POST.get('image_url')\n if image_url:\n s = get_service_instance()\n media_root = getattr(settings, 'MEDIA_ROOT')\n path = image_url.replace(getattr(settings, 'MEDIA_URL'), '')\n path = path.replace(ikwen_settings.MEDIA_URL, '')\n if not obj.image.name or path != obj.image.name:\n filename = image_url.split('/')[-1]\n try:\n with open(media_root + path, 'r') as f:\n content = File(f)\n destination = media_root + obj.UPLOAD_TO + \"/\" + s.project_name_slug + '_' + filename\n obj.image.save(destination, content)\n destination2 = destination.replace(media_root, ikwen_settings.MEDIA_ROOT)\n os.rename(destination, destination2)\n os.unlink(media_root + path)\n except IOError as e:\n if getattr(settings, 'DEBUG', False):\n raise e\n return {'error': 'File failed to upload. May be invalid or corrupted image file'}\n next_url = self.get_object_list_url(request, obj, *args, **kwargs)\n if object_id:\n messages.success(request, u'%s %s %s' % (obj._meta.verbose_name.capitalize(), unicode(obj), _('successfully updated')))\n else:\n messages.success(request, u'%s %s %s' % (obj._meta.verbose_name.capitalize(), unicode(obj), _('successfully updated')))\n return HttpResponseRedirect(next_url)\n else:\n context = self.get_context_data(**kwargs)\n context['errors'] = form.errors\n return render(request, self.template_name, context)\n\n\nclass CouponDetail(DetailView):\n model = Coupon\n\n def get(self, request, *args, **kwargs):\n coupon_id = request.GET['id']\n try:\n coupon = Coupon.objects.using(UMBRELLA).get(pk=coupon_id)\n except:\n raise Http404(\"No Coupon found with ID: %s\" % coupon_id)\n return HttpResponse(json.dumps(coupon.to_dict()), content_type='application/json')\n\n\nclass CouponUploadBackend(DefaultUploadBackend):\n\n def upload_complete(self, request, filename, *args, **kwargs):\n path = self.UPLOAD_DIR + \"/\" + filename\n self._dest.close()\n media_root = getattr(settings, 'MEDIA_ROOT')\n media_url = ikwen_settings.MEDIA_URL\n object_id = request.GET.get('object_id')\n if object_id:\n s = get_service_instance()\n coupon = Coupon.objects.using(UMBRELLA).get(pk=object_id)\n try:\n with open(media_root + path, 'r') as f:\n content = File(f)\n current_image_path = ikwen_settings.MEDIA_ROOT + coupon.image.name if coupon.image.name else None\n dir = media_root + coupon.UPLOAD_TO\n unique_filename = False\n filename_suffix = 0\n filename_no_extension, extension = os.path.splitext(filename)\n seo_filename_no_extension = slugify(coupon.name)\n seo_filename = s.project_name_slug + '_' + seo_filename_no_extension + extension\n if os.path.isfile(os.path.join(dir, seo_filename)):\n while not unique_filename:\n try:\n if filename_suffix == 0:\n open(os.path.join(dir, seo_filename))\n else:\n open(os.path.join(dir, seo_filename_no_extension + str(filename_suffix) + extension))\n filename_suffix += 1\n except IOError:\n unique_filename = True\n if filename_suffix > 0:\n seo_filename = seo_filename_no_extension + str(filename_suffix) + extension\n\n destination = os.path.join(dir, seo_filename)\n if not os.path.exists(dir):\n os.makedirs(dir)\n coupon.image.save(destination, content)\n destination2_folder = ikwen_settings.MEDIA_ROOT + coupon.UPLOAD_TO\n if not os.path.exists(destination2_folder):\n os.makedirs(destination2_folder)\n destination2 = destination.replace(media_root, ikwen_settings.MEDIA_ROOT)\n os.rename(destination, destination2)\n url = media_url + coupon.image.name\n try:\n if coupon.image and os.path.exists(media_root + path):\n os.unlink(media_root + path) # Remove file from upload tmp folder\n except Exception as e:\n if getattr(settings, 'DEBUG', False):\n raise e\n if current_image_path:\n try:\n if destination2 != current_image_path and os.path.exists(current_image_path):\n os.unlink(current_image_path)\n except OSError as e:\n if getattr(settings, 'DEBUG', False):\n raise e\n return {\n 'path': url\n }\n except IOError as e:\n if settings.DEBUG:\n raise e\n return {'error': 'File failed to upload. May be invalid or corrupted image file'}\n else:\n return super(CouponUploadBackend, self).upload_complete(request, filename, *args, **kwargs)\n\n\nupload_coupon_image = AjaxFileUploader(CouponUploadBackend)\n\n\ndef render_reward_offered_event(event, request):\n event_type = event.event_type\n if event_type.codename == WELCOME_REWARD_OFFERED:\n reward_list = Reward.objects.using(UMBRELLA).filter(type=Reward.JOIN, member=event.member)\n elif event_type.codename == FREE_REWARD_OFFERED:\n reward_list = Reward.objects.using(UMBRELLA).filter(type=Reward.FREE, member=event.member)\n elif event_type.codename == REFERRAL_REWARD_OFFERED:\n reward_list = Reward.objects.using(UMBRELLA).filter(type=Reward.REFERRAL, member=event.member)\n else:\n reward_list = Reward.objects.using(UMBRELLA).filter(type=Reward.MANUAL, member=event.member)\n\n html_template = get_template('rewarding/events/reward_offered.html')\n entries_count = len(reward_list)\n more_entries = entries_count - 3 # Number to show on the \"View more\" button\n total_coupon = 0\n tile_count = min(len(reward_list), 3)\n for reward in reward_list:\n total_coupon += reward.count\n from ikwen.conf import settings as ikwen_settings\n c = Context({'event': event, 'service': event.service, 'reward_list': reward_list,\n 'more_entries': more_entries, 'total_coupon': total_coupon, 'tile_count': tile_count,\n 'IKWEN_MEDIA_URL': ikwen_settings.MEDIA_URL})\n return html_template.render(c)\n\n\ndef render_payment_reward_offer_event(event, request):\n service = event.service\n reward_list = Reward.objects.using(UMBRELLA).filter(type=Reward.PAYMENT, member=event.member,\n object_id=event.object_id)\n html_template = get_template('rewarding/events/payment_reward_offer.html')\n entries_count = len(reward_list)\n more_entries = entries_count - 3 # Number to show on the \"View more\" button\n total_coupon = 0\n tile_count = min(len(reward_list), 3)\n amount = reward_list[0].amount\n for reward in reward_list:\n total_coupon += reward.count\n from ikwen.conf import settings as ikwen_settings\n currency_symbol = service.config.currency_symbol\n c = Context({'event': event, 'service': event.service, 'reward_list': reward_list,\n 'more_entries': more_entries, 'total_coupon': total_coupon, 'tile_count': tile_count,\n 'currency_symbol': currency_symbol, 'amount_paid': amount,\n 'IKWEN_MEDIA_URL': ikwen_settings.MEDIA_URL})\n return html_template.render(c)\n","sub_path":"rewarding/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":23117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"516848487","text":"'''\n4\n1 2 1 2\n'''\nsoa = int(input())\narr = [-1 if int(x)&1 else 1 for x in input().split()]\nhashmap = {}\nsums = 0\ncnt = 0\nfor i, x in enumerate(arr):\n hashmap[i] = arr[i]\n sums += [1, -1][arr[i]%2]\n if sums == 0:cnt += 1\nprint(cnt)","sub_path":"HackerEarth/airtel1.py","file_name":"airtel1.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"195920468","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom ArticleSpider.items import Job51\nimport re\nfrom scrapy_redis.spiders import RedisCrawlSpider\n\nclass A51jobSpider(RedisCrawlSpider):\n name = '51job'\n allowed_domains = ['51job.com']\n # start_urls = ['https://search.51job.com/list/000000,000000,0000,00,9,99,python,2,1.html']\n redis_key = 'start_url'\n\n rules = (\n Rule(LinkExtractor(restrict_xpaths='//div[@class=\"el\"]//p[@class=\"t1 \"]//a'), callback='parse_item'),\n Rule(LinkExtractor(restrict_xpaths='//div[@class=\"p_in\"]//li/a'),follow=True)\n )\n def parse_item(self, response):\n item = Job51()\n\n item['title'] = response.xpath('//div[@class=\"cn\"]/h1/@title').extract_first()\n item['money'] = response.xpath('//div[@class=\"cn\"]/strong/text()').extract_first()\n item['company'] = response.xpath('//div[@class=\"cn\"]/p/a/@title').extract_first()\n item['msg'] = response.xpath('//p[@class=\"msg ltype\"]/@title').extract_first()\n item['msg'] = re.sub(r'\\xa0\\xa0','', item['msg'])\n item['address'] = response.xpath('//div[@class=\"bmsg inbox\"]//p[@class=\"fp\"]//text()').extract()[-1] if response.xpath('//div[@class=\"bmsg inbox\"]//p[@class=\"fp\"]//text()').extract() else None\n item['url'] = response.url\n yield item\n\n","sub_path":"spider/ArticleSpider/ArticleSpider/spiders/a51job.py","file_name":"a51job.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"142648283","text":"from random import randint\n\ni = randint(0, 100)\nn, item = -1, 10\n\nwhile i != n or item > 0:\n item -= 1\n n = int(input(f'Введите число от 0 до 100: '))\n if n > i:\n print('Ваше число больше загаданного')\n elif n < i:\n print('Ваше число меньше загаданного')\n else:\n print(f'Загадано число = {i}')\n break\n\nif i != n or item == 0:\n print(f'Вы не отгадали число. Загадано число = {i}')","sub_path":"outOfQuarter/Алгоритмы и структуры данных на Python/lesson_2/task_6.py","file_name":"task_6.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"328194239","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\nimport uploader\n\n\ndef test_aggregate_exception_str():\n e1 = KeyError('error 1')\n e2 = KeyError('error 2')\n agg = uploader.AggregateException([('file1.txt', '*.txt', e1),\n ('file2.png', '**/*.png', e2)])\n assert str(agg) == \"file: file1.txt from pattern: *.txt hit \" \\\n \"error: KeyError('error 1',), \" \\\n \"file: file2.png from pattern: **/*.png \" \\\n \"hit error: KeyError('error 2',)\"\n","sub_path":"azure/cli/command_modules/batch_extensions/fileegress/test/test_aggregate_exception.py","file_name":"test_aggregate_exception.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"573211443","text":"from math import pi, sqrt, asin\n\n\ndef getOscillationParameters(parameter_set=\"globes_default\"):\n parameters = {}\n if parameter_set == \"globes_default\":\n parameters['theta_12'] = 0.553574 # about asin(sqrt(0.8))/2\n parameters['theta_13'] = 0.160875 # about asin(sqrt(0.1))/2\n parameters['theta_23'] = pi/4\n parameters['delta_cp'] = 0\n parameters['sdm'] = 7 * 10**-5 # eV^2, m12\n parameters['ldm'] = 3 * 10**-3 # eV^2, m31\n elif parameter_set == \"globes_tour\":\n parameters['theta_12'] = asin(sqrt(0.8))/2\n parameters['theta_13'] = asin(sqrt(0.001))/2\n parameters['theta_23'] = pi/4\n parameters['delta_cp'] = pi/2\n parameters['sdm'] = 7 * 10**-5 # eV^2, m12\n parameters['ldm'] = 2 * 10**-3 # eV^2, m31\n elif parameter_set == \"test\":\n parameters['theta_12'] = asin(sqrt(0.8))/2 # solar\n parameters['theta_13'] = asin(sqrt(0.001))/2 # reactor\n parameters['theta_23'] = pi/4 # atmo\n parameters['delta_cp'] = 0#pi/2\n parameters['sdm'] = 7 * 10**-5 # eV^2, m12\n parameters['ldm'] = 2 * 10**-3 # eV^2, m31\n else:\n raise ValueError(\"Bad parameter set passed\")\n\n return parameters\n","sub_path":"code/Exp_simulation/Tunnell/cuda_polar/oscillation_parameters.py","file_name":"oscillation_parameters.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"389235649","text":"import GaudiKernel.SystemOfUnits as Units\nfrom Gaudi.Configuration import *\nfrom PhysSelPython.Wrappers import AutomaticData, DataOnDemand, Selection, SelectionSequence\nfrom Configurables import CombineParticles, FilterDesktop, OfflineVertexFitter\nfrom Configurables import DaVinci\n\nfrom Configurables import MCDecayTreeTuple\nfrom Configurables import MCTupleToolReconstructed, MCReconstructed\n\n#--Scaler----------------------------------------------------------------\nfrom Configurables import TrackScaleState\nscaler = TrackScaleState( 'StateScale' )\n#------------------------------------------------------------------------\n\n\nkaons = DataOnDemand(Location = \"Phys/StdAllNoPIDsKaons/Particles\")\nprotons = DataOnDemand(Location = \"Phys/StdAllNoPIDsProtons/Particles\")\nlongpions = DataOnDemand(Location = \"Phys/StdAllNoPIDsPions/Particles\")\n\n\n\n#-------------------------------------------------------------------------------------------------\nlocationLb = \"/Event/BhadronCompleteEvent/Phys/Lb2LcPiNoIPLc2PKPiBeauty2CharmLine/Particles\"\nif simulation:\n locationLb = \"/Event/AllStreams/Phys/Lb2LcPiNoIPLc2PKPiBeauty2CharmLine/Particles\"\nLb2Lcpi = AutomaticData(Location = locationLb)\n\n_MyLb2Lcpi = FilterDesktop('_MyLb2Lcpi')\n_MyLb2Lcpi.Code = \"(MAXTREE('p+'==ABSID,PROBNNp)>0.05)&(MAXTREE('K+'==ABSID,PROBNNk)>0.05)&(MAXTREE('Lambda_b0'==ABSID,M)>5350*MeV)&(MAXTREE('Lambda_b0'==ABSID,M)<6000*MeV)&(MAXTREE('Lambda_c+'==ABSID, M)>2260*MeV)&(MAXTREE('Lambda_c+'==ABSID, M)<2315*MeV)\"\nMyLb2Lcpi = Selection(\"MyLb2Lcpi\", Algorithm = _MyLb2Lcpi, RequiredSelections = [Lb2Lcpi] )\n#-------------------------------------------------------------------------------------------------\n\n\n#BPVVDCHI2: chi2 separation from related PV \n#BPVIPCHI2(): Computes the chi2-IP on the related PV \n\n\n#----Selection Xibb -> /\\b pi+/-----------------------------------------------------------------\n_Sigb2Lbpi = CombineParticles( \"_Sigb2Lbpi\",\n DecayDescriptors = [\"[Xi_bc+ -> Lambda_b0 pi+]cc\"],\n CombinationCut = \"(AM>5800*MeV) & (APT>2*GeV)\",\n DaughtersCuts = { \"pi+\" : \"(PT > 200*MeV) & (P > 2000*MeV) & (TRCHI2DOF < 4.0) & (MIPCHI2DV(PRIMARY)>4)\"},\n MotherCut = \"(VFASPF(VCHI2/VDOF)<10) & (MIPCHI2DV(PRIMARY)<16) & (BPVDIRA>0.999) & (BPVVDCHI2>16)\", \n ReFitPVs = True )\nSigb2Lbpi = Selection( \"Sigb2Lbpi \",\n Algorithm = _Sigb2Lbpi ,\n RequiredSelections = [ MyLb2Lcpi, longpions] )\n\n_wsSigb2Lbpi = CombineParticles( \"_wsSigb2Lbpi\",\n DecayDescriptors = [\"[Xi_bc+ -> Lambda_b~0 pi+]cc\"],\n CombinationCut = \"(AM>5800*MeV) & (APT>2*GeV)\",\n DaughtersCuts = { \"pi+\" : \"(PT > 200*MeV) & (P > 2000*MeV) & (TRCHI2DOF < 4.0) & (MIPCHI2DV(PRIMARY)>4)\"},\n MotherCut = \"(VFASPF(VCHI2/VDOF)<10) & (MIPCHI2DV(PRIMARY)<16) & (BPVDIRA>0.999) & (BPVVDCHI2>16)\", \n ReFitPVs = True )\nwsSigb2Lbpi = Selection( \"wsSigb2Lbpi \",\n Algorithm = _wsSigb2Lbpi ,\n RequiredSelections = [ MyLb2Lcpi, longpions] )\n\n\n#-------------------------------------------------------------------------------------------------\n\n\n### Gaudi sequences ----------------------------------------------\nSeqLb2Lcpi = SelectionSequence(\"SeqLb2Lcpi\", TopSelection = MyLb2Lcpi)\nseqLb = SeqLb2Lcpi.sequence()\nSeqSigb2Lbpi = SelectionSequence(\"SeqSigb2Lbpi\", TopSelection = Sigb2Lbpi)\nseqXib = SeqSigb2Lbpi.sequence()\nwsSeqSigb2Lbpi = SelectionSequence(\"wsSeqSigb2Lbpi\", TopSelection = wsSigb2Lbpi)\nwsseqXib = wsSeqSigb2Lbpi.sequence()\n#---------------------------------------------------------------\n\n\n\n###########################################################################\n# Configure DaVinci\n###########################################################################\nfrom Configurables import DaVinci\nfrom Configurables import CondDB\nfrom Configurables import DecayTreeTuple, MCDecayTreeTuple\nimportOptions(\"DecayTreeTuple_Xibc.py\")\n\nfrom PhysConf.Filters import LoKi_Filters\nfltrs = LoKi_Filters (STRIP_Code = \" HLT_PASS_RE('StrippingLb2LcPiNoIPLc2PKPiBeauty2CharmLineDecision') \")\nfltrSeq = fltrs.sequence ( 'MyFilters' ) \n\nfrom Configurables import LoKi__HDRFilter as StripFilter\nif simulation == False:\n DaVinci().EventPreFilters = [fltrSeq]\n\n\ntuple0 = DecayTreeTuple( \"xibc\" )\ntuple0.Inputs = [ SeqSigb2Lbpi.outputLocation() ]\ntuple1 = DecayTreeTuple( \"wsxibc\")\ntuple1.Inputs = [ wsSeqSigb2Lbpi.outputLocation() ]\ntupleLb = DecayTreeTuple( \"lambdab\" )\ntupleLb.Inputs = [ SeqLb2Lcpi.outputLocation() ]\n\n\nif simulation:\n tuple0.ToolList += [ \"TupleToolMCTruth\" ]\n tuple1.ToolList += [ \"TupleToolMCTruth\" ]\n tuple0.ToolList += [ \"TupleToolMCBackgroundInfo\" ]\n tupleLb.ToolList += [ \"TupleToolMCTruth\" ]\n tupleLb.ToolList += [ \"TupleToolMCBackgroundInfo\" ]\n \n\n # MC Truth information - filled for ALL events\n decay1 = \"[Xi_bc+ => ^(Lambda_b0 => ^pi- ^(Lambda_c+ ==> ^p+ ^K- ^pi+) ) ^pi+]CC\"\n mcTuple1 = MCDecayTreeTuple(\"MCTupleXb2LbPi\")\n mcTuple1.Decay = decay1\n mcTuple1.ToolList = [ \"MCTupleToolKinematic\", \"MCTupleToolReconstructed\" ] \n mcTuple1.UseLabXSyntax = True\n mcTuple1.RevertToPositiveID = False \n\n\n\n#DaVinci().appendToMainSequence( [scaler] )\nDaVinci().appendToMainSequence( [seqLb, seqXib, wsseqXib, tuple0, tuple1, tupleLb] )\nif simulation:\n DaVinci().appendToMainSequence( [mcTuple1] )\n\n#\nDaVinci().EvtMax = -1\nDaVinci().DataType = year\nDaVinci().TupleFile = \"tuple.root\"\nDaVinci().PrintFreq = 2000\n\nfrom Configurables import CondDB\nif simulation:\n sim08_CondDB = \"Sim08-20130503-1-vc-\" #md100\"\n sim09_CondDB = \"sim-20160321-2-vc-\" #md100\"\n sim08_DDDB = \"Sim08-20130503-1\"\n sim09_DDDB = \"dddb-20150928\"\n\n sim_DDDB = sim09_DDDB\n sim_CondDB = sim09_CondDB \n DaVinci().DDDBtag = sim_DDDB\n if polarity<0: DaVinci().CondDBtag = sim_CondDB+\"md100\"\n if polarity>0: DaVinci().CondDBtag = sim_CondDB+\"mu100\"\n DaVinci().Lumi = False\n DaVinci().Simulation = True\nelse:\n CondDB( LatestGlobalTagByDataType = year )\n DaVinci().Lumi = True\n DaVinci().InputType = 'DST'\n\n#\n\n\n\n\n","sub_path":"sblusk/GridScripts/Xb2LbPi/RunXb2LbPi.py","file_name":"RunXb2LbPi.py","file_ext":"py","file_size_in_byte":6404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"98214706","text":"import os\nfrom newsapi import NewsApiClient\nfrom datetime import date, timedelta\n\n\nnewsapi = NewsApiClient(api_key=API_KEY)\ntoday_date = date.today().strftime(\"%Y-%m-%d\")\nyesterday_date = (date.today() - timedelta(1)).strftime(\"%Y-%m-%d\")\n\nclass NewsApi(object):\n\tdef __init__(self, parameter):\n\t\tself.parameter = parameter\n\t\tself.top_headlines = newsapi.get_top_headlines(q=self.parameter)\n\t\tself.description = []\n\t\tself.url = []\n\t\tself.image_link = []\n\t\tself.title = []\n\t\tself.sources = []\n\t\tfor article in self.top_headlines['articles']:\n\t\t\tself.description.append(article['description'])\n\t\t\tself.url.append(article['url'])\n\t\t\tself.image_link.append(article['urlToImage'])\n\t\t\tself.title.append(article['title'])\n\t\t\tself.sources.append(article['source']['name'])\n\n\tdef get_description(self):\n\t\treturn self.description\n\n\tdef get_url(self):\n\t\treturn self.url\n\n\tdef get_images(self):\n\t\treturn self.image_link\n\n\tdef get_title(self):\n\t\treturn self.title\n\n\tdef get_sources(self):\n\t\treturn self.sources\n\nclass NewsApiEverything(NewsApi):\n\tdef __init__(self, parameter,sources):\n\t\tself.parameter = parameter\n\t\tself.sources = sources\n\t\tself.allnews = newsapi.get_everything(q=self.parameter,\n\t\t\t\t\t\t\t\t\t\tsources=self.sources,\n\t\t\t\t\t\t\t\t\t\tlanguage='en',\n\t\t\t\t\t\t\t\t\t\tsort_by='relevancy',\n\t\t\t\t\t\t\t\t\t\tpage=1)\n\t\tself.description = []\n\t\tself.url = []\n\t\tself.image_link = []\n\t\tself.title = []\n\t\tself.sources = []\n\t\tfor article in self.allnews['articles']:\n\t\t\tself.description.append(article['description'])\n\t\t\tself.url.append(article['url'])\n\t\t\tself.image_link.append(article['urlToImage'])\n\t\t\tself.title.append(article['title'])\n\t\t\tself.sources.append(article['source']['name'])\n","sub_path":"news/app/news_api.py","file_name":"news_api.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"126012220","text":"from __future__ import unicode_literals\nfrom django.db import models, migrations\nfrom django.utils import timezone\n\ndef load_defaults(apps, schema_editor):\n user_list = apps.get_model('mails', 'users')\n\n user_list_res = user_list(\n username = 'cyrus@localhost.com',\n password = 'freyfvfnfnf',\n enabled = True,\n acl = '{imap,smtp}',\n memo = 'main admin user. do not delete it',\n ).save()\n\n domain_list = apps.get_model('mails', 'domains')\n\n domain_list_res = domain_list(\n domain = 'localhost',\n postmaster = 'cyrus@localhost.com',\n enabled = True,\n ).save()\n\nclass Migration(migrations.Migration):\n #dependencies = [\n # ('auth', '0001_initial'),\n #]\n\n operations = [\n migrations.CreateModel(\n name='users',\n fields=[\n ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),\n ('username', models.EmailField(unique=True, max_length=254)),\n ('password', models.CharField(verbose_name='password', max_length=128)),\n ('enabled', models.BooleanField(default=True, verbose_name='Enable/Disable status')),\n ('acl', models.TextField(default='{imap,smtp}', verbose_name='ACL to access mail server')),\n ('memo', models.TextField(null=True, blank=True)),\n ('server_admin', models.BooleanField(default=True, verbose_name='Custom all domain admin permissions')),\n #('last_login', models.DateTimeField(_('last login'), default=timezone.now, blank=True, null=True)),\n ('last_login', models.DateTimeField(default=timezone.now, blank=True, null=True)),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='domains',\n fields=[\n ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),\n ('domain', models.CharField(unique=True, max_length=254)),\n ('postmaster', models.EmailField(max_length=254)),\n ('enabled', models.BooleanField(default=True, verbose_name='Enable/Disable status')),\n ],\n options={\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='mails',\n fields=[\n ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),\n ('name', models.CharField(max_length=254)),\n ('domain', models.CharField(max_length=254)),\n ('fullname', models.CharField(max_length=254, null=True, blank=True)),\n ('enabled', models.BooleanField(default=True, verbose_name='Enable/Disable status')),\n ('local', models.BooleanField(default=True, verbose_name='Enable/Disable local user status')),\n ('destinations', models.CharField(max_length=254, null=True, blank=True)),\n ('parrot', models.BooleanField(default=False, verbose_name='Enable/Disable autoanswer')),\n ('parrotext', models.TextField(null=True, blank=True)),\n ],\n options={\n 'abstract': False,\n },\n ),\n migrations.RunPython(load_defaults),\n ]\n","sub_path":"mails/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"649418839","text":"from __future__ import print_function\n\nimport sys\nfrom pprint import pprint\n\nfrom ckan import model\nfrom ckan.logic import get_action, ValidationError\nfrom ckan.plugins import toolkit\n\nfrom ckan.lib.cli import CkanCommand\n\nclass CehComment(CkanCommand):\n '''CehComment remotely mastered metadata\n\n Usage:\n\n cehcomment initdb\n - Creates the necessary tables in the database\n\n cehcomment cleandb\n - Remove the tables in the database\n\n The command should be run from the ckanext-ceh-comment directory and expect\n a development.ini file to be present. Most of the time you will\n specify the config explicitly though::\n\n paster cehcomment [command] --config=../ckan/development.ini\n\n '''\n\n summary = __doc__.split('\\n')[0]\n usage = __doc__\n max_args = 2\n min_args = 0\n\n def command(self):\n self._load_config()\n\n context = {'model': model, 'session': model.Session, 'ignore_auth': True}\n self.admin_user = get_action('get_site_user')(context, {})\n\n print('')\n\n if len(self.args) == 0:\n self.parser.print_usage()\n sys.exit(1)\n cmd = self.args[0]\n if cmd == 'initdb':\n self.initdb()\n elif cmd == 'cleandb':\n self.cleandb()\n else:\n print('Command {0} not recognized'.format(cmd))\n\n def _load_config(self):\n super(CehComment, self)._load_config()\n\n def initdb(self):\n from ckanext.ceh_comment.model import init_db as db_setup\n db_setup()\n\n print('DB tables created')\n\n def cleandb(self):\n from ckanext.ceh_comment.model import clean_db as db_remove\n db_remove()\n\n print('DB tables removed')","sub_path":"ckanext-ceh-comment/ckanext/ceh_comment/commands/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"20080160","text":"import tensorflow as tf\nfrom tensorflow.python.tools import freeze_graph\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.framework import graph_util\n\ndef save_graph_to_file(sess, graph, graph_file_name):\n output_graph_def = graph_util.convert_variables_to_constants(\n sess, graph.as_graph_def(), ['input'])\n with gfile.FastGFile(graph_file_name, 'wb') as f:\n f.write(output_graph_def.SerializeToString())\n return\n\ndef main():\n Output = tf.placeholder(tf.float32, shape=[5], name='output') # output\n O = tf.reshape(Output, [1, 5])\n W = tf.Variable(tf.random_normal(shape=[5, 224*224*3]), dtype=tf.float32, name='W') # weights\n b = tf.Variable(tf.random_normal(shape=[224*224*3]), dtype=tf.float32, name='b') # biases\n I = tf.nn.softmax(tf.matmul(O, W) + b, name='input') # activation / output\n \n saver = tf.train.Saver()\n init_op = tf.global_variables_initializer()\n \n with tf.Session() as sess:\n sess.run(init_op)\n \n # save the graph\n # tf.train.write_graph(sess.graph_def, '.', 'tfdroid.pbtxt') \n\n # normally you would do some training here\n # but fornow we will just assign something to W\n #sess.run(tf.assign(W, [[1, 2],[4,5],[7,8]]))\n #sess.run(tf.assign(b, [1,1]))\n init = tf.global_variables_initializer()\n sess.run(init)\n save_graph_to_file(sess, sess.graph, 'nn_backward.pb')\n \n '''\n #save a checkpoint file, which will store the above assignment \n saver.save(sess, 'tfdroid.ckpt')\n\n \n MODEL_NAME = 'tfdroid'\n \n # Freeze the graph\n\n input_graph_path = MODEL_NAME+'.pbtxt'\n checkpoint_path = './'+MODEL_NAME+'.ckpt'\n input_saver_def_path = \"\"\n input_binary = False\n output_node_names = \"final_result\"\n restore_op_name = \"save/restore_all\"\n filename_tensor_name = \"save/Const:0\"\n output_frozen_graph_name = 'frozen_'+MODEL_NAME+'.pb'\n output_optimized_graph_name = 'optimized_'+MODEL_NAME+'.pb'\n clear_devices = True\n\n freeze_graph.freeze_graph(input_graph_path, input_saver_def_path,\n input_binary, checkpoint_path, output_node_names,\n restore_op_name, filename_tensor_name,\n output_frozen_graph_name, clear_devices, \"\")\n \n f = tf.gfile.FastGFile(output_optimized_graph_name, \"w\")\n f.write(output_graph_def.SerializeToString())\n '''\n \nif __name__ == '__main__':\n main()\n \n","sub_path":"scripts/nn_backward.py","file_name":"nn_backward.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"155266976","text":"from flask import Blueprint\nfrom credentials import bot\nfrom database.group import Group\nfrom database.student import Student\nfrom keyboards.keyboard import make_keyboard, make_menu_keyboard\nfrom emoji import emojize\nimport re\n\nregistration = Blueprint('registration', __name__)\n\n\n@registration.route('/registration')\ndef add_another_fac(message):\n Student.add_student(Student(id=message.from_user.id,\n username=message.from_user.username,\n group_id=Group.get_id_by_group('other')))\n\n\ndef register(message):\n group_keyboard = make_keyboard(keyboard_type='group', elem_list=Group.get_groups(), marker='group_')\n\n bot.delete_message(chat_id=message.from_user.id, message_id=message.message.message_id)\n\n bot.send_message(chat_id=message.from_user.id, text='Вибери свою групу:', reply_markup=group_keyboard)\n bot.register_next_step_handler_by_chat_id(message.from_user.id, get_group)\n\n\ndef get_group(message):\n group_id = Group.get_id_by_group(message.text)\n\n if group_id is False:\n bot.clear_step_handler_by_chat_id(message.from_user.id)\n bot.send_message(chat_id=message.from_user.id,\n text='Вибери свою групу:')\n\n bot.register_next_step_handler_by_chat_id(message.from_user.id, get_group)\n else:\n student = Student()\n student.id = message.from_user.id\n student.username = message.from_user.username\n student.group_id = group_id\n\n message = bot.send_message(chat_id=message.from_user.id, text='Введи ПІБ українською мовою')\n bot.register_next_step_handler(message, get_name, student)\n\n\ndef get_name(message, student):\n name = message.text\n\n if bool(re.search(\"[^А-ЯҐЄІIЇа-яiієїґ' -]+\", name)) or len(name.split(' ')) != 3 or len(name) > 256:\n message = bot.send_message(chat_id=message.from_user.id,\n text=f'Неккоректний ввід {emojize(\":x:\", use_aliases=True)}'\n f'\\nВведи ПІБ українською мовою')\n bot.register_next_step_handler(message, get_name, student)\n else:\n student.name = name\n\n message = bot.send_message(chat_id=message.from_user.id, text='Введи номер своєї залікової книжки')\n bot.register_next_step_handler(message, get_gradebook_id, student)\n\n\ndef get_gradebook_id(message, student):\n gradebook_id = message.text\n\n if bool(re.search('^\\d+(\\.\\d+)*$', gradebook_id)) is False:\n message = bot.send_message(chat_id=message.from_user.id,\n text='Неккоректний ввід\\nВведи номер своєї залікової книжки')\n bot.register_next_step_handler(message, get_gradebook_id, student)\n else:\n student.gradebook_id = gradebook_id\n\n message = bot.send_message(chat_id=message.from_user.id, text='Введи свій номер телефону')\n bot.register_next_step_handler(message, get_phone, student)\n\n\ndef get_phone(message, student):\n phone = message.text\n\n if bool(re.search(\"[^0-9+]+\", phone)) or len(phone) > 13:\n message = bot.send_message(chat_id=message.from_user.id,\n text=f'Неккоректний ввід {emojize(\":x:\", use_aliases=True)}\\n'\n f'Введи свій номер телефону')\n bot.register_next_step_handler(message, get_phone, student)\n else:\n student.phone = phone\n student.add_student(student)\n\n success_message = f'Вітаю, ти зареєстрований {emojize(\":white_check_mark:\", use_aliases=True)}'\n bot.send_message(chat_id=message.from_user.id, text=success_message,\n reply_markup=make_menu_keyboard(message, other_fac=False))\n\n # bot.send_message(chat_id=374464076,\n # text=f'#registered {student.name} '\n # f'КНТ-{Group.get_group_by_id(student.group_id)}',\n # parse_mode='html',\n # disable_web_page_preview=True)\n\n\n@bot.message_handler(commands=['reg301198'])\ndef register_for_admins(message):\n if Student.get_student_by_id(message.from_user.id) is None:\n group_keyboard = make_keyboard(keyboard_type='group', elem_list=Group.get_groups(), marker='group_')\n\n bot.send_message(chat_id=message.from_user.id, text='Вибери свою групу:', reply_markup=group_keyboard)\n bot.register_next_step_handler_by_chat_id(message.from_user.id, get_group)\n else:\n bot.send_message(chat_id=message.from_user.id, text='Ти вже зареєстрований')\n bot.clear_step_handler_by_chat_id(chat_id=message.from_user.id)\n","sub_path":"roles/student/registration.py","file_name":"registration.py","file_ext":"py","file_size_in_byte":4959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"232547097","text":"import cs50\n\nfrom flask import Flask, flash, jsonify, redirect, render_template, request\nfrom helpers import error\n\n# Configure application\napp = Flask(__name__)\n\n# Reload templates when they are changed\napp.config[\"TEMPLATES_AUTO_RELOAD\"] = True\n\n\n@app.after_request\ndef after_request(response):\n \"\"\"Disable caching\"\"\"\n response.headers[\"Cache-Control\"] = \"no-cache, no-store, must-revalidate\"\n response.headers[\"Expires\"] = 0\n response.headers[\"Pragma\"] = \"no-cache\"\n return response\n\n\n@app.template_filter('usd')\ndef usd(value):\n \"\"\"Format value as USD.\"\"\"\n return f\"${value:,.2f}\"\n\n\n# Get index page for splits, accept spot submissions\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef index():\n\n # generate index template with form\n if request.method == \"GET\":\n return render_template(\"/index.html\")\n\n # collect user input in the form\n if request.method == \"POST\":\n\n # check that arguments entered\n if not request.form.get(\"total\") or not request.form.get(\"splits\") or not request.form.get(\"tip\"):\n return error(\"Form incomplete please retry.\")\n\n # store form data into variables\n total = request.form.get(\"total\")\n splits = request.form.get(\"splits\")\n tip = request.form.get(\"tip\")\n\n # check valid usage of the splitter\n if not total.replace('.', '', 1).isdigit():\n return error(\"Please enter a valid bill amount without dollar sign\")\n if not splits.isdigit():\n return error(\"Please enter a valid number of splits\")\n if not tip.isdigit():\n return error(\"Please enter a valid tip amount\")\n\n # cast variables\n splits = int(splits)\n tip = int(tip)\n bill = float(total)\n total = round((float(total) * 100) * (1 + (tip / 100)))\n rem = total % splits\n splitdict = {}\n\n for i in range(splits):\n splitdict[i] = (total // splits) / 100\n\n for i in range(rem):\n splitdict[i] = splitdict[i] + .01\n\n total = total / 100\n tip = bill * (tip / 100)\n\n return render_template(\"/splits.html\", splitdict=splitdict, splits=splits, tip=tip, total=total)","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"230176561","text":"\"\"\"\nThese will be functions maybe for each class that specify a tighter upper bound for q_max,\nas opposed to q_max everywhere. These will just be state-based... Easy example would using\ndistance-from-goal if you know the maximum step size. The benefit over a dense reward is\nthat this will be \"provably\" convergent even if you'd think there were local optima.\n\nNote that these should probably depend on gamma for the most part. Don't know how to\nadd that easily.\n\"\"\"\n\nimport numpy as np\nimport torch\n\ndef maze_shaping(states, gamma=0.99):\n \"\"\"\n Distance-based shaping for the PointMaze domain\n \"\"\"\n assert len(states.shape) == 2, states.shape\n assert states.shape[1] == 2, states.shape\n\n\n distance_from_goal = torch.absolute(-states + 9.0)\n # distance_from_goal = np.maximum(distance_from_goal, 0)\n num_steps_from_goal = distance_from_goal.sum(dim=1) / 0.95\n num_discounts = torch.pow(gamma, num_steps_from_goal)\n\n assert len(num_discounts) == len(states)\n\n return num_discounts\n\ndef mcar_shaping_1(states, gamma=0.99):\n \"\"\"\n Shaping towards the goal\n \"\"\"\n x_coord_states = states[:,0]\n\n min_steps_away = (0.45 - x_coord_states) / 0.07\n min_steps_away = torch.clamp(min_steps_away, min=0.)\n\n Q_max = 100. * (gamma ** min_steps_away)\n return Q_max\n\ndef mcar_shaping_bad(states, gamma=0.99):\n \"\"\"\n The opposite of our good shaping function. Shapes towards the right side,\n while maintaining the Qmax > Q* property\n \"\"\"\n x_coord_states = states[:,0]\n\n min_steps_away = (0.45 - x_coord_states) / 0.07\n min_steps_away = torch.clamp(min_steps_away, min=0.)\n reversed_min_steps_away = -1 * min_steps_away\n\n Q_max = 100. * (gamma ** reversed_min_steps_away)\n return Q_max\n\ndef plane_shaping(states, gamma=0.99):\n assert len(states.shape) == 2, states.shape\n assert states.shape[1] == 2, states.shape\n x_coords = states[:,0]\n shifted_x_coords = x_coords + 50\n\n # print('plane')\n\n assert len(shifted_x_coords) == len(states)\n return shifted_x_coords\n\ndef plane_quadrants_shaping(states, gamma=0.99):\n values = [(s[0] >= 0) == (s[1] >= 0) for s in states]\n values = np.array([1. if v else 0. for v in values])\n assert len(values) == len(states)\n return values\n\ndef plane_reverse_quadrants_shaping(states, gamma=0.99):\n orig_values = plane_quadrants_shaping(states, gamma=gamma)\n new_values = 1 - orig_values\n return new_values\n\nclass ShapingFunctions:\n\n \"\"\"Okay, I want this to take in a tensor. Much faster that way. \"\"\"\n\n shaping_functions = {\n 'SibRivPointMaze-v1': {\n 'default': maze_shaping\n },\n 'PlaneWorld-v1': {\n 'default': plane_shaping,\n 'force_right': plane_shaping,\n 'force_xor': plane_quadrants_shaping,\n 'force_reverse_xor': plane_reverse_quadrants_shaping,\n },\n 'MountainCarContinuous-v0': {\n 'default': mcar_shaping_1,\n 'max_steps_away': mcar_shaping_1,\n 'reversed_max_steps_away': mcar_shaping_bad,\n }\n }\n\n def __init__(self, env_name, gamma, func_name=None):\n\n assert env_name in self.shaping_functions.keys(), env_name\n\n self.env_name = env_name\n self.gamma = gamma\n self.func_name = func_name\n\n self._assign_shaping_function()\n \n def _assign_shaping_function(self):\n sfd = self.shaping_functions[self.env_name]\n\n func_name = 'default' if self.func_name is None else self.func_name\n sf = sfd[func_name]\n self._shaping_function = sf\n\n def get_values(self, states):\n reshaped = False\n if len(states.shape) == 1:\n print('reshping!')\n reshaped = True\n states = states.view(1,-1)\n\n shaping_values = self._shaping_function(states, self.gamma)\n\n if reshaped == True:\n shaping_values = shaping_values.view(-1)\n \n return shaping_values\n\n\n\ndef _test_shaping():\n state = np.array([[20.,20.],[0.,0.]])\n upper_bounds = maze_shaping(state)\n print(upper_bounds)\n\n states = np.array([[1.,1.],[-1.,-1.],[-1.,1.],[1.,-1.]])\n values = plane_quadrants_shaping(states)\n print(values)\n\n\n pass\n\nif __name__ == \"__main__\":\n _test_shaping()","sub_path":"rbfdqn/shaping_functions.py","file_name":"shaping_functions.py","file_ext":"py","file_size_in_byte":4276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"279376620","text":"import argparse\nimport json\nimport numpy as np\nimport random\n\nfrom lm_eval import models, tasks\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--model', required=True)\n parser.add_argument('--model_args', default=\"\")\n parser.add_argument('--tasks', default=\"all_tasks\")\n parser.add_argument('--provide_description', action=\"store_true\")\n parser.add_argument('--num_fewshot', type=int, default=1)\n parser.add_argument('--seed', type=int, default=1234)\n parser.add_argument('--output_path', default=None)\n parser.add_argument('--run_mc_validation', action=\"store_true\")\n return parser.parse_args()\n\ndef largest_indices(ary, n):\n \"\"\"Returns the n largest indices from a numpy array.\"\"\"\n flat = ary.flatten()\n indices = np.argpartition(flat, -n)[-n:]\n indices = indices[np.argsort(-flat[indices])]\n return np.unravel_index(indices, ary.shape)\n\ndef cross_validation(args, training_docs, task, shuffled_train_indices=None, b_idx=None):\n lm = models.get_model(args.model).create_from_arg_string(args.model_args)\n results = []\n\n if shuffled_train_indices is None:\n shuffled_train_indices= [*range(len(training_docs))]\n random.shuffle(shuffled_train_indices)\n for i in range(0, len(shuffled_train_indices), args.num_fewshot):\n train_indices = shuffled_train_indices[i: i+args.num_fewshot]\n train_subset = []\n val_subset = []\n for i in range(len(shuffled_train_indices)):\n if i in train_indices:\n train_subset.append(training_docs[i])\n else:\n val_subset.append(training_docs[i])\n print(len(val_subset))\n\n accuracy = task.evaluate(val_subset, lm, args.provide_description, args.num_fewshot, train_doc=train_subset)\n\n result = {}\n result['indices'] = train_indices\n result['accuracy'] = accuracy\n results.append(result)\n with open(args.output_path + '/'+args.task_names[0] + \"_\"+ str(b_idx) + str(i), \"w\") as f:\n dumped = json.dumps(result)\n f.write(dumped)\n return results\n\ndef mc_cross_validation(args, training_docs, task, shuffled_train_indices=None):\n num_cross_validation = 2\n all_cross_validation_results = np.zeros((len(training_docs), num_cross_validation))\n for i in range(num_cross_validation):\n results = cross_validation(args, training_docs, task, shuffled_train_indices, b_idx=i)\n for tr_subset in results:\n all_cross_validation_results[tr_subset[\"indices\"], i] = tr_subset['accuracy']['major']\n print(\"Cross-val {}, accuracy: {}\".format(i, tr_subset['accuracy']['major']))\n item_scores = all_cross_validation_results.mean(axis=1)\n return all_cross_validation_results, item_scores\n\ndef cross_validation_main(args):\n if args.tasks == \"all_tasks\":\n task_names = tasks.ALL_TASKS\n else:\n task_names = args.tasks.split(\",\")\n task_dict = tasks.get_task_dict(task_names)\n task = task_dict[task_names[0]]\n args.task_names=task_names\n training_docs = task.training_docs()\n\n all_cross_validation_results, item_scores = mc_cross_validation(args, training_docs, task)\n best_k = largest_indices(item_scores, 100)[0]\n print(best_k)\n print(item_scores)\n all_cross_validation_results, item_scores = mc_cross_validation(args, training_docs, task, best_k.tolist())\n best_k = largest_indices(item_scores, 32)[0]\n print(best_k)\n print(item_scores)\n\n train_subset = []\n for i in range(len(training_docs)):\n if i in best_k:\n train_subset.append(training_docs[i])\n lm = models.get_model(args.model).create_from_arg_string(args.model_args)\n accuracy = task.evaluate(task.validation_docs(), lm, args.provide_description, args.num_fewshot, train_doc=train_subset)\n print(\"final accuracy: \", accuracy)\n\ndef main(args):\n lm = models.get_model(args.model).create_from_arg_string(args.model_args)\n if args.tasks == \"all_tasks\":\n task_names = tasks.ALL_TASKS\n else:\n task_names = args.tasks.split(\",\")\n task_dict = tasks.get_task_dict(task_names)\n results = {}\n for task_name, task in task_dict.items():\n if not task.has_validation_docs():\n continue\n result = task.evaluate(\n docs=task.validation_docs(),\n lm=lm,\n provide_description=args.provide_description,\n num_fewshot=args.num_fewshot,\n )\n results[task_name] = result\n\n dumped = json.dumps(results, indent=2)\n print(dumped)\n if args.output_path:\n with open(args.output_path+task_names[0]+'.jsonl', \"w\") as f:\n f.write(dumped)\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n random.seed(args.seed)\n np.random.seed(args.seed)\n args.output_path = \"./outputs/\"\n if args.run_mc_validation:\n print(\"running MCCV\")\n cross_validation_main(args)\n else:\n print(\"running main\")\n main(args)\n","sub_path":"main_mccv.py","file_name":"main_mccv.py","file_ext":"py","file_size_in_byte":4984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"196906661","text":"'''\nCreated on Feb 15, 2020\n\n@author: Siddhartha\n'''\nfrom sense_hat import SenseHat\nfrom labs.common.SensorData import SensorData\nfrom labs.module04 import SensorDataManager\nfrom time import sleep\nimport logging\n\nimport smbus\n\n#\n\nclass I2CSensorAdaptorTask:\n \n def __init__(self):\n self.sdm = None\n self.sensorData = None\n self.i2cBus = smbus.SMBus(1)\n self.humidAddr = 0x5F # address for humidity sensor\n self.bits = 8\n self.i2cBus.write_byte_data(self.humidAddr, 0, 0)\n #Method to implement lazy object initialization \n def objectLoader(self):\n self.sensorData = SensorData()\n self.sensorData.setName(\"HumidityI2C\")\n self.sdm = SensorDataManager.SensorDataManager() \n #Method for fetching the sensor value from senseHat I2C module \n def displayHumidityData(self):\n coeffH0 = self.i2cBus.read_byte_data(self.humidAddr, 0x30)\n coeffH1 = self.i2cBus.read_byte_data(self.humidAddr, 0x31)\n H0_rH= float(coeffH0/2.0)\n H1_rH = float(coeffH1/2.0) \n #print(\"H0_RH = \" + str(H0_rH))\n #print(\"H1_rH = \" + str(H1_rH))\n valH0T0a = self.i2cBus.read_byte_data(self.humidAddr, 0x36)\n valH0T0b = self.i2cBus.read_byte_data(self.humidAddr, 0x37)\n H0_T0_OUT = (valH0T0b<\n# Author: Vlad Balmos \n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport urwid\n\nfrom mitzasql.ui.widgets.info_widget import InfoWidget\n\nclass RowWidget(InfoWidget):\n def __init__(self, row, columns):\n self._row = row;\n self._columns = columns\n contents = self._create_contents()\n super().__init__([contents])\n\n @property\n def name(self):\n return u'Row data'\n\n def _create_contents(self):\n grid = []\n\n index = 0\n for item in self._row:\n if item is None:\n cell_data = u'NULL'\n else:\n if isinstance(item, bytearray):\n try:\n cell_data = item.decode(encoding='utf8')\n except:\n cell_data = item.hex()\n else:\n cell_data = str(item)\n cell_name = str(self._columns[index]['name'])\n\n contents = []\n contents.append((40, urwid.AttrMap(urwid.Text(cell_name), 'editbox:label')))\n contents.append(urwid.AttrMap(urwid.Text(cell_data),\n 'editbox'))\n grid.append(urwid.Columns(contents))\n index += 1\n\n grid = urwid.GridFlow(grid, cell_width=80, h_sep=1, v_sep=1,\n align='left')\n return grid\n","sub_path":"mitzasql/ui/widgets/row_widget.py","file_name":"row_widget.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"596494359","text":"import sys\nimport os\nimport multiprocessing\n\nproc_num = int(sys.argv[1])\ncmds = sys.argv[2:]\n\npool = multiprocessing.Pool(proc_num)\nfor cmd in cmds:\n pool.apply(os.system, args=cmd)\npool.close()\npool.join()\n\n\n","sub_path":"batch.py","file_name":"batch.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"179751930","text":"from collections import OrderedDict\n\nN, M = [int(x) for x in input().split()]\nAB = sorted([[int(x) for x in input().split()] for _ in range(N)], key=lambda x: x[0])\n\ny = 0\nfor ab in AB:\n n = min(ab[1], M)\n y += ab[0] * n\n M -= n\n\n if M == 0:\n break\nprint(y)\n","sub_path":"ABC/121/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"89636074","text":"from __future__ import division\n\nimport gym\nimport tflearn\nimport numpy as np\n\nfrom tflearn.layers.core import input_data, dropout, fully_connected\nfrom statistics import mean, median\nfrom tflearn.layers.estimator import regression\nfrom collections import Counter\n\nLR = 1e-3\nenv = gym.make('CartPole-v0')\nenv.reset()\n\ngoal_steps = 500\nscore_requirement = 50\ninitial_games = 10000\n\nenv._max_episode_steps = goal_steps\n\ndef ran_game():\n for ep in range(5):\n env.reset()\n for t in range(goal_steps):\n env.render()\n action = env.action_space.sample()\n obs, reward, done, info = env.step(action)\n if done:\n break\n\ndef initial_population():\n training_data = []\n scores = []\n accepted_scores = []\n for _ in range(initial_games):\n score = 0\n game_memory = []\n prev_obs = []\n for _ in range(goal_steps):\n #env.render()\n action = env.action_space.sample()\n obs, reward, done, info = env.step(action)\n if len(prev_obs) > 0:\n game_memory.append([prev_obs, action])\n prev_obs = obs\n score += reward\n if done:\n break\n if score >= score_requirement:\n accepted_scores.append(score)\n for data in game_memory:\n if data[1] == 1:\n out = [0, 1]\n else:\n out = [1, 0]\n training_data.append([data[0], out])\n env.reset()\n scores.append(score)\n training_data_save = np.array(training_data)\n np.save('training.npy', training_data_save)\n print('Average accepted score', mean(accepted_scores))\n print('Median accepted score', median(accepted_scores))\n print(Counter(accepted_scores))\n\n return training_data\n\ndef make_nn(input_size):\n network = input_data(shape=[None, input_size, 1], name='input')\n\n network = fully_connected(network, 128, activation='relu')\n network = dropout(network, 0.8)\n\n network = fully_connected(network, 256, activation='relu')\n network = dropout(network, 0.8)\n\n network = fully_connected(network, 512, activation='relu')\n network = dropout(network, 0.8)\n\n network = fully_connected(network, 256, activation='relu')\n network = dropout(network, 0.8)\n\n network = fully_connected(network, 128, activation='relu')\n network = dropout(network, 0.8)\n\n network = fully_connected(network, 2, activation='softmax')\n network = regression(network, optimizer='adam', learning_rate=LR,\n loss='categorical_crossentropy', name='targets')\n model = tflearn.DNN(network, tensorboard_dir='cart-pole')\n return model\n\ndef train_model(training_data, model=False):\n X = np.array([i[0] for i in training_data]).reshape(-1, len(training_data[0][0]), 1)\n y = [i[1] for i in training_data]\n if not model:\n model = make_nn(input_size=len(X[0]))\n model.fit({'input':X}, {'targets':y}, n_epoch=5, snapshot_step=500, show_metric=True, run_id='openaistuff')\n return model\n\ndo_all = False\nif do_all:\n training_data = initial_population()\n model = train_model(training_data)\n model.save('cart-pole.model')\nelse:\n model = make_nn(input_size=4)\n model.load('cart-pole-save.model')\n\nscores = []\nchoices = []\n\nfor game in range(10):\n score = 0;\n game_memory = []\n prev_obs = []\n env.reset()\n for step in range(goal_steps):\n env.render()\n if len(prev_obs) == 0:\n action = env.action_space.sample()\n else:\n obs = prev_obs.reshape(-1, len(prev_obs), 1)\n inp = model.predict(obs)\n action = np.argmax(model.predict(obs)[0])\n choices.append(action)\n\n new_obs, reward, done, info = env.step(action)\n prev_obs = new_obs\n game_memory.append([new_obs, action])\n score += reward\n if done:\n print(step, score)\n break\n scores.append(score)\n\nprint('Average score {}'.format(mean(scores)))\nprint('Choice 1: {}, Choice {}'.format(choices.count(1)/len(choices),\n choices.count(0)/len(choices)))\nprint(Counter(scores))\n#ran_game()\n\n\n\n\n\n","sub_path":"cart-pole.py","file_name":"cart-pole.py","file_ext":"py","file_size_in_byte":4233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"495831073","text":"#!/usr/bin/env python3\n# encoding: utf-8\nfrom setuptools import setup, find_packages\nfrom setuptools.command.sdist import sdist\n\nimport os\nimport sys\n\n\nused = sys.version_info\nrequired = (3, 6)\n\n# if version of pip that doesn't understand the python_requires classifier, must be pip >= 9.0.0\n# must be built using at least version 24.2.0 of setuptools\n# in order for the python_requires argument to be recognized and the appropriate metadata generated\n# python -m pip install --upgrade pip setuptools\nif used[:2] < required:\n sys.stderr.write(\"Unsupported Python version: %s.%s. \"\n \"Python 3.6 or later is required.\" % (sys.version_info.major, sys.version_info.minor))\n sys.exit(1)\n\nshort_desc = \"A tkinter based GUI application that helps you count money.\"\n\n\ndef read_readme(file_name):\n with open(os.path.join(os.path.dirname(__file__), file_name)) as f:\n return f.read()\n\n\nclass Sdist(sdist):\n \"\"\"Custom ``sdist`` command to ensure that mo files are always created.\"\"\"\n def run(self):\n self.run_command('compile_catalog')\n sdist.run(self)\n\n\nsetup(name='count-money',\n version=__import__('count_money').__version__,\n description=short_desc,\n packages=find_packages(),\n long_description=read_readme('README.md'), # for PyPI\n long_description_content_type=\"text/markdown\",\n license='MIT',\n url='https://no-title.victordomingos.com/projects/contar-dinheiro/', # homepage\n python_requires='>=3.6',\n setup_requires=['babel'],\n\n cmdclass={'sdist': Sdist},\n\n classifiers=[\n 'Development Status :: 5 - Production/Stable ',\n 'Environment :: MacOS X',\n 'Intended Audience :: End Users/Desktop',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Operating System :: MacOS :: MacOS X',\n 'Operating System :: Microsoft :: Windows',\n 'Operating System :: POSIX :: Linux ',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Topic :: Utilities',\n 'Topic :: Desktop Environment :: File Managers',\n 'Topic :: System :: Filesystems',\n ],\n \n keywords='money count sum coins bills gui accounting commerce',\n\n entry_points={\n 'console_scripts': [\n 'count-money = count_money.__main__:main'\n ]\n },\n\n package_data={'': ['locale/*/*/*.mo', 'locale/*/*/*.po']},\n\n project_urls={\n 'Documentation': 'https://github.com/victordomingos/ContarDinheiro.py/blob/master/README.md',\n 'Source': 'https://github.com/victordomingos/ContarDinheiro.py',\n 'Bug Reports': 'https://github.com/victordomingos/ContarDinheiro.py/issues',\n },\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"524388031","text":"'''Train CIFAR10 with PyTorch.'''\nfrom __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torch.backends.cudnn as cudnn\nfrom torch.utils import data\n\nimport torchvision\nimport torchvision.transforms as transforms\n\nimport os\nimport argparse\nimport pickle\nimport numpy as np\n\n#from models.senet import *\nfrom utils import progress_bar\nfrom augment.cutout import Cutout\n\n#from resnet import resnet18\nfrom wrn import wrn\n#from autoaugment_extra_only_color import CIFAR10Policy\nfrom augment.autoaugment_extra import CIFAR10Policy\n\nDATASET = 'CIFAR10'\nSEED = 0\nSPLIT_ID = None\n\nparse = argparse.ArgumentParser(description='PyTorch SSL CIFAR10 UDA Training')\nparse.add_argument('--dataset', type=str, default=DATASET, help='dataset')\nparse.add_argument('--num-classes', default=10, type=int, help='number of classes')\n\nparse.add_argument('--lr', default=0.003, type=float, help='learning rate')\nparse.add_argument('--softmax-temp', default=-1, type=float, help='softmax temperature controlling')\nparse.add_argument('--confidence-mask', default=-1, type=float, help='Confidence value for masking')\n\nparse.add_argument('--num-labeled', default=1000, type=int, help='number of labeled_samples')\n\nparse.add_argument('--batch-size-lab', default=64, type=int, help='training batch size')\nparse.add_argument('--batch-size-unlab', default=320, type=int, help='training batch size')\nparse.add_argument('--num-steps', default=100000, type=int, help='number of iterations')\nparse.add_argument('--lr-warm-up', action='store_true', help='increase lr slowly')\nparse.add_argument('--warm-up-steps', default=20000, type=int, help='number of iterations for warmup')\nparse.add_argument('--num-cycles', default=1, type=int, help='number of sgdr cycles')\n\nparse.add_argument('--split-id', type=str, default=SPLIT_ID, help='restore partial id list')\nparse.add_argument('--resume', '-r', action='store_true', help='resume from checkpoint')\nparse.add_argument('--resume-path', type=str, default=None, help='dataset')\nparse.add_argument('--verbose', action='store_true', help='show progress bar')\nparse.add_argument('--seed', default=SEED, type=int, help='seed index')\n\n# Supervised or Semi-supervised\nparse.add_argument('--lab-only', action='store_true', help='if using only labeled samples')\n\n# Augmenatations\nparse.add_argument('--cutout', action='store_true', help='use cutout augmentation')\nparse.add_argument('--n-holes', default=1, type=float, help='number of holes for cutout')\nparse.add_argument('--cutout-size', default=16, type=float, help='size of the cutout window')\nparse.add_argument('--autoaugment', action='store_true', help='use autoaugment augmentation')\n\nargs = parse.parse_args()\n\n#CHECKPOINT_DIR = './results/dataset_' + str(args.dataset) + '_labels_' + str(args.num_labeled) + '_batch_lab_' + str(args.batch_size_lab) + '_batch_unlab_' + str(args.batch_size_unlab) + '_steps_' + str(args.num_steps) +'_warmup_' + str(args.warm_up_steps) + '_softmax_temp_' + str(args.softmax_temp) + '_conf_mask_' + str(args.confidence_mask) + '_SEED_' + str(args.seed)\nCHECKPOINT_DIR = './results/dataset_CIFAR5_labels_' + str(args.num_labeled) + '_batch_lab_' + str(args.batch_size_lab) + '_batch_unlab_' + str(args.batch_size_unlab) + '_steps_' + str(args.num_steps) +'_warmup_' + str(args.warm_up_steps) + '_softmax_temp_' + str(args.softmax_temp) + '_conf_mask_' + str(args.confidence_mask) + '_SEED_' + str(args.seed) + '_ft'\n\nif not os.path.exists(CHECKPOINT_DIR):\n os.makedirs(CHECKPOINT_DIR)\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nbest_acc = 0 # best test accuracy\nstart_epoch = 1 # start from epoch 0 or last checkpoint epoch\nnp.random.seed(args.seed)\n\nclass TransformTwice:\n def __init__(self, transform, aug_transform):\n self.transform = transform\n self.aug_transform = aug_transform\n\n def __call__(self, inp):\n out1 = self.transform(inp)\n out2 = self.aug_transform(inp)\n return out1, out2\n\n# Data\nprint('==> Preparing data..')\ntransform_ori = transforms.Compose([\n transforms.RandomCrop(32, padding=4, padding_mode='reflect'),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\n\ntransform_aug = transforms.Compose([\n CIFAR10Policy(),\n transforms.ToTensor(),\n Cutout(n_holes=args.n_holes, length=args.cutout_size),\n transforms.ToPILImage(),\n transforms.RandomCrop(32, padding=4, padding_mode='reflect'),\n transforms.RandomHorizontalFlip(), \n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\n\n\ntransform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))\n])\n\ntransform_train = TransformTwice(transform_ori, transform_aug)\nif args.dataset == 'CIFAR10':\n trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train)\n labelset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_test)\n testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)\nif args.dataset == 'CIFAR100':\n trainset = torchvision.datasets.CIFAR100(root='./data', train=True, download=True, transform=transform_train)\n labelset = torchvision.datasets.CIFAR100(root='./data', train=True, download=True, transform=transform_test)\n testset = torchvision.datasets.CIFAR100(root='./data', train=False, download=True, transform=transform_test)\n#trainset_aug = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train)\n#trainloader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True, num_workers=8)\n\ntrain_dataset_size = len(trainset)\ntest_dataset_size = len(testset)\n\n#if args.partial_id is not None:\n#train_ids = pickle.load(open(args.split_id, 'rb'))\n#print('loading train ids from {}'.format(args.split_id))\n#else:\n# train_ids = np.arange(train_dataset_size)\n# np.random.shuffle(train_ids)\n\n#pickle.dump(train_ids, open('train_id.pkl', 'wb'))\n\nif args.split_id is not None:\n train_ids = pickle.load(open(args.split_id, 'rb'))\n print('loading train ids from {}'.format(args.split_id))\nelse:\n train_ids = np.arange(train_dataset_size)\n test_ids = np.arange(test_dataset_size)\n np.random.shuffle(train_ids)\n pickle.dump(train_ids, open(os.path.join(CHECKPOINT_DIR, 'train_id_' + str(args.seed) + '.pkl'), 'wb'))\n\nmask = np.zeros(train_ids.shape[0], dtype=np.bool)\nlabels = np.array([trainset[i][1] for i in train_ids], dtype=np.int64)\n'''\nfor i in range(args.num_classes):\n mask[np.where(labels == i)[0][: int(args.num_labeled / args.num_classes)]] = True\nlabeled_indices, unlabeled_indices = train_ids[mask], train_ids[~ mask]\n#labeled_indices, unlabeled_indices = train_ids[mask], train_ids\n'''\nmask_ = np.zeros(train_ids.shape[0], dtype=np.bool)\nmask_test = np.zeros(test_ids.shape[0], dtype=np.bool)\nlabels_test = np.array([testset[i][1] for i in test_ids], dtype=np.int64)\nfor i in range(5, 10):\n mask[np.where(labels == i)[0][: int(args.num_labeled / args.num_classes)]] = True\n mask_[np.where(labels == i)[0][int(args.num_labeled / args.num_classes): ]] = True\n mask_test[np.where(labels_test == i)[0]] = True\nlabeled_indices, unlabeled_indices = train_ids[mask], train_ids[mask_]\ntest_indices = test_ids[mask_test]\n\ntrain_sampler_lab = data.sampler.SubsetRandomSampler(labeled_indices)\ntrain_sampler_unlab = data.sampler.SubsetRandomSampler(unlabeled_indices)\ntest_sampler = data.sampler.SubsetRandomSampler(test_indices)\n\ntrainloader_lab = data.DataLoader(trainset, batch_size=args.batch_size_lab, sampler=train_sampler_lab, num_workers=16, drop_last=True)\ntrainloader_unlab = data.DataLoader(trainset, batch_size=args.batch_size_unlab, sampler=train_sampler_unlab, num_workers=16, pin_memory=True)\n\ntrainloader_val = data.DataLoader(labelset, batch_size=100, sampler=train_sampler_lab, num_workers=16, drop_last=False)\n\ntestloader = data.DataLoader(testset, batch_size=100, sampler=test_sampler, num_workers=16)\n#testloader = torch.utils.data.DataLoader(testset, batch_size=100, shuffle=False, num_workers=16)\n\nclasses = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n\n# Model\nprint('==> Building model..')\nnet = wrn(num_classes=args.num_classes).cuda()\n\nif device == 'cuda':\n net = torch.nn.DataParallel(net)\n cudnn.benchmark = True\n\nif args.resume:\n # Load checkpoint.\n print('==> Resuming from checkpoint..')\n assert os.path.isdir('checkpoint'), 'Error: no checkpoint directory found!'\n checkpoint = torch.load(args.resume_path + '/best_ckpt.t7')\n net.load_state_dict(checkpoint['net'])\n best_acc = checkpoint['acc']\n #start_epoch = checkpoint['cycle']\n net.cuda()\n\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(net.parameters(), lr=args.lr, momentum=0.9, weight_decay=5e-4, nesterov=True)\n#optimizer = optim.Adam(net.parameters(), lr=args.lr, betas= (0.9, 0.999))\nscheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.num_steps, eta_min=0.0001)\n\ndef _kl_divergence_with_logits(p_logits, q_logits):\n p = torch.nn.functional.softmax(p_logits, dim=1)\n log_p = torch.nn.functional.log_softmax(p_logits, dim=1)\n log_q = torch.nn.functional.log_softmax(q_logits, dim=1)\n\n kl = torch.sum(p * (log_p - log_q), dim=1)\n return kl\n\ndef set_optimizer_lr(optimizer, lr):\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n return optimizer\n\n# Training\ndef train(cycle, trainloader_lab, trainloader_unlab, scheduler, optimizer):\n print('\\nCycle: %d' % cycle)\n train_loss = 0\n train_loss_lab = 0\n train_loss_unlab = 0\n correct = 0\n total = 0\n\n trainloader_lab_iter = iter(trainloader_lab)\n trainloader_unlab_iter = iter(trainloader_unlab)\n \n for i_iter in range(args.num_steps):\n net.train()\n optimizer.zero_grad()\n \n if args.lr_warm_up:\n if i_iter < args.warm_up_steps:\n warmup_lr = i_iter/args.warm_up_steps* args.lr\n optimizer = set_optimizer_lr(optimizer, warmup_lr)\n \n if i_iter%1000==0:\n for param_group in optimizer.param_groups:\n print(param_group['lr'])\n \n try:\n batch_lab = next(trainloader_lab_iter)\n except:\n trainloader_lab_iter = iter(trainloader_lab)\n batch_lab = next(trainloader_lab_iter) \n \n (inputs_lab, _), targets_lab = batch_lab\n inputs_lab, targets_lab = inputs_lab.to(device), targets_lab.to(device)\n \n targets_lab = targets_lab - 5 \n outputs_lab = net(inputs_lab)\n loss_lab = criterion(outputs_lab, targets_lab)\n #inputs, targets = inputs.to(device), targets.to(device)\n\n if args.lab_only: \n loss_unlab = 0.0 \n loss = loss_lab \n else:\n try:\n batch_unlab = next(trainloader_unlab_iter)\n except:\n trainloader_unlab_iter = iter(trainloader_unlab)\n batch_unlab = next(trainloader_unlab_iter) \n \n (inputs_unlab, inputs_unlab_aug), _ = batch_unlab\n inputs_unlab, inputs_unlab_aug = inputs_unlab.cuda(), inputs_unlab_aug.cuda()\n \n outputs_unlab = net(inputs_unlab)\n outputs_unlab_aug = net(inputs_unlab_aug)\n\n if args.softmax_temp != -1:\n \n loss_unlab = _kl_divergence_with_logits(\n p_logits=(outputs_unlab/args.softmax_temp).detach(),\n q_logits=outputs_unlab_aug)\n \n if args.confidence_mask != -1:\n unlab_prob = torch.nn.functional.softmax(outputs_unlab, dim=1)\n largest_prob, _ = unlab_prob.max(1)\n mask = (largest_prob>args.confidence_mask).float().detach()\n loss_unlab = loss_unlab*mask \n \n loss_unlab = torch.mean(loss_unlab)\n\n else:\n loss_unlab = torch.nn.functional.kl_div( \n torch.nn.functional.log_softmax(outputs_unlab_aug, dim=1), \n torch.nn.functional.softmax(outputs_unlab, dim=1).detach(), reduction='batchmean') \n\n loss = loss_lab + loss_unlab\n\n ''' \n loss_unlab = torch.nn.functional.kl_div( \n torch.nn.functional.log_softmax(outputs_unlab_aug/args.softmax_temp, dim=1), \n torch.nn.functional.softmax(outputs_unlab/args.softmax_temp, dim=1).detach(), reduction='batchmean') \n '''\n\n loss.backward()\n optimizer.step()\n scheduler.step()\n \n train_loss += loss.item()\n train_loss_lab += loss_lab.item()\n if args.lab_only:\n train_loss_unlab = 0.0\n else:\n train_loss_unlab += loss_unlab.item()\n \n #progress_bar(i_iter, args.num_steps, 'Loss: %.6f | Loss_lab: %.6f'\n #% (loss.item(), loss_lab.item()))\n \n if args.verbose:\n progress_bar(i_iter, args.num_steps, 'Loss: %.6f | Loss_lab: %.6f | Loss_unlab: %.6f'\n % (train_loss/1000.0, train_loss_lab/1000.0, train_loss_unlab/1000.0))\n \n if i_iter%500==0:\n train_loss /= 1000\n train_loss_lab /= 1000\n train_loss_unlab /= 1000\n \n test(cycle, i_iter, train_loss, train_loss_lab, train_loss_unlab)\n #val() \n \n train_loss = 0\n train_loss_lab = 0\n train_loss_unlab = 0\n \n \ndef val():\n global best_acc\n net.eval()\n test_loss = 0\n correct = 0\n total = 0\n U_all = []\n fp = open('results_with_val.txt','a') \n with torch.no_grad():\n for batch_idx, (inputs, targets) in enumerate(trainloader_val):\n inputs, targets = inputs.to(device), targets.to(device)\n outputs = net(inputs)\n\n probs = F.softmax(outputs, dim=1)\n log_probs = torch.log(probs)*(-1)\n U = (probs*log_probs).sum(1)\n U_all.append(U)\n \n loss = criterion(outputs, targets)\n\n test_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n\n if args.verbose:\n progress_bar(batch_idx, len(trainloader_val), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (test_loss/(batch_idx+1), 100.*correct/total, correct, total))\n \n\ndef test(cycle, i_iter, loss, loss_lab, loss_unlab):\n global best_acc\n net.eval()\n test_loss = 0\n correct = 0\n total = 0\n U_all = []\n #filename = 'results_semi_' + str(args.batch_size_lab) + '_' + str(args.batch_size_unlab) + '_labels_' + str(args.num_labeled) + '_steps_' + str(args.num_steps)+ '_warm_' + str(args.warm_up_steps) + '_softmax_temp_' + str(args.softmax_temp) + '_conf_mask_' + str(args.confidence_mask) + '.txt'\n filename = os.path.join(CHECKPOINT_DIR, 'results.txt')\n #fp = open('results_semi_64_320_100k_w_flip_and_crop_20k_warm_up_sep_masks_wo_GCN_last_norm_again.txt','a') \n fp = open(filename, 'a')\n with torch.no_grad():\n for batch_idx, (inputs, targets) in enumerate(testloader):\n inputs, targets = inputs.to(device), targets.to(device)\n outputs = net(inputs)\n\n probs = F.softmax(outputs, dim=1)\n log_probs = torch.log(probs)*(-1)\n U = (probs*log_probs).sum(1)\n U_all.append(U)\n \n targets = targets -5 \n loss = criterion(outputs, targets)\n\n test_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n\n if args.verbose:\n progress_bar(batch_idx, len(testloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (test_loss/(batch_idx+1), 100.*correct/total, correct, total))\n \n fp.write(str(i_iter) + ' ' + str(100.*correct/total) + ' loss: ' + str(loss) + ' loss lab: ' + str(loss_lab) + ' loss unlab: ' + str(loss_unlab) + '\\n') \n \n # Save checkpoint.\n acc = 100.*correct/total\n if acc > best_acc:\n print('Saving..')\n \n state = {\n 'net': net.state_dict(),\n 'acc': acc,\n 'cycle': cycle,\n }\n #if not os.path.isdir('checkpoint'):\n # os.mkdir('checkpoint')\n #torch.save(state, './checkpoint/ckpt.t7')\n torch.save(state, os.path.join(CHECKPOINT_DIR, 'best_ckpt.t7'))\n \n best_acc = acc\n \nfor cycle in range(args.num_cycles):\n train(cycle, trainloader_lab, trainloader_unlab, scheduler, optimizer)\n","sub_path":"main_ft.py","file_name":"main_ft.py","file_ext":"py","file_size_in_byte":17053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"109702250","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\n'''\n字典和列表方法\n1.创建一个字典,并把这个字典中的键按照字母顺序显示出来\n2.按照字母顺序排序好的键,显示出这个字典中的键和值\n3.按照字母顺序排序好的值,显示出这个字典的键和值\n'''\nimport random\ntest1 = {chr(i):random.uniform(0,i) for i in range(65,90)}\n#'键'\nfor i in sorted(test1.items()):\n print('键:%s,值:%s'% (i[0],i[1]))\n#'值' 注意这里的key函数\nfor i in sorted(test1.items(), key=lambda x: x[1]):\n print('键:%s,值:%s'% (i[0],i[1]))\n","sub_path":"7_3.py","file_name":"7_3.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"446969298","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jun 22 13:52:46 2019\r\n\r\n@author: javaa\r\n\r\n\"\"\"\r\nbalance = 3926\r\nannualInterestRate = 0.2\r\ndef min_rate(bal, air, mina):\r\n \"\"\"\r\n balance - the outstanding balance on the credit card\r\n annualInterestRate - annual interest rate as a decimal\r\n monthlyPaymentRate - minimum monthly payment rate as a decimal\r\n \r\n returns: minimum monthly payment required by the credit card company \r\n each month such that debt is paid of in 12 months.\r\n \"\"\"\r\n temp = bal\r\n for i in range(12):\r\n temp = (temp-mina)\r\n temp *= (1+air/12)\r\n if temp > 0:\r\n return min_rate(bal, air, mina+10)\r\n else:\r\n return mina\r\n\r\nprint('Lowest Payment: ' + str(min_rate(balance, annualInterestRate, 10)))\r\n","sub_path":"Problems/PSET2_recur.py","file_name":"PSET2_recur.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"107936898","text":"from lux.utils import test\nfrom lux.models import fields\n\nfrom tests.auth.utils import AuthUtils\n\n\nclass TestBackend(test.AppTestCase, AuthUtils):\n config_file = 'tests.auth'\n\n @classmethod\n def populatedb(cls):\n pass\n\n def test_backend(self):\n self.assertTrue(self.app.auth)\n\n @test.green\n def test_get_user_none(self):\n auth = self.app.auth\n with self.app.models.begin_session() as session:\n self.assertEqual(\n auth.get_user(session, id=18098098),\n None\n )\n self.assertEqual(\n auth.get_user(session, email='ksdcks.sdvddvf@djdjhdfc.com'),\n None\n )\n self.assertEqual(\n auth.get_user(session, username='dhvfvhsdfgvhfd'),\n None\n )\n\n def test_create_user(self):\n return self._new_credentials()\n\n @test.green\n def test_create_superuser(self):\n with self.app.models.begin_session() as session:\n user = self.app.auth.create_superuser(\n session,\n username='foo',\n email='foo@pippo.com',\n password='pluto',\n first_name='Foo'\n )\n self.assertTrue(user.id)\n self.assertEqual(user.first_name, 'Foo')\n self.assertTrue(user.superuser)\n self.assertTrue(user.active)\n\n @test.green\n def test_permissions(self):\n '''Test permission models\n '''\n odm = self.app.odm()\n\n with odm.begin() as session:\n user = odm.user(username=test.randomname())\n group = odm.group(name='staff')\n session.add(user)\n session.add(group)\n group.users.append(user)\n\n self.assertTrue(user.id)\n self.assertTrue(group.id)\n\n groups = user.groups\n self.assertTrue(group in groups)\n\n with odm.begin() as session:\n # add goup to the session\n session.add(group)\n permission = odm.permission(name='admin',\n description='Can access the admin',\n policy={})\n group.permissions.append(permission)\n\n def test_rest_user(self):\n \"\"\"Check that the RestField was overwritten properly\"\"\"\n model = self.app.models['users']\n schema = model.get_schema(model.model_schema)\n self.assertIsInstance(schema.fields['email'], fields.Email)\n","sub_path":"tests/auth/test_backend.py","file_name":"test_backend.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"104538221","text":"\nimport os.path\nimport tkinter\nimport tkinter.filedialog\nimport logging\nimport pprint\n\n# logging\nPY_FILE_NAME = os.path.basename(__file__).replace('.py', '')\nLOG_PATH = PY_FILE_NAME+'.log'\n\nlogger = logging.basicConfig(\n level=logging.INFO, filename=LOG_PATH, filemode='w')\nlogger = logging.getLogger(PY_FILE_NAME)\n\n\n# 隐藏主窗口\ntkobj = tkinter.Tk(); tkobj.withdraw()\n\n\n# ------------------------------------\n# init set\n\nfile_dir = os.path.dirname(__file__)\noutput_path = os.path.join(file_dir, '__temp_create_node.tcl')\ntemplate_path = tkinter.filedialog.askopenfilename(\n filetypes = (('template_csv_path', '*.csv'), ),\n initialdir=file_dir)\n\n\n# ------------------------------------\ndef template_read(csv_path):\n with open(csv_path, 'r') as f:\n csv_lines = [line for line in f.read().split('\\n') if line]\n\n node_ids, names, xs, ys, zs = [], [], [], [], []\n for line in csv_lines[1:]:\n list1d = [value for value in line.split(',') if value]\n new_id = int(''.join(list1d[:4]))\n node_ids.append(new_id)\n name, x, y, z = list1d[4:]\n names.append(name)\n xs.append(float(x))\n ys.append(float(y))\n zs.append(float(z))\n\n data = {'node_ids': node_ids, 'xs': xs, 'ys': ys, 'zs':zs, 'names': names}\n data_list = [node_ids, xs, ys, zs]\n\n return data, data_list\n\n\n\ndef tcl_write(output_path, data_list):\n\n f_output = open(output_path, 'w')\n temp_ids = {}\n for node_id, x, y, z in zip(*data_list):\n \tnode_str = f\"\"\"\n \t*createnode {x} {y} {z} 0 0 0\n \t\"\"\"\n \tf_output.write(node_str)\n\n logger.info(output_path)\n f_output.close()\n\n return True\n\n\n# ------------------------------------\n\ndata_template, data_template_list = template_read(template_path)\nresult = tcl_write(output_path, data_template_list)\nlogger.info('End')\n\nprint(result)\n","sub_path":"02.hm/AsetNodeIdRename/hmNodeCreate.py","file_name":"hmNodeCreate.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"69729854","text":"#lambida é uma função anonima e é um modo de\n# simplificar o que utilizaremos\n# varias vezes no código\ncontador_letras = lambda lista: [len(x) for x in lista]\n\nlista_animais = ['cachorro', 'gato', 'elefante']\nprint(contador_letras(lista_animais))\n\nsomaA = lambda a, b: a + b\nsubtracao = lambda a, b: a - b\n\ncalculadora = {\n 'soma': lambda a, b: a + b,\n 'subtracao': lambda a, b: a - b,\n 'multiplicacao':lambda a, b: a * b,\n 'divisao':lambda a, b: a / b,\n}\n\nprint(type(calculadora))\nsomaB = calculadora['soma']\n#somaB = lambda a, b: a + b\nmultiplicacao = calculadora['multiplicacao']\nprint('A multiplicação é: {}'.format( multiplicacao(10, 3)))\nprint('A soma é : {}'.format(somaA(10, 5)))\nprint('A soma é : {}'.format(somaB(5, 10)))\nprint('A subtração é : {}'.format(subtracao(8,2)))","sub_path":"Aula8_lambda.py","file_name":"Aula8_lambda.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"169520545","text":"\nfrom .api_types import ApiCall\n\nAPI_BASE_URL = \"http://www.openaustralia.org/api\"\n\n__version__ = \"1.0.1\"\n\n__all__ = [\n \"OpenAustralia\"\n]\n\n\nclass OpenAustralia:\n \"\"\" Client for OpenAustralia API.\n\n Provides an implementation for the REST api given at:\n http://www.openaustralia.org.au/api\n\n :param api_key: API Access key\n (http://www.openaustralia.org.au/api/key)\n :type api_key: string\n\n :param api_url: API url endpoint. Defaults to API_BASE_URL,\n but can be switched out (eg. point at your\n own instance for testing).\n :type api_url: string\n \"\"\"\n\n API_VERSION = __version__\n\n class House:\n representatives = 'representatives'\n senate = 'senate'\n\n def __init__(self, api_key, api_url=API_BASE_URL):\n self.api_key = api_key\n self.api_url = api_url\n if not api_url or not api_key:\n raise ValueError('Invalid parameters')\n if self.api_url.endswith('/'):\n self.api_url = self.api_url[:-1]\n\n def _oa_call(self, function, **kwargs):\n return ApiCall(\n self.api_url,\n self.api_key, function,\n **kwargs\n ).result\n\n def get_divisions(self, postcode=None, date=None, search=None):\n \"\"\" Fetch a list of electoral divisions.\n\n **Arguments:**\n\n :param postcode: (optional) Fetch the list of electoral divisions\n that are within the given postcode (there can be more\n than one)\n\n :param date: (optional) Fetch the list of electoral divisions as\n it was on this date.\n\n :param search: (optional) Fetch the list of electoral divisions\n that match this search string\n \"\"\"\n return self._oa_call(\n \"getDivisions\", postcode=postcode, date=date, search=search\n )\n\n def get_representative(\n self, person_id=None, division=None, always_return=None\n ):\n \"\"\" Fetch a particular member of the House of Representatives.\n\n **Arguments:**\n\n :param person_id: (optional) If you know the person ID for the member\n you want (returned from getRepresentatives or\n elsewhere), this will return data for that person.\n\n :param division: (optional) The name of an electoral division;\n we will try and work it out from whatever you\n give us. :)\n\n :param always_return: (optional) For the division option,\n sets whether to always try and return a Representative,\n even if the seat is currently vacant.\n \"\"\"\n return self._oa_call(\n \"getRepresentative\",\n id=person_id, division=division, always_return=always_return\n )\n\n def get_representatives(\n self, postcode=None, data=None, party=None, search=None\n ):\n \"\"\" Fetch a list of members of the House of Representatives.\n\n **Arguments:**\n\n :param postcode: (optional) Fetch the list of Representatives whose\n electoral division lies within the postcode (there may be\n more than one)\n\n :param date: (optional) Fetch the list of members of the House of\n Representatives as it was on this date.\n\n :param party: (optional) Fetch the list of Representatives from\n the given party.\n\n :param search: (optional) Fetch the list of Representatives that\n match this search string in their name.\n \"\"\"\n return self._oa_call(\n \"getRepresentatives\",\n postcode=postcode, data=data, party=party, search=search\n )\n\n def get_senator(self, person_id):\n \"\"\" Fetch a particular Senator.\n\n **Arguments:**\n\n :param person_id: (required) If you know the person ID for the Senator\n you want, this will return data for that person.\n \"\"\"\n return self._oa_call(\n \"getSenator\", id=person_id\n )\n\n def get_senators(self, date=None, party=None, state=None, search=None):\n \"\"\" Fetch a list of Senators.\n\n **Arguments:**\n\n :param date: (optional) Fetch the list of Senators as it was on this\n date.__version__\n\n :param party: (optional) Fetch the list of Senators from the given\n party.\n\n :param state: (optional) Fetch the list of Senators from the given\n state. (NSW, Tasmania, WA, Queensland, Victoria, SA, NT, ACT)\n\n :param search: (optional) Fetch the list of Senators that match this\n search string in their name.\n \"\"\"\n return self._oa_call(\n \"getSenators\",\n date=date, party=party, state=state, search=search\n )\n\n def get_debates(\n self, debate_type, date=None, search=None, person_id=None,\n gid=None, year=None, order=None, page=None, num=None\n ):\n \"\"\" Fetch Debates.\n\n This includes Oral Questions.\n\n **Arguments:**\n\n :param debate_type: (required) One of \"representatives\" or \"senate\".\n\n Note you can only supply one of the following search terms at present.\n\n :param date: Fetch the debates for this date.\n\n :param search: Fetch the debates that contain this term.\n\n :param person_id: Fetch the debates by a particular person ID.\n\n :param gid: Fetch the speech or debate that matches this GID.\n\n :param year: (Undocumented. Seems to return dates of debates, for\n matching year.)\n\n Result filtering:\n\n :param order: (optional, when using search or person)\n d for date ordering, r for relevance ordering.\n\n :param page: (optional, when using search or person) Page of results\n to return.\n\n :param num: (optional, when using search or person) Number of results\n to return.\n \"\"\"\n if not debate_type or debate_type.lower() not in (\n 'representatives', 'senate'\n ):\n raise ValueError(\"Invalid debate_type: {}\".format(debate_type))\n\n if not (date or search or person_id or gid or year):\n raise ValueError(\"At least one type of search must be given\")\n\n return self._oa_call(\n \"getDebates\",\n type=debate_type.lower(), date=date, search=search,\n person=person_id, gid=gid, year=year, order=order,\n page=page, num=num\n )\n\n def get_hansard(\n self, search=None, person_id=None, order=None, page=None, num=None\n ):\n \"\"\" Fetch all Hansard.\n\n **Arguments:**\n\n Note you can only supply one of the following at present.\n\n :param search: Fetch the data that contain this term.\n\n :param person_id: Fetch the data by a particular person ID.\n\n Result filtering:\n\n :param order: (optional, when using search or person, defaults to date)\n d for date ordering, r for relevance ordering, p for use by\n person.\n\n :param page: (optional, when using search or person) Page of results\n to return.\n\n :param num: (optional, when using search or person) Number of results\n to return.\n \"\"\"\n return self._oa_call(\n \"getHansard\",\n search=search, person=person_id,\n order=order, page=page, num=num\n )\n\n def get_comments(\n self, date=None, search=None, user_id=None, pid=None,\n page=None, num=None\n ):\n \"\"\" Fetch comments left on OpenAustralia.\n\n With no arguments, returns most recent comments in reverse date order.\n\n **Arguments:**\n\n :param date: (optional) Fetch the comments for this date.\n\n :param search: (optional) Fetch the comments that contain this term.\n\n :param user_id: (optional) Fetch the comments by a particular user ID.\n\n :param pid: (optional) Fetch the comments made on a particular\n person ID (Representative/Senator).\n\n :param page: (optional) Page of results to return.\n\n :param num: (optional) Number of results to return.\n \"\"\"\n return self._oa_call(\n \"getComments\",\n date=date, search=search, user_id=user_id, pid=pid,\n page=page, num=num\n )\n","sub_path":"venv/lib/python3.7/site-packages/openaustralia/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":8367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"630325093","text":"# -*- coding: utf-8 -*-\n\n\nclass Heuristic3Player(object):\n \"\"\"Implementa a herística que leva em conta a\n quantidade de peças que cada um vai ter\"\"\"\n\n def __init__(self, color):\n self.color = color\n\n def play(self, board):\n from models.minimax_alfabeta import MiniMaxAlfaBeta\n from models.players.heuristics import heuristic_mobility\n depth = 3\n minimax = MiniMaxAlfaBeta(depth)\n minimax.mini_max_alfa_beta(\n board,\n depth,\n self.color,\n float('-inf'),\n float('inf'),\n True,\n heuristic_mobility\n )\n\n return minimax.chosen_move\n\n","sub_path":"models/players/heuristic_3_player.py","file_name":"heuristic_3_player.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"53480130","text":"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Contains definitions for Residual Networks.\n\nResidual networks ('v1' ResNets) were originally proposed in:\n[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun\n Deep Residual Learning for Image Recognition. arXiv:1512.03385\n\nThe full preactivation 'v2' ResNet variant was introduced by:\n[2] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun\n Identity Mappings in Deep Residual Networks. arXiv: 1603.05027\n\nThe key difference of the full preactivation 'v2' variant compared to the\n'v1' variant in [1] is the use of batch normalization before every weight layer\nrather than after.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\napprox_module1616 = tf.load_op_library('./approx_kernel1616.so')\napprox_module1632 = tf.load_op_library('./approx_kernel1632.so')\napprox_module3232 = tf.load_op_library('./approx_kernel3232.so')\napprox_module6464 = tf.load_op_library('./approx_kernel6464.so')\napprox_module_flex = tf.load_op_library('./approx_module_flex.so')\n\n_BATCH_NORM_DECAY = 0.997\n_BATCH_NORM_EPSILON = 1e-5\nDEFAULT_VERSION = 2\nDEFAULT_DTYPE = tf.float32\nCASTABLE_TYPES = (tf.float16,)\nALLOWED_TYPES = (DEFAULT_DTYPE,) + CASTABLE_TYPES\n\nglobal my_layer\nmy_layer = 0\n\n################################################################################\n# Convenience functions for building the ResNet model.\n################################################################################\ndef batch_norm(inputs, training, data_format):\n \"\"\"Performs a batch normalization using a standard set of parameters.\"\"\"\n # We set fused=True for a significant performance boost. See\n # https://www.tensorflow.org/performance/performance_guide#common_fused_ops\n return tf.layers.batch_normalization(\n inputs=inputs, axis=1 if data_format == 'channels_first' else 3,\n momentum=_BATCH_NORM_DECAY, epsilon=_BATCH_NORM_EPSILON, center=True,\n scale=True, training=training, fused=True)\n\n\ndef fixed_padding(inputs, kernel_size, data_format):\n \"\"\"Pads the input along the spatial dimensions independently of input size.\n\n Args:\n inputs: A tensor of size [batch, channels, height_in, width_in] or\n [batch, height_in, width_in, channels] depending on data_format.\n kernel_size: The kernel to be used in the conv2d or max_pool2d operation.\n Should be a positive integer.\n data_format: The input format ('channels_last' or 'channels_first').\n\n Returns:\n A tensor with the same format as the input with the data either intact\n (if kernel_size == 1) or padded (if kernel_size > 1).\n \"\"\"\n pad_total = kernel_size - 1\n pad_beg = pad_total // 2\n pad_end = pad_total - pad_beg\n\n if data_format == 'channels_first':\n padded_inputs = tf.pad(inputs, [[0, 0], [0, 0],\n [pad_beg, pad_end], [pad_beg, pad_end]])\n else:\n padded_inputs = tf.pad(inputs, [[0, 0], [pad_beg, pad_end],\n [pad_beg, pad_end], [0, 0]])\n return padded_inputs\n\n\ndef conv2d_fixed_padding(inputs, filters, kernel_size, strides, data_format):\n\n global my_layer\n \"\"\"Strided 2-D convolution with explicit padding.\"\"\"\n # The padding is consistent and is based only on `kernel_size`, not on the\n # dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone).\n\n if strides > 1:\n inputs = fixed_padding(inputs, kernel_size, data_format)\n\n # return tf.layers.conv2d(\n # inputs=inputs, filters=filters, kernel_size=kernel_size, strides=strides,\n # padding=('SAME' if strides == 1 else 'VALID'), use_bias=False,\n # kernel_initializer=tf.variance_scaling_initializer(),\n # data_format=data_format)\n\n conversion_dict = {'channels_first':'NCHW','channels_last':'NHWC'}\n name = 'kernel' + str(my_layer)\n my_layer += 1\n\n if data_format == 'channels_first':\n channels = inputs.get_shape().as_list()[1]\n stride_list = [1,1,strides,strides]\n else:\n channels = inputs.get_shape().as_list()[-1]\n stride_list = [1,strides,strides,1]\n\n @tf.custom_gradient\n def tony_conv(input, filter):\n\n padding = ('SAME' if strides == 1 else 'VALID')\n\n print(filter.get_shape().as_list())\n def grad(dy):\n selector = tf.floor(tf.reduce_sum(dy[0,0,0,:]))\n print(selector.shape)\n\n def regular_grad():\n return [\n tf.nn.conv2d_backprop_input(input_sizes=tf.shape(input), filter=filter, out_backprop=dy,\n strides=stride_list,\n padding=padding,data_format=conversion_dict[data_format]),\n tf.nn.conv2d_backprop_filter(input=input, filter_sizes=filter.shape, out_backprop=dy,\n strides=stride_list,\n padding=padding,data_format=conversion_dict[data_format])]\n\n def tony_grad():\n\n filter_x = filter.get_shape().as_list()[0]\n filter_y = filter.get_shape().as_list()[1]\n\n assert data_format == \"channels_first\"\n\n if padding == 'VALID':\n\n input_1 = tf.transpose(input,perm = [0,2,3,1])\n tony = approx_module.tony_conv_grad(input_1, dy, stride_list[2],filter_x, filter_y)\n print(tony.shape)\n return [\n tf.nn.conv2d_backprop_input(input_sizes=tf.shape(input), filter=filter, out_backprop=dy,\n strides=stride_list,\n padding=padding,data_format=conversion_dict[data_format]),\n tf.transpose(tony,perm=[1,2,3,0])]\n else:\n\n\n padded_input = tf.pad(input, [[0, 0], [0,0], [1, 2], [1, 2]])\n\n input_channel = input.shape[1]\n output_channel = dy.shape[1]\n\n padded_input = tf.transpose(padded_input,perm = [0,2,3,1])\n\n if input_channel == 16 and output_channel == 16:\n tony = approx_module1616.tony_conv_grad1616(padded_input, dy, stride_list[2],filter_x, filter_y)\n elif input_channel == 16 and output_channel == 32:\n tony = approx_module1632.tony_conv_grad1616(padded_input, dy, stride_list[2],filter_x, filter_y)\n elif input_channel == 32 and output_channel == 32:\n tony = approx_module3232.tony_conv_grad1616(padded_input, dy, stride_list[2],filter_x, filter_y)\n elif input_channel == 64 and output_channel == 64:\n tony = approx_module6464.tony_conv_grad1616(padded_input, dy, stride_list[2],filter_x, filter_y)\n else:\n tony = approx_module_flex.tony_conv_grad1616(padded_input, dy, stride_list[2],filter_x, filter_y)\n\n print(tony.shape)\n print(dy.shape)\n\n return [\n tf.nn.conv2d_backprop_input(input_sizes=tf.shape(input), filter=filter, out_backprop=dy,\n strides=stride_list,\n padding=padding,data_format=conversion_dict[data_format]),\n tf.transpose(tony,perm=[1,2,3,0])]\n\n def zero_grad():\n\n filter_x = filter.get_shape().as_list()[0]\n filter_y = filter.get_shape().as_list()[1]\n ic = input.get_shape().as_list()[1]\n oc = dy.get_shape().as_list()[1]\n\n left_pad1 = filter.shape[0] // 2\n right_pad1 = filter.shape[0] - left_pad1\n left_pad2 = filter.shape[1] // 2\n right_pad2 = filter.shape[1] - left_pad2\n padded_input = tf.pad(input, [[0, 0], [0,0], [left_pad1, right_pad1], [left_pad2, right_pad2]])\n\n padded_input = tf.transpose(padded_input,perm = [0,2,3,1])\n padded_input = tf.Print(padded_input) \n return [\n tf.nn.conv2d_backprop_input(input_sizes=tf.shape(input), filter=filter, out_backprop=dy,\n strides=stride_list,\n padding=padding,data_format=conversion_dict[data_format]),\n tf.zeros([filter_x,filter_y,ic,oc])]\n\n\n return tf.cond(tf.logical_or(tf.equal(tf.mod(selector * 10001, 2), 1),tf.logical_not(tf.equal(tf.shape(input)[0],128))), regular_grad, tony_grad)\n\n #return tf.cond(tf.equal(tf.mod(selector * 10001, 2), 1), regular_grad, tony_grad)\n #return tf.cond(tf.equal(tf.mod(selector * 10001, 2), 1), zero_grad, zero_grad)\n #return [\n # tf.nn.conv2d_backprop_input(input_sizes=tf.shape(input), filter=filter, out_backprop=dy,\n # strides=stride_list,\n # padding=padding,data_format=conversion_dict[data_format]),\n # tf.nn.conv2d_backprop_filter(input=input, filter_sizes=filter.shape, out_backprop=dy,\n # strides=stride_list,\n # padding=padding,data_format=conversion_dict[data_format])]\n\n return tf.nn.conv2d(input, filter, strides=stride_list, padding=padding,data_format=conversion_dict[data_format]), grad\n\n filts = tf.get_variable(name,initializer=tf.variance_scaling_initializer(),shape=[kernel_size, kernel_size, channels, filters],trainable=True)\n\n if my_layer %2 == 0 and kernel_size != 1:\n return tony_conv(inputs,filts)\n else:\n return tf.nn.conv2d(input=inputs,filter=filts,strides=stride_list,padding=('SAME' if strides == 1 else 'VALID'),data_format=conversion_dict[data_format])\n\n\n\n\n\n\n################################################################################\n# ResNet block definitions.\n################################################################################\ndef _building_block_v1(inputs, filters, training, projection_shortcut, strides,\n data_format):\n \"\"\"A single block for ResNet v1, without a bottleneck.\n\n Convolution then batch normalization then ReLU as described by:\n Deep Residual Learning for Image Recognition\n https://arxiv.org/pdf/1512.03385.pdf\n by Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun, Dec 2015.\n\n Args:\n inputs: A tensor of size [batch, channels, height_in, width_in] or\n [batch, height_in, width_in, channels] depending on data_format.\n filters: The number of filters for the convolutions.\n training: A Boolean for whether the model is in training or inference\n mode. Needed for batch normalization.\n projection_shortcut: The function to use for projection shortcuts\n (typically a 1x1 convolution when downsampling the input).\n strides: The block's stride. If greater than 1, this block will ultimately\n downsample the input.\n data_format: The input format ('channels_last' or 'channels_first').\n\n Returns:\n The output tensor of the block; shape should match inputs.\n \"\"\"\n shortcut = inputs\n\n if projection_shortcut is not None:\n shortcut = projection_shortcut(inputs)\n shortcut = batch_norm(inputs=shortcut, training=training,\n data_format=data_format)\n\n inputs = conv2d_fixed_padding(\n inputs=inputs, filters=filters, kernel_size=3, strides=strides,\n data_format=data_format)\n inputs = batch_norm(inputs, training, data_format)\n inputs = tf.nn.relu(inputs)\n\n inputs = conv2d_fixed_padding(\n inputs=inputs, filters=filters, kernel_size=3, strides=1,\n data_format=data_format)\n inputs = batch_norm(inputs, training, data_format)\n inputs += shortcut\n inputs = tf.nn.relu(inputs)\n\n return inputs\n\n\ndef _building_block_v2(inputs, filters, training, projection_shortcut, strides,\n data_format):\n \"\"\"A single block for ResNet v2, without a bottleneck.\n\n Batch normalization then ReLu then convolution as described by:\n Identity Mappings in Deep Residual Networks\n https://arxiv.org/pdf/1603.05027.pdf\n by Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun, Jul 2016.\n\n Args:\n inputs: A tensor of size [batch, channels, height_in, width_in] or\n [batch, height_in, width_in, channels] depending on data_format.\n filters: The number of filters for the convolutions.\n training: A Boolean for whether the model is in training or inference\n mode. Needed for batch normalization.\n projection_shortcut: The function to use for projection shortcuts\n (typically a 1x1 convolution when downsampling the input).\n strides: The block's stride. If greater than 1, this block will ultimately\n downsample the input.\n data_format: The input format ('channels_last' or 'channels_first').\n\n Returns:\n The output tensor of the block; shape should match inputs.\n \"\"\"\n shortcut = inputs\n inputs = batch_norm(inputs, training, data_format)\n inputs = tf.nn.relu(inputs)\n\n # The projection shortcut should come after the first batch norm and ReLU\n # since it performs a 1x1 convolution.\n if projection_shortcut is not None:\n shortcut = projection_shortcut(inputs)\n\n inputs = conv2d_fixed_padding(\n inputs=inputs, filters=filters, kernel_size=3, strides=strides,\n data_format=data_format)\n\n inputs = batch_norm(inputs, training, data_format)\n inputs = tf.nn.relu(inputs)\n inputs = conv2d_fixed_padding(\n inputs=inputs, filters=filters, kernel_size=3, strides=1,\n data_format=data_format)\n\n return inputs + shortcut\n\n\ndef _bottleneck_block_v1(inputs, filters, training, projection_shortcut,\n strides, data_format):\n \"\"\"A single block for ResNet v1, with a bottleneck.\n\n Similar to _building_block_v1(), except using the \"bottleneck\" blocks\n described in:\n Convolution then batch normalization then ReLU as described by:\n Deep Residual Learning for Image Recognition\n https://arxiv.org/pdf/1512.03385.pdf\n by Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun, Dec 2015.\n\n Args:\n inputs: A tensor of size [batch, channels, height_in, width_in] or\n [batch, height_in, width_in, channels] depending on data_format.\n filters: The number of filters for the convolutions.\n training: A Boolean for whether the model is in training or inference\n mode. Needed for batch normalization.\n projection_shortcut: The function to use for projection shortcuts\n (typically a 1x1 convolution when downsampling the input).\n strides: The block's stride. If greater than 1, this block will ultimately\n downsample the input.\n data_format: The input format ('channels_last' or 'channels_first').\n\n Returns:\n The output tensor of the block; shape should match inputs.\n \"\"\"\n shortcut = inputs\n\n if projection_shortcut is not None:\n shortcut = projection_shortcut(inputs)\n shortcut = batch_norm(inputs=shortcut, training=training,\n data_format=data_format)\n\n inputs = conv2d_fixed_padding(\n inputs=inputs, filters=filters, kernel_size=1, strides=1,\n data_format=data_format)\n inputs = batch_norm(inputs, training, data_format)\n inputs = tf.nn.relu(inputs)\n\n inputs = conv2d_fixed_padding(\n inputs=inputs, filters=filters, kernel_size=3, strides=strides,\n data_format=data_format)\n inputs = batch_norm(inputs, training, data_format)\n inputs = tf.nn.relu(inputs)\n\n inputs = conv2d_fixed_padding(\n inputs=inputs, filters=4 * filters, kernel_size=1, strides=1,\n data_format=data_format)\n inputs = batch_norm(inputs, training, data_format)\n inputs += shortcut\n inputs = tf.nn.relu(inputs)\n\n return inputs\n\n\ndef _bottleneck_block_v2(inputs, filters, training, projection_shortcut,\n strides, data_format):\n \"\"\"A single block for ResNet v2, without a bottleneck.\n\n Similar to _building_block_v2(), except using the \"bottleneck\" blocks\n described in:\n Convolution then batch normalization then ReLU as described by:\n Deep Residual Learning for Image Recognition\n https://arxiv.org/pdf/1512.03385.pdf\n by Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun, Dec 2015.\n\n Adapted to the ordering conventions of:\n Batch normalization then ReLu then convolution as described by:\n Identity Mappings in Deep Residual Networks\n https://arxiv.org/pdf/1603.05027.pdf\n by Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun, Jul 2016.\n\n Args:\n inputs: A tensor of size [batch, channels, height_in, width_in] or\n [batch, height_in, width_in, channels] depending on data_format.\n filters: The number of filters for the convolutions.\n training: A Boolean for whether the model is in training or inference\n mode. Needed for batch normalization.\n projection_shortcut: The function to use for projection shortcuts\n (typically a 1x1 convolution when downsampling the input).\n strides: The block's stride. If greater than 1, this block will ultimately\n downsample the input.\n data_format: The input format ('channels_last' or 'channels_first').\n\n Returns:\n The output tensor of the block; shape should match inputs.\n \"\"\"\n shortcut = inputs\n inputs = batch_norm(inputs, training, data_format)\n inputs = tf.nn.relu(inputs)\n\n # The projection shortcut should come after the first batch norm and ReLU\n # since it performs a 1x1 convolution.\n if projection_shortcut is not None:\n shortcut = projection_shortcut(inputs)\n\n inputs = conv2d_fixed_padding(\n inputs=inputs, filters=filters, kernel_size=1, strides=1,\n data_format=data_format)\n\n inputs = batch_norm(inputs, training, data_format)\n inputs = tf.nn.relu(inputs)\n inputs = conv2d_fixed_padding(\n inputs=inputs, filters=filters, kernel_size=3, strides=strides,\n data_format=data_format)\n\n inputs = batch_norm(inputs, training, data_format)\n inputs = tf.nn.relu(inputs)\n inputs = conv2d_fixed_padding(\n inputs=inputs, filters=4 * filters, kernel_size=1, strides=1,\n data_format=data_format)\n\n return inputs + shortcut\n\n\ndef block_layer(inputs, filters, bottleneck, block_fn, blocks, strides,\n training, name, data_format):\n \"\"\"Creates one layer of blocks for the ResNet model.\n\n Args:\n inputs: A tensor of size [batch, channels, height_in, width_in] or\n [batch, height_in, width_in, channels] depending on data_format.\n filters: The number of filters for the first convolution of the layer.\n bottleneck: Is the block created a bottleneck block.\n block_fn: The block to use within the model, either `building_block` or\n `bottleneck_block`.\n blocks: The number of blocks contained in the layer.\n strides: The stride to use for the first convolution of the layer. If\n greater than 1, this layer will ultimately downsample the input.\n training: Either True or False, whether we are currently training the\n model. Needed for batch norm.\n name: A string name for the tensor output of the block layer.\n data_format: The input format ('channels_last' or 'channels_first').\n\n Returns:\n The output tensor of the block layer.\n \"\"\"\n\n # Bottleneck blocks end with 4x the number of filters as they start with\n filters_out = filters * 4 if bottleneck else filters\n\n def projection_shortcut(inputs):\n return conv2d_fixed_padding(\n inputs=inputs, filters=filters_out, kernel_size=1, strides=strides,\n data_format=data_format)\n\n # Only the first block per block_layer uses projection_shortcut and strides\n inputs = block_fn(inputs, filters, training, projection_shortcut, strides,\n data_format)\n\n for _ in range(1, blocks):\n inputs = block_fn(inputs, filters, training, None, 1, data_format)\n\n return tf.identity(inputs, name)\n\n\nclass Model(object):\n \"\"\"Base class for building the Resnet Model.\"\"\"\n\n def __init__(self, resnet_size, bottleneck, num_classes, num_filters,\n kernel_size,\n conv_stride, first_pool_size, first_pool_stride,\n block_sizes, block_strides,\n final_size, resnet_version=DEFAULT_VERSION, data_format=None,\n dtype=DEFAULT_DTYPE):\n \"\"\"Creates a model for classifying an image.\n\n Args:\n resnet_size: A single integer for the size of the ResNet model.\n bottleneck: Use regular blocks or bottleneck blocks.\n num_classes: The number of classes used as labels.\n num_filters: The number of filters to use for the first block layer\n of the model. This number is then doubled for each subsequent block\n layer.\n kernel_size: The kernel size to use for convolution.\n conv_stride: stride size for the initial convolutional layer\n first_pool_size: Pool size to be used for the first pooling layer.\n If none, the first pooling layer is skipped.\n first_pool_stride: stride size for the first pooling layer. Not used\n if first_pool_size is None.\n block_sizes: A list containing n values, where n is the number of sets of\n block layers desired. Each value should be the number of blocks in the\n i-th set.\n block_strides: List of integers representing the desired stride size for\n each of the sets of block layers. Should be same length as block_sizes.\n final_size: The expected size of the model after the second pooling.\n resnet_version: Integer representing which version of the ResNet network\n to use. See README for details. Valid values: [1, 2]\n data_format: Input format ('channels_last', 'channels_first', or None).\n If set to None, the format is dependent on whether a GPU is available.\n dtype: The TensorFlow dtype to use for calculations. If not specified\n tf.float32 is used.\n\n Raises:\n ValueError: if invalid version is selected.\n \"\"\"\n self.resnet_size = resnet_size\n\n if not data_format:\n data_format = (\n 'channels_first' if tf.test.is_built_with_cuda() else 'channels_last')\n\n self.resnet_version = resnet_version\n if resnet_version not in (1, 2):\n raise ValueError(\n 'Resnet version should be 1 or 2. See README for citations.')\n\n self.bottleneck = bottleneck\n if bottleneck:\n if resnet_version == 1:\n self.block_fn = _bottleneck_block_v1\n else:\n self.block_fn = _bottleneck_block_v2\n else:\n if resnet_version == 1:\n self.block_fn = _building_block_v1\n else:\n self.block_fn = _building_block_v2\n\n if dtype not in ALLOWED_TYPES:\n raise ValueError('dtype must be one of: {}'.format(ALLOWED_TYPES))\n\n self.data_format = data_format\n self.num_classes = num_classes\n self.num_filters = num_filters\n self.kernel_size = kernel_size\n self.conv_stride = conv_stride\n self.first_pool_size = first_pool_size\n self.first_pool_stride = first_pool_stride\n self.block_sizes = block_sizes\n self.block_strides = block_strides\n self.final_size = final_size\n self.dtype = dtype\n self.pre_activation = resnet_version == 2\n\n def _custom_dtype_getter(self, getter, name, shape=None, dtype=DEFAULT_DTYPE,\n *args, **kwargs):\n \"\"\"Creates variables in fp32, then casts to fp16 if necessary.\n\n This function is a custom getter. A custom getter is a function with the\n same signature as tf.get_variable, except it has an additional getter\n parameter. Custom getters can be passed as the `custom_getter` parameter of\n tf.variable_scope. Then, tf.get_variable will call the custom getter,\n instead of directly getting a variable itself. This can be used to change\n the types of variables that are retrieved with tf.get_variable.\n The `getter` parameter is the underlying variable getter, that would have\n been called if no custom getter was used. Custom getters typically get a\n variable with `getter`, then modify it in some way.\n\n This custom getter will create an fp32 variable. If a low precision\n (e.g. float16) variable was requested it will then cast the variable to the\n requested dtype. The reason we do not directly create variables in low\n precision dtypes is that applying small gradients to such variables may\n cause the variable not to change.\n\n Args:\n getter: The underlying variable getter, that has the same signature as\n tf.get_variable and returns a variable.\n name: The name of the variable to get.\n shape: The shape of the variable to get.\n dtype: The dtype of the variable to get. Note that if this is a low\n precision dtype, the variable will be created as a tf.float32 variable,\n then cast to the appropriate dtype\n *args: Additional arguments to pass unmodified to getter.\n **kwargs: Additional keyword arguments to pass unmodified to getter.\n\n Returns:\n A variable which is cast to fp16 if necessary.\n \"\"\"\n\n if dtype in CASTABLE_TYPES:\n var = getter(name, shape, tf.float32, *args, **kwargs)\n return tf.cast(var, dtype=dtype, name=name + '_cast')\n else:\n return getter(name, shape, dtype, *args, **kwargs)\n\n def _model_variable_scope(self):\n \"\"\"Returns a variable scope that the model should be created under.\n\n If self.dtype is a castable type, model variable will be created in fp32\n then cast to self.dtype before being used.\n\n Returns:\n A variable scope for the model.\n \"\"\"\n\n return tf.variable_scope('resnet_model',\n custom_getter=self._custom_dtype_getter)\n\n def __call__(self, inputs, training):\n \"\"\"Add operations to classify a batch of input images.\n\n Args:\n inputs: A Tensor representing a batch of input images.\n training: A boolean. Set to True to add operations required only when\n training the classifier.\n\n Returns:\n A logits Tensor with shape [, self.num_classes].\n \"\"\"\n\n with self._model_variable_scope():\n if self.data_format == 'channels_first':\n # Convert the inputs from channels_last (NHWC) to channels_first (NCHW).\n # This provides a large performance boost on GPU. See\n # https://www.tensorflow.org/performance/performance_guide#data_formats\n inputs = tf.transpose(inputs, [0, 3, 1, 2])\n\n inputs = conv2d_fixed_padding(\n inputs=inputs, filters=self.num_filters, kernel_size=self.kernel_size,\n strides=self.conv_stride, data_format=self.data_format)\n inputs = tf.identity(inputs, 'initial_conv')\n\n # We do not include batch normalization or activation functions in V2\n # for the initial conv1 because the first ResNet unit will perform these\n # for both the shortcut and non-shortcut paths as part of the first\n # block's projection. Cf. Appendix of [2].\n if self.resnet_version == 1:\n inputs = batch_norm(inputs, training, self.data_format)\n inputs = tf.nn.relu(inputs)\n\n if self.first_pool_size:\n inputs = tf.layers.max_pooling2d(\n inputs=inputs, pool_size=self.first_pool_size,\n strides=self.first_pool_stride, padding='SAME',\n data_format=self.data_format)\n inputs = tf.identity(inputs, 'initial_max_pool')\n\n for i, num_blocks in enumerate(self.block_sizes):\n num_filters = self.num_filters * (2**i)\n inputs = block_layer(\n inputs=inputs, filters=num_filters, bottleneck=self.bottleneck,\n block_fn=self.block_fn, blocks=num_blocks,\n strides=self.block_strides[i], training=training,\n name='block_layer{}'.format(i + 1), data_format=self.data_format)\n\n # Only apply the BN and ReLU for model that does pre_activation in each\n # building/bottleneck block, eg resnet V2.\n if self.pre_activation:\n inputs = batch_norm(inputs, training, self.data_format)\n inputs = tf.nn.relu(inputs)\n\n # The current top layer has shape\n # `batch_size x pool_size x pool_size x final_size`.\n # ResNet does an Average Pooling layer over pool_size,\n # but that is the same as doing a reduce_mean. We do a reduce_mean\n # here because it performs better than AveragePooling2D.\n axes = [2, 3] if self.data_format == 'channels_first' else [1, 2]\n inputs = tf.reduce_mean(inputs, axes, keepdims=True)\n inputs = tf.identity(inputs, 'final_reduce_mean')\n\n inputs = tf.reshape(inputs, [-1, self.final_size])\n inputs = tf.layers.dense(inputs=inputs, units=self.num_classes)\n inputs = tf.identity(inputs, 'final_dense')\n return inputs\n","sub_path":"model_harness/models/resnet_model.py","file_name":"resnet_model.py","file_ext":"py","file_size_in_byte":30827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"389922108","text":"import tweepy\nfrom pymongo import MongoClient\nimport json\nimport os\nimport time\nimport sys \nfrom Timeline import getUserTimeline\n\nclient = MongoClient()\ndb = client.IDs\n\nAUTH_KEYS = []\n\n\n\n# General helper function for initAuthKeys. This adds the authenticated key to AUTH_KEYS\n# for the program to use later. Currently, this does not work. I get an exception trying to use\n# multiple keys at once. \ndef authenticate(listWithAuthKeys):\n\tauth = tweepy.OAuthHandler(listWithAuthKeys[0], listWithAuthKeys[1])\n\tauth.set_access_token(listWithAuthKeys[2], listWithAuthKeys[3])\n\tAUTH_KEYS.append(tweepy.API(auth))\n\n# Function will init the auth keys recursively and throw a \"Used all keys.\" Error message when it \n# has stepped through all of the auth keys in the secrets.json file.\ndef initAuthKeys(keyCount):\n\ttry:\n\t\twith open('secrets.json', 'r') as f:\n\t\t\tdata = json.load(f)\n\t\t\tCKEY = data[\"auth\" + str(keyCount)][\"CKEY\"]\n\t\t\tCSECRET = data[\"auth\" + str(keyCount)][\"CSecret\"]\n\t\t\tAKEY = data[\"auth\" + str(keyCount)][\"AToken\"]\n\t\t\tASECRET = data[\"auth\" + str(keyCount)][\"ASecret\"]\n\t\t\tkey = [CKEY, CSECRET, AKEY, ASECRET]\n\t\t\tauthenticate(key)\n\t\t\tinitAuthKeys(keyCount + 1)\n\texcept KeyError:\n\t\tprint(\"Used all keys.\")\n\n# This function takes information from getUserOneLevel and formats it into a python dictionary\n# which MongoDB will gladly accept and insert into the database.\ndef formatJson(id, followersList, following):\n\tuser = {\"TID\" : id}\n\tuser[\"followers\"] = {}\n\tuser[\"following\"] = {}\n\t\n\tfor i,value in enumerate(followersList):\n\t\tuser[\"followers\"][str(i)] = str(value)\t\n\tfor i, value in enumerate(following):\n\t\tuser[\"following\"][str(i)] = str(value)\n\treturn user\n\n# Given an originaly user (passed from main), this function will collect all of \n# the followers and people following of every single person in relation to the original user.\ndef getUserOneLevel(follower, api):\n\tprint(\"Getting info for \" + str(follower))\n\tfollowerIDS = []\n\tfollowingIDS = []\n\tdbCollectionName = \"info_\" + str(follower) \n\tfor page in tweepy.Cursor(api.followers_ids, id = follower).pages(1):\n\t\tfollowerIDS.extend(page)\n\t\ttime.sleep(61)\n\t\n\tfor page in tweepy.Cursor(api.friends_ids, id = follower).pages(1):\n\t\tfollowingIDS.extend(page)\n\t\ttime.sleep(61)\n\tdb[dbCollectionName].insert_one(formatJson(follower, followerIDS, followingIDS))\n\nif __name__ == '__main__':\n\t\n\tlookupTerm = sys.argv[1]\n\tdbCollectionName = \"info_\" + lookupTerm\n\n\tinitAuthKeys(0)\n\n\t# getUserTimeline is implemented and works, however I haven't implemented it into this code yet.\n\t# Simply call the function with the (, ) and it will return\n\t# the raw data of the user's metadata, and 20 most recent tweets.\n\t#print(getUserTimeline(lookupTerm, AUTH_KEYS[0]))\n\n\t#Get initial following/follower list of user entered. \n\tfollowerIDS = []\n\tfollowingIDS = []\n\tCKEY = \"\"\n\tCSECRET = \"\"\n\tAKEY = \"\"\n\tASECRET = \"\"\n\tkeyCount = 0 \n\twith open('secrets.json', 'r') as f:\n\t\tdata = json.load(f)\n\t\tCKEY = data[\"auth\" + str(keyCount)][\"CKEY\"]\n\t\tCSECRET = data[\"auth\" + str(keyCount)][\"CSecret\"]\n\t\tAKEY = data[\"auth\" + str(keyCount)][\"AToken\"]\n\t\tASECRET = data[\"auth\" + str(keyCount)][\"ASecret\"]\n\t#api = AUTH_KEYS[0]\n\tprint(\"CKEY: \" + str(CKEY) + \"\\n\" + \"CSECRET: \" + str(CSECRET) + \"\\nAKEY: \" + str(AKEY) + \"\\nASECRET\" + str(ASECRET))\n\tauth = tweepy.OAuthHandler(CKEY, CSECRET)\n\tauth.set_access_token(AKEY, ASECRET)\n\tapi = tweepy.API(auth)\n\t\n\t\t\n\tfor page in tweepy.Cursor(AUTH_KEYS[0].followers_ids, id=lookupTerm).pages(1):\n\t\tprint(\"Getting followers for \" + str(lookupTerm))\n\t\tfollowerIDS.extend(page)\n\t\ttime.sleep(61)\n\t\n\tfor page in tweepy.Cursor(AUTH_KEYS[0].friends_ids, id=lookupTerm).pages(1):\n\t\tprint(\"Getting people who \" + str(lookupTerm) + \" follows\")\n\t\tfollowingIDS.extend(page)\n\t\ttime.sleep(61)\n\t\n\tdb[dbCollectionName].insert_one(formatJson(lookupTerm, followerIDS, followingIDS))\n\tfor follower in followerIDS:\n\t\tgetUserFollowers(follower, AUTH_KEYS[0])\t\n\n\n","sub_path":"GetData.py","file_name":"GetData.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"119779036","text":"import json\nimport numpy as np\nfrom itertools import groupby\nfrom sortedcontainers import SortedList\n\nfrom TS.Edge import Edge\nfrom TS.State import State\n\n\nclass TransitionSystem:\n def __init__(self, ordering: SortedList):\n self.states_encoding = dict() # State -> int\n self.edges = set() # Edge objects: (int from, int to, probability), can be used for explicit Storm format\n self.ordering = ordering # used to decode State to actual agents\n self.init = int\n\n # for TS generating\n self.unprocessed = set()\n self.processed = set()\n\n def __str__(self):\n return str(self.states_encoding) + \"\\n\" + \"\\n\".join(list(map(str, self.edges))) + \"\\n\" + str(self.ordering)\n\n def __repr__(self):\n return str(self)\n\n def __iter__(self):\n \"\"\"\n Used to iterate over equivalence classes (given by source) of sorted edges.\n \"\"\"\n self.index = 0\n edges = sorted(self.edges)\n self.data = groupby(edges, key=lambda edge: edge.source)\n return self\n\n def __next__(self):\n new = next(self.data)\n return list(new[-1])\n\n def __eq__(self, other: 'TransitionSystem'):\n \"\"\"\n Compares with another TransitionSystem regardless the particular encoding (i.e. check isomorphism).\n\n :param other: given TransitionSystem\n :return: True if equal\n \"\"\"\n success, reordering_indices = create_indices(other.ordering, self.ordering)\n if not success: # the agents in orderings are different => also whole TSs are different\n return False\n\n re_encoding = {key.reorder(reordering_indices): self.states_encoding[key] for key in self.states_encoding}\n\n # new TransitionSystem with ordering taken from other and reordered states in re_encoding\n ts = TransitionSystem(other.ordering)\n ts.states_encoding = re_encoding\n ts.edges = self.edges\n\n try:\n ts.recode(other.states_encoding)\n except KeyError:\n return False\n\n # this is weird, but well...\n return set(map(hash, ts.edges)) == set(map(hash, other.edges))\n # return ts.edges == other.edges\n\n def encode(self, init: State):\n \"\"\"\n Assigns a unique code to each State for storing purposes\n \"\"\"\n for state in self.processed | self.unprocessed:\n if state not in self.states_encoding:\n self.states_encoding[state] = len(self.states_encoding) + 1\n\n self.init = self.states_encoding[init]\n self.processed = set()\n self.encode_edges()\n\n def encode_edges(self):\n \"\"\"\n Encodes every State in Edge according to the unique encoding.\n \"\"\"\n for edge in self.edges:\n edge.encode(self.states_encoding)\n\n def create_decoding(self) -> dict:\n \"\"\"\n Swaps encoding dictionary for decoding purposes.\n\n :return: swapped dictionary\n \"\"\"\n return {value: key for key, value in self.states_encoding.items()}\n\n def recode(self, new_encoding: dict):\n \"\"\"\n Recodes the transition system according to the new encoding.\n\n :param new_encoding: given new encoding\n :return: new TransitionSystem\n \"\"\"\n # swap dictionary\n old_encoding = self.create_decoding()\n self.edges = set(map(lambda edge: edge.recode(old_encoding, new_encoding), self.edges))\n\n def save_to_json(self, output_file: str):\n \"\"\"\n Save current TS as a JSON file.\n\n :param output_file: given file to write to\n \"\"\"\n nodes = {value: str(key) for key, value in self.states_encoding.items()}\n unique = list(map(str, self.ordering))\n edges = [edge.to_dict() for edge in self.edges]\n\n data = {'nodes': nodes, 'edges': edges, 'ordering': unique, \"initial\": self.init}\n\n if self.unprocessed:\n data['unprocessed'] = [str(state) for state in self.unprocessed]\n\n with open(output_file, 'w') as json_file:\n json.dump(data, json_file, indent=4)\n\n def change_hell(self, bound):\n \"\"\"\n Changes hell from inf to bound + 1.\n\n TODO: maybe we could get rid of inf completely, but it is more clear for\n debugging purposes\n\n :param bound: given allowed bound\n \"\"\"\n for key, value in self.states_encoding.items():\n if key.is_inf:\n del self.states_encoding[key]\n hell = State(np.array([bound + 1] * len(key)))\n hell.is_inf = True\n self.states_encoding[hell] = value\n break\n\n def save_to_STORM_explicit(self, transitions_file: str, labels_file: str, state_labels: dict, AP_labels):\n \"\"\"\n Save the TransitionSystem as explicit Storm file (no parameters).\n\n :param transitions_file: file for transitions\n :param labels_file: file for labels\n :param labels: labels representing atomic propositions assigned to states\n \"\"\"\n trans_file = open(transitions_file, \"w+\")\n trans_file.write(\"dtmc\\n\")\n\n for edge in sorted(self.edges):\n trans_file.write(str(edge) + \"\\n\")\n trans_file.close()\n\n label_file = open(labels_file, \"w+\")\n unique_labels = ['init'] + list(map(str, AP_labels.values()))\n label_file.write(\"#DECLARATION\\n\" + \" \".join(unique_labels) + \"\\n#END\\n\")\n\n label_file.write(\"\\n\".join([str(state) + \" \" + \" \".join(list(map(str, state_labels[state])))\n for state in sorted(state_labels)]))\n label_file.close()\n\n def save_to_prism(self, output_file: str, bound: int, params: set, prism_formulas: list):\n \"\"\"\n Save the TransitionSystem as a PRISM file (parameters present).\n\n :param output_file: output file name\n :param bound: given bound\n :param params: set of present parameters\n :param prism_formulas: definition of abstract Complexes\n \"\"\"\n\n prism_file = open(output_file, \"w+\")\n prism_file.write(\"dtmc\\n\")\n\n # declare parameters\n prism_file.write(\"\\n\" + \"\\n\".join([\"\\tconst double {};\".format(param) for param in params]) + \"\\n\")\n prism_file.write(\"\\nmodule TS\\n\")\n\n # to get rid of inf\n self.change_hell(bound)\n decoding = self.create_decoding()\n\n # declare state variables\n init = decoding[self.init]\n vars = [\"\\tVAR_{} : [0..{}] init {}; // {}\".format(i, bound + 1, init.sequence[i], self.ordering[i])\n for i in range(len(self.ordering))]\n prism_file.write(\"\\n\" + \"\\n\".join(vars) + \"\\n\")\n\n # write transitions\n transitions = self.edges_to_PRISM(decoding)\n prism_file.write(\"\\n\" + \"\\n\".join(transitions))\n\n prism_file.write(\"\\nendmodule\\n\\n\")\n\n # write formulas\n if prism_formulas:\n prism_file.write(\"\\n\\tformula \" + \"\\n\".join(prism_formulas))\n\n prism_file.close()\n\n def edges_to_PRISM(self, decoding):\n \"\"\"\n Takes ordered edges grouped by source and for each group creates PRISM file representation\n\n :return: list of strings for each group (source)\n \"\"\"\n output = []\n for group in self:\n source = group[0].source\n line = \"\\t[] \" + decoding[source].to_PRISM_string() + \" -> \" + \\\n \" + \".join(list(map(lambda edge: edge.to_PRISM_string(decoding), group))) + \";\"\n output.append(line)\n return output\n\n\ndef create_indices(ordering_1: SortedList, ordering_2: SortedList):\n \"\"\"\n Creates indices np.array which represents how agents from ordering_1 have to be rearranged\n in order to fit agents from ordering_2. If such relation is not possible, return False.\n\n :param ordering_1: first agents ordering\n :param ordering_2: second agents ordering\n :return: np.array of indices\n \"\"\"\n if set(ordering_1) == set(ordering_2):\n result = []\n for i_1 in range(len(ordering_1)):\n for i_2 in range(len(ordering_2)):\n if ordering_1[i_1] == ordering_2[i_2]:\n result.append(i_2)\n break\n return True, np.array(result)\n else:\n return False, None\n","sub_path":"TS/TransitionSystem.py","file_name":"TransitionSystem.py","file_ext":"py","file_size_in_byte":8274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"153588957","text":"import random\n\n# Teams\nteams = ['Brad','Felix','Frank','Laura','Matt','Meghan','Rex','Russell','Ryne','Zach']\ntweet_digits = {}\n\n# Seed random numbers\nseed_number = 923*992*17*73*42*828*3 \nrandom.seed(seed_number)\n\n# Loop over tweet digits\nfor d in range(10):\n # Flag for matching team to tweet digits\n team_not_added = True\n while team_not_added:\n # Randomly select team to this position \n t = random.randint(0,9)\n team = teams[t]\n # If team not already assigned a digit, assign it\u001B$(Q)\"\u001B(B\n if team not in tweet_digits:\n tweet_digits[team] = d\n team_not_added = False\n \nfor t in tweet_digits:\n print('Digit: %d Team: %s'%(tweet_digits[t],t))\n\n","sub_path":"draft_trump_tweets.py","file_name":"draft_trump_tweets.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"136586096","text":"import argparse\nimport subprocess\nimport time\nimport sys\nimport os\nimport boto3\n\nfrom create_jobs import create_turk_job\nfrom get_results import get_hits_result\n\n\"\"\"\nKicks off a pipeline that schedules Turk jobs for tool 1B,\ncollects results in batches and collates data.\n\n1. Read in newline separated commands and construct CSV input.\n2. Create HITs for each input command using tool 1B template.\n3. Continuously check for completed assignments, fetching results in batches.\n4. Collate turk output data with the input job specs.\n5. Postprocess datasets to obtain well formed action dictionaries.\n\"\"\"\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--default_write_dir\", type=str, required=True)\nparser.add_argument(\"--dev\", default=False, action=\"store_true\")\nparser.add_argument(\"--timeout\", type=float, default=60)\n\nargs = parser.parse_args()\ndev_flag = \"--dev\" if args.dev else \"\"\ndefault_write_dir = args.default_write_dir\ntimeout = args.timeout\n\n# CSV input\nrc = subprocess.call(\n [\n f\"python3 construct_input_for_turk.py --input_file {default_write_dir}/C/input.txt --tool_num 3 > {default_write_dir}/C/turk_input.csv\"\n ],\n shell=True,\n)\nif rc != 0:\n print(\"Error preprocessing. Exiting.\")\n sys.exit()\n\nhit_id = create_turk_job(\"fetch_question_C.xml\", 3, f\"{default_write_dir}/C/turk_input.csv\", f\"{default_write_dir}/C/turk_job_specs.csv\", dev_flag)\n\n# Wait for results to be ready\nprint(\"Turk jobs created for tool C at : %s \\n Waiting for results...\" % time.ctime())\nprint(\"*\"*50)\n\naccess_key = os.getenv(\"MTURK_AWS_ACCESS_KEY_ID\")\nsecret_key = os.getenv(\"MTURK_AWS_SECRET_ACCESS_KEY\")\naws_region = os.getenv(\"MTURK_AWS_REGION\", default=\"us-east-1\")\n\nif dev_flag:\n MTURK_URL = \"https://mturk-requester-sandbox.{}.amazonaws.com\".format(aws_region)\nelse:\n MTURK_URL = \"https://mturk-requester.{}.amazonaws.com\".format(aws_region)\n\nmturk = boto3.client(\n \"mturk\",\n aws_access_key_id=access_key,\n aws_secret_access_key=secret_key,\n region_name=aws_region,\n endpoint_url=MTURK_URL,\n)\n\nget_hits_result(mturk, hit_id, f\"{default_write_dir}/C/turk_output.csv\", True if dev_flag else False, timeout)\n\n# Collate datasets\nprint(\"*\"*50)\nprint(\"*** Collating turk outputs and input job specs ***\")\nrc = subprocess.call([f\"python3 collate_answers.py --turk_output_csv {default_write_dir}/C/turk_output.csv --job_spec_csv {default_write_dir}/C/turk_job_specs.csv --collate_output_csv {default_write_dir}/C/processed_outputs.csv\"], shell=True)\nif rc != 0:\n print(\"Error collating answers. Exiting.\")\n sys.exit()\n\n\n# Postprocess\nprint(\"*\"*50)\nprint(\"*** Postprocessing results ***\")\nrc = subprocess.call([f\"python3 parse_tool_C_outputs.py --folder_name {default_write_dir}/C/\"], shell=True)\nif rc != 0:\n print(\"Error collating answers. Exiting.\")\n sys.exit()\n\n# Create inputs for other tools\nprint(\"*\"*50)\nprint(\"*** Postprocessing results and generating input for tool D***\")\nrc = subprocess.call([f\"python3 generate_input_for_tool_D.py --write_dir_path {default_write_dir}\"], shell=True)\nif rc != 0:\n print(\"Error generating input for other tools. Exiting.\")\nprint(\"*\"*50)","sub_path":"tools/annotation_tools/turk_with_s3/run_tool_1C.py","file_name":"run_tool_1C.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"416275244","text":"import numpy as np\nimport math\nfrom numpy.linalg import inv\nimport matplotlib.pyplot as plt\n\n# Local calls to own modules\nfrom gauss import GAUSS_PY\n\nt=[]\nx=[]\nx_hat=[]\nxdot=[]\nxdot_hat=[]\nxddot=[]\nxddot_hat=[]\nx_hat_ERR=[]\nsp11=[]\nsp11P=[]\nxdot_hat_ERR=[]\nsp22=[]\nsp22P=[]\nxddot_hat_ERR=[]\nsp33=[]\nsp33P=[]\n\n\nPHIS=0.\nTS=.1\nA0=400000\nA1=-6000.\nA2=-16.1\nXH=0\nXDH=0\nXDDH=0\nSIGMA_NOISE=1000.\n\nPHI = np.matrix([[1, TS, 0.5*TS*TS],[0, 1, TS] ,[0, 0, 1] ])\nP = np.matrix([[99999999., 0, 0],[0,99999999. , 0], [0, 0, 99999999.]])\nI = np.matrix([[1, 0, 0],[0, 1, 0], [0, 0, 1]])\nQ = np.matrix([[TS**5/20, TS**4/8, TS**3/6],[TS**4/8, TS**3/3, TS*TS/2] ,[TS**3/6, TS*TS/2, TS] ])\nH = np.matrix([[1, 0 , 0]])\nR = np.matrix([[SIGMA_NOISE**2]])\n\n\nfor T in [x*TS for x in range(0,301)]:\n\tM=PHI*P*PHI.transpose()+PHIS*Q\n\tK = M*H.transpose()*(inv(H*M*H.transpose() + R))\n\tfor v in range(0,4):\n\t\tprint (K[0,0], K[1,0], K[2,0])\n\tP=(I-K*H)*M\n\tfor v in range(0,4):\n\t\tprint (P[0,0], P[1,1], P[2,2])\t\n\tXNOISE = GAUSS_PY(SIGMA_NOISE)\n\tX=A0+A1*T+A2*T*T\n\tXD=A1+2*A2*T\n\tXDD=2*A2\n\tXS=X+XNOISE\n\tRES=XS-XH-TS*XDH-.5*TS*TS*XDDH\n\tXH=XH+XDH*TS+.5*TS*TS*XDDH+K[0,0]*RES\n\tXDH=XDH+XDDH*TS+K[1,0]*RES\n\tXDDH=XDDH+K[2,0]*RES\n\tSP11=math.sqrt(P[0,0])\n\tSP22=math.sqrt(P[1,1])\n\tSP33=math.sqrt(P[2,2])\n\tXHERR=X-XH\n\tXDHERR=XD-XDH\n\tXDDHERR=XDD-XDDH\n\tSP11P=-SP11\n\tSP22P=-SP22\n\tSP33P=-SP33\n\t#print(T,X,XH,XD,XDH,XDD,XDDH)\n\t#print(T,XHERR,SP11,-SP11,XDHERR,SP22,-SP22,XDDHERR,SP33,-SP33)\n\tt.append(T)\n\tx.append(X)\n\tx_hat.append(XH)\n\txdot.append(XD)\n\txdot_hat.append(XDH)\n\txddot.append(XDD)\n\txddot_hat.append(XDDH)\n\tx_hat_ERR.append(XHERR)\n\tsp11.append(SP11)\n\tsp11P.append(SP11P)\n\txdot_hat_ERR.append(XDHERR)\n\tsp22.append(SP22)\n\tsp22P.append(SP22P)\n\txddot_hat_ERR.append(XDDHERR)\n\tsp33.append(SP33)\n\tsp33P.append(SP33P)\n\nplt.figure(1)\nplt.grid(True)\nplt.plot(t,x)\nplt.plot(t,x_hat)\nplt.xlabel('Time (Sec)')\nplt.ylabel('Altitude (Ft)')\nplt.xlim(0,30)\nplt.ylim(0,400000)\n\nplt.figure(2)\nplt.grid(True)\nplt.plot(t,xdot)\nplt.plot(t,xdot_hat)\nplt.xlabel('Time (Sec)')\nplt.ylabel('Velocity (Ft/Sec)')\nplt.xlim(0,30)\nplt.ylim(-10000,0)\n\nplt.figure(3)\nplt.grid(True)\nplt.plot(t,xddot)\nplt.plot(t,xddot_hat)\nplt.xlabel('Time (Sec)')\nplt.ylabel('Acceleration (Ft/Sec^2)')\nplt.xlim(0,30)\nplt.ylim(-100,100)\n\nplt.figure(4)\nplt.grid(True)\nplt.plot(t,x_hat_ERR)\nplt.plot(t,sp11)\nplt.plot(t,sp11P)\nplt.xlabel('Time (Sec)')\nplt.ylabel('Error in Estimate of Altitude (Ft)')\nplt.xlim(0,30)\nplt.ylim(-1500,1500)\n\nplt.figure(5)\nplt.grid(True)\nplt.plot(t,xdot_hat_ERR)\nplt.plot(t,sp22)\nplt.plot(t,sp22P)\nplt.xlabel('Time (Sec)')\nplt.ylabel('Error in Estimate of Velocity (Ft/Sec)')\nplt.xlim(0,30)\nplt.ylim(-500,500)\n\nplt.show()\n","sub_path":"Chapter4/listing4_3.py","file_name":"listing4_3.py","file_ext":"py","file_size_in_byte":2657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"254682418","text":"__author__ = \"Samvid Mistry\"\n\nfrom enum import IntEnum\n\nfrom PySide.QtGui import *\nfrom PySide.QtCore import *\n\nfrom MComponents.MShape import MShape\n\n\nclass MButton(MShape):\n def __init__(self):\n MShape.__init__(self)\n\n self.__text = QLabel()\n self.__text.setText(\"Button\")\n self.__text.setAlignment(Qt.AlignCenter)\n self.__style = MButtonStyle.Raised\n self.__color = QColor(\"#EEE\")\n self.__should_stick = False\n self.__blur = 2\n self.__color_anim = None\n self.__elev_anim = None\n self.__blur_anim = None\n self.__brush = QBrush(self.__color)\n self.__pen = QPen(self.__color)\n self.__shadow = QGraphicsDropShadowEffect()\n self.__shadow.setBlurRadius(self.blur)\n self.__animationSet = QParallelAnimationGroup()\n self.elevation = 1\n self.__shadow.setOffset(self.elevation)\n self.add_layout_item(self.__text, 0, 0)\n self.setLayout(self.layout)\n self.max_width = self.__text.fontMetrics().width(self.__text.text())\n self.max_height = self.__text.fontMetrics().height()\n self.width = self.max_width\n self.height = self.max_height\n self.margin_left = 5\n self.margin_top = 5\n self.setFixedSize(self.width + self.margin_left * 2, self.height + self.margin_top * 2)\n self.__painter = QPainter()\n self.__bounding_rect = QRect(self.x, self.y,\n self.width + self.margin_left * 2, self.height + self.margin_top * 2)\n\n def paintEvent(self, event):\n painter = self.__painter\n painter.begin(self)\n painter.save()\n self.__brush.setColor(self.__color)\n self.__pen.setColor(self.__color)\n if self.__style == MButtonStyle.Raised or self.__style == MButtonStyle.Toggles:\n self.__shadow.setOffset(self.elevation)\n self.setGraphicsEffect(self.__shadow)\n painter.setBrush(self.__brush)\n painter.setPen(self.__pen)\n painter.setRenderHint(QPainter.Antialiasing)\n painter.drawRoundedRect(self.__bounding_rect, 2, 2)\n painter.restore()\n painter.end()\n\n def mousePressEvent(self, event):\n if self.__style == MButtonStyle.Disabled:\n return\n\n self.__animationSet.stop()\n self.__animationSet.clear()\n if self.__style == MButtonStyle.Flat or self.__style == MButtonStyle.Raised or \\\n self.__style == MButtonStyle.Toggles:\n self.__animationSet.addAnimation(self.get_color_animation(QColor(\"#CCC\")))\n\n if self.__style == MButtonStyle.Raised or self.__style == MButtonStyle.Toggles:\n self.__animationSet.addAnimation(self.get_elev_animation(3))\n self.__animationSet.addAnimation(self.get_blur_animation(6))\n\n if self.__style == MButtonStyle.Toggles:\n self.__should_stick = not self.__should_stick\n\n self.__animationSet.start()\n\n def get_elev_animation(self, end_val: float) -> QAbstractAnimation:\n self.__elev_anim = QPropertyAnimation(self, \"a_elevation\", self)\n self.__elev_anim.setStartValue(self.elevation)\n self.__elev_anim.setEndValue(end_val)\n self.__elev_anim.setDuration(150)\n self.__elev_anim.setEasingCurve(QEasingCurve.InOutQuad)\n return self.__elev_anim\n\n def get_color_animation(self, end_val: QColor) -> QAbstractAnimation:\n self.__color_anim = QPropertyAnimation(self, \"acolor\", self)\n self.__color_anim.setStartValue(self.color)\n self.__color_anim.setEndValue(end_val)\n self.__color_anim.setDuration(150)\n return self.__color_anim\n\n def get_blur_animation(self, end_val: float) -> QAbstractAnimation:\n self.__blur_anim = QPropertyAnimation(self, \"a_blur\", self)\n self.__blur_anim.setStartValue(self.blur)\n self.__blur_anim.setEndValue(end_val)\n self.__blur_anim.setDuration(150)\n return self.__blur_anim\n\n def mouseReleaseEvent(self, event):\n if self.__style == MButtonStyle.Disabled:\n return\n\n self.__animationSet.stop()\n self.__animationSet.clear()\n self.__animationSet.addAnimation(self.get_color_animation(QColor(\"#EEE\")))\n\n if not self.__should_stick:\n self.__animationSet.addAnimation(self.get_elev_animation(1))\n self.__animationSet.addAnimation(self.get_blur_animation(2))\n\n self.__animationSet.start()\n\n @property\n def text(self) -> str:\n return self.__text\n\n @text.setter\n def text(self, text: str):\n self.__text = text\n\n @property\n def style(self):\n return self.__style\n\n @style.setter\n def style(self, value):\n self.__style = value\n self.repaint()\n\n @property\n def color(self) -> QColor:\n return self.__color\n\n @color.setter\n def color(self, value: QColor):\n self.__color = value\n self.repaint()\n\n @property\n def blur(self) -> float:\n return self.__blur\n\n @blur.setter\n def blur(self, value: float):\n self.__blur = value\n\n def getcolor(self) -> QColor:\n return self.color\n\n def setcolor(self, value: QColor):\n self.color = value\n\n def setElevation(self, value: int):\n self.elevation = value\n\n def getElevation(self) -> int:\n return self.elevation\n\n def getBlur(self) -> float:\n return self.blur\n\n def setBlur(self, val: float):\n self.blur = val\n\n acolor = Property(QColor, getcolor, setcolor)\n a_elevation = Property(float, getElevation, setElevation)\n a_blur = Property(float, getBlur, setBlur)\n\n\nclass MButtonStyle(IntEnum):\n Flat = 0\n Raised = 1\n Toggles = 2\n Disabled = 3\n","sub_path":"MComponents/MButton.py","file_name":"MButton.py","file_ext":"py","file_size_in_byte":5748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"633216680","text":"from reportlab.lib import colors\nfrom reportlab.lib.pagesizes import A4\nfrom reportlab.platypus import Table, Spacer, SimpleDocTemplate\n\nguion = []\n\nfila1 = ['', 'lunes', 'martes', 'miercoles', 'jueves', 'viernes', 'sabado', 'domingo']\nfila2 = ['Mañana', 'Clases', 'Deporte', 'medico', '', 'Clases', 'Estudio', 'Faojfokai']\nfila3 = ['Tarde', 'Trabajo', 'Trabajo', 'Trabajo', 'Piscina', 'Estudio', 'Estudio', '']\nfila4 = ['Noche', '', '', '', 'Trabajo', '', 'Mdoahasdh', '']\n\ntabla = Table([fila1, fila2, fila3, fila4])\ntabla.setStyle([('TEXTCOLOR', (1, 0), (7, 0), colors.red),\n ('TEXTCOLOR', (0, 0), (0, 3), colors.blue),\n ('BACKGROUND', (1, 1), (-1, -1), colors.lightgrey),\n ('INNERGRID', (1, 1), (-1, -1), 0.25, colors.gray),\n ('BOX', (0, 0), (-1, -1), 0.25, colors.black)])\nguion.append(tabla)\n\ndatos = [\n ['Arriba\\nIzquierda', '', '02', '03', '04'],\n ['', '', '12', '13', '44'],\n ['20', '21', '12', 'Abajo\\nDerecha', ''],\n ['30', '31', '32', '', '']\n]\n\nestilo = [\n ('GRID', (0, 0), (-1, -1), 0.5, colors.gray),\n ('BACKGROUND', (0, 0), (-1, -1), colors.palegreen),\n ('SPAN', (0, 0), (1, 1)),\n ('BACKGROUND', (-2, -2), (-1, -1), colors.pink),\n ('SPAN', (-2, -2), (-1, -1))\n]\n\nguion.append(Spacer(0, 40))\n\ntabla2 = Table(datos, style=estilo)\nguion.append(tabla2)\n\ndoc = SimpleDocTemplate(\"ejemploTabla2Platypus.pdf\", pagesize=A4, showBoundary=0)\n\ndoc.build(guion)\n","sub_path":"ejemploTabla.py","file_name":"ejemploTabla.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"246759639","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 2 11:29:28 2020\n\n:author: Michael\n:author: Luis\n\"\"\"\n\nimport pytest\nimport flowsym\nimport pandas as pd\nimport numpy as np\n\n\ndef test_create_controls():\n \"\"\"\n Test the create_controls function to make sure that we created\n all of our control DataFrames correctly\n \"\"\"\n\n greens, reds = flowsym.create_controls(10, ['green', 'red']) # Params for test function\n\n assert len(greens) == 10 # Did we output dataframe of correct size?\n assert type(reds) == type(pd.DataFrame()) # Did we output an actual dataframe object?\n assert list(greens.columns) == ['Wavelength', 'Excitation Efficiency',\n 'Emission Efficiency'] # Did we make the right columns?\n\n # Check to make sure wavelengths are equal\n for index, val in greens.iterrows():\n assert val['Wavelength'] == reds['Wavelength'][index]\n assert val['Excitation Efficiency'] != reds['Excitation Efficiency'][index]\n assert val['Emission Efficiency'] != reds['Emission Efficiency'][index]\n\n # Make sure all excitation or emission efficiencies are the same in a given dataframe\n assert greens['Excitation Efficiency'][0] == greens['Excitation Efficiency'][\n np.random.choice(range(1, len(greens)))]\n assert reds['Emission Efficiency'][0] == reds['Emission Efficiency'][np.random.choice(range(1, len(reds)))]\n\n\ndef test_create_sample():\n \"\"\"\n Test the create sample function to make sure we made our sample DataFrames correctly\n \"\"\"\n sample = flowsym.create_sample(10, ['blue', 'green', 'NIR']) # Params for test function\n\n assert len(sample) == 10 # Is dataframe correct size from input step?\n assert type(sample) == type(pd.DataFrame()) # Did we actually output a dataframe?\n assert list(sample.columns) == ['Wavelength', 'Excitation Efficiency', 'Emission Efficiency',\n 'Copy number'] # Are these the columns?\n\n # Check to make sure excitation wavelengths aren't the same as emission\n for index, val in sample.iterrows():\n assert val['Excitation Efficiency'] != val['Emission Efficiency']\n\n\n# Now that we've tested the create sample function, make a fixture for following function tests\n@pytest.fixture()\ndef sample():\n dataframe = flowsym.create_sample(100)\n\n return dataframe\n\n\n# Now that we've tested the create controls function, make a fixture for following function tests\n@pytest.fixture()\ndef controls():\n blue, green, red, far_red, NIR, IR = flowsym.create_controls(100)\n\n return blue, green, red, far_red, NIR, IR\n\n\ndef test_measure(sample):\n measured = flowsym.measure(sample)\n\n assert len(list(measured.columns)) == 6\n assert type(measured) == type(pd.DataFrame())\n","sub_path":"test_flowsym.py","file_name":"test_flowsym.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"288124682","text":"#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\n\"\"\"Plik do walidacji danych.\"\"\"\n# importy modułów py\nimport datetime\nimport re\nfrom flask import abort\nfrom flask_login import current_user\nfrom functools import wraps\nfrom urllib.parse import urlparse\nfrom wtforms import Form, StringField, PasswordField, IntegerField, RadioField\nfrom wtforms.fields.html5 import DateField\nfrom wtforms.validators import ValidationError, input_required, email, length, equal_to, Optional\n\n\ndef owner_required(db_param, func_param):\n \"\"\"Funkcja z parametrami dla dekoratora.\"\"\"\n def owner_required_call(func):\n \"\"\"Prawdziwy dekorator, sprawdza czy dany element należy do użytkownika.\"\"\"\n @wraps(func)\n def wrapper(*args, **kwargs):\n param = db_param.query.get_or_404(kwargs[func_param])\n if current_user.id == param.user_id:\n return func(*args, **kwargs)\n return abort(404)\n return wrapper\n return owner_required_call\n\n\ndef is_safe_next(next_page):\n \"\"\"Funkcja do weryfikacji parametru next.\"\"\"\n return not urlparse(next_page).netloc\n\n\ndef is_time_format(time_to_check):\n \"\"\"Funkcja sprawdza czy czas ma prawidłowy format: HH:MM:SS w zakresie 00:00:00 do 23:59:59.\"\"\"\n return True if re.search(r'(^[0-1][0-9]|2[0-3])(:[0-5][0-9]){1,2}$', time_to_check) else False\n\n\ndef is_date_format(date_to_check):\n \"\"\"Funkcja sprawdza czy data w formacie str jest prawidłowa.\"\"\"\n try:\n datetime.datetime.strptime(date_to_check, '%Y-%m-%d')\n return True\n except Exception:\n return False\n\n\n# walidacja danych użytkownika\nclass PwForm(Form):\n \"\"\"Klasa wtforms do ustalania hasła użytkownika.\"\"\"\n\n password = PasswordField(\n 'Hasło:',\n [input_required(message='Pole wymagane!'),\n length(max=72, message='Hasło nie może być dłuższe niż 72 znaki!'),\n equal_to('repeat_password', message='Hasła nie są identyczne!')],\n render_kw={'placeholder': 'hasło'})\n repeat_password = PasswordField(\n 'Powtórz hasło:',\n render_kw={'placeholder': 'powtórz hasło'})\n\n\nclass OldPwForm(Form):\n \"\"\"Klasa wtforms do weryfikacji aktualnego hasła.\"\"\"\n\n old_password = PasswordField(\n 'Aktualne hasło:',\n [input_required(message='Pole wymagane!')],\n render_kw={'placeholder': 'aktualne hasło'})\n\n\nclass DataForm(Form):\n \"\"\"Klasa wtforms do ustawiania danych personalnych użytkownika.\"\"\"\n\n def digit_or_none(self, field):\n \"\"\"Pole musi pozostac puste lub być liczbą.\"\"\"\n if isinstance(field.data, int):\n if not field.data.isdigit():\n raise ValidationError('Niepoprawny numer!')\n\n def zip_code_validator(self, field):\n \"\"\"Walidacja kodu pocztowego zgodnie ze standarem polskim \"dd-ddd\".\"\"\"\n if isinstance(field.data, str):\n if not re.match(r'^\\d\\d-\\d\\d\\d$', field.data):\n raise ValidationError('Niepoprawny kod pocztowy!')\n\n name = StringField(\n 'Imię:',\n [Optional(), length(max=80)],\n render_kw={'placeholder': 'imię'},\n filters=[lambda x: x or None])\n last_name = StringField(\n 'Nazwisko:',\n [Optional(), length(max=120)],\n render_kw={'placeholder': 'nazwisko'},\n filters=[lambda x: x or None])\n city = StringField(\n 'Miasto:',\n [Optional(), length(max=80)],\n render_kw={'placeholder': 'miasto'},\n filters=[lambda x: x or None])\n zip_code = StringField(\n 'Kod pocztowy:',\n [zip_code_validator],\n render_kw={'placeholder': 'kod pocztowy'},\n filters=[lambda x: x or None])\n street = StringField(\n 'Ulica:',\n [Optional(), length(max=150)],\n render_kw={'placeholder': 'ulica'},\n filters=[lambda x: x or None])\n house_number = StringField(\n 'Numer domu:',\n [digit_or_none],\n render_kw={'placeholder': 'nr domu', 'type': 'number', 'min': 1},\n filters=[lambda x: x or None])\n flat_number = StringField(\n 'Numer mieszkania:',\n [digit_or_none],\n render_kw={'placeholder': 'nr mieszkania', 'type': 'number', 'min': 1},\n filters=[lambda x: x or None])\n\n\nclass EmailForm(Form):\n \"\"\"Klasa wtforms do rejestracji użytkownika - ustawianie adresu e-mail.\"\"\"\n\n email = StringField(\n 'Adres e-mail:',\n [input_required(message='Pole wymagane!'),\n email(message='Niepoprawny adres e-mail!'),\n length(max=63, message='Adres e-mail przekracza 63 znaki!')],\n render_kw={'placeholder': 'adres e-mail'})\n\n\nclass LoginForm(Form):\n \"\"\"Klasa wtforms do logowania.\"\"\"\n\n email_login = StringField(\n 'Adres e-mail',\n [input_required(message='Pole wymagane!')],\n render_kw={'placeholder': 'adres e-mail'})\n password = PasswordField(\n 'Hasło',\n [input_required(message='Pole wymagane!')],\n render_kw={'placeholder': 'hasło'})\n\n\n# walidacja danych podawanych przez administratora\nclass ObituaryForm(Form):\n \"\"\"Klasa wtforms do walidacji tworzonych nekrologów.\"\"\"\n\n name = StringField(\n 'Imię',\n [input_required(message='Pole wymagane!')],\n render_kw={'required': True})\n surname = StringField(\n 'Nazwisko',\n [input_required(message='Pole wymagane!')],\n render_kw={'required': True})\n years_old = IntegerField(\n 'Wiek',\n [input_required(message='Pole wymagane!')],\n render_kw={'required': True, 'type': 'number', 'min': 0, 'max': 150})\n death_date = DateField(\n 'Data śmierci',\n format='%Y-%m-%d',\n render_kw={'required': True})\n gender = RadioField(\n 'Płeć',\n choices=[('man', 'Mężczyzna'), ('woman', 'Kobieta')],\n default='man')\n\n\nclass NewGraveForm(Form):\n \"\"\"Klasa wtforms do walidacji danych dotyczących grobu.\"\"\"\n def name_validator(self, field):\n if not re.match(r'^[A-Za-z -]+$', field.data):\n raise ValidationError('Pole może zawierać tylko litery, spacje i myślniki!')\n\n def date_past(self, field):\n today = datetime.datetime.today()\n if field.data > datetime.datetime.date(today):\n raise ValidationError('Data musi być starsza od dzisiejszej daty!')\n\n def death_after(self, field):\n if field.data < self.birth_date.data:\n raise ValidationError('Data urodzenia nie może przekroczyć daty śmierci!')\n\n name = StringField(\n 'Imię',\n [input_required(message='Pole wymagane!'), name_validator],\n render_kw={'required': True})\n surname = StringField(\n 'Nazwisko',\n [input_required(message='Pole wymagane!'), name_validator],\n render_kw={'required': True})\n birth_date = DateField(\n 'Data urodzenia',\n [date_past],\n format='%Y-%m-%d',\n render_kw={'required': True})\n death_date = DateField(\n 'Data śmierci',\n [Optional(), date_past, death_after],\n format='%Y-%m-%d')\n","sub_path":"data_validate.py","file_name":"data_validate.py","file_ext":"py","file_size_in_byte":7040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"125047639","text":"n = int(input())\n\nx = 0\ncount = 1\ncount_2 = 0\n\nfor a in range(1, n + 1):\n if a <= x:\n continue\n for b in range(a, a + count):\n print(f'{b} ', end ='')\n x = b\n count_2 += 1\n if count_2 == n:\n break\n print()\n count += 1\n\n\n\n","sub_path":"PythonFundamentals/Sting_Processing/TREWQ.py","file_name":"TREWQ.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"24757344","text":"from teamb2l.Classes.Class import Class\nfrom teamb2l import main\n\nclass TeacherAcct():\n\n #Constructor initializes an empty list of classes an instructor is teaching,\n #as well as add the account to the Master List.\n #Turns the first and last name into a Last, First naming convention\n def __init__(self,firstName,lastName,email,):\n self.name = lastName+\", \"+firstName\n self.email = email\n self.classes = []\n main.teacherMasterl.append(self)\n\n #Creates a new Class, adds it to personal class list, and Master\n #Returns the newly created Class\n def createClass(self,name):\n tmp = Class(self,name)\n self.classes.append(tmp)\n main.classMasterl.append(tmp)\n return tmp\n\n #If the Class exists, it is removed from both lists, and the new teacher level class list is returned\n #Otherwise, None is returned\n def deleteClass(self,clas):\n if self.classes.contains(clas):\n self.classes.remove(clas)\n main.classMasterl.remove(clas)\n return self.classes\n else:\n return None\n\n #Takes a string of emails separated by commas \",\"\n #If the Class exists, each student account with that email will be \"enrolled\" in the class\n #It returns a dictionary of students by (email string, StudentAcct) if students are succesfully enrolled\n #Otherwise, None\n def addStudents(self,clas,students):\n if self.classes.contains(clas):\n clas.enroll(students)\n return clas.students\n else:\n return None\n\n #Takes the string of a student's email\n #If the Class exists, the student is removed from that Class' student list and the updated list is returned\n # Otherwise, None\n def removeStudent(self,clas,student):\n if self.classes.contains(clas):\n clas.unenroll(student)\n return clas.students\n else:\n return None","sub_path":"teamb2l/Classes/TeacherAcct.py","file_name":"TeacherAcct.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"208840951","text":"class Solution:\n def largestRectangleArea(self, heights: List[int]) -> int:\n \n if not heights:\n return 0\n \n stack = [(-1, -1)]\n ans = 0\n for i, num in enumerate(heights):\n if num > stack[-1][1]:\n stack.append((i, num))\n else:\n while not num > stack[-1][1]:\n _, tmp = stack.pop()\n ans = max(ans, (i - stack[-1][0] - 1) * tmp)\n stack.append((i, num))\n n = len(heights)\n while len(stack) > 1:\n _, tmp = stack.pop()\n ans = max(ans, (n - stack[-1][0] - 1) * tmp)\n return ans\n\n","sub_path":"84_Largest_Rectangle_in_Histogram/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"279787223","text":"from presidio_analyzer import Pattern, PatternRecognizer\n\n\nclass IMEIRecognizer(PatternRecognizer):\n \"\"\"\n Recognizes common imei numbers using regex + checksum\n\n \"\"\"\n\n # pylint: disable=line-too-long\n PATTERNS = [\n Pattern(\n \"IMEI check\",\n r\"\\d{15}\", # noqa: E501\n 0.5,\n ),\n ]\n\n CONTEXT = [\n \"imei\",\n \"International Mobile Equipment Identity\",\n ]\n\n def __init__(\n self,\n patterns=None,\n context=None,\n supported_language=\"en\",\n supported_entity=\"IMEI\",\n replacement_pairs=None,\n ):\n \"\"\"\n :param replacement_pairs: list of tuples to replace in the string.\n ( default: [(\"-\", \"\"), (\" \", \"\")] )\n i.e. remove dashes and spaces from the string during recognition.\n \"\"\"\n self.replacement_pairs = replacement_pairs \\\n if replacement_pairs \\\n else [(\"-\", \"\"), (\" \", \"\")]\n context = context if context else self.CONTEXT\n patterns = patterns if patterns else self.PATTERNS\n super().__init__(\n supported_entity=supported_entity,\n patterns=patterns,\n context=context,\n supported_language=supported_language,\n )\n\n def validate_result(self, pattern_text):\n sanitized_value = self.__sanitize_value(pattern_text, self.replacement_pairs)\n checksum = self.__isValidEMEI(sanitized_value)\n\n return checksum\n\n @staticmethod\n def __sanitize_value(text, replacement_pairs):\n for search_string, replacement_string in replacement_pairs:\n text = text.replace(search_string, replacement_string)\n return text\n\n def __sumDig(self, n ): \n a = 0\n while n > 0: \n a = a + n % 10\n n = int(n / 10)\n return a \n\n # Returns True if n is valid EMEI \n def __isValidEMEI(self, n): \n\n # Converting the number into \n # Sting for finding length \n s = str(n) \n n = int(n)\n l = len(s) \n \n # If length is not 15 then IMEI is Invalid \n if l != 15: \n return False\n\n d = 0\n sum = 0\n for i in range(15, 0, -1): \n d = (int)(n % 10) \n if i % 2 == 0: \n \n # Doubling every alternate digit \n d = 2 * d \n \n # Finding sum of the digits \n sum = sum + self.__sumDig(d) \n n = n / 10\n return (sum % 10 == 0) \n","sub_path":"presidio-analyzer/presidio_analyzer/predefined_recognizers/imei_recognizer.py","file_name":"imei_recognizer.py","file_ext":"py","file_size_in_byte":2527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"38670728","text":"toolsFolder = 'BristolAnalysis/Tools/'\nimport os\nif os.environ.has_key('toolsFolder'):\n toolsFolder = os.environ['toolsFolder']\n#File for pile-up re-weighting\nPUFile = toolsFolder + \"data/PileUp_2011_truth_finebin_64600microbarn.root\"\n#Jet Energy Resolutions files (L7 corrections) \nbJetResoFile = toolsFolder + \"data/bJetReso.root\"\nlightJetResoFile = toolsFolder + \"data/lightJetReso.root\"\n#JES Systematic, the +/- number of uncertainties to vary the jets with\nJESsystematic = 0\n#number of events to be processed\nmaxEvents = 0\n#use HitFit for analysis\nuseHitFit = False\nproduceFitterASCIIoutput = False\n\ninputFiles = []\nfiletype = '*.root'\n\n\nmc_path = '/storage/TopQuarkGroup/mc/7TeV/'\n\n\nmcFolders = ['DYJetsToLL_TuneZ2_M-50_7TeV-madgraph-tauola/nTuple_v8c_Fall11-PU_S6_START44_V9B-v1_LeptonPlus3Jets',\n ]\n\nmcFolders = [mc_path + path + '/' + filetype for path in mcFolders]\n\ninputFiles.extend(mcFolders)\n\n#relative Path from calling BAT to the TopQuarkAnalysis folder\nTQAFPath = \"\"\n\n#integrated luminosity the MC simulation will be scaled to\nlumi = 5050.#pb-1\n\n#center of mass energy: 7TeV for 2010/2011 data/MC, 8TeV for 2012 data\n#this value will be part of the output file name: DataType_CenterOfMassEnergyTeV_lumipb-1_....\ncenterOfMassEnergy = 7\n\n#file with information (cross-section, number of processed events) for event weight calculation\ndatasetInfoFile = \"\"\nif centerOfMassEnergy == 7:\n datasetInfoFile = toolsFolder + \"python/DataSetInfo.py\"\nelif centerOfMassEnergy == 8:\n datasetInfoFile = toolsFolder + \"python/DataSetInfo_8TeV.py\"\nnTuple_version = 8\n\ncustom_file_suffix = \"PU_64600mb\"","sub_path":"python/PU_down/leptonAnalysis_DYPlusJetsMC.py","file_name":"leptonAnalysis_DYPlusJetsMC.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"2742124","text":"import pandas as pd\nfrom QUANTAXIS.QAUtil.QASetting import DATABASE\nimport datetime\n\nSTART_DATE_OF_SHSX_STOCK = '19930101'\n\n\ndef get_trading_days_between(start_date=None, end_date=None) -> pd.DataFrame:\n '''\n return all dates before end_date if start_date is null, inclusive of end_date\n return all dates after start_date if end_date is null, inclusive of start_date\n otherwise give all dates between the two given date\n :param start_date:\n :param end_date:\n :return:\n '''\n if (start_date is None and end_date is None):\n raise ValueError(\"Start and end date must not be None at the same time\")\n calendar = get_trading_calendar()\n '''\n return all dates before end_date if start_date is null, inclusive of end_date\n '''\n if (start_date is None):\n return calendar[calendar['date'] <= int(end_date)]\n\n '''\n return all dates after start_date if end_date is null, inclusive of start_date\n '''\n if (end_date is None):\n return calendar[calendar['date'] >= int(start_date)]\n\n # otherwise give all dates between the two given date\n return calendar[(int(start_date) <= calendar['date']) & (calendar['date'] <= int(end_date))]\n\n\ndef get_last_x_trading_day_from_mongodb(x_day_ago=1):\n '''\n return the date as int specified by the days ago parameter. 1 will be yesterday and 2 will be the day before yesterday\n :param x_day_ago:\n :return:\n '''\n list_of_trading_date = get_trading_calendar()\n return list_of_trading_date['date'].tolist()[-1 * x_day_ago]\n\n\ndef get_trading_calendar(engine=DATABASE) -> pd.DataFrame:\n today = int(datetime.date.today().strftime(format=\"%Y%m%d\"))\n\n cursor = DATABASE.trade_date.find(projection={\"_id\": 0, \"date\": 1, \"exchangeName\": 1})\n list_of_cursor = list(cursor)\n\n df = pd.DataFrame(list_of_cursor)\n df['date'] = df['date'].astype(int)\n df = df[df.date < today]\n return df\n\n\ndef get_today_as_str():\n return datetime.date.today().strftime(format=\"%Y%m%d\")\n\n\ndef get_yesterday_as_str():\n yesterday = datetime.datetime.now() - datetime.timedelta(1)\n return datetime.datetime.strftime(yesterday, format=\"%Y%m%d\")\n\n\ndef get_days_between(start_date=None, end_date=None):\n '''\n logic:\n if start_date and end_date are not provided, return yesterday\n if start_date and end_date equals, return the day\n if start_date not provided, return from 19930101 to end_date, inclusive of end_date\n if end_date not provided, return from start_date to today, inclusive of both sides\n Args:\n start_date:\n end_date:\n\n Returns:\n single-column dataframe containing the days, with column name \"date\"\n '''\n __list = []\n\n if (start_date is None and end_date is None):\n df= pd.DataFrame(__list.append(get_yesterday_as_str()), columns=['date'])\n return df\n if start_date is None:\n start_date = START_DATE_OF_SHSX_STOCK\n if end_date is None:\n end_date = get_today_as_str()\n if start_date == end_date:\n df = pd.DataFrame(__list.append(str(start_date)), columns=['date'])\n return df\n start_as_datetime = datetime.datetime.strptime(start_date, '%Y%m%d')\n end_as_datetime = datetime.datetime.strptime(end_date, '%Y%m%d')\n span = end_as_datetime - start_as_datetime\n\n for n in range(span.days + 1):\n day = start_as_datetime + datetime.timedelta(days=n)\n __list.append(day.strftime(format=\"%Y%m%d\"))\n\n return pd.DataFrame(__list, columns=['date'])\n","sub_path":"AY/Crius/Utils/trading_calendar_utils.py","file_name":"trading_calendar_utils.py","file_ext":"py","file_size_in_byte":3514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"163662050","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport xlwt\nimport os\nclass baseLog:\n def __init__(self):\n self.revision = \"\"\n self.author = \"\"\n self.time = \"\"\n self.message = \"\"\n def setRevision(self, revision):\n self.revision = revision\n def setAuthor(self, author):\n self.author = author\n def setTime(self, time):\n self.time = time\n def setMessage(self, msg):\n self.message = msg\n def getRevision(self):\n return self.revision\n def getAuthor(self):\n return self.author\n def getTime(self):\n return self.time\n def getMessage(self):\n return self.message\n def __str__(self):\n str = (\"Revision : %s\\nTime : %s\\nAuthor : %s\\nMessage : %s\\n\") %(self.revision, self.time, self.author, self.message)\n return str\n\ndef readSVNLog():\n\n rootDir = \"svn://172.16.1.201:3692/mahjong/src_quanguo/branches/branch_cangzhou_gameplay_20180820_0823\" ## svn路径\n\n startDate = \"{2018-08-21T14:35:06}\" ## 开始时间\n endDate = \"{2018-08-23T14:35:06}\" ## 终止时间\n xlsx = \"D:\\\\Book1.xlsx\" ## 保存的excel路径以及文件名\n\n command = \"svn log \" + \"-r\" + startDate + \":\" + endDate + \" \" + rootDir\n print(command)\n rootLogList = os.popen(command)\n\n res = rootLogList.read()\n rootLogList.close()\n\n i = 0\n log = baseLog()\n message = \"\"\n result = []\n for line in res.splitlines():\n if line is None or (len(line) < 1):\n continue\n if '--------' in line:\n continue\n i = i + 1\n if line.count(\"|\") >= 3:\n log.setMessage(message)\n message = \"\"\n if len(log.getMessage()) > 0:\n result.append(log)\n log = baseLog()\n tmpList = line.split(\"|\")\n log.setRevision(tmpList[0])\n log.setAuthor(tmpList[1])\n log.setTime(tmpList[2])\n else:\n message = message + line\n log.setMessage(message)\n result.append(log)\n\n book = xlwt.Workbook(encoding='utf-8')\n sheet = book.add_sheet(\"log\", cell_overwrite_ok=True)\n j = 0\n for i in result:\n tmpStr = str(i)\n sheet.write(j, 0, tmpStr)\n j = j + 1\n book.save(xlsx)\n\nif __name__ == '__main__':\n readSVNLog()","sub_path":"01 小工具/old/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"503715052","text":"from datetime import datetime\n\nfrom bots import *\nimport gym\nfrom gym import wrappers\n\n\ndef main():\n\n env_id = 'GuessCard-v1'\n opponent = SmarterBaselineBot()\n player = MishaBotV1New(debug=False)\n record_folder = f'./GuessCard_{player.name}_{datetime.now().strftime(\"%Y-%m-%dT%H:%M:%S\")}'\n\n gym.envs.register(\n id=env_id,\n entry_point='env:CardsGuessing',\n kwargs={\n \"starting_money\": 100,\n \"opponent\": opponent\n },\n max_episode_steps=1000,\n nondeterministic=True\n )\n\n env = gym.envs.make(env_id)\n env = wrappers.Monitor(env, record_folder, lambda _: True, uid=player.name)\n player.set_env(env)\n player.run(10)\n env.close()\n\n for video, _ in env.videos:\n print(f'asciinema play {video}')\n\n # gym.upload(record_folder, api_key='sk_OKAdH4EQUaO9mSyYJNPw')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"223489775","text":"import json\nimport requests\nfrom typing import Dict, Tuple, cast, List, Optional\nfrom pydantic import BaseModel\nimport functools\n\nbase_url = 'https://68ecj67379.execute-api.ap-northeast-2.amazonaws.com/api'\nx_token = '68bf2112d9082beba4d412c10d8f7c96'\n@functools.total_ordering\nclass ReservationInfo(BaseModel):\n id: int\n amount: int\n check_in_date: int\n check_out_date: int\n day: Optional[int]\n\n def __gt__(self, other):\n other = cast(ReservationInfo, other)\n if self.check_in_date == other.check_in_date:\n return self.amount < other.amount\n return self.check_in_date > other.check_in_date \n\nclass OrderReservationInfo(ReservationInfo):\n room_number: int\n\n\ndef start_api(problem_number: int) -> Tuple[str, str, str]:\n response : requests.Response = requests.post(f'{base_url}/start', \n headers={\n 'X-Auth-Token':x_token, \n 'Content-Type': 'application/json'\n },\n data= json.dumps({\n \"problem\": problem_number\n })\n )\n _response:Dict = response.json()\n auth_key = _response.get('auth_key')\n problem = _response.get('problem')\n day = _response.get('day')\n return auth_key, problem, day\n\n\ndef simulate_api(auth, req:List) -> Tuple[int, int]:\n response : requests.Response = requests.put(f'{base_url}/simulate', \n headers={\n 'Authorization': auth, \n 'Content-Type': 'application/json'\n },\n data= json.dumps({\n \"room_assign\": req\n })\n )\n _response:Dict = response.json()\n day = _response.get('day')\n fail_count = _response.get('fail_count')\n return int(day), int(fail_count)\n\ndef score_api(auth) -> Tuple[float, float, float, float]:\n response : requests.Response = requests.get(f'{base_url}/score', \n headers={\n 'Authorization': auth, \n 'Content-Type': 'application/json'\n })\n _response:Dict = response.json()\n accuracy_score = _response.get('accuracy_score')\n efficiency_score = _response.get('efficiency_score')\n penalty_score = _response.get('penalty_score')\n score = _response.get('score')\n return accuracy_score, efficiency_score, penalty_score, score\n\ndef reservation_api(auth): \n response : requests.Response = requests.get(f'{base_url}/new_requests', \n headers={\n 'Authorization': auth, \n 'Content-Type': 'application/json'\n })\n _response:Dict = response.json()\n _reservations = _response.get('reservations_info')\n reservations = [ReservationInfo(**d) for d in _reservations]\n return reservations\n\ndef reply_api(auth, replies):\n response : requests.Response = requests.put(f'{base_url}/reply', \n headers={\n 'Authorization': auth, \n 'Content-Type': 'application/json'\n },\n data= json.dumps({\n \"replies\": replies\n })\n )\n _response:Dict = response.json()\n day = _response.get('day')\n return int(day)\n\n","sub_path":"swtest/kakao/2022kakao/kakao_second_problem/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"518121677","text":"\"\"\"\nThis file contains useful QUA macros meant to simplify and ease QUA programs.\nAll the macros below have been written and tested with the basic configuration. If you modify this configuration\n(elements, operations, integration weights...) these macros will need to be modified accordingly.\n\"\"\"\n\nfrom qm.qua import *\n\n##############\n# QUA macros #\n##############\n\n\n# Macro for measuring the qubit state with single shot\ndef readout_macro(threshold=None, state=None, I=None, Q=None):\n \"\"\"\n A macro for performing the single-shot readout, with the ability to perform state discrimination.\n If `threshold` is given, the information in the `I` quadrature will be compared against the threshold and `state`\n would be `True` if `I > threshold`.\n Note that it is assumed that the results are rotated such that all the information is in the `I` quadrature.\n\n :param threshold: Optional. The threshold to compare `I` against.\n :param state: A QUA variable for the state information, only used when a threshold is given.\n Should be of type `bool`. If not given, a new variable will be created\n :param I: A QUA variable for the information in the `I` quadrature. Should be of type `Fixed`. If not given, a new\n variable will be created\n :param Q: A QUA variable for the information in the `Q` quadrature. Should be of type `Fixed`. If not given, a new\n variable will be created\n :return: Three QUA variables populated with the results of the readout: (`state` (only if threshold is not None), `I`, `Q`)\n \"\"\"\n if I is None:\n I = declare(fixed)\n if Q is None:\n Q = declare(fixed)\n if (threshold is not None) and (state is None):\n state = declare(bool)\n measure(\n \"readout\",\n \"resonator\",\n None,\n dual_demod.full(\"rotated_cos\", \"out1\", \"rotated_sin\", \"out2\", I),\n dual_demod.full(\"rotated_minus_sin\", \"out1\", \"rotated_cos\", \"out2\", Q),\n )\n if threshold is not None:\n assign(state, I > threshold)\n return state, I, Q\n else:\n return I, Q\n\n\n# Macro for measuring the averaged ground and excited states for calibration\ndef ge_averaged_measurement(cooldown_time, n_avg):\n \"\"\"Macro measuring the qubit's ground and excited states n_avg times. The averaged values for the corresponding I\n and Q quadratures can be retrieved using the stream processing context manager `Ig_st.average().save(\"Ig\")` for instance.\n\n :param cooldown_time: cooldown time between two successive qubit state measurements in clock cycle unit (4ns).\n :param n_avg: number of averaging iterations. Must be a python integer.\n :return: streams for the 'I' and 'Q' data for the ground and excited states respectively: [Ig_st, Qg_st, Ie_st, Qe_st].\n \"\"\"\n n = declare(int)\n I = declare(fixed)\n Q = declare(fixed)\n Ig_st = declare_stream()\n Qg_st = declare_stream()\n Ie_st = declare_stream()\n Qe_st = declare_stream()\n with for_(n, 0, n < n_avg, n + 1):\n # Ground state calibration\n align(\"qubit\", \"resonator\")\n measure(\n \"readout\",\n \"resonator\",\n None,\n dual_demod.full(\"cos\", \"out1\", \"sin\", \"out2\", I),\n dual_demod.full(\"minus_sin\", \"out1\", \"cos\", \"out2\", Q),\n )\n wait(cooldown_time, \"resonator\", \"qubit\")\n save(I, Ig_st)\n save(Q, Qg_st)\n\n # Excited state calibration\n align(\"qubit\", \"resonator\")\n play(\"x180\", \"qubit\")\n align(\"qubit\", \"resonator\")\n measure(\n \"readout\",\n \"resonator\",\n None,\n dual_demod.full(\"cos\", \"out1\", \"sin\", \"out2\", I),\n dual_demod.full(\"minus_sin\", \"out1\", \"cos\", \"out2\", Q),\n )\n wait(cooldown_time, \"resonator\", \"qubit\")\n save(I, Ie_st)\n save(Q, Qe_st)\n\n return Ig_st, Qg_st, Ie_st, Qe_st\n","sub_path":"Quantum-Control-Applications/Superconducting/Single-Flux-Tunable-Transmon/macros.py","file_name":"macros.py","file_ext":"py","file_size_in_byte":3887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"260401795","text":"import select\nimport socket\nimport json\n\nconfig = json.load(\"config.json\")\n\n\ndef create_remote():\n remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n remote.connect((config[\"server_ip\"], config[\"server_port\"]))\n remote.setblocking(0)\n return remote\n\n\nmanager = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nmanager.setblocking(0)\n\nmanager.bind(('localhost', config['manager_port']))\nmanager.listen(10)\n\ninputs = [manager]\n\nlocal2remote = {}\nremote2local = {}\n\nwhile inputs:\n readable, _, _ = select.select(inputs, [], [])\n\n for s in readable:\n if s is manager:\n client, _ = manager.accept()\n client.setblocking(0)\n inputs.append(client)\n\n remote = create_remote()\n local2remote[client] = remote\n remote2local[remote] = client\n \n else:\n data = s.recv(4096)\n \n\n\n\n","sub_path":"proxy/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"34267906","text":"\n\"\"\" se peude iterar sobre cualquier tipo de dato \"\"\"\n\nmyarray = ['python', 'javascript']\nmyarray2 = range(1, 10)\n\n# new_list = []\n# for item in myarray2:\n# if item % 2 == 0:\n# new_list.append(item)\n\n# print(new_list)\n\n\n# new_iterador = [\n# item\n# for item in range(1,10)\n# if item == 9\n# ]\n\n# print(new_iterador)\n\n\n# username = 'henry'\n# email = 'hola@dojo.com'\n\nusername, email, lastname = 'henry', 'hola@dojo.com', 'vasquez'\n\nprint(username, email)\n\n\n# for item in 'HENRY':\n# print(item)\n\n# for item in (1, 'a', 3):\n# print(item)\n\n# for item in {'user': 'pedro', 'id': 1}:\n# print(item)\n","sub_path":"bootcamp-dojopy-sd/iteradores/iterardor_for.py","file_name":"iterardor_for.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"12623545","text":"import dataprocessor as dp\nimport classifiers as cla\nimport features as ft\nimport time\ndef print_baseline_nb(X,y):\n \"\"\"\n Baseline model only run Multinomial Naive bayes\n :param X: The tokenized reviews\n :param y: The lables\n \"\"\"\n classifier = cla.classifiers(X,y,1)\n classifier.get_classifiers(1,0,0)\n\ndef print_three_classifiers_results(X,y,svm,multinomial):\n \"\"\"\n Method to run and print the evaluation metrics of three classifiers seperately\n :param X: The tokenized reviews\n :param y: The lables\n :param svm: Whether uses SVM\n :param multinominal: Whether uses Multinomial\n\n \"\"\"\n if multinomial:\n classifier = cla.classifiers(X,y,1)\n else:\n classifier = cla.classifiers(X,y,0)\n #nb\n classifier.get_classifiers(1, 0, 0)\n #max entropy\n classifier.get_classifiers(0, 1, 0)\n #svm\n if svm:\n classifier.get_classifiers(0, 0, 1)\n\n\nif __name__ == '__main__':\n \"\"\"\n This is the main method \n \"\"\"\n\n df = dp.dataprocessor('./Reviews_new.csv')\n source_data = df.df_base\n #baseline\n baseline = ft.unigram(df)\n X, y =baseline.get_features()\n print(\"the cross validation scores for baseline model \")\n print_baseline_nb(X,y)\n\n #unigram+ pos features\n pos_uni = ft.pos_unigram(df)\n reviews_pos = pos_uni.add_pos_tag()\n X,y = pos_uni.get_unigram_features(reviews_pos)\n print(\"the cross validation scores for unigram + POS: \")\n print_three_classifiers_results(X,y,1,1)\n #bigram features\n pos_bi = ft.pos_bigram(df)\n X,y = pos_bi.deliver_feature_vector()\n print(\"the cross validation scores for bigram + POS: \")\n print_three_classifiers_results(X,y,0,1)\n \n #lexical compound features\n lexi = ft.lexicon()\n feature_compound, feature_neg_pos = lexi.lexicon_feature(source_data)\n X, y = lexi.test_train(source_data, feature_compound)\n print(\"the cross validation scores for lexical compound: \")\n print_three_classifiers_results(X,y,1,0)\n\n \n #lexical neg+pos features\n X, y = lexi.test_train(source_data, feature_neg_pos)\n print(\"the cross validation scores for lexical neg pos: \")\n print_three_classifiers_results(X,y,1,0)\n \n #word2vec\n w2v = ft.word_2_vec(source_data)\n X,y = w2v.get_feature_vector()\n print(\"the cross validation scores for word2vec: \")\n print_three_classifiers_results(X,y,1,0)\n\n #glove\n print(\"start creating glv features\")\n start_time = time.time()\n glv = ft.glove(source_data)\n X, y = glv.get_feature_vectors()\n print(\"createing glv feature vectors takes \" + str(time.time()-start_time))\n print(\"the cross validation scores for GLoVe: \")\n print_three_classifiers_results(X,y,1,0)\n\n","sub_path":"source code/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"437862529","text":"from task_manager.models import *\n\ndef delete_extra_annos():\n annos = DialogAnnotation.objects()\n result = []\n tasks = {u2t.user_id:set([task.task_name for task in u2t.tasks_id])for u2t in User2Task.objects()}\n for anno in annos:\n username = anno.user.username\n if anno.dialog.dialog_id not in tasks[username]:\n result.append(anno)\n for anno in tasks:\n anno.delete()\n\n\n\n\n\n\n","sub_path":"platform/uch_analysis/quality_analysis.py","file_name":"quality_analysis.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"151816409","text":"# -*- coding: utf-8 -*-\n\n# 逐行比较两二进制文件,以确定它们是否一样\nimport struct\none = open('d:\\one.jar', 'rb')\ntwo = open('d:\\two.jar', 'rb')\n\ndifferent = False\nwhile True:\n readOne = one.read(1)\n readTwo = two.read(1)\n if not readOne or not readTwo: break\n one4one = struct.unpack('s', readOne)\n two24one = struct.unpack('s', readTwo)\n different = one4one != two24one\n if different: break\none.close()\ntwo.close()\n\nprint('两个文件不同:', different)\n\n\n","sub_path":"hello/chap11/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"448089999","text":"class Category:\n \n def __init__(self, name):\n self.name = name\n self.ledger = list()\n self.balance = 0\n\n def __str__(self):\n number_of_stars = int((30-(len(self.name)))/2)\n headline = \"*\"*number_of_stars+self.name+\"*\"*number_of_stars+\"\\n\"\n ledger_items = \"\"\n total = 0\n for ledger_item in self.ledger:\n total = total + ledger_item[\"amount\"]\n amount_to_string = str(\"{:.2f}\".format(ledger_item[\"amount\"]))\n amount_to_string_shortened = amount_to_string[0:7]\n ledger_items += ledger_item[\"description\"][0:23] + \" \" * (30 - (len(amount_to_string_shortened) + len(ledger_item[\"description\"][0:23]))) + amount_to_string[0:7] + \"\\n\"\n return headline+ledger_items + \"Total: \" + str(total)\n\n def deposit(self, amount, description=\"\"):\n self.balance = self.balance + amount\n self.ledger.append({\"amount\": round(amount, 2), \"description\": description})\n\n def withdraw(self, amount, description=\"\"):\n if (not self.check_funds(amount)):\n return False\n else:\n self.balance = self.balance - amount\n self.ledger.append({\"amount\": -round(amount, 2), \"description\": description})\n return True\n\n def get_balance(self):\n return self.balance\n\n def transfer(self, amount, destination_category):\n if (not self.check_funds(amount)):\n return False\n else:\n self.withdraw(amount, \"Transfer to \"+destination_category.name)\n destination_category.deposit(amount, \"Transfer from \"+self.name)\n return True\n\n def check_funds(self, amount):\n if (self.balance - amount < 0): \n return False\n else: \n return True\n\n\ndef create_spend_chart(list_of_categories):\n spending_hist = dict()\n total_spent = 0\n graph = \"Percentage spent by category\\n\"\n for category in list_of_categories:\n spending_hist[category.name] = 0\n for ledger_entry in category.ledger:\n if (ledger_entry[\"amount\"] < 0):\n #print(category.name, ledger_entry[\"amount\"])\n spending_hist[category.name] += ledger_entry[\"amount\"]\n total_spent += ledger_entry[\"amount\"]\n\n #print(total_spent)\n #print(spending_hist)\n\n x_axis = 100\n longest_category_name = 0\n\n while x_axis >= 0:\n if (x_axis == 100): line = str(x_axis) + \"|\"\n elif (x_axis == 0): line = \" \" + str(x_axis) + \"|\"\n else: line = \" \" + str(x_axis) + \"|\"\n for name, total in spending_hist.items():\n if (len(name) > longest_category_name): longest_category_name = len(name)\n if (total == 0): current_category = 0\n else: current_category = (100 * total / total_spent) - (100 * total / total_spent)%10\n #print(current_category)\n if (current_category >= x_axis):\n line += \" o \"\n else:\n line += \" \"\n #print(line)\n graph += line + \" \\n\"\n x_axis -= 10\n\n graph+= \" -\"+(\"---\"*len(spending_hist))\n counter = 0\n\n while counter < longest_category_name:\n #print(longest_category_name)\n line = []\n for name, total in spending_hist.items():\n if len(name) > counter:\n #print(\"name = \", name, \"length of name = \", len(name), \"counter = \", counter)\n line.append(name[counter])\n else:\n line.append(\" \")\n counter += 1\n graph += \"\\n \"+\" \".join(line) + \" \"\n\n \n\n return graph","sub_path":"budget.py","file_name":"budget.py","file_ext":"py","file_size_in_byte":3235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"355484599","text":"#Email:fanyucai1@126.com\n#2019.8.19\n\nimport os\nimport sys\nimport subprocess\n\nmsisensor=\"/software/MSIsensor/MSIsensor-v0.6/msisensor-0.6/msisensor\"\nref=\"/data/Database/hg19/ucsc.hg19.fasta\"\n\ndef single(tumor,bed,outdir,prefix):\n if not os.path.exists(outdir):\n os.mkdir(outdir)\n out=outdir+\"/\"+prefix\n subprocess.check_call(\"%s scan -d %s -o %s/microsatellites.list\" % (msisensor, ref, outdir),shell=True)\n cmd=\"%s msi -d %s/microsatellites.list -t %s -e %s -o %s\" %(msisensor,outdir,tumor,bed,out)\n subprocess.check_call(cmd,shell=True)\n\nif __name__==\"__main__\":\n if len(sys.argv)!=5:\n print(\"usage:python3 %s tumor.bam panel.bed outdir prefix\\n\"%(sys.argv[0]))\n print(\"Email:fanyucai1@126.com\")\n else:\n tumor=sys.argv[1]\n bed=sys.argv[2]\n outdir=sys.argv[3]\n prefix=sys.argv[4]\n single(tumor, bed, outdir, prefix)","sub_path":"MSI/MSI_single.py","file_name":"MSI_single.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"71217282","text":"import cv2\nimport numpy as np\nfrom random import randrange\nfrom matplotlib import pyplot as plt\nfrom mysite.plot_bound_detector.MaskPosition import MaskPosition\nfrom mysite.plot_bound_detector.ImageOperations import ImageOperations\n\n\nclass PlotBoundDetector:\n\n def __init__(self, image_processor):\n self.image_processor = image_processor\n\n def get_plot_bound(self, image):\n image = image.copy()\n\n image = self.image_processor.delete_text(image)\n bottom, top = self.image_processor.split_image(image)\n\n bottom = self.__prepare_image(bottom)\n top = self.__prepare_image(top)\n\n top_chunks = self.__get_chunks(top)\n bottom_chunks = self.__get_chunks(bottom)\n\n top_chunks, bottom_chunks = self.remove_reflexes(top_chunks, bottom_chunks)\n top_chunks = self.merge_nearest(top_chunks, 10)\n bottom_chunks = self.merge_nearest(bottom_chunks, 10)\n top_chunks = self.filter_chunks(top_chunks)\n bottom_chunks = self.filter_chunks(bottom_chunks)\n\n\n return top_chunks, bottom_chunks\n\n def remove_reflexes(self, top_chunks, bottom_chunks):\n bottom_chunks_to_remove = []\n top_chunks_to_remove = []\n\n for top_chunk in top_chunks:\n for bottom_chunk in bottom_chunks:\n if self.is_reflex(top_chunk, bottom_chunk):\n if bottom_chunk not in bottom_chunks_to_remove:\n bottom_chunks_to_remove.append(bottom_chunk)\n\n for chunks_to_remove in bottom_chunks_to_remove:\n bottom_chunks.remove(chunks_to_remove)\n\n for bottom_chunk in bottom_chunks:\n for top_chunk in top_chunks:\n if self.is_reflex(bottom_chunk, top_chunk):\n if top_chunk not in top_chunks_to_remove:\n top_chunks_to_remove.append(top_chunk)\n\n for chunks_to_remove in top_chunks_to_remove:\n top_chunks.remove(chunks_to_remove)\n\n return top_chunks, bottom_chunks\n\n def is_reflex(self, top_chunk, bottom_chunk):\n k = 10\n return top_chunk[0] - k < bottom_chunk[0] and top_chunk[-1] + k > bottom_chunk[-1]\n\n def __prepare_image(self, image):\n image = image.copy()\n image = self.image_processor.remove_ox(image)\n gray = ImageOperations.convert_to_gray(image)\n\n manual_thresholded = ImageOperations.color_threshold(gray)\n bilateral_filtered = cv2.bilateralFilter(manual_thresholded.copy(), 11, 75, 75)\n _, thresholded = cv2.threshold(bilateral_filtered, 70, 255, cv2.THRESH_BINARY)\n\n kernel = np.ones((3, 3), np.uint8)\n dilated = cv2.dilate(thresholded, kernel, iterations=1)\n\n return dilated\n\n def __get_chunks(self, image):\n histogram = self.get_histogram(image)\n\n continous_chunks = self.get_continous_chunks(histogram)\n\n return continous_chunks\n\n def get_histogram(self, image):\n result = []\n rows, cols = ImageOperations.get_shape(image)\n\n for j in range(cols):\n sum = 0\n for i in range(rows):\n sum = sum + image[i, j]\n result.append(sum)\n\n return result\n\n def get_continous_chunks(self, array):\n result = []\n min_value = min(array)\n i = 0\n while i < len(array) - 1:\n value = array[i]\n if value > min_value:\n chunk = [i]\n counter = i + 1\n for j in range(counter, len(array)):\n value = array[j]\n if value > min_value:\n chunk.append(j)\n else:\n i = j\n result.append(chunk)\n break\n else:\n result.append(chunk)\n i = j\n continue\n elif value <= min_value:\n i += 1\n continue\n return result\n\n def filter_chunks(self, chunks, min_length_chunk=6):\n if len(chunks) > 0:\n if len(chunks) > 1:\n result = list(filter(lambda x: len(x) > min_length_chunk, chunks))\n return result\n else:\n return chunks\n else:\n return chunks\n\n def get_avrage_length(self, chunks):\n sum_len = sum(len(c) for c in chunks)\n chunks_count = len(chunks)\n return round(sum_len / chunks_count)\n\n def merge_nearest(self, chunks, distance):\n something_merged = False\n\n counter = 0\n while counter < len(chunks):\n has_next_chunk = counter + 1 < len(chunks)\n\n if not has_next_chunk:\n counter += 1\n continue\n\n current_chunk = chunks[counter]\n next_chunk = chunks[counter + 1]\n\n if self.can_merge(current_chunk, next_chunk, distance):\n chunks[counter] = list(range(current_chunk[0], next_chunk[-1] + 1))\n del chunks[counter + 1]\n something_merged = True\n counter += 1\n\n if something_merged:\n return self.merge_nearest(chunks, distance)\n\n return chunks\n\n def can_merge(self, first_chunk, second_chunk, k):\n end_first = first_chunk[-1]\n start_second = second_chunk[0]\n\n return (start_second - end_first) <= k\n\n @staticmethod\n def draw_chunks(chunks, image, position):\n width, height = ImageOperations.get_shape(image)\n\n for chunk in chunks:\n color = list(map(lambda x: int(x), list(np.random.choice(range(256), size=3))))\n start_column = chunk[0]\n end_column = chunk[-1]\n\n if position == MaskPosition.TOP:\n cv2.line(image, (start_column, 0), (start_column, 100), color, 1)\n cv2.line(image, (end_column, 0), (end_column, 100), color, 1)\n if position == MaskPosition.BOTTOM:\n cv2.line(image, (start_column, 100), (start_column, height), color, 1)\n cv2.line(image, (end_column, 100), (end_column, height), color, 1)\n\n\n\n\n","sub_path":"mysite/plot_bound_detector/PlotBoundDetector.py","file_name":"PlotBoundDetector.py","file_ext":"py","file_size_in_byte":6130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"375671668","text":"# -*- coding: utf-8 -*-\n# created by lilei at 2020/2/24\n\nfrom flask import url_for\n\nfrom app.components.logger import get_logger\nfrom tests.conftest import http_req\n\nlog = get_logger(__name__)\n\n\nclass TestEdcForm(object):\n \"\"\"edc_form相关单元测试\"\"\"\n def test_edc_form_add(self, client):\n payload = {'visit_id': 1, 'form_name': '表单1', 'form_remark': '备注1', 'form_repeat': '否'}\n payload2 = {'visit_id': 1, 'form_name': '表单2', 'form_remark': '备注2', 'form_repeat': '否'}\n resp_json = http_req(client, url_for('edc.form-add'), method='POST', payload=payload)\n resp_json2 = http_req(client, url_for('edc.form-add'), method='POST', payload=payload2)\n log.info(str(resp_json)+str(resp_json2))\n assert resp_json['code'] == 0 and resp_json2['code'] == 0\n\n def test_edc_form_list(self, client):\n payload = {'visit_id': 1}\n resp_json = http_req(client, url_for('edc.form-list'), method='GET', payload=payload)\n log.info(str(resp_json))\n assert resp_json['code'] == 0\n\n def test_edc_form_sort(self, client):\n payload = {'visit_id': 1, 'form_ids': [2, 1]}\n resp_json = http_req(client, url_for('edc.form-sort'), method='POST', payload=payload)\n log.info(str(resp_json))\n assert resp_json['code'] == 0\n\n def test_edc_form_update(self, client):\n payload = {'form_id': 2, 'form_name': '新表单2', 'form_remark': '新备注2', 'form_repeat': '是'}\n resp_json = http_req(client, url_for('edc.form-update'), method='POST', payload=payload)\n log.info(str(resp_json))\n assert resp_json['code'] == 0\n\n def test_edc_form_delete(self, client):\n payload = {'form_id': 2}\n resp_json = http_req(client, url_for('edc.form-delete'), method='POST', payload=payload)\n log.info(str(resp_json))\n assert resp_json['code'] == 0\n\n def test_edc_form_copy(self, client):\n payload = {'visit_id': 1, 'form_ids': [1]}\n resp_json = http_req(client, url_for('edc.form-copy'), method='POST', payload=payload)\n log.info(str(resp_json))\n assert resp_json['code'] == 0","sub_path":"tests/test_a.py","file_name":"test_a.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"604448056","text":"import unittest\n\nfrom model.utils.gradient_check import eval_numerical_gradient\nfrom model.utils.gradient_check import eval_numerical_gradient_array\nfrom model.layers.core import *\n\ndef rel_error(x, y):\n return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))\n\n\nclass TestCoreLayers(unittest.TestCase):\n \n def test_affine_forward(self):\n \"\"\"\n check backprop with numerical gradient\n \"\"\"\n x = np.random.randn(10, 3, 5)\n w = np.random.randn(15, 20)\n b = np.random.randn(20)\n dout = np.random.randn(10, 20)\n\n dx_num = eval_numerical_gradient_array(lambda x: affine_forward(x, w, b)[0], x, dout)\n db_num = eval_numerical_gradient_array(lambda b: affine_forward(x, w, b)[0], b, dout)\n dw_num = eval_numerical_gradient_array(lambda w: affine_forward(x, w, b)[0], w, dout)\n\n _, cache = affine_forward(x, w, b)\n dx, dw, db = affine_backward(dout, cache)\n\n self.assertTrue(rel_error(dx, dx_num) < 1e-7)\n self.assertTrue(rel_error(db, db_num) < 1e-7)\n self.assertTrue(rel_error(dw, dw_num) < 1e-7)\n\n def test_relu_backward(self):\n \"\"\"\n check backprop with numerical gradient\n \"\"\"\n x = np.random.randn(10, 10) * 3\n dout = np.random.randn(*x.shape)\n\n dx_num = eval_numerical_gradient_array(lambda x: relu_forward(x)[0], x, dout)\n\n _, cache = relu_forward(x)\n dx = relu_backward(dout, cache)\n\n self.assertTrue(rel_error(dx, dx_num) < 1e-8)\n\n def test_batchnorm_forward_simple(self):\n \"\"\" gamma = 1 and beta = 0\n \"\"\"\n N, D1, D2, D3 = 100, 30, 40, 3\n X = np.random.randn(N, D1)\n W1 = np.random.randn(D1, D2)\n W2 = np.random.randn(D2, D3)\n a = np.maximum(0, np.dot(X, W1)).dot(W2)\n a_norm, _ = batchnorm_forward(a, np.ones(D3), np.zeros(D3), {'mode': 'train'})\n expected_mean, expected_variance = np.zeros(D3), np.ones(D3)\n self.assertTrue(rel_error(a_norm.mean(axis=0), expected_mean) < 1e-7) \n self.assertTrue(rel_error(a_norm.std(axis=0), expected_variance) < 1e-7)\n\n\n def test_batchnorm_forward(self):\n \"\"\" explicitely introduce gamma and beta\n \"\"\"\n N, D1, D2, D3 = 100, 30, 40, 3\n X = np.random.randn(N, D1)\n W1 = np.random.randn(D1, D2)\n W2 = np.random.randn(D2, D3)\n a = np.maximum(0, np.dot(X, W1)).dot(W2)\n gamma = np.asarray([1.0, 2.0, 3.0])\n beta = np.asarray([11.0, 12.0, 13.0])\n a_norm, _ = batchnorm_forward(a, gamma, beta, {'mode': 'train'})\n self.assertTrue(rel_error(a_norm.mean(axis=0), beta) < 1e-5)\n self.assertTrue(rel_error(a_norm.std(axis=0), gamma) < 1e-5)\n\n \n def test_batchnorm_backward(self):\n \"\"\"\n check backprop with numerical gradient\n \"\"\"\n N, D = 4, 5\n x = 5 * np.random.randn(N, D) + 12 # std = 5 and var = 12\n gamma = np.random.randn(D)\n beta = np.random.randn(D)\n dout = np.random.randn(N, D)\n bn_param = {'mode': 'train'}\n fx = lambda x: batchnorm_forward(x, gamma, beta, bn_param)[0]\n fg = lambda a: batchnorm_forward(x, gamma, beta, bn_param)[0]\n fb = lambda b: batchnorm_forward(x, gamma, beta, bn_param)[0]\n\n dx_num = eval_numerical_gradient_array(fx, x, dout)\n dg_num = eval_numerical_gradient_array(fg, gamma, dout)\n db_num = eval_numerical_gradient_array(fb, beta, dout)\n\n _, cache = batchnorm_forward(x, gamma, beta, bn_param)\n dx, dgamma, dbeta = batchnorm_backward(dout, cache)\n\n self.assertTrue(rel_error(dx_num, dx) < 1e-8)\n self.assertTrue(rel_error(dgamma, dg_num) < 1e-8)\n self.assertTrue(rel_error(dbeta, db_num) < 1e-8)\n\n\n def test_dropout_backward(self):\n \"\"\"\n check backprop with numerical gradient\n \"\"\"\n x = np.random.randn(30, 30) + 17\n dout = np.random.randn(*x.shape)\n dropout_param = {'mode': 'train', 'p': 0.8, 'seed': 123}\n out, cache = dropout_forward(x, dropout_param)\n dx = dropout_backward(dout, cache)\n dx_num = eval_numerical_gradient_array(lambda x: dropout_forward(x, dropout_param)[0], x, dout)\n self.assertTrue(rel_error(dx_num, dx) < 1e-8)\n\n\n def test_mse(self):\n \"\"\"\n check backprop with numerical gradient\n \"\"\"\n x = np.random.randn(5, 5)\n y = np.random.randn(5, 5)\n num_x = eval_numerical_gradient(lambda x: mse_loss(x, y)[0], x, verbose=False)\n _, dx = mse_loss(x, y)\n self.assertTrue(rel_error(dx, num_x) < 1e-7)\n\n","sub_path":"tests/test_layers.py","file_name":"test_layers.py","file_ext":"py","file_size_in_byte":4256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"58681031","text":"def read_file(file_name):\n \"\"\"\n This function will be used to read the text file in which the test will be written.\n\n @param : file_name is the path used to read the file\n @return : str\n \"\"\"\n file_content = \"\"\n try:\n with open(file_name, mode='r') as file:\n file_content = file_name.read()\n except Exception as e:\n print(\"Error while reading file : {}, got error : {}\".format(file_name, e))\n raise e\n\n return file_content\n","sub_path":"HardCoreDS&ALGO/Learning/commons.py","file_name":"commons.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"386357507","text":"import random\nclass Solution:\n def __init__(self, nums):\n \"\"\"\n :type nums: List[int]\n \"\"\"\n self.nums = nums\n\n def pick(self, target):\n \"\"\"\n :type target: int\n :rtype: int\n \"\"\"\n l = []\n k = 0\n for i in self.nums:\n if i == target:\n l.append(k)\n k += 1\n return random.choice(l)\n\n def pick_quick(self, target):\n return random.choice([k for k, v in enumerate(self.nums) if v == target])\n\n\nnums = [1,2,3,3,3]\nobj = Solution(nums)\nparam_1 = obj.pick(3)\nprint(param_1)","sub_path":"python/398_randomPick.py","file_name":"398_randomPick.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"113629286","text":"from gocept.amqprun.interfaces import IResponse\nimport logging\nimport transaction\n\ntry:\n from zope.security.management import endInteraction as end_interaction\n from zope.security.testing import create_interaction\nexcept ImportError: # pragma: no cover\n def create_interaction(principal):\n log.warn(\n 'create_interaction(%s) called but zope.security is not available',\n principal)\n\n def end_interaction():\n pass\n\n\nlog = logging.getLogger(__name__)\n\n\nclass PrefixingLogger(object):\n \"\"\"Convenience for spelling log.foo(prefix + message)\"\"\"\n\n def __init__(self, log, prefix):\n self.log = log\n self.prefix = prefix\n\n def __getattr__(self, name):\n def write(message, *args, **kw):\n log_method = getattr(self.log, name)\n return log_method(self.prefix + message, *args, **kw)\n return write\n\n\nclass Worker(object):\n\n def __init__(self, session, handler):\n self.session = session\n self.handler = handler\n\n def __call__(self):\n session = self.session\n handler = self.handler\n self.log = PrefixingLogger(log, 'Worker ')\n self.log.info('starting')\n try:\n message = session.received_message\n self.log.info('Processing message %s %s (%s)',\n message.delivery_tag,\n message.header.message_id,\n message.routing_key)\n self.log.debug(str(message.body))\n transaction.begin()\n if handler.principal is not None:\n create_interaction(handler.principal)\n session.join_transaction()\n response = None\n try:\n response = handler(message)\n if IResponse.providedBy(response):\n response_messages = response.responses\n else:\n response_messages = response\n self._send_response(session, message, response_messages)\n transaction.commit()\n except Exception:\n self.log.error(\n 'Error while processing message %s',\n message.delivery_tag, exc_info=True)\n transaction.abort()\n if IResponse.providedBy(response):\n try:\n session.received_message = message\n error_messages = response.exception()\n self._send_response(session, message, error_messages)\n transaction.commit()\n except Exception:\n self.log.error(\n 'Error during exception handling', exc_info=True)\n transaction.abort()\n except Exception:\n self.log.error(\n 'Unhandled exception, prevent thread from crashing',\n exc_info=True)\n finally:\n end_interaction()\n\n def _send_response(self, session, message, response):\n for msg in response:\n self.log.info(\n 'Sending message to %s in response to message %s',\n msg.routing_key, message.delivery_tag)\n session.send(msg)\n","sub_path":"src/gocept/amqprun/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":3257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"476615383","text":"#SENSOR D'HUMITAT HTU21D-F\nimport pycom\nimport time\nfrom ustruct import unpack as unp\nimport math\nfrom machine import Pin, I2C\n\nHTU21D_HOLDMASTER = 0x00\nHTU21D_NOHOLDMASTER = 0x10\nHTU21D_MAX_MEASURING_TIME=100\nmode=HTU21D_HOLDMASTER\nI2C_ADDRESS=0X40\nTEMP_ADDR=0XE3\nHUM_ADDR=0XE5\ni2c = I2C()\nclass SensorHumT:\n\n def __init__(self,i2c=None):\n #Delete data's contents\n f = open('data_HTU.txt', 'w')\n f.close()\n pass\n\n def checkcrc(self,msb, lsb, crc):\n remainder = ((msb << 8) | lsb) << 8\n remainder |= crc\n divsor = 0x988000\n\n for i in range(0, 16):\n if remainder & 1 << (23 - i):\n remainder ^= divsor\n divsor >>= 1\n\n if remainder == 0:\n return True\n else:\n return False\n\n def readTemperature(self):\n th=bytearray(1)\n tl=bytearray(1)\n crct=bytearray(1)\n\n\n #print(\"hum Adress: \",i2c.scan()) #64 dec es 0X40.\n #i2c.writeto_mem(I2C_ADDRESS, HUM_ADDR, buf *, addrsize=8)\n #self._htu_handler.send_command((HTU21D_TRIGGERTEMPCMD | mode) & 0xFF)\n #time.sleep(HTU21D_MAX_MEASURING_TIME/1000)\n #msb, lsb, chsum = self._htu_handler.read_bytes(3)\n #Llegir Temperatura\n i2c.writeto(I2C_ADDRESS,TEMP_ADDR) # write 2 bytes to slave 0x42, slave memory 0x10\n time.sleep(HTU21D_MAX_MEASURING_TIME/1000)\n th,tl,crct=i2c.readfrom(I2C_ADDRESS, 3) # receive 5 bytes from slave\n Stemp=(th<<8) | tl\n Stemp=Stemp & 0xFFFC\n Temp=-46.85+175.72*(Stemp/(2**16))\n okt=self.checkcrc(th,tl,crct)\n if okt == False: print(\"Error\")\n else:\n print(\"Temp(ºC)\",Temp)\n return Temp\n #Llegir Humitat\n\n def readHumidity(self):\n\n hh=bytearray(1)\n hl=bytearray(1)\n crch=bytearray(1)\n i2c.writeto(I2C_ADDRESS,HUM_ADDR) # write 2 bytes to slave 0x42, slave memory 0x10\n time.sleep(HTU21D_MAX_MEASURING_TIME/1000)\n hh,hl,crch=i2c.readfrom(I2C_ADDRESS, 3) # receive 5 bytes from slave\n Shum=(hh<<8) | hl\n Shum=Shum & 0xFFFC\n Hum=-6+125*(Shum/(2**16))\n okh=self.checkcrc(hh,hl,crch)\n if okh == False: print(\"Error\")\n else:\n print(\"Hum (%)\",Hum)\n return Hum # La conversió està al TTN per enviar paquets més petits\n\n def saveFile(self,T,rtc):\n '''\n Format of the data: date (DD/MM/YYYY HH:MM:SS) Temperature [ºC]\n Example: 15/10/2019 13:21:31 26.4\n '''\n #Write the image temp in data.txt\n f = open('data_HTU.txt', 'a')\n f.write(\"{}/{}/{} {}:{}:{} {}\\n\".format(rtc.now()[2],rtc.now()[1],rtc.now()[0],rtc.now()[3],rtc.now()[4],rtc.now()[5],T))\n f.close()\n return\n","sub_path":"Capitol carcteritzar nodes/Caracteritzacio sensors Temp/lib/SensorHumT.py","file_name":"SensorHumT.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"497773888","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/multicore/tests/test_utils.py\n# Compiled at: 2017-08-07 06:18:36\nimport unittest\nfrom multicore.utils import ranges\n\nclass TaskUtilsCase(unittest.TestCase):\n\n def test_ranges(self):\n li = list(ranges(range(80), number_of_workers=4))\n self.assertEqual(li, [(0, 20), (20, 40), (40, 60), (60, 80)])\n li = list(ranges(range(80), min_range_size=30, number_of_workers=4))\n self.assertEqual(li, [(0, 30), (30, 60), (60, 80)])\n li = list(ranges(range(80), min_range_size=100, number_of_workers=4))\n self.assertEqual(li, [(0, 80)])","sub_path":"pycfiles/multicore-0.1.1-py2.7/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"358607997","text":"#https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014323389656575142d0bcfeec434e9639a80d3684a7da000\nimport logging; logging.basicConfig(level=logging.INFO)\n\nimport asyncio\nimport aiomysql\n\n@asyncio.coroutine\ndef create_pool(loop, **kw):\n\tlogging.info(\"create datebase connection pool...\")\n\tglobal __pool\n\t__pool = yield from aiomysql.create_pool(\n\t\thost = kw.get('host', 'localhost'),\n\t\tport = kw.get('port', 3306),\n\t\tuser = kw['user'],\n\t\tpassword = kw['password'],\n\t\tdb = kw['db'],\n\t\tcharset = kw.get('charset', 'utf8'),\n\t\tautocommit = kw.get('autocommint', True),\n\t\tmaxsize = kw.get('maxsize', 10),\n\t\tminsize = kw.get('minsize', 1),\n\t\tloop = loop\n\t\t)\n\n@asyncio.coroutine\ndef select(sql, args, size=None):\n\tlog(sql, args)\n\tglobal __pool\n\twith (yield from __pool) as conn:\n\t\tcur = yield from conn.cursor(aiomysql.DictCursor)\n\t\tyield from cur.execute(sql.replace('?', '%s'), args or())\n\t\tif size:\n\t\t\trs = yield from cur.fetchmany(size)\n\t\telse:\n\t\t\trs = yield from cur.fetchall()\n\t\tyield from cur.close()\n\t\tlogging.ifno('rows returned: %s', len(rs))\n\t\treturn rs\n\n@asyncio.coroutine\ndef execute(sql, args):\n\tlog(sql)\n\twith (yield from __pool) as conn:\n\t\ttry:\n\t\t\tcur = yield from conn.cursor()\n\t\t\tyield from cur.execute(sql.replace('?', '%s'), args)\n\t\t\taffected = cur.rowcount\n\t\t\tyield from cur.close()\n\t\texcept BaseException as e:\n\t\t\traise\n\t\treturn affected\n\nclass User(Model):\n\t\"\"\"docstring for User\"\"\"\n\t__table__ = 'users'\n\n\tid = IntegerField(primary_key=True)\n\tname = StringField()\n\nclass Model(dict, metaclass=ModelMetaclass):\n\t\t\"\"\"docstring for Model\"\"\"\n\t\tdef __init__(self, **kw):\n\t\t\tsuper(Model, self).__init__(**kw)\n\t\t\n\t\tdef __getattr__(self, key):\n\t\t\ttry:\n\t\t\t\treturn self[key]\n\t\t\texcept keyError:\n\t\t\t\traise AttributeError(r\"'Model' object has no attribute '%s'\" % key)\n\n\t\tdef __setattr__(self, key, value):\n\t\t\tself[key] = value\n\t\t\n\t\tdef getValue(self, key):\n\t\t\treturn getattr(self, key, None)\n\n\t\tdef getValueOrDefault(self, key):\n\t\t\tvalue = getattr(self, key, None)\n\t\t\tif value is None:\n\t\t\t\tfield = self.__mappings__[key]\n\t\t\t\tif field.default is not None:\n\t\t\t\t\tvalue = field.default() if callable(field.default) else field.default\n\t\t\t\t\tlogging.debug('using default value for %s: %s' % (key, str(value)))\n\t\t\t\t\tsetattr(self, key, value)\n\t\t\treturn value\n\n\nuser = User(id = 123, name = 'Michael')\nuser.insert()\nusers = User.findAll()\n\n\n\n\t\t\n","sub_path":"awesome-python3-webapp/www/static/orm.py","file_name":"orm.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"105033321","text":"from flask_sqlalchemy import SQLAlchemy\nfrom app import app\nimport os, csv, sys\n\ndb = SQLAlchemy(app)\nbasedir = os.path.abspath(os.path.dirname(__file__))\nDATABASE_URL = 'sqlite:///' + os.path.join(basedir, 'app.db')\n\nclass Course(db.Model):\n __tablename__ = \"course\"\n id = db.Column(db.Integer, primary_key = True)\n course_number = db.Column(db.String, nullable = False)\n course_title = db.Column(db.String, nullable = False)\n\nclass RegisteredStudent(db.Model):\n __tablename__ = \"registeredstudents\"\n id = db.Column(db.Integer, primary_key = True)\n name = db.Column(db.String, nullable = False)\n grade = db.Column(db.Integer, nullable = False)","sub_path":"playground/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"364746164","text":"import sys\nimport csv\nimport csvClient\n\nmaxInt = sys.maxsize\nwhile True:\n # decrease the maxInt value by factor 10\n # as long as the OverflowError occurs.\n try:\n csv.field_size_limit(maxInt)\n break\n except OverflowError:\n maxInt = int(maxInt/10)\n\n\nclass Client(object):\n def __init__(self, file_path):\n self._file_path = file_path\n self._header = self._read_header()\n self._issues_reader = None\n\n def _read_header(self):\n header = self._get_reader().next()\n return [field_name\n for field_name in [h.strip() for h in header]\n if len(field_name)]\n\n def _get_reader(self):\n return csv.reader(open(self._file_path, \"r\"),\n delimiter=csvClient.CSV_DELIMITER)\n\n def get_rows(self):\n reader = self._get_reader()\n for row in reader:\n yield row\n\n def get_issues(self):\n reader = self._get_reader()\n reader.next()\n header_len = len(self._header)\n for row in reader:\n if not row:\n continue\n issue = {\"comments\": []}\n for i in range(len(row)):\n value = row[i].strip()\n if len(value):\n if i < header_len:\n issue[self._header[i]] = value\n else:\n issue[\"comments\"].append(value)\n yield issue\n\n def get_header(self):\n return self._header\n\n def reset(self):\n self._issues_reader = self._get_reader()\n self._read_header()\n","sub_path":"python/csvClient/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"200114045","text":"from os import system\n\narq = \"entrada.c\"\ndef tratamento(arq):\n arquivo = open(arq,'r')\n if (arquivo == None):\n print(\"Erro ao ler arquivo\")\n \n # Separa o código do arquivo entrada por linhas.\n lista = []\n for line in arquivo:\n linha = line.strip('\\n')\n lista.append(linha)\n arquivo.close()\n\n # Remove os comentários //\n for linha in lista:\n if '//' in linha:\n aux = linha.index('/')\n aux2 = lista.index(linha)\n lista[aux2] = linha[0:aux]\n\n # Separa as \"listas de string\" em \"lista de listas de strings\".\n listaEspaco = []\n for esq in lista:\n varA = esq.split()\n listaEspaco.append(varA)\n \n # Armazenando os includes\n listainclude = []\n for db in listaEspaco:\n if (\"#include\" in db):\n listainclude.append(db[1][1:-1])\n del(listaEspaco[listaEspaco.index(db)])\n\n # Coloca as linhas da biblioteca na frente\n if len(listainclude) != 0:\n for w in listainclude:\n aux = tratamento(w)\n listaEspaco = aux + listaEspaco \n return listaEspaco\n\nlistaEspaco = tratamento(arq)\n\n# Muda os '#define' pelos seus determinados valores.\ndef tratardefine(nomedef, valordef, listaEspaco):\n for linhas in listaEspaco:\n for palavras in linhas:\n if nomedef in palavras:\n indexLinha = listaEspaco.index(linhas)\n indexPalavra = listaEspaco[indexLinha].index(palavras)\n listaEspaco[indexLinha][indexPalavra] = listaEspaco[indexLinha][indexPalavra].replace(nomedef, valordef)\n return listaEspaco\n\n# Armazenando os defines em listas e deletando a linha dos '#define'.\nlistaNomeDef = []\nlistaValorDef = []\n\nfor db in listaEspaco:\n if '#define' in db:\n listaEspaco = tratardefine(db[1], db[2], listaEspaco)\n listaEspaco[listaEspaco.index(db)] = ''\n\n\n# Remove os comentários do tipo '/*' '*/' do código.\nfor string in listaEspaco:\n index = listaEspaco.index(string)\n listaEspaco[index] = ''.join(listaEspaco[index])\n\nlistaEspaco = ''.join(listaEspaco)\nlistaEspaco = listaEspaco.replace('/*','*/')\nlistaEspaco = listaEspaco.split('*/')\n\nfor y in range (1,len(listaEspaco),2):\n listaEspaco[y] = \"\"\nlistaEspaco = ''.join(listaEspaco)\n\n# tratamento para execução\nfuncoes_em_c = ['void','int','if','char']\nprintf = 'print f'\nfor s in funcoes_em_c:\n if s in listaEspaco:\n j = s + ' '\n listaEspaco = listaEspaco.replace(s,j)\nif printf in listaEspaco:\n listaEspaco = listaEspaco.replace(printf,'printf')\n\n\n\n\nsystem('cls')\nprint('Pronto!')\nprint('\\n\\n\\n')\nsystem('pause')\n\nwith open('ProgramaPreProcessado.c', 'w') as output:\n output.write(listaEspaco)\n output.close()\n","sub_path":"pre_processador.py","file_name":"pre_processador.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"300462615","text":"#!/usr/bin/env python\n\n#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. 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\n# Utility for generating changelogs for fix versions\n# requirements: pip install jira\n# Set $JIRA_USERNAME, $JIRA_PASSWORD environment variables\n\nfrom collections import defaultdict\nfrom io import StringIO\nimport os\nimport sys\n\nimport jira.client\n\n# ASF JIRA username\nJIRA_USERNAME = os.environ.get(\"JIRA_USERNAME\")\n# ASF JIRA password\nJIRA_PASSWORD = os.environ.get(\"JIRA_PASSWORD\")\n\nJIRA_API_BASE = \"https://issues.apache.org/jira\"\n\nasf_jira = jira.client.JIRA({'server': JIRA_API_BASE},\n basic_auth=(JIRA_USERNAME, JIRA_PASSWORD))\n\n\ndef get_issues_for_version(version):\n jql = (\"project=ARROW \"\n \"AND fixVersion='{0}' \"\n \"AND status = Resolved \"\n \"AND resolution in (Fixed, Done) \"\n \"ORDER BY issuetype DESC\").format(version)\n\n return asf_jira.search_issues(jql, maxResults=9999)\n\n\nLINK_TEMPLATE = '[{0}](https://issues.apache.org/jira/browse/{0})'\n\n\ndef format_changelog_markdown(issues, out, links=False):\n issues_by_type = defaultdict(list)\n for issue in issues:\n issues_by_type[issue.fields.issuetype.name].append(issue)\n\n\n for issue_type, issue_group in sorted(issues_by_type.items()):\n issue_group.sort(key=lambda x: x.key)\n\n out.write('## {0}\\n\\n'.format(issue_type))\n for issue in issue_group:\n if links:\n name = LINK_TEMPLATE.format(issue.key)\n else:\n name = issue.key\n out.write('* {0} - {1}\\n'.format(name,\n issue.fields.summary))\n out.write('\\n')\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n print('Usage: make_changelog.py $FIX_VERSION [$LINKS]')\n\n buf = StringIO()\n\n links = len(sys.argv) > 2 and sys.argv[2] == '1'\n\n issues_for_version = get_issues_for_version(sys.argv[1])\n format_changelog_markdown(issues_for_version, buf, links=links)\n print(buf.getvalue())\n","sub_path":"dev/make_changelog.py","file_name":"make_changelog.py","file_ext":"py","file_size_in_byte":2745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"554561809","text":"from datetime import datetime\nimport pytz\n\nportland = datetime.now(pytz.timezone('US/Pacific')).time()\nnewYork = datetime.now(pytz.timezone('America/New_York')).time()\nlondon = datetime.now(pytz.timezone('Europe/London')).time()\n\npor = int(portland.strftime('%H'))\nnew = int(newYork.strftime('%H'))\nlon = int(london.strftime('%H'))\n\nporStr = portland.strftime('%I:%M %p')\nnewStr = newYork.strftime('%I:%M %p')\nlonStr = london.strftime('%I:%M %p')\n\nif 9 < por < 17:\n print(\"It is {} in Portland, OR. \\\n \\nWe are currently open at this location.\\\n \\nOur operating hours are from 9:00 AM to 5:00 PM\\n\".format(porStr))\nelse:\n print(\"It is {} in Portland, OR. \\\n \\nWe are currently closed at this location.\\\n \\nOur operating hours are from 9:00 AM to 5:00 PM\\n\".format(porStr))\n\nif 9 < new < 17:\n print(\"It is {} in New York, NY. \\\n \\nWe are currently open at this location.\\\n \\nOur operating hours are from 9:00 AM to 5:00 PM\\n\".format(newStr))\nelse:\n print(\"It is {} in New York, NY. \\\n \\nWe are currently closed at this location.\\\n \\nOur operating hours are from 9:00 AM to 5:00 PM\\n\".format(newStr))\n\nif 9 < lon < 17:\n print(\"It is {} in London, England. \\\n \\nWe are currently open at this location.\\\n \\nOur operating hours are from 9:00 AM to 5:00 PM\\n\".format(lonStr))\nelse:\n print(\"It is {} in London, England. \\\n \\nWe are currently closed at this location.\\\n \\nOur operating hours are from 9:00 AM to 5:00 PM\\n\".format(lonStr))\n","sub_path":"challenges/challenge-page-222.py","file_name":"challenge-page-222.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"505555504","text":"########################################\n#\n# This file part of the ganglia-dyngraph package\n#\n# https://pypi.python.org/pypi/ganglia-dyngraph\n#\n# https://github.com/dcarrollno/Ganglia-Modules/wiki/Overview:-Ganglia-Dynamic-Metrics%3F\n#\n# Dave Carroll - davecarrollno@gmail.com\n#\n########################################\n\nimport os\nimport sys\nimport read_config as cfg\nfrom loglib import loglib\n\nclass PurgeMetrics(object):\n\n\n def __init__(self,expiredMetricList):\n ''' This class expects a list of metrics to process'''\n\n self.expiredMetricList = expiredMetricList\n\n\n def purge(self):\n\n\n if not self.expiredMetricList:\n #print(\"WARN: An empty list was sent to PurgeMetrics\")\n return()\n\n for self.met in self.expiredMetricList:\n\n try:\n os.remove(self.met)\t\n loglib(cfg.logfile,'INFO: Metric %s successfully purged' % self.met)\n self.metpurge = 0\n except:\n loglib(cfg.logfile,'WARN: Purge of metric %s encountered an error.' % self.met)\n #print(\"Error purging metric %s\" % self.met)\n self.metpurge = 1\n\n finally:\n if self.metpurge == 0:\n cfg.purged +=1\n\t\t #print(\"Adding to purge. Count is now %s\" % cfg.purged)\n else:\n cfg.purge_errors +=1\n","sub_path":"Ganglia-DynGraph/ganglia-dyngraph/ganglia-dyngraph/purge_metrics.py","file_name":"purge_metrics.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"569206966","text":"import torch\nimport numpy as np\nimport pandas as pd\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\nfrom torch.autograd import Variable,function\n\nfrom tensorboardX import SummaryWriter\n\n##author:veritas xu\n##time:2018/3/7\n#设计深度学习P230页图10.3计算循环网络\n\n#########################################\n## 与自带RNN输入输出维度相同 ####\n## seq_len(T) batch feature ####\n#########################################\n\nclass computeRNN(nn.Module):\n def __init__(self,in_feature,hidden_size,n_class):\n super(computeRNN, self).__init__()\n self.in_feature=in_feature\n self.hidden_size=hidden_size\n self.n_class=n_class\n self.in2hidden=nn.Linear(in_feature+self.hidden_size,self.hidden_size)\n self.hidden2out=nn.Linear(self.hidden_size,self.n_class)\n self.tanh=nn.Tanh()\n self.softmax=nn.Softmax(dim=1)\n\n ##此处input的尺寸为[seq_len,batch,in_feature]\n def forward(self,input,pre_state):\n T=input.shape[0]\n batch=input.shape[1]\n a=Variable(torch.zeros(T,batch,self.hidden_size)) #a-> [T,hidden_size]\n o=Variable(torch.zeros(T,batch,self.n_class)) #o ->[T,n_class]\n predict_y=Variable(torch.zeros(T,batch,self.n_class))\n # pre_state = Variable(torch.zeros(batch, self.hidden_size)) # pre_state=[batch,hidden_size]\n\n\n if pre_state is None:\n pre_state = Variable(torch.zeros(batch, self.hidden_size)) # hidden ->[batch,hidden_size]\n\n for t in range(T):\n # input:[T,batch,in_feature]\n tmp = torch.cat((input[t], pre_state), 1) # [batch,in_feature]+[batch,hidden_size]-> [batch,hidden_size+in_featue]\n a[t]=self.in2hidden(tmp) # [batch,hidden_size+in_feature]*[hidden_size+in_feature,hidden_size] ->[batch,hidden_size]\n hidden = self.tanh(a[t])\n\n #这里不赋值的话就没有代表隐层向前传递\n pre_state=hidden\n\n o[t] = self.hidden2out(hidden) # [batch,hidden_size]*[hidden_size,n_class]->[batch,n_class]\n #由于此次是一个单分类问题,因此不用softmax函数\n if self.n_class ==1:\n predict_y[t]=F.sigmoid(o[t])\n else:\n predict_y[t] = self.softmax(o[t])\n\n\n return predict_y, hidden\n\ninput_size=2 #一个序列的长度,也就是输入特征数\nn_hidden = 12 #隐层神经元数目\ntarget_size = 1 #输出的尺寸\nrnn = computeRNN(in_feature=input_size,hidden_size=n_hidden,n_class=target_size)\n\n\n\n#定义训练集\ndata_csv = pd.read_csv('./data/data.csv',usecols=[1])\ndata_csv=data_csv.dropna()\ndata_set=data_csv.values\ndata_set=data_set.astype('float32')\nmax_value = np.max(data_set)\nscalar = max_value\ndata_set = list(map(lambda x: x / scalar, data_set))\n# print(data_set)\n\ndef create_dataset(dataset, look_back=2):\n dataX, dataY = [], []\n for i in range(len(dataset) - look_back):\n a = dataset[i:(i + look_back)]\n dataX.append(a)\n dataY.append(dataset[i + look_back])\n return np.array(dataX), np.array(dataY)\n\n# 创建好输入输出\ndata_X, data_Y = create_dataset(data_set)\n# print(data_X)\n\n# 划分训练集和测试集,70% 作为训练集\ntrain_size = int(len(data_X) * 0.7)\ntest_size = len(data_X) - train_size\ntrain_X = data_X[:train_size]\ntrain_Y = data_Y[:train_size]\ntest_X = data_X[train_size:]\ntest_Y = data_Y[train_size:].astype('float32')\nprint(train_Y.shape)\nprint(test_X.shape)\ntrain_X = train_X.reshape(-1,3, 2)\ntrain_Y = train_Y.reshape(-1,3, 1)\ntest_X = test_X.reshape(-1,1, 2)\n\ntrain_x = Variable(torch.from_numpy(train_X))\ntrain_y = Variable(torch.from_numpy(train_Y))\ntest_x = Variable(torch.from_numpy(test_X))\nprint(train_x[0])\nprint(train_y[0])\n\noptimizer=optim.Adam(rnn.parameters(),lr=0.016)\nloss_fun=nn.MSELoss()\n\nnum_epoch=1000\n# print(len(train_x))\n#\nfor epoch in range(num_epoch):\n state=None\n out, state = rnn(train_x, state)\n loss=loss_fun(out,train_y)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n if (epoch + 1) % 100 == 0: # 每 100 次输出结果\n print('Epoch: {}, Loss: {:.5f}'.format(epoch + 1, loss.data[0]))\n # state = None\n# #\nrnn.eval()\nhidden1=None\nout2,_=rnn(train_x,hidden1)\nplt.plot(out2.data.numpy().reshape(99,1))\nplt.plot(train_Y.reshape(99,1))\nplt.show()\n\n\nmodel=computeRNN(2,3,1)\ndummy_input = Variable(torch.randn(2,1,2)) #[torch.FloatTensor of size Nxinput_size],成员都是0\n# print(dummy_input)\ndummy_hidden=None\noutput,dummy_hidden = model(dummy_input,dummy_hidden) #得到[seq_num*target_size],[1*128]\n# print(output)\nwith SummaryWriter(comment='RNN') as w:\n w.add_graph(model, (dummy_input,dummy_hidden,))","sub_path":"RNNs_2.py","file_name":"RNNs_2.py","file_ext":"py","file_size_in_byte":4831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"640401273","text":"#!/usr/bin/env python3\n\nimport re\nimport sys\nfrom datetime import datetime, timezone\n\nfrom bs4 import BeautifulSoup\n\npage = sys.stdin.read()\nsoup = BeautifulSoup(page, 'html.parser')\n\ntitle = soup.html.head.title.text\nlink = soup.html.head.find('link', {'rel': 'canonical', 'href': True})['href']\n\nentries = []\n\ntimeline = soup.find('div', {'id': 'timeline'})\n\nfor item in timeline.findAll('div', {'class': re.compile('.*js-stream-tweet.*')}):\n timestamp = item.find('span', {'class': re.compile('.*js-short-timestamp.*')})['data-time']\n content = item.find('p', {'class': re.compile('TweetTextSize.*')})\n\n for a in content.findAll('a'):\n for tag in a.findAll(recursive=False):\n tag.replaceWith(tag.text.strip())\n\n entry = {\n 'name': item['data-name'] + ' (@' + item['data-screen-name'] + ')',\n 'link': 'https://twitter.com' + item['data-permalink-path'],\n 'text': content.text.strip(),\n 'html': str(content),\n 'updated': datetime.fromtimestamp(float(timestamp), timezone.utc).isoformat(),\n }\n\n entries.append(entry)\n\nif entries:\n rss = '''\n \n\n {}\n \n {}\n \n {}\n {}\n \n {}\n\n '''.format(title, link, entries[0]['updated'], entries[0]['name'], link, link)\n\n for entry in entries:\n rss += '''\n \n {}\n \n {}\n {}\n \n {}\n {}\n \n {}\n \n '''.format(entry['text'], entry['link'], entry['link'], entry['updated'], entry['name'], link, entry['html'])\n\n print(rss + '')\n","sub_path":"filters/twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"261124772","text":"'''\n7. Faça um programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a\nser pintada. Considere que a cobertura da tinta é de 1 litro para cada 3 metros quadrados e que a tinta é vendida\nem latas de 18 litros, que custam R$ 80,00. Informe ao usuário a quantidades de latas de tinta a serem\ncompradas e o preço total. Obs. : somente são vendidos um número inteiro de latas.\n'''\n\nfrom math import *\n\narea = float(raw_input('Informe a quantidade de metros quadrados a serem pintados\\n'))\n\nlitros = (area * 1.0) / 3.0\n\nbarril = 18.0\n\nlatas = litros / barril\n\nlatas = ceil(latas)\n\nvalor = latas * 80\n\nprint(\"Para realizar está pintura, será gasto %.2f litros\\nNecessária %s latas de tintas\\nCom o total de R$%.2f\"\n % (litros, latas, valor))\n","sub_path":"Python Para Zumbis/Lista 2/ex7.py","file_name":"ex7.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"3376412","text":"import glob\nimport os\nimport stat\nfrom distutils.core import setup\nfrom distutils.extension import Extension\n\nsetup(\n name = \"Roundware Server\",\n version = \"2.0\",\n description = 'Roundware Server',\n author = 'Mike MacHenry, Ben McAllister',\n author_email = 'contact@roundware.org',\n url = 'http://roundware.sourceforge.net',\n license = 'LGPL',\n scripts = glob.glob('bin/*'),\n packages = [\"roundware.rw\", \"roundware\", \"roundwared\", \"roundware.notifications\"],\n# data_files = [\n# ('/usr/lib/cgi-bin', glob.glob('cgi-bin/*.py')),\n# ('/var/www/roundware', glob.glob('www/*py')),\n# ('/etc/dbus-1/system.d', ['data_files/org.roundware.StreamScript.conf']),\n# ],\n)\n\n# chmod all cgi-bin files to executable.\nfor file in glob.glob('cgi-bin/*.py'):\n os.chmod(\n os.path.join('/usr/lib/cgi-bin', os.path.basename(file)),\n stat.S_IRWXU | stat.S_IROTH | stat.S_IXOTH | stat.S_IXGRP | stat.S_IRGRP)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"353347342","text":"from multiprocessing import Process, Queue, Lock\r\nfrom DeepPipeline.Buffer import Buffer\r\nimport time\r\n\r\nclass Pipeline(object):\r\n def __init__(self, stages, end_stage = None, buffer_size=1):\r\n self.stages = stages\r\n self.stage_num = len(stages)\r\n\r\n if type(buffer_size) == type(0):\r\n self.buffers = [Buffer(size = buffer_size) for _ in range(self.stage_num + 1)]\r\n elif type(buffer_size) == list:\r\n try:\r\n self.buffers = [Buffer(size = buffer_size[i]) for i in range(self.stage_num + 1)]\r\n except:\r\n raise Exception(\"length of buffer_size (list) should be equal to length of stages (list)\")\r\n else:\r\n raise Exception(\"type of buffer_size should be (int) or (list)\")\r\n self.stage_process = [Process(target = stages[i] , args = (self.buffers[i], self.buffers[i+1])) for i in range(self.stage_num)]\r\n \r\n try:\r\n self.end_stage = Process(target = end_stage , args = (self.buffers[-1], None, True))\r\n except:\r\n raise Exception(\"the end of the pipeline should be a class (class )\")\r\n\r\n def put(self, x):\r\n self.buffers[0].put(x)\r\n\r\n def get(self):\r\n return self.buffers[-1].get()\r\n\r\n def start(self):\r\n for i in range(self.stage_num):\r\n self.stage_process[i].start()\r\n self.end_stage.start()\r\n \r\n def __len__(self):\r\n return self.stage_num\r\n\r\n\r\nif __name__ == '__main__':\r\n # queuetest()\r\n pass","sub_path":"DeepPipeline/Pipeline.py","file_name":"Pipeline.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"158717869","text":"import serial\nimport threading\nimport struct\nimport serial.tools.list_ports\n# import getch\nimport sys, getopt\nimport os.path\nimport time\nimport math\nfrom time import sleep\n\nrunning = True\ndistance = [80, 80, 80, 80, 80, 30, 30]\nbeacon_data = [0, 0, 0, 0]\nports = list(serial.tools.list_ports.comports())\nif len(ports) == 0:\n print('Cannot find any serial ports: check MBED connection.')\n quit()\n# Configure the serial connection to the MBED\nmbed_of_BadBoy = serial.Serial(\n port=str(ports[0][0]),\n baudrate=115200,\n timeout=0\n)\n\n\ndef decode_2y0a21(int_val):\n # Decode a int value [0-255] corresponding to 0-3.3V for the Sharp GP2Y0A21 sensor\n # Use values from datasheet for the 8.75cm to 80cm range\n # Power curve is a good fit\n # y = 4336.6 * x ^ -1.165579 (where x = 77.3 x voltage)\n number = float(int_val)\n if number < 32.0:\n distance = 80\n else:\n x_inv_power = pow(number, -1.165579)\n distance = x_inv_power * 4336.6\n return round(distance,1)\n\n\ndef decode_2y0a41(int_val):\n # Decode a int value [0-255] corresponding to 0-3.3V for the Sharp GP2Y0A41 sensor\n # Use values from datasheet for the 3.5cm to 30cm range\n # Power curve is a good fit\n # y = 1093.955 * x ^ -1.02475 (where x = 77.3 x voltage)\n number = float(int_val)\n if number < 35.0:\n distance = 30\n else:\n x_inv_power = pow(number, -1.02475)\n distance = x_inv_power * 1093.955\n return round(distance,1)\n\n\ndef read():\n global distance\n while running:\n data = mbed_of_BadBoy.read(32)\n if len(data) > 0:\n if data[0] == '\\x1B' and len(data) == 9:\n distance[0] = decode_2y0a21(struct.unpack('B', data[1])[0])\n distance[1] = decode_2y0a21(struct.unpack('B', data[2])[0])\n distance[2] = decode_2y0a21(struct.unpack('B', data[3])[0])\n distance[3] = decode_2y0a21(struct.unpack('B', data[4])[0])\n distance[4] = decode_2y0a21(struct.unpack('B', data[5])[0])\n distance[5] = decode_2y0a41(struct.unpack('B', data[6])[0])\n distance[6] = decode_2y0a41(struct.unpack('B', data[8])[0])\n print('distance:', distance)\n sleep(0.05)\n\n\ndef poll():\n get_sensors = b'\\x1d\\x6b\\x01\\x01\\x1d'\n while running:\n mbed_of_BadBoy.write(get_sensors)\n sleep(0.5)\n\n\ndef brake():\n message = b'\\x1d\\x06\\x00\\x00\\x1d'\n mbed_of_BadBoy.write(message)\n print('BRAKE MOTORS')\n\n\n\ndef right_turn(speed):\n message = b'\\x1d\\x08'\n kspeed = speed * 32767.0\n byte0 = int(kspeed / 256) + 128\n byte1 = int(kspeed % 256)\n message += chr(byte0)\n message += chr(byte1)\n message += chr(29)\n mbed_of_BadBoy.write(message)\n print('TURN RIGHT')\n\n\ndef left_turn(speed):\n message = b'\\x1d\\x08'\n kspeed = speed * 32767.0\n byte0 = int(kspeed / 256)\n byte1 = int(kspeed % 256)\n message += chr(byte0)\n message += chr(byte1)\n message += chr(29)\n mbed_of_BadBoy.write(message)\n print('TURN LEFT')\n\n\ndef set_left_speed(speed):\n message = b'\\x1d\\x01'\n kspeed = speed * 32767.0\n byte0 = int(kspeed / 256) + 128\n byte1 = int(kspeed % 256)\n message += chr(byte0)\n message += chr(byte1)\n message += chr(29)\n mbed_of_BadBoy.write(message)\n # print('SET LEFT SPEED', speed)\n\n\ndef set_right_speed(speed):\n message = b'\\x1d\\x02'\n kspeed = speed * 32767.0\n byte0 = int(kspeed / 256) + 128\n byte1 = int(kspeed % 256)\n message += chr(byte0)\n message += chr(byte1)\n message += chr(29)\n mbed_of_BadBoy.write(message)\n\n\ndef turn_to_beacon():\n global beacon_data\n if abs(beacon_data[0] - beacon_data[2]) == 1:\n if 7 > beacon_data[0] + beacon_data[2] > 0:\n print(\"turn right beacon\")\n set_right_speed(0.4)\n set_left_speed(0.7)\n elif beacon_data[0] + beacon_data[2] > 7:\n print(\"turn left beacon\")\n set_right_speed(0.8)\n set_left_speed(0.3)\n elif beacon_data[0] + beacon_data[2] == 7:\n print(\"turn around beacon\")\n set_right_speed(1)\n set_left_speed(-0.956)\n else:\n print(\"forward\")\n set_right_speed(1)\n set_left_speed(0.956)\n\n\n# according to the IR sensor data, make the badboy move forwards or turn.\ndef motor():\n global distance\n global running\n #global beacon_data\n while running:\n if distance[2] < 40:\n if distance[2] < 20:\n if distance[1] < distance[3]:\n right_turn(1)\n else:\n left_turn(1)\n else:\n if distance[1] < 20 or distance[3] < 20:\n if distance[1] < distance[3]:\n print(\"turn right\")\n set_right_speed(0.4)\n set_left_speed(0.7)\n else:\n print(\"turn left\")\n set_right_speed(0.8)\n set_left_speed(0.3)\n else:\n turn_to_beacon()\n elif distance[1] < 40 or distance[0] < 40:\n if distance[1]<20 or distance[0] < 20:\n right_turn(1)\n else:\n print(\"turn right\")\n set_right_speed(0.4)\n set_left_speed(0.7)\n elif distance[3] < 40 or distance[4] < 40:\n if distance[3] < 20 or distance[4] < 20:\n left_turn(1)\n else:\n print(\"turn left\")\n set_right_speed(0.8)\n set_left_speed(0.3)\n else:\n turn_to_beacon()\n sleep(0.1)\n\n\ndef avoid_obstacles():\n global running\n if mbed_of_BadBoy.isOpen():\n mbed_of_BadBoy.close()\n mbed_of_BadBoy.open()\n poll_thread = threading.Thread(target=poll)\n poll_thread.start()\n read_thread = threading.Thread(target=read)\n read_thread.start()\n motor_thread = threading.Thread(target=motor)\n motor_thread.start()\n sleep(60)\n running = False\n brake()\n sleep(1)\n mbed_of_BadBoy.close()\n\nprint(\"start\")\navoid_obstacles()\nprint(\"end\")\n","sub_path":"irsensor_newchassis_test_0804.py","file_name":"irsensor_newchassis_test_0804.py","file_ext":"py","file_size_in_byte":6251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"440354771","text":"import pandas as pd\nimport datetime\nimport requests\nfrom lxml import etree\nimport os.path\nimport time\nimport logging\nimport sys\n\n# def send_simple_message\n# it is for sending plain-text email messages\n'''\ndef send_simple_message(subject, text):\n return requests.post(\n \"https://api.mailgun.net/v3/sandboxbc5425db5f0e46be99aa28b2746769d1.mailgun.org/messages\",\n auth=(\"api\", \"your api key\"), //enter your API key\n data={\"from\": \"Mailgun Sandbox \",\n \"to\": \"tairan <2730891246@qq.com>\",\n \"subject\": subject,\n \"text\": text})\n'''\n\n\n# You can see a record of this email in your logs: https://app.mailgun.com/app/logs\n# You can send up to 300 emails/day from this sandbox server.\n# Next, you should add your own domain so you can send 10,000 emails/month for free.\n\n# 快速上手 requests 库 http://docs.python-requests.org/zh_CN/latest/user/quickstart.html\n# Xpath教程\n# https://zhuanlan.zhihu.com/p/25572729\n# https://cuiqingcai.com/2621.html\n# http://www.w3school.com.cn/xpath/\n\ndef send_complex_message(subject, text):\n return requests.post(\n \"https://api.mailgun.net/v3/sandboxbc5425db5f0e46be99aa28b2746769d1.mailgun.org/messages\",\n auth=(\"api\", \"a97454c453feb1d0f9bdba318381c3e7-47317c98-3ea1f3d8\"),\n data={\"from\": \"Mailgun Sandbox \",\n \"to\": \"2730891246@qq.com\",\n \"subject\": subject,\n \"text\": \"Testing some Mailgun awesomness!\",\n \"html\": text})\n\nmydate = datetime.datetime.now().strftime(\"%Y%m%d\")\nurl = \"http://www.eastday.com/eastday/shouye/node670813/n847507/{0}/index_T1722.html\".format(mydate)\nr = requests.get(url)\ntext_to_send = ''\n\n# logging\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\nrq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))\nlog_path = os.path.dirname(os.getcwd()) + '/GetThemAll/Logs/'\nlog_name = log_path + rq + '.log'\nlogfile = log_name\nfh = logging.FileHandler(logfile, mode='w')\nfh.setLevel(logging.DEBUG)\nformatter = logging.Formatter(\"%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s\")\nfh.setFormatter(formatter)\nlogger.addHandler(fh)\n\ntry:\n r.raise_for_status()\n r.encoding = 'utf-8'\n s = etree.HTML(r.text)\n\n list_of_title = []\n list_of_images = []\n list_of_time = s.xpath('//p[@class=\"gray14\"]/text()')\n list_of_body = s.xpath('//div[@class=\"cnt-inner\"]/div/a/text()')\n\n total_num = len(list_of_time)\n\n for j in range(total_num):\n news_title = '//*[@id=\"maincnt\"]/div[{0}]/div[3]/h2/a/text()'.format(j+1)\n news_link = '//*[@id=\"maincnt\"]/div[{0}]/div[3]/h2/a/@href'.format(j+1)\n if ''.join(s.xpath(news_link)) != '':\n news_to_add = ''.join(s.xpath(news_title)) + ' ' + '详细'\n else:\n news_to_add = ''.join(s.xpath(news_title))\n list_of_title.append(news_to_add)\n image = '//*[@id=\"maincnt\"]/div[{0}]/div[3]/div[@class=\"cnt-inner\"]/div[@class=\"left pic1 mypic\"]/img/@src'.format(j+1)\n list_of_images.append(''.join(s.xpath(image)))\n\n\n # weather\n text_to_send += '直播上海'\n text_to_send += ''.join(s.xpath('//*[@id=\"timebar\"]/p[1]/text()'))\n text_to_send += '

'\n\n\n for i in range(total_num):\n text_to_send += ''.join(list_of_time[i])\n text_to_send += '
'\n text_to_send += ' ' + '' + list_of_title[i] + ''\n #text_to_send += ''.join(s.xpath('//*[@id=\"maincnt\"]/div[{0}]/div[3]/h2/a/@href'.format(i+1)))\n text_to_send += '

'\n if list_of_images[i] != '':\n text_to_send += ''\n text_to_send += '

'\n text_to_send += ''.join(list_of_body[i])\n text_to_send += '

'\n\n text_to_send += ''\n\n subject = '直播上海 ' + ''.join(list_of_time[-1]) + ' --' + ''.join(list_of_time[0])[6:]\n # send_simple_message(subject,text_to_send)\n # print(text_to_send)\n send_complex_message(subject, text_to_send)\n\nexcept Exception as exc:\n send_complex_message('东方网错误','unable to connect. {}'.format(exc))\n\nsys.exit()\n\n# For Testing....\n# print(subject)\n# print(text_to_send)\n\n","sub_path":"SendEmail.py","file_name":"SendEmail.py","file_ext":"py","file_size_in_byte":4444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"100254062","text":"#-*- coding: utf-8 -*-\n#@Time :2018/12/5 16:25\n#@Author :yangjuan\n#@Email :269573175@qq.com\n#@File :test_suite.py\n\nimport unittest\nfrom api_auto_1.test_http_request import TestHttp\nfrom api_auto_1.do_excel import DoExcel\nimport HTMLTestRunnerNew\n\n# unittest四大类:\n# Testcase:一个testcase的实例就是一个测试用例\n# TestSuite:多个测试用例集合在一起\n# TestLoader:是用来加载TestCase到TestSuite中的\n# TextTestRunner:用来执行测试用例的,其中的run(test)会执行TestSuite/TestCase中的run(result)方法\n# TextTestResult:保存TextTestRunnwe执行的测试结果\n# fixture:测试用例环境的搭建和销毁。测试前的准备环境的搭建(setUp),执行测试代码(run),以及测试后环境的还原(tearDown)\n\nfrom api_auto_1.read_config import Readconfig\n\n# 利用我们写的配置类 从配置文件case_conf里面的section:Case option:button的value\nbutton =Readconfig().read_config('case.conf','button')\n\n# 调用do_excel这个模块里面的DoExcel类里面的get_data方法 方法需要几个参数\n# 文件名 表单名 配置的值\ntest_data=DoExcel().get_data('test_case.xlsx','Sheet',button)\n\nsuite = unittest.TestSuite()\n\nfor item in test_data:\n suite.addTest(TestHttp(item['http_method'],\n item['url'],\n eval(item['param']), #转回它原本python可以识别的数据类型\n str(item['expected']),\n 'test_api'))\n\n\nwith open('test.api.html',\"wb+\") as file:\n runner = HTMLTestRunnerNew.HTMLTestRunner(stream=file,\n title=\"充值接口测试报告\",\n tester=\"yj\",\n description=\"充值接口测试方法\")\n runner.run(suite)","sub_path":"python_interface/api_auto_1/test_suite.py","file_name":"test_suite.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"528953369","text":"# def genAllArtwork(K):\r\n# \tif K == 0:\r\n# \t\treturn ['']\r\n# \tl = genAllArtwork(K-1)\r\n# \tl1 = [('L' + e) for e in l]\r\n# \tl2 = [('G' + e) for e in l]\r\n# \treturn l1 + l2\r\n\r\n# def genFutureArtwork(originalSequence,K,art,C):\r\n# \tif C = 1:\r\n# \t\treturn art\r\n# \ts = ''\r\n# \tfor e in art:\r\n# \t\tif e == 'L':\r\n# \t\t\ts += originalSequence\r\n# \t\telif e == 'G':\r\n# \t\t\ts += 'G'*K\r\n# \treturn genFutureArtwork(originalSequence,K,s,C-1)\r\n\r\nT = int(input())\r\nfor t in range(T):\r\n\tK,C,S = list(map(int,input().split()))\r\n\tA = pow(K,C-1)\r\n\tl = []\r\n\tfor i in range(K):\r\n\t\tl.append(1+i*A)\r\n\tprint('Case #{}: {}'.format(t+1,' '.join(list(map(str,l)))))\r\n\r\n","sub_path":"codes/CodeJamCrawler/16_0_4/Garvys/Source.py","file_name":"Source.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"10606646","text":"# ################################################### #\nimport argparse\nimport datetime\nimport math\nimport random\nimport time\n\nfrom modules import badpixels, coloroverlay, colorutils\nfrom PIL import Image, ImageChops, ImageDraw, ImageEnhance, ImageFont, ImageOps\n\n\"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\n\n\ndef main(run=True):\n\tglobal config, workConfig\n\n\tconfig.delay = float(workConfig.get(\"flag\", \"delay\"))\n\tconfig.whiteBrightness = float(workConfig.get(\"flag\", \"whiteBrightness\"))\n\tconfig.starBrightness = float(workConfig.get(\"flag\", \"starBrightness\"))\n\tconfig.colorBrightness = float(workConfig.get(\"flag\", \"colorBrightness\"))\n\n\tconfig.image = Image.new(\"RGBA\", (config.screenWidth, config.screenHeight))\n\tconfig.draw = ImageDraw.Draw(config.image)\n\n\tconfig.canvasImage = Image.new(\"RGBA\", (config.canvasWidth, config.canvasHeight))\n\tconfig.canvasDraw = ImageDraw.Draw(config.canvasImage)\n\n\tcolorutils.brightness = config.brightness\n\tconfig.colOverlay = coloroverlay.ColorOverlay()\n\tconfig.colOverlay.randomSteps = False\n\tconfig.colOverlay.timeTrigger = True\n\tconfig.colOverlay.tLimitBase = 5\n\tconfig.colOverlay.maxBrightness = config.brightness\n\tconfig.colOverlay.steps = 50\n\tconfig.colOverlay.colorTransitionSetup()\n\n\tconfig.stripeHeight = config.canvasHeight / 13\n\tconfig.redVal = (120, 0, 0, 255)\n\tconfig.whtVal = (220, 220, 220, 255)\n\tconfig.starWhtVal = (220, 220, 220, 255)\n\tconfig.blueVal = (0, 0, 120, 255)\n\n\t# config.blueVal = (120,0,0,255)\n\t# config.starWhtVal = (200,180,0,255)\n\n\tconfig.starHDis = 0.063 * config.canvasHeight\n\tconfig.starVDis = 0.054 * config.canvasHeight\n\tconfig.starDiam = 0.036 * config.canvasHeight\n\tconfig.blueWidth = config.canvasHeight * 0.76 * 0.8\n\tconfig.blueHeight = config.canvasHeight * 0.5385\n\n\tconfig.starPointsAngle = 2 * math.pi / 5\n\tconfig.radius = config.starDiam / 2\n\n\tbadpixels.numberOfDeadPixels = int(workConfig.get(\"flag\", \"numberOfDeadPixels\"))\n\tbadpixels.config = config\n\tbadpixels.sizeTarget = list(config.canvasImage.size)\n\tbadpixels.setBlanksOnScreen()\n\n\tif run:\n\t\trunWork()\n\n\n\"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\n\n\ndef drawRects():\n\n\tstarWhtVal = tuple(round(c * config.starBrightness) for c in config.starWhtVal)\n\tblueVal = tuple(round(c * config.colorBrightness) for c in config.blueVal)\n\tredVal = tuple(round(c * config.colorBrightness) for c in config.redVal)\n\twhtVal = tuple(round(c * config.whiteBrightness) for c in config.whtVal)\n\n\tfor s in range(0, 13):\n\t\tfillVal = redVal\n\t\tif s % 2 > 0:\n\t\t\tfillVal = whtVal\n\t\tconfig.canvasDraw.rectangle(\n\t\t\t(\n\t\t\t\t0,\n\t\t\t\tconfig.stripeHeight * s,\n\t\t\t\tconfig.canvasWidth,\n\t\t\t\tconfig.stripeHeight * s + config.stripeHeight,\n\t\t\t),\n\t\t\tfill=fillVal,\n\t\t)\n\n\tconfig.canvasDraw.rectangle(\n\t\t(0, config.canvasWidth, config.blueWidth, config.blueHeight), fill=blueVal\n\t)\n\n\tfor r in range(0, 7):\n\t\tstarsNum = 6\n\t\toffset = 0\n\t\tif r % 2 > 0:\n\t\t\tstarsNum = 5\n\t\t\toffset = config.starHDis\n\t\tfor s in range(0, starsNum):\n\t\t\txPos = (\n\t\t\t\toffset + config.starHDis / 1.5 + (config.starHDis + config.starDiam) * s\n\t\t\t)\n\t\t\tyPos = (\n\t\t\t\tconfig.canvasWidth\n\t\t\t\t+ config.starVDis\n\t\t\t\t- 100\n\t\t\t\t+ (config.starVDis / 1.5 + config.starDiam) * r\n\t\t\t)\n\t\t\tstarPoints = []\n\t\t\tfor i in range(0, 5):\n\t\t\t\txP = xPos + config.radius * math.cos(\n\t\t\t\t\ti * config.starPointsAngle + 2 / 3 * config.starPointsAngle\n\t\t\t\t)\n\t\t\t\tyP = yPos + config.radius * math.sin(\n\t\t\t\t\ti * config.starPointsAngle + 2 / 3 * config.starPointsAngle\n\t\t\t\t)\n\t\t\t\tstarPoints.append((xP, yP))\n\t\t\t# config.canvasDraw.rectangle(xPos, yPos,xPos + starDiam,yPos + starDiam), fill=whtVal)\n\t\t\t# config.canvasDraw.chord((xPos, yPos,xPos + starDiam,yPos + starDiam),0,360, fill=whtVal)\n\t\t\tconfig.canvasDraw.polygon(\n\t\t\t\t(\n\t\t\t\t\tstarPoints[0],\n\t\t\t\t\tstarPoints[2],\n\t\t\t\t\tstarPoints[4],\n\t\t\t\t\tstarPoints[1],\n\t\t\t\t\tstarPoints[3],\n\t\t\t\t),\n\t\t\t\tfill=starWhtVal,\n\t\t\t)\n\n\n\"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\n\n\ndef iterate():\n\tglobal config\n\n\tdrawRects()\n\n\t# config.canvasImage.paste(config.image, (0,0), config.image)\n\tbadpixels.drawBlanks(config.canvasImage, False)\n\tif random.random() > 0.999:\n\t\tbadpixels.setBlanksOnScreen()\n\tif random.random() > 0.998:\n\t\tconfig.whiteBrightness = random.uniform(0.1, 0.9)\n\tif random.random() > 0.998:\n\t\tconfig.colorBrightness = random.uniform(0.1, 0.9)\n\tif random.random() > 0.998:\n\t\tconfig.starBrightness = random.uniform(0.1, 0.9)\n\tif random.random() > 0.998:\n\t\tconfig.starBrightness = random.uniform(0.8, 0.95)\n\t\tconfig.colorBrightness = random.uniform(0.7, 0.9)\n\t\tconfig.whiteBrightness = random.uniform(0.7, 0.9)\n\tconfig.render(config.canvasImage, 0, 0, config.canvasImage)\n\n\t# config.render(config.canvasImage, 0, 0, config.image)\n\n\n\"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\n\n\ndef runWork():\n\tglobal config\n\twhile True:\n\t\titerate()\n\t\ttime.sleep(config.delay)\n\n\n\"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\n\n\ndef reset():\n\tglobal config\n\n\n\"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\n\n\ndef callBack():\n\tglobal config\n\n\n\"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\n","sub_path":"pieces/singletons/flag.py","file_name":"flag.py","file_ext":"py","file_size_in_byte":5140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"620461917","text":"from data_engineering_pulumi_components.utils import Tagger\nfrom pulumi_aws.s3 import Bucket, BucketPublicAccessBlock, BucketObject\nfrom pulumi import ResourceOptions, FileAsset\nfrom eks import cluster\nimport json\n\ntagger = Tagger(environment_name=\"dev\")\n\nbucket = Bucket(\n resource_name=\"airflow\",\n bucket=\"mojap-airflow-test\",\n server_side_encryption_configuration={\n \"rule\": {\"applyServerSideEncryptionByDefault\": {\"sseAlgorithm\": \"AES256\"}}\n },\n versioning={\"enabled\": True},\n)\n\nBucketPublicAccessBlock(\n resource_name=\"airflow\",\n block_public_acls=True,\n block_public_policy=True,\n bucket=bucket.id,\n ignore_public_acls=True,\n restrict_public_buckets=True,\n opts=ResourceOptions(parent=bucket),\n)\n\ncontent = \"awscli\\nkubernetes==12.0.1\"\n\nBucketObject(\n resource_name=\"airflow-requirements\",\n opts=ResourceOptions(parent=bucket),\n bucket=bucket.id,\n content=content,\n key=\"requirements.txt\",\n server_side_encryption=\"AES256\",\n)\n\nBucketObject(\n resource_name=\"airflow-dag\",\n opts=ResourceOptions(parent=bucket),\n bucket=bucket.id,\n key=\"dags/dag.py\",\n server_side_encryption=\"AES256\",\n source=FileAsset(path=\"./dag.py\"),\n)\n\n\ndef prepare_kube_config(kube_config: str) -> str:\n kube_config[\"users\"][0][\"user\"][\"exec\"][\n \"command\"\n ] = \"/usr/local/airflow/.local/bin/aws\"\n return json.dumps(kube_config, indent=4)\n\n\nBucketObject(\n resource_name=\"airflow-kube-config\",\n opts=ResourceOptions(parent=bucket),\n bucket=bucket.id,\n content=cluster.kubeconfig.apply(prepare_kube_config),\n key=\"dags/.kube/config\",\n server_side_encryption=\"AES256\",\n)\n","sub_path":"airflow/s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"312318428","text":"from app import app, tickers_count, censor_dict, ts\nfrom flask import jsonify\nfrom data_processing_service import DataProcessingService\nfrom alpha_vantage.timeseries import TimeSeries\nfrom flask_cors import cross_origin\nimport requests\nimport json\n\n@app.route(\"/\")\n@cross_origin()\ndef index():\n return \"nwHacks 2017 - YoloOnFannieMae - Alex Lim, Alex Tsang, Clarence Lam, Felix Tso :)\"\n\n@app.route(\"/shares\")\n@cross_origin()\ndef shares():\n shares = requests.get(\"https://www.reddit.com/r/WallStreetBets/.json?limit=20&after=t3_10omtd/\").json()\n result = []\n if 'data' in shares:\n shares_json = shares['data']['children']\n data_processing_service = DataProcessingService()\n result = data_processing_service.process_shares(shares_json)\n return jsonify(result)\n\n@app.route(\"/yolo_buy\")\n@cross_origin()\ndef yolo_buy():\n shares = requests.get(\"https://www.reddit.com/r/WallStreetBets/.json?limit=100&after=t3_10omtd/\")\n yolo_list = []\n data_processing_service = DataProcessingService()\n yolo_list = data_processing_service.process_yolo_buy(shares)\n return jsonify(yolo_list)\n\n@app.route(\"/yolo_short\")\n@cross_origin()\ndef yolo_short():\n shares = requests.get(\"https://www.reddit.com/r/WallStreetBets/.json?limit=100&after=t3_10omtd/\")\n yolo_list = []\n data_processing_service = DataProcessingService()\n yolo_list = data_processing_service.process_yolo_short(shares)\n return jsonify(yolo_list)\n","sub_path":"app/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"504649401","text":"#! user/bin/python3\n# -*- coding: utf-8 -*-\n\n__Author__ = \"CaiTao\"\n\nimport sys\nfrom PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QAction, qApp, QMenu, QTextEdit\nfrom PyQt5.QtGui import QIcon\n\n\nclass Window(QMainWindow):\n def __init__(self):\n super(Window, self).__init__()\n self.init_ui()\n\n def init_ui(self):\n\n self.status = self.statusBar() # 创建一个状态栏,该方法为QMainWindow的方法\n self.status.showMessage(\"Read\") # 设置状态栏信息\n textEditor = QTextEdit(self) # 创建一个文本编辑区域\n\n self.setCentralWidget(textEditor) # 设置窗口的核心部件为文本编辑区域\n\n\n menu = self.menuBar() # 创建菜单栏\n fileMenu = menu.addMenu(\"&File\") # 添加一个主菜单\n\n # 创建一级菜单\n exitAct = QAction(QIcon(), \"&Exit\", self)\n exitAct.setShortcut(\"Ctrl+Q\")\n exitAct.setStatusTip(\"Exit application\")\n exitAct.triggered.connect(qApp.quit)\n\n # 创建一级菜单\n viewStartAct = QAction(\"View statusbar\", self, checkable=True) # 可勾选菜单\n viewStartAct.setStatusTip(\"View statusbar\")\n viewStartAct.setChecked(True) # 设置初始化勾选上\n viewStartAct.triggered.connect(self.toggleMenu)\n\n # 创建一级子菜单\n impMenu = QMenu(\"Import\", self)\n # 创建二级菜单\n impAct = QAction(\"Import mail\", self)\n impMenu.addAction(impAct)\n\n fileMenu.addAction(exitAct)\n fileMenu.addMenu(impMenu)\n fileMenu.addAction(viewStartAct)\n\n # 添加一个工具\n self.toolbar = self.addToolBar(\"Exit\")\n self.toolbar.addAction(exitAct)\n\n self.setGeometry(500, 100, 400, 400)\n self.setWindowTitle(\"simple\")\n self.show()\n\n def toggleMenu(self, state):\n if state:\n self.status.show()\n else:\n self.status.hide()\n\n def contextMenuEvent(self, event):\n \"\"\"\n 右键菜单事件\n \"\"\"\n cmenu = QMenu(self)\n\n newAct = cmenu.addAction(\"New\")\n openAct = cmenu.addAction(\"Open\")\n quitAct = cmenu.addAction(\"Quit\")\n action = cmenu.exec_(self.mapToGlobal(event.pos()))\n\n if action == quitAct:\n qApp.quit()\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n window = Window()\n sys.exit(app.exec_())","sub_path":"SourcesCode/菜单栏和工具栏.py","file_name":"菜单栏和工具栏.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"644920458","text":"from lux.extensions.ui.lib import *\n\n\ndef add_css(all):\n css = all.css\n media = all.app.config['MEDIA_URL']\n vars = all.variables\n\n vars.background_color = '#FAFAFA'\n vars.background_footer_color = '#ededed'\n vars.background_footer_border = '#D4D4D4'\n vars.colors.blue = '#2B4E72'\n vars.navbar_height = 80\n vars.animate.fade.top = px(vars.navbar_height)\n\n vars.font_family = ('\"freight-text-pro\",Georgia,Cambria,\"Times New Roman\",'\n 'Times,serif')\n vars.font_size = px(18)\n vars.line_height = 1.5\n vars.color = color(0, 0, 0, 0.8)\n\n link = vars.link\n link.color = '#428bca'\n\n css('html, body, .fullpage',\n height=pc(100),\n min_height=pc(100))\n\n css('.angular-view',\n height=pc(100),\n min_height=pc(100))\n\n css('body',\n FontSmoothing(),\n letter_spacing='0.01rem',\n font_weight=400)\n\n css('#page-main',\n background_color=vars.background_color,\n min_height=px(200),\n padding_top=px(20),\n padding_bottom=px(50))\n\n css('#page-footer',\n Skin(only='default', noclass='default'),\n Border(top=px(1), color=vars.background_footer_border),\n background_color=vars.background_footer_color,\n min_height=px(200))\n\n css('.block',\n padding=px(10))\n\n css('.text-large',\n font_size=pc(150))\n\n page_error(all)\n\n\ndef page_error(all):\n css = all.css\n media = all.media\n cfg = all.app.config\n mediaurl = cfg['MEDIA_URL']\n collapse_width = px(cfg['NAVBAR_COLLAPSE_WIDTH'])\n\n css('#page-error',\n css(' a, a:hover',\n color=color('#fff'),\n text_decoration='underline'),\n Background(url=mediaurl+'lux/see.jpg',\n size='cover',\n repeat='no-repeat',\n position='left top'),\n color=color('#fff'))\n css('.error-message-container',\n BoxSizing('border-box'),\n padding=spacing(40, 120),\n background=color(0, 0, 0, 0.4),\n height=pc(100)),\n css('.error-message',\n css(' p',\n font_size=px(50)))\n media(max_width=collapse_width).css(\n '.error-message p',\n font_size=px(32)).css(\n '.error-message-container',\n text_align='center',\n padding=spacing(40, 0))\n","sub_path":"lux/core/commands/templates/cms/project_name/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"58948407","text":"# Copyright (c) 2015,\n# Philipp Hertweck\n#\n# This code is provided under the BSD 2-Clause License.\n# Please refer to the LICENSE.txt file for further information.\n\nimport sys\nfrom os import path\nsys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )\n\nimport unittest\nfrom testing.iperf.IPerfTest import IPerfTest\n\nfrom testing import integration_test as integration_test\n\n# Network used in this test\nfrom networks import sample_network as network\n\n\nclass TestIPerf(integration_test.IntegrationTestCase):\n\n def setUp(self):\n # TestConfiguration\n self.CONTROLLER_PATH = '../../controller/routing_switch.py'\n self.NETWORK = network.Network\n super(TestIPerf, self).setUp()\n\n def test_iperf_on_one_host(self):\n iperf_test = IPerfTest(self.net)\n iperf_test.start_test(\"h1\", [\"h2\"])\n transfer_number, transfer_unit = iperf_test.get_transfer(0)\n print(\"transfer: \" + str(transfer_number) + \" \" + transfer_unit)\n bandwidth_number, bandwidth_unit = iperf_test.get_bandwidth(0)\n print(\"bandwidth: \" + str(bandwidth_number) + \" \" + bandwidth_unit)\n\n self.assertEqual(transfer_unit, \"GBytes\", \"Correct unit of iperf transfer.\")\n self.assertEqual(bandwidth_unit, \"Gbits/sec\", \"Correct unit of iperf bandwidth.\")\n\n self.assertTrue(isinstance(transfer_number, float), \"Transfer value is a number.\")\n self.assertTrue(isinstance(bandwidth_number, float), \"Bandwidth value is a number.\")\n\n def test_iperf_on_multiple_hosts(self):\n iperf_test = IPerfTest(self.net)\n iperf_test.start_test(\"h1\", [\"h2\", \"h3\"])\n\n transfer_number, transfer_unit = iperf_test.get_transfer(0)\n bandwidth_number, bandwidth_unit = iperf_test.get_bandwidth(0)\n transfer_number1, transfer_unit1 = iperf_test.get_transfer(1)\n bandwidth_number1, bandwidth_unit1 = iperf_test.get_bandwidth(1)\n\n self.assertEqual(transfer_unit, transfer_unit1,\"Same unit for both hosts.\")\n self.assertEqual(bandwidth_unit, bandwidth_unit1, \"Same unit for both hosts.\")\n\n self.assertTrue(abs(transfer_number - transfer_number1) < 5, \"Transfered nearly same traffic on both hosts.\")\n self.assertTrue(abs(bandwidth_number - bandwidth_number1) < 5, \"Bandwidth nearly the same on both hosts.\")\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"SDN_Related Stuffs/sdn-test-framework/testcases/test_iperf.py","file_name":"test_iperf.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"104197513","text":"from django.shortcuts import render\nfrom django.http import JsonResponse\nfrom ..models import Post\nfrom .serializers import PostSerializer\nfrom rest_framework.parsers import JSONParser\nfrom django.views.decorators.csrf import csrf_exempt\n# Create your views here.\n\n\n@csrf_exempt\ndef get_all_post(request):\n all_posts = {}\n all_posts = Post.objects.all()\n print(all_posts)\n serializer = PostSerializer(\n all_posts, context={'request': request}, many=True)\n print(serializer, serializer.data)\n return JsonResponse(serializer.data, safe=False)\n # return JsonResponse({'all_posts': all_posts})\n\n\ndef create_post(request):\n if request.method == 'GET':\n posts = Post.objects.all()\n serializer = PostSerializer(posts, many=True)\n return JsonResponse(serializer.data, safe=False)\n elif request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = PostSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=201)\n return JsonResponse(serializer.errors, status=400)\n","sub_path":"posts/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"135841809","text":"\"\"\"ESI Slack bot.\"\"\"\n\n\n# pylint: disable=unused-argument,wrong-import-position,wrong-import-order\nfrom gevent import monkey\nmonkey.patch_all()\n\nimport re\nimport os\nimport logging\nimport pkg_resources\nfrom functools import wraps\nfrom functools import partial\nfrom collections import namedtuple\n\nimport requests\nfrom requests.adapters import HTTPAdapter\n\n\nLOG = logging.getLogger(__name__)\nLOG.setLevel(logging.INFO)\nlogging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s:%(name)s:%(levelname)s: %(message)s\",\n)\n\nESI = \"https://esi.evetech.net\"\nSNIPPET = namedtuple(\n \"Snippet\",\n (\"content\", \"filename\", \"filetype\", \"comment\", \"title\"),\n)\nREPLY = namedtuple(\"Reply\", (\"content\", \"attachments\"))\nMESSAGE = namedtuple(\"Message\", (\"speaker\", \"command\", \"args\"))\nCOMMANDS = {} # trigger: function\nEXTENDED_HELP = {} # name: docstring\n__version__ = pkg_resources.get_distribution(\"esi-bot\").version\n\n\ndef _build_session():\n \"\"\"Builds a requests session with a pool and retries.\"\"\"\n\n ses = requests.Session()\n ses.headers[\"User-Agent\"] = \"esi-bot/{}\".format(__version__)\n adapt = HTTPAdapter(max_retries=3, pool_connections=10, pool_maxsize=100)\n ses.mount(\"http://\", adapt)\n ses.mount(\"https://\", adapt)\n return ses\n\n\nSESSION = _build_session()\n\n\ndef command(func=None, **kwargs):\n \"\"\"Declare a function an ESI-bot command.\n\n NB: the function name is used as the help name\n\n KWargs:\n trigger: string, list of strings, or compiled regex pattern.\n optional, will default to the function name\n \"\"\"\n\n if func is None:\n return partial(command, **kwargs)\n\n COMMANDS[kwargs.get(\"trigger\", func.__name__)] = func\n EXTENDED_HELP[func.__name__] = func.__doc__\n if isinstance(kwargs.get(\"trigger\"), (list, tuple)):\n for trigger in kwargs.get(\"trigger\"):\n EXTENDED_HELP[trigger] = func.__doc__\n return None\n\n\ndef do_request(url, *args, **kwargs):\n \"\"\"Make a GET request, return the status code and json response.\"\"\"\n\n try:\n res = SESSION.get(url, *args, **kwargs)\n except Exception as error:\n LOG.warning(\"failed to request %s: %r\", url, error)\n return 499, \"failed to request {}\".format(url)\n\n try:\n res.raise_for_status()\n except Exception as error:\n LOG.warning(\"request to %s failed: %r\", url, error)\n else:\n LOG.info(\"requested: %s\", url)\n\n try:\n content = res.json()\n except Exception:\n content = res.text\n\n return res.status_code, content\n","sub_path":"esi_bot/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"305888995","text":"\n\n#calss header\nclass _ECHO():\n\tdef __init__(self,): \n\t\tself.name = \"ECHO\"\n\t\tself.definitions = [u'If a sound echoes or a place echoes with a sound, you hear the sound again because you are in a large, empty space: ', u'to repeat details that are similar to, and make you think of, something else: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_echo.py","file_name":"_echo.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"578662844","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.http import Http404\nfrom django.shortcuts import render, redirect, reverse, get_object_or_404\nfrom .models import Checklist, ChecklistItem\n\n\ndef checklist(request):\n checklist_list = Checklist.objects.all()\n return render(request, 'checklist_checklist/checklist_page.html', {'checklist_list': checklist_list})\n\n\ndef checklist_item(request, checklist_id):\n c = get_object_or_404(Checklist, pk=checklist_id)\n checklist_item_list = c.checklistitem_set.all()\n return render(request, 'checklist_checklist/checklist_item_page.html',\n {'checklist': c, 'checklist_item_list': checklist_item_list})\n\n\ndef add_checklist(request):\n if 'title' not in request.POST:\n raise Http404('Error: Title should be provided.')\n\n title = request.POST['title']\n cl = Checklist(title=title)\n cl.save()\n return redirect(reverse('checklist'))\n\n\ndef remove_checklist(request, checklist_id):\n c = get_object_or_404(Checklist, pk=checklist_id)\n c.delete()\n return redirect(reverse('checklist'))\n\n\ndef add_checklist_item(request, checklist_id):\n if 'text' not in request.POST:\n raise Http404('Error: Text should be provided.')\n\n text = request.POST['text']\n c = get_object_or_404(Checklist, pk=checklist_id)\n c.checklistitem_set.create(text=text) # Not sure checklist_item_set or checklistitem_set?\n return redirect(reverse('checklist_item', kwargs={'checklist_id': checklist_id}))\n\n\ndef remove_checklist_item(request, checklist_id, checklist_item_id):\n i = get_object_or_404(ChecklistItem, pk=checklist_item_id)\n i.delete()\n return redirect(reverse('checklist_item', kwargs={'checklist_id': checklist_id}))","sub_path":"checklist_checklist/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"463050542","text":"#!/usr/bin/env python3\nfrom sys import stderr\n\nfrom multilanguage import Env, Lang, TALcolors\nfrom TALinputs import TALinput\nfrom TALfiles import TALfilesHelper\n\nimport os\nimport random\nimport networkx as nx\nfrom networkx.algorithms import approximation\nimport vertex_cover_lib as vcl\nimport matplotlib\nimport multiprocessing\n\n# METADATA OF THIS TAL_SERVICE:\nargs_list = [\n ('source',str),\n ('collection',str),\n ('instance_id',int),\n ('instance_format',str),\n ('num_vertices',int),\n ('num_edges',int),\n ('plot',bool),\n ('plot_sol',bool),\n ('seed',str),\n ('vc_sol_val',str),\n ('display',bool),\n ('silent',bool),\n ('lang',str),\n]\n\nENV =Env(args_list)\nTAc =TALcolors(ENV)\nLANG=Lang(ENV, TAc, lambda fstring: eval(f\"f'{fstring}'\"), print_opening_msg = 'now')\nTALf = TALfilesHelper(TAc, ENV)\n\nchk_backend = False\nif matplotlib.get_backend().lower() in map(str.lower,vcl.backends):\n chk_backend = True\n\n## Input Sources\nif TALf.exists_input_file('instance'):\n instance = vcl.get_instance_from_str(TALf.input_file_as_str('instance'), instance_format_name=ENV[\"instance_format\"])\n TAc.print(LANG.render_feedback(\"successful-load\", 'The file you have associated to `instance` filehandler has been successfully loaded.'), \"yellow\", [\"bold\"])\n\nelif ENV[\"source\"] == 'terminal':\n instance = {}\n instance['num_vertices'] = ENV['num_vertices']\n instance['num_edges'] = ENV['num_edges']\n\n #TAc.print(LANG.render_feedback(\"waiting-line\", f'#? Waiting for the graph.\\nGraph format: (x,y) (w,z) ... (n,m)\\n'), \"yellow\")\n TAc.print(LANG.render_feedback(\"waiting-line\", f'#? Waiting for the graph.\\n'), \"yellow\")\n\n TAc.print(LANG.render_feedback(\"insert-edges\", f'Given {ENV[\"num_vertices\"]} vertices labelled with the naturals in the interval [0,{ENV[\"num_vertices\"]-1}], you are now expected to enter {ENV[\"num_edges\"]} edges. To specify an edge, simply enter its two endonodes separated by spaces.'), \"yellow\", [\"bold\"])\n edges = []\n for i in range(1,1+ENV[\"num_edges\"]):\n TAc.print(LANG.render_feedback(\"insert-edge\", f'Insert the two endpoints of edge {i}, that is, enter a line with two naturals in the interval [0,{ENV[\"num_vertices\"]-1}], separated by spaces.'), \"yellow\", [\"bold\"])\n u,v = TALinput(int, 2, TAc=TAc)\n edges.append([u,v])\n\n for u,v in edges:\n if u not in range(ENV['num_vertices']) or v not in range(ENV['num_vertices']):\n TAc.print(f'Edge ({u}, {v}) is not a valid edge for the graph. Aborting.\\n', \"red\", [\"bold\"], flush=True)\n exit(0)\n\n if len(edges) != ENV['num_edges']:\n TAc.print(LANG.render_feedback(\"wrong-edges-number\", f'\\nWrong number of edges ({len(edges)} instead of {ENV[\"num_edges\"]})\\n'), \"red\", [\"bold\"])\n exit(0)\n\n TAc.print(LANG.render_feedback(\"insert-weights\", f'Enter nodes weights. Format: integers separated by spaces:'), \"yellow\", [\"bold\"])\n l = TALinput(str, line_recognizer=lambda val,TAc, LANG: True, TAc=TAc, LANG=LANG)\n\n if len(l) != ENV['num_vertices']:\n TAc.print(LANG.render_feedback(\"wrong-weights-number\", f'\\nWrong number of weights ({len(l)} instead of {ENV[\"num_vertices\"]})\\n'), \"red\", [\"bold\"])\n exit(0)\n\n for w in l:\n if not w.isdigit():\n TAc.print(LANG.render_feedback(\"wrong-weights-format\", f'\\nWeights must be integer numbers. Aborting.\\n'), \"red\", [\"bold\"])\n exit(0)\n\n G = nx.Graph()\n G.add_nodes_from([int(v) for v in range(ENV['num_vertices'])])\n G.add_edges_from(edges)\n\n i = 0\n\n for v in sorted(G.nodes()):\n G.add_node(v, weight=int(l[i]))\n i += 1\n\n instance['graph'] = G\n\n instance_str = vcl.instance_to_str(instance, format_name=ENV['instance_format'])\n output_filename = f\"terminal_instance.{ENV['instance_format']}.txt\"\n\nelif ENV[\"source\"] == 'randgen_1':\n # Get random instance\n instance = vcl.instances_generator(1, 1, ENV['num_vertices'], ENV['num_edges'], ENV['seed'], 1)[0]\n\nelse: # take instance from catalogue\n #instance_str = TALf.get_catalogue_instancefile_as_str_from_id_and_ext(ENV[\"instance_id\"], format_extension=vcl.format_name_to_file_extension(ENV[\"instance_format\"],'instance'))\n instance_str = TALf.get_catalogue_instancefile_as_str_from_id_collection_and_ext(ENV[\"collection\"], ENV[\"instance_id\"], format_extension=vcl.format_name_to_file_extension(ENV[\"instance_format\"],'instance'))\n instance = vcl.get_instance_from_str(instance_str, instance_format_name=ENV[\"instance_format\"])\n if instance['weighted']:\n TAc.print(LANG.render_feedback(\"instance-from-catalogue-successful\", f'The instance with instance_id={ENV[\"instance_id\"]} has been successfully retrieved from the catalogue.'), \"yellow\", [\"bold\"], flush=True)\n else:\n TAc.print(LANG.render_feedback(\"graph-not-weighted\", f'The instance with instance_id={ENV[\"instance_id\"]} does not contain a weighted graph. Aborting.'), \"red\", [\"bold\"])\n exit(0)\n\nif ENV['display']:\n TAc.print(LANG.render_feedback(\"this-is-the-instance\", '\\nThis is the instance:\\n'), \"white\", [\"bold\"], flush=True)\n TAc.print(vcl.instance_to_str(instance,ENV[\"instance_format\"]), \"white\", [\"bold\"], flush=True, end='')\n\n if not 'weighted' in instance:\n for n,w in nx.get_node_attributes(instance['graph'], 'weight').items():\n TAc.print(f'{w}', \"white\", [\"bold\"], flush=True, end=' ')\n\n print('\\n', flush=True)\n \n\nif ENV['vc_sol_val'] == '0': # manual insertion\n TAc.print(LANG.render_feedback(\"insert-opt-value\", f'\\nWrite here your conjectured approximated vertex cover for this weighted graph if you have one (format: integer numbers separated by spaces). Otherwise, if you only intend to be told about the approximation, enter \"C\".'), \"yellow\", [\"bold\"], flush=True)\n if ENV['plot'] and chk_backend:\n proc = multiprocessing.Process(target=vcl.plot_graph, args=(instance['graph'],))\n proc.start()\n #vcl.plot_graph(instance['graph'],1)\n answer = TALinput(str, line_recognizer=lambda val,TAc, LANG: True, TAc=TAc, LANG=LANG) # a quanto pare è un array: ogni elemento separato da spazio nella stringa è un elemento dell'array...\nelse:\n answer = ENV['vc_sol_val']\n\nif answer[0] != 'C' and answer[0] != 'c':\n for v in answer:\n if int(v) not in instance['graph'].nodes():\n TAc.print(LANG.render_feedback(\"node-not-in-graph\", f'Vertex {v} is not a vertex of the graph. Aborting'), \"red\", [\"bold\"], flush=True)\n if ENV['plot'] and chk_backend:\n proc.terminate()\n exit(0)\n\nweight_ans = 0\nfor n,w in nx.get_node_attributes(instance['graph'], 'weight').items():\n if str(n) in answer:\n weight_ans += w \n\nif (ENV['source'] == \"catalogue\" and instance['exact_sol'] == 1) or (ENV['source'] != \"catalogue\"):\n appr_sol, size_sol, weight_sol = vcl.calculate_weighted_approx_vc(instance['graph'])\nelse:\n appr_sol = instance['sol']\n appr_sol = [int(i) for i in appr_sol.split()]\n size_sol = len(appr_sol)\n\n weight_sol = instance['sol_weight']\n\n\nif answer[0] == 'C' or answer[0] == 'c':\n TAc.print(LANG.render_feedback(\"best-sol\", f'A possible 2-approximated weighted vertex cover is: '), \"green\", [\"bold\"], flush=True, end='')\n TAc.print(f'{appr_sol}.', \"white\", [\"bold\"], flush=True)\n TAc.print(LANG.render_feedback(\"size-sol\", f'The size of the 2-approximated weighted vertex cover is: '), \"green\", [\"bold\"], flush=True, end='')\n TAc.print(f'{size_sol}.', \"white\", [\"bold\"], flush=True)\n TAc.print(LANG.render_feedback(\"weight-sol\", f'The weight of the 2-approximated weighted vertex cover is: '), \"green\", [\"bold\"], flush=True, end='')\n TAc.print(f'{weight_sol}.', \"white\", [\"bold\"], flush=True)\n\nelse:\n is_vertex_cover, rem_edges = vcl.verify_vc(answer, instance['graph'])\n vc_sol, size_exact_sol, min_weight_sol = vcl.calculate_minimum_weight_vc(instance['graph'])\n size_ans = len(answer)\n\n if is_vertex_cover and (weight_ans <= 2 * min_weight_sol):\n if weight_ans == weight_sol:\n TAc.OK()\n TAc.print(LANG.render_feedback(\"right-best-sol\", f'We agree, the solution you provided is a valid 2-approximation of the weighted vertex cover for the graph (weight={weight_ans}).'), \"green\", [\"bold\"], flush=True)\n elif weight_ans > weight_sol:\n TAc.print(LANG.render_feedback(\"right-sol\", f'The solution you provided is a valid 2-approximation of the weighted vertex cover for the graph (weight={weight_ans}). You can improve your approximation.'), \"yellow\", [\"bold\"], flush=True)\n else:\n TAc.OK()\n TAc.print(LANG.render_feedback(\"new-best-sol\", f'Great! The solution you provided is a valid 2-approximation of the weighted vertex cover for the graph (weight={weight_ans}) and it\\'s better than mine ({weight_sol})!'), \"green\", [\"bold\"], flush=True)\n \n if ENV['source'] == 'catalogue' and not instance['exact_sol']:\n #path=os.path.join(ENV.META_DIR, 'instances_catalogue', 'all_instances')\n path=os.path.join(ENV.META_DIR, 'instances_catalogue', ENV['collection'])\n instance_filename = f'instance_{str(ENV[\"instance_id\"]).zfill(3)}'\n answer = ' '.join(map(str, answer))\n answer = f'{answer}\\n{weight_ans}'\n\n vcl.update_instance_txt(path, instance_filename, answer)\n else:\n TAc.NO()\n TAc.print(LANG.render_feedback(\"wrong-sol\", f'We don\\'t agree, the solution you provided is not a valid 2-approximation weighted vertex cover for the graph.'), \"red\", [\"bold\"], flush=True)\n if not is_vertex_cover:\n TAc.print(LANG.render_feedback(\"reason-wrong-sol-no_vc\", f'Not a vertex cover. Edges not covered: '), \"red\", [\"bold\"], flush=True, end='')\n for t in rem_edges:\n TAc.print(f'{t} ', \"red\", [\"bold\"], flush=True, end='')\n print('\\n')\n else:\n TAc.print(LANG.render_feedback(\"reason-wrong-sol-weight\", f'Your solution weight: {weight_ans}; max 2-approximation weight: {2 * min_weight_sol}.'), \"red\", [\"bold\"], flush=True)\n\nif ENV['plot_sol'] and chk_backend:\n if ENV['plot']:\n proc.terminate()\n if answer[0] != 'C' and answer[0] != 'c':\n answer = ' '.join(map(str,answer))\n proc1 = multiprocessing.Process(target=vcl.plot_mvc, args=(instance['graph'],answer,rem_edges,1,1))\n proc1.start()\n #vcl.plot_mvc(instance['graph'], answer, rem_edges, 1, 1)\n else:\n proc1 = multiprocessing.Process(target=vcl.plot_mvc, args=(instance['graph'],appr_sol,[],1,1))\n proc1.start()\n #vcl.plot_mvc(instance['graph'], appr_sol, [], 1, 1)\n\nexit(0)\n","sub_path":"example_problems/tutorial/vertex_cover/services/check_approx_weighted_vc_driver.py","file_name":"check_approx_weighted_vc_driver.py","file_ext":"py","file_size_in_byte":10268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"154365306","text":"import os\nimport sys\nimport time\nimport pickle\nimport winreg\nimport datetime\nimport PIL.Image\nfrom PIL import ImageDraw, ImageFont\nfrom openpyxl import load_workbook\nfrom tkinter import *\nfrom tkinter.filedialog import askopenfilename\n\n\n### Variables ###\n# General\ndt = datetime.datetime.now()\n\n# Tkinter\nroot = Tk()\nroot.withdraw()\n\n# Data\nsheets = []\nprinters = []\nsettings = {}\nbill_data = {}\nschool_year = \"2017/2018.\"\ncurrent_date = \"{}.{}.{}.\".format(dt.day, dt.month, dt.year)\n\n# Paths\nbill_image = \"src\\priznanica.png\"\nconfig_file = \"src\\config\"\ncurrent_path = \"{}\\\\\".format(os.getcwd())\n\n# Pillow\nfont = ImageFont.truetype(\"src\\\\arimo.ttf\", 40)\nimg = PIL.Image.open(bill_image)\ndraw = ImageDraw.Draw(img)\nvertical_offset = 1520\n\n\nclass ManageConfig():\n def checkFiles(self):\n global settings\n # Check if config file exists\n if os.path.exists(\"src\\config\"):\n settings = pickle.load(open(config_file, \"rb\"))\n Main().showMenu()\n else:\n print(\"Create config!\")\n print(current_path)\n self.pickFile()\n self.checkFiles()\n\n # Collect and store initial settings\n def pickFile(self):\n Main().printHeader()\n print(\"Odaberite datoteku...\")\n temp_path = askopenfilename(initialdir = current_path,\n title = \"Izaberite Excel datoteku\",\n filetypes = ((\"Excel files\",\"*.xlsx\"),\n (\"all files\",\"*.*\")))\n if len(temp_path) > 0:\n settings[\"chosen_file\"] = temp_path\n self.chooseSheet()\n self.writeToConfig()\n else:\n print(\"[!] Nijedna datoteka nije odabrana...\")\n\n def chooseSheet(self):\n os.system(\"cls\")\n Main().printHeader()\n excel_workbook = load_workbook(settings[\"chosen_file\"])\n print(\"\\nOdaberite listu Excel tabele\\n\")\n num = 1\n for sheet in excel_workbook.get_sheet_names():\n print(\"[{}] {}\".format(num, sheet))\n sheets.append(sheet)\n num += 1\n try:\n settings[\"chosen_sheet\"] = sheets[int(input(\"\\nUnesite željenu opciju: \")) - 1] #TODO\n except:\n os.system(\"cls\")\n print(\"Nepostojeća lista, pokušajte ponovo...\")\n time.sleep(2)\n self.chooseSheet()\n Main().printHeader()\n\n def writeToConfig(self):\n pickle.dump(settings, open(config_file, \"wb\"))\n\n\n# Do the wiggle\nclass Main():\n def printHeader(self):\n os.system(\"cls\")\n print(\"Rosette v1.1\\n\")\n\n # Main menu\n def showMenu(self):\n self.printHeader()\n print(\"[1] Štampa priznanice\")\n print(\"[2] Opcije i podešavanja\")\n print(\"[3] O programu\")\n print(\"[0] Izlaz\")\n menu_choice = input(\"\\nUnesite željenu opciju: \")\n if menu_choice == \"1\" or \"2\" or \"3\" or \"0\":\n if menu_choice == \"1\":\n PrintDocument().getExcelData()\n elif menu_choice == \"2\":\n Settings().settingsMenu()\n elif menu_choice == \"3\":\n Settings().aboutRosette()\n elif menu_choice == \"0\":\n sys.exit()\n else:\n print(\"Nepoznata opcija, pokušajte ponovo...\")\n time.sleep(2)\n\nclass Settings():\n def settingsMenu(self):\n Main().printHeader()\n print(\"Odabrana datoteka: {}\".format(settings[\"chosen_file\"]))\n print(\"\\n[1] Promeni datoteku\")\n print(\"[0] Nazad\")\n menu_choice = input(\"\\nUnesite željenu opciju: \")\n if menu_choice == \"1\" or \"0\":\n if menu_choice == \"1\":\n ManageConfig().pickFile()\n Main().showMenu()\n elif menu_choice == \"0\" or \" \":\n Main().showMenu()\n else:\n print(\"Nepoznata opcija, pokušajte ponovo...\")\n time.sleep(2)\n\n def aboutRosette(self):\n Main().printHeader()\n print(\"Rosette služi kao alatka za automatizaciju i pomoć\")\n print(\"u kreiranju uplatnica za odsek računovodstva E-Gimnazije.\")\n print(\"\\nAutor: Tomislav Perić\")\n print(\" email: tomislavperich@protonmail.com\")\n print(\" github: tomislavperich\")\n print(\"\\nVerzija: 1.1\")\n print(\"Datum verzije: 18.10.2017.\")\n input(\"\\nPritisnite da se vratite u glavni meni...\")\n Main().showMenu()\n\n\nclass PrintDocument():\n # Exctract student data from the Excel sheet\n def getExcelData(self):\n global bill_data\n Main().printHeader()\n # Select sheet\n excel_workbook = load_workbook(settings[\"chosen_file\"])\n sheet = excel_workbook.get_sheet_by_name(settings[\"chosen_sheet\"])\n # Pick student\n menu_choice = int(input(\"Izaberite redni broj učenika: \")) + 1\n # Collect data\n student_name = sheet[\"B{}\".format(menu_choice)].value\n student_surname = sheet[\"D{}\".format(menu_choice)].value\n bill_data[\"student_name\"] = student_name + \" \" + student_surname\n # Paid sum\n bill_data[\"paid_sum\"] = input(\"Uplaćeno EUR: \")\n self.showExcelData()\n\n def showExcelData(self):\n Main().printHeader()\n print(\"Učenik: {}\".format(bill_data[\"student_name\"]))\n print(\"Uplaćeno: {}\".format(bill_data[\"paid_sum\"]))\n print(\"Školska godina: {}\".format(school_year))\n print(\"Datum: {}\".format(current_date))\n print(\"\\n[ ] Nastavi\\n[1] Nazad\\n[0] Glavni meni\")\n menu_choice = str(input(\"\\nUnesite željenu opciju: \"))\n if menu_choice == \"\":\n self.drawToImage()\n elif menu_choice == \"1\":\n self.getExcelData()\n elif menu_choice == \"0\":\n Main().showMenu()\n else:\n os.system(\"cls\")\n print(\"Nepoznata opcija, pokušajte ponovo...\")\n time.sleep(2)\n self.showExcelData()\n\n # Use Pillow library to draw data to src/priznanica.png file\n def drawToImage(self):\n # Student name\n draw.text((1010, 634), bill_data[\"student_name\"], (0,0,0), font=font)\n draw.text((1010, 634 + vertical_offset), bill_data[\"student_name\"],(0,0,0), font=font)\n # Sum\n draw.text((740, 790), bill_data[\"paid_sum\"], (0,0,0), font=font)\n draw.text((740, 790 + vertical_offset), bill_data[\"paid_sum\"],(0,0,0), font=font)\n # School year - deprecated\n #draw.text((1230, 615), school_year, (0,0,0), font=font)\n #draw.text((1230, 615 + vertical_offset), school_year, (0,0,0), font=font)\n # Date\n draw.text((1780, 1165), current_date, (0,0,0), font=font)\n draw.text((1780, 1165 + vertical_offset), current_date, (0,0,0), font=font)\n\n # TODO: Expenses left (extract payment info from Excel sheet,\n # calculate expenses left, draw to src/priznanica.png\n\n # Export image\n img.save(\"src\\out.png\")\n self.printImage()\n\n def printImage(self):\n Main().printHeader()\n os.startfile(\"src\\out.png\", \"print\")\n print(\"[\\] Štampanje...\")\n time.sleep(1)\n Main().printHeader()\n print(\"[|] Štampanje...\")\n time.sleep(1)\n Main().printHeader()\n print(\"[/] Štampanje...\")\n time.sleep(1)\n Main().printHeader()\n print(\"[*] Štampanje uspešno!\")\n input(\"\\nPritisnite bilo koje dugme da se vratite u glavni meni...\")\n Main().showMenu()\n\n\nManageConfig().checkFiles()\n","sub_path":"Rosette.py","file_name":"Rosette.py","file_ext":"py","file_size_in_byte":7533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"237742729","text":"import PyPDF2 \nimport textract\nfrom docx import Document \n\ndef PDFRead(filepath): \n pdfFileObj = open(filepath, 'rb') \n pdfReader = PyPDF2.PdfFileReader(pdfFileObj) \n x=pdfReader.numPages\n for i in range(x): \n pageObj = pdfReader.getPage(i) \n print(pageObj.extractText()) \n pdfFileObj.close() \n\ndef DOCRead(filepath):\n document = Document(filepath)\n for para in document.paragraphs:\n print(para.text)\n\n\n# PDFRead(\"ENTER_FILE_PATH\")\n# DOCRead(\"ENTER_FILE_PATH\")","sub_path":"reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"434517712","text":"from pyspark.sql import SparkSession\n\nif __name__ == \"__main__\":\n sparkSession = SparkSession \\\n .builder \\\n .getOrCreate()\n\n dataset = sparkSession \\\n .read \\\n .format(\"libsvm\") \\\n .load(\"data/simple_libsvm_data.txt\")\n\n dataset.printSchema()\n dataset.show(truncate=False)\n\n sparkSession.stop()\n","sub_path":"pythonSparkML/ReadLibSVM.py","file_name":"ReadLibSVM.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"624351670","text":"n = int(input())\narr = []\ndp = [[0]*(i+1) for i in range(n)]\nfor i in range(n):\n arr.append(list(map(int,input().split())))\ndp[0][0] = arr[0][0]\nfor i in range(1,n):\n length = len(arr[i])\n for j in range(length):\n if j == 0:\n dp[i][j] = arr[i][j]+dp[i-1][j]\n elif j == length-1:\n dp[i][j] = arr[i][j]+dp[i-1][j-1]\n elif i != 1 and 0 < j < length-1:\n dp[i][j] = max(dp[i-1][j],dp[i-1][j-1])+arr[i][j]\n\nprint(max(dp[n-1]))\n","sub_path":"1000번/1932_정수 삼각형.py","file_name":"1932_정수 삼각형.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"274523369","text":"from flask import request\nfrom flask_restplus import Resource, Namespace\n\nfrom ..service import user_service, auth_service\n\nfrom . import api_model\nfrom ..util.decorator import token_required\n\nnamespace = Namespace(\n name='user',\n path='/',\n description='User related operations'\n)\n\n\n@namespace.route('/user')\nclass UserList(Resource):\n\n # @namespace.marshal_with(api_model.user_basic, as_list=True, envelope='users')\n # def get(self):\n # \"\"\"List all Users\"\"\"\n # return user_service.get_all_users()\n\n @namespace.expect(api_model.user_new, api_model.auth_token_header, validate=True)\n @namespace.marshal_with(api_model.user_basic, envelope='user')\n def post(self):\n \"\"\"Creates a new User\"\"\"\n data = request.json\n return user_service.create_new_user(data=data), 201\n\n\n@namespace.route('/user/')\n@namespace.param('user_public_id', 'The User identifier')\nclass User(Resource):\n\n @namespace.expect(api_model.auth_token_header, validate=True)\n @namespace.marshal_with(api_model.user_basic, envelope='user')\n @token_required('user', 'login')\n def get(self, user_public_id):\n \"\"\"Get a User\"\"\"\n return user_service.get_a_user(user_public_id), 200\n\n @namespace.expect(api_model.user_change, api_model.auth_token_header, validate=True)\n @namespace.marshal_with(api_model.user_basic, envelope='user')\n @token_required('user', 'login')\n def patch(self, user_public_id):\n \"\"\"Update a User\"\"\"\n data = request.json\n return user_service.update_a_user(public_id=user_public_id, data=data), 200\n\n @namespace.expect(api_model.auth_token_header, validate=True)\n @namespace.marshal_with(api_model.response)\n @token_required('user', 'login')\n def delete(self, user_public_id):\n \"\"\"delete a user\"\"\"\n res = user_service.delete_a_user(user_public_id)\n return res, 200\n","sub_path":"api/main/controller/user_controller.py","file_name":"user_controller.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"61581204","text":"from django.urls import path\nfrom .views import *\n\n\nurlpatterns = [\n path('dashboard/', dashboard, name='dashboard'),\n path('staff_list/', staff_list, name='staff_list'),\n path('example_staff_file/', example_staff_file, name='example_staff_file'),\n path('group_management/', group_management, name='group_management'),\n path('history_chronology/', history_chronology, name='history_chronology')\n]","sub_path":"AwaSRM/django_crm/staff/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"21986268","text":"import asyncio\nimport asyncpg\nimport config\nimport datetime\nimport discord\nfrom discord.ext import commands\nimport footers\nimport json\nimport logging\nimport math\nimport os\nimport random\nimport subprocess\nimport time\nfrom typing import Union\n\nprefixes = [\n \"[] \",\n \"[]\",\n \"lopez pls \",\n \"lopez, please \",\n \"lopez, \",\n \"hey lopez, \",\n \"hey lopez \",\n \"hey, lopez \",\n]\n\n\ndef get_pre(bot: commands.Bot, message: discord.Message) -> Union[str, list]:\n lowercased = message.content.lower()\n for prefix in prefixes:\n if lowercased.startswith(prefix):\n return commands.when_mentioned_or(message.content[: len(prefix)])(\n bot, message\n )\n return commands.when_mentioned_or(*prefixes)(bot, message)\n\n\nbot = commands.Bot(\n get_pre,\n None,\n \"A bot created for everybody.\",\n None,\n owner_id=164342765394591744,\n case_insensitive=True,\n)\n\nlogger = logging.getLogger(\"discord\")\nlogger.setLevel(logging.INFO)\nhandler = logging.FileHandler(\n filename=\"logs/lopez_{}.log\".format(datetime.datetime.today()),\n encoding=\"utf-8\",\n mode=\"w\",\n)\nhandler.setFormatter(\n logging.Formatter(\"[%(asctime)s] %(levelname)s: %(name)s: %(message)s\")\n)\nlogger.addHandler(handler)\nbot.log_handler = handler\n\n\nasync def open_conn(b: commands.Bot):\n b.connect_pool = await asyncpg.create_pool(config.postgresql)\n\n\nasync def watchdog():\n await bot.wait_until_ready()\n while True:\n subprocess.call(\n [\"/bin/systemd-notify\", \"--pid=\" + str(os.getpid()), \"WATCHDOG=1\"]\n )\n await asyncio.sleep(15)\n\n\n@bot.event\nasync def on_ready():\n logging.info(\"\\n\".join([\"Logged in as\", bot.user.name, str(bot.user.id), \"------\"]))\n subprocess.call([\"/bin/systemd-notify\", \"--pid=\" + str(os.getpid()), \"--ready\"])\n\n\n@bot.event\nasync def on_message(message: discord.Message):\n await bot.process_commands(message)\n if not (message.author == bot.user):\n if bot.user.mentioned_in(message) and not message.mention_everyone:\n await message.add_reaction(bot.get_emoji(406171759365062656))\n\n\n@bot.event\nasync def on_command_completion(ctx: commands.Context):\n if ctx.command.name == \"help\":\n await ctx.message.add_reaction(\"\\N{OPEN MAILBOX WITH RAISED FLAG}\")\n\n\n@bot.command()\nasync def prefix(ctx: commands.Context):\n send = \"*My prefixes are* \"\n for i in range(len(prefixes)):\n if i is not len(prefixes) - 1 and i is not len(prefixes) - 2:\n send += \"**{}**; \".format(prefixes[i])\n elif i is len(prefixes) - 2:\n send += \"**{}**; *and* \".format(prefixes[i])\n else:\n send += \"**{}**\".format(prefixes[i])\n send += \"\\nThese are case insensitive, so `{} ` is a valid command prefix (please don't shout at me!)\".format(\n random.choice(prefixes[1:]).upper()\n )\n fix = random.choice(prefixes)\n send += \"\\nAlso, a prefix must be followed by a space to work (e.g. `{0}roll 1d20` is valid while `{1}roll 1d20` is not.)\".format(\n fix, fix.strip()\n )\n await ctx.send(send)\n\n\n@bot.command()\nasync def quote(ctx: commands.Context):\n \"\"\"Quotes are fun!\"\"\"\n await ctx.send(random.choice(footers.quotes_e10))\n\n\n@bot.command()\nasync def uptime(ctx: commands.Context):\n \"\"\"Tells how long the bot has been online.\"\"\"\n delta = datetime.timedelta(seconds=int(time.time() - botstart))\n await ctx.send(\"**Uptime:** {}\".format(str(delta)))\n\n\n@bot.command()\nasync def invite(ctx: commands.Context):\n \"\"\"Gets a link to invite Lopez.\"\"\"\n perms = discord.Permissions.none()\n perms.view_audit_log = True\n perms.manage_roles = True\n perms.manage_channels = True\n perms.create_instant_invite = True\n perms.send_messages = True\n perms.manage_messages = True\n perms.embed_links, perms.attach_files, perms.read_message_history = True, True, True\n perms.external_emojis, perms.add_reactions = True, True\n await ctx.send(\n \"Use this link to invite Lopez into your Discord server!\\n\"\n + discord.utils.oauth_url(\"436251140376494080\", perms)\n )\n\n\nbot.loop.create_task(watchdog())\nbot.loop.run_until_complete(open_conn(bot))\n\ncogs = [\n \"git_update\",\n \"roles\",\n \"moderate\",\n \"modi_bot\",\n \"developer\",\n \"roller\",\n \"wild_speller\",\n \"parts\",\n \"moderation.channels\",\n \"moderation.guild\",\n]\nfor cog in cogs:\n bot.load_extension(\"cogs.\" + cog)\n\ntoken = None\nwith open(\"creds.txt\") as creds:\n token = creds.read().strip()\nlogging.info(\"Starting Lopez...\")\nbotstart = time.time()\nbot.run(token, reconnect=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"426595976","text":"#!/usr/bin/env python3\nfrom glob import glob\nimport os\nimport sys\n\n# Parámetros:\ninputDirList = [\"input/graficoCentrales\", \"input/graficoTiempoLiso\"]\n\ntry:\n arg = sys.argv[1]\nexcept:\n arg = \"-time\"\n\n\n\nif( arg == \"-resultados\"):\n def correr(archivo):\n os.system(\"./ej2 < {} > {}\".format(archivo, output))\nelif (arg == \"-todo\"):\n def correr(archivo):\n os.system(\"./ej2 < {} > {}\".format(archivo, output))\n os.system(\"./ej2.time < {} > {}\".format(archivo, output + \".time\"))\nelse:\n def correr(archivo):\n os.system(\"./ej2.time < {} > {}\".format(archivo, output+ \".time\"))\n\n\nfor dir in inputDirList:\n inputFiles = glob( \"{}/*.txt\".format(dir))\n for file in sorted(inputFiles):\n output = file.replace(\"input\",\"output\")\n print(\"corriendo:\", file)\n correr(file)\n\n","sub_path":"tp2/ej2/correrTest.py","file_name":"correrTest.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"69414191","text":"from django.shortcuts import render, get_object_or_404\nfrom .models import Note\n\n\ndef notes_list_view(request):\n notes = Note.objects.all()\n\n context = {\n 'notes': notes\n }\n\n return render(request, 'notes/notes_list.html', context=context)\n\n\ndef notes_detail_view(request, pk=None):\n note = get_object_or_404(Note, id=pk)\n context = {\n 'note': note,\n }\n\n return render(request, 'notes/notes_detail.html', context)\n","sub_path":"class-27-django-mvc/demos/notes_401d9/notes_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"482711650","text":"from func.data import db\nfrom func.user import *\nfrom time import sleep, strftime\nimport re, json\n\nwith open('data/set.txt', 'r', encoding='utf-8') as file:\n\ts = json.loads(file.read())['read']\n\ttags = s['tags']\n\tfrom_id = str(s['channel'])\n\nmessages = db['messages']\n\ndef tag(text): #! update.message.caption\n\ttext = text.lower()\n\tfor i in tags:\n\t\tif i in text:\n\t\t\treturn True\n\treturn False\n\ndef replier(update):\n\tif isinstance(update, (UpdateNewMessage, UpdateNewChannelMessage)) and str(update.message.to_id.channel_id) in from_id:\n\t\t#print(update)\n\t\ttext = update.message.message\n\n\t\ttry:\n\t\t\ttext += '\\n' + update.message.media.caption\n\t\texcept:\n\t\t\tpass\n\n\t\t#+изображения\n\n\t\tif tag(text):\n\t\t\ttry:\n\t\t\t\tid = messages.find().sort('id', -1)[0]['id'] + 1\n\t\t\texcept:\n\t\t\t\tid = 1\n\n\t\t\tdoc = {\n\t\t\t\t'id': id,\n\t\t\t\t'chat': update.message.from_id,\n\t\t\t\t'message': update.message.id,\n\t\t\t\t'text': text,\n\t\t\t\t'time': strftime('%d.%m.%Y %H:%M:%S')\n\t\t\t}\n\t\t\tmessages.insert(doc)\n\nclient.add_update_handler(replier)\ninput('!')\nclient.disconnect()\nprint('!!')\n'''\nwhile True:\n\ttry:\n\t\tclient.add_update_handler(replier)\n\t\tinput()\n\texcept:\n\t\tpass\n'''","sub_path":"autoadd.py","file_name":"autoadd.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"612773266","text":"import pygame\nfrom pygame.locals import *\nfrom sys import exit\n\npygame.init()\nSCREEN_SIZE = (640, 480)\nscreen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)\n\nfont = pygame.font.SysFont(\"arial\", 10)\nfont_height = font.get_linesize()\nevent_text = []\n\nwhile True:\n\tevent = pygame.event.wait()\n\tevent_text.append(str(event))\n\t#get the name of time\n\tevent_text = event_text[-SCREEN_SIZE[1]/font_height:]\n\t#confirm that there always reserve a screen's word\n\n\tif event.type == QUIT:\n\t\texit()\n\n\tscreen.fill((0, 255, 0))\n\n\ty = SCREEN_SIZE[1] - font_height\n\t#find a appropriate position to start write from bottom but reserve one line\n\tfor text in reversed(event_text):\n\t\tscreen.blit( font.render(text, True, (0, 0, 0)), (0, y))\n\t\t#discuss it later :)\n\t\ty -= font_height\n\t\t#up one line with pencil\n\n\tpygame.display.update()","sub_path":"2nd_1.py","file_name":"2nd_1.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"360714635","text":"import asyncio\nimport os\nimport shutil\nimport subprocess\nimport unittest\nfrom functools import wraps\nfrom time import sleep\n\n\ndef run_until_complete(fun):\n if not asyncio.iscoroutinefunction(fun):\n fun = asyncio.coroutine(fun)\n\n @wraps(fun)\n def wrapper(test, *args, **kw):\n loop = test.loop\n ret = loop.run_until_complete(fun(test, *args, **kw))\n return ret\n return wrapper\n\n\nclass BaseTest(unittest.TestCase):\n '''Base test case for unittests.\n '''\n @classmethod\n def setUpClass(cls):\n cls._dir = os.path.abspath('/tmp/__nsqdata')\n\n try:\n os.mkdir(cls._dir)\n except FileExistsError:\n shutil.rmtree(cls._dir)\n os.mkdir(cls._dir)\n\n kwargs = {k: subprocess.DEVNULL for k in ('stdout', 'stderr')}\n cls._nsqlookupd = subprocess.Popen(['nsqlookupd'], **kwargs)\n cls._nsqd = subprocess.Popen(['nsqd',\n '--data-path={}'.format(cls._dir),\n '--lookupd-tcp-address=127.0.0.1:4160'],\n **kwargs)\n sleep(0.5)\n\n @classmethod\n def tearDownClass(cls):\n cls._nsqlookupd.kill()\n cls._nsqd.kill()\n shutil.rmtree(cls._dir)\n sleep(0.5)\n\n def setUp(self):\n self.loop = asyncio.get_event_loop()\n\n if self.loop.is_closed():\n self.loop = asyncio.new_event_loop()\n asyncio.set_event_loop(self.loop)\n\n self.loop.run_until_complete(self.aioSetUp())\n\n def tearDown(self):\n self.loop.run_until_complete(self.aioTearDown())\n\n for task in asyncio.Task.all_tasks():\n task.cancel()\n\n self.loop.run_until_complete(asyncio.sleep(0.015))\n self.loop.stop()\n self.loop.close()\n\n async def aioSetUp(self):\n pass\n\n async def aioTearDown(self):\n pass\n","sub_path":"tests/_testutils.py","file_name":"_testutils.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"256528050","text":"# 1. Write a python program to add below matrices\n\nMatrix_1 = [[12, 7, 3],\n [4,5,6],\n [7,8,9]]\nMatrix_2 = [[5, 8, 1],\n [6,7,3],\n [4,5,9]]\n\nResultant_Matrix = [[0, 0, 0],\n [0,0,0],\n [0,0,0]]\n# Matrix= []\nfor index_1 in range(len(Matrix_1)):\n for index_2 in range(len(Matrix_1[0])):\n Resultant_Matrix[index_1][index_2] = Matrix_1[index_1][index_2] + Matrix_2[index_1][index_2]\n\nprint(Resultant_Matrix)\n","sub_path":"Matrices/Matrix_addition_1.py","file_name":"Matrix_addition_1.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"153614330","text":"import tensorflow as tf\nfrom tensorflow import keras\n\nimport pandas as pd\nimport numpy as np\n\n\n# Predicting 2 things at once\n# First six indicate the color last three indicate the marker\n# 3\n# [0 0 0 0 0 1 0 0 1] - This is One-Hot encoding\n\ntrain_df = pd.read_csv('C:/Users/wspic/Documents/GitHub/neural-nets/examples/clusters_two_categories/data/train.csv')\n\none_hot_color = pd.get_dummies(train_df.color).values\none_hot_marker = pd.get_dummies(train_df.marker).values\n\nlabels = np.concatenate((one_hot_color, one_hot_marker), axis=1)\nprint(labels[0:5])\n\nprint(train_df.head())\n\nmodel = keras.Sequential([\n\tkeras.layers.Dense(64, input_shape=(2,), activation='relu'),\n\tkeras.layers.Dense(64, activation='relu'),\n\tkeras.layers.Dense(9, activation='sigmoid')]) # 6 for colors 3 for markers = 9\n\nmodel.compile(optimizer='adam', \n\t loss=keras.losses.BinaryCrossentropy(from_logits=True), \n\t metrics=['accuracy'])\n\nx = np.column_stack((train_df.x.values, train_df.y.values))\n\n# Ensuring that the same shuffling is happening in both places (what places)\nnp.random.RandomState(seed=42).shuffle(x)\nnp.random.RandomState(seed=42).shuffle(labels)\n\nmodel.fit(x, labels, batch_size=4, epochs=10)\n\ntest_df = pd.read_csv('C:/Users/wspic/Documents/GitHub/neural-nets/examples/clusters_two_categories/data/train.csv')\ntest_x = np.column_stack((test_df.x.values, test_df.y.values))\n\ntest_one_hot_color = pd.get_dummies(test_df.color).values\ntest_one_hot_marker = pd.get_dummies(test_df.marker).values\n\ntest_labels = np.concatenate((test_one_hot_color, test_one_hot_marker), axis=1)\n\nprint(\"EVALUATION\")\nmodel.evaluate(test_x, test_labels)\n\nprint(\"Prediction\", np.round(model.predict(np.array([[0,3], [0,1], [-2, 1]]))))\n\n\n\n\n\n","sub_path":"examples/clusters_two_categories/network_clusters_2.py","file_name":"network_clusters_2.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"249436894","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nclass Solution:\n def twoSum(self, nums, target):\n re = []\n for i in range(0,len(nums)):\n for j in range(i+1,len(nums)):\n if nums[i] + nums[j] == target:\n re.append(i)\n re.append(j)\n return re\n\n\nif __name__ == \"__main__\":\n s = Solution()\n nums = [1, 4, 2, 5, 9]\n target = 11\n print(s.twoSum(nums, target))\n","sub_path":"1. 两数之和/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"63399521","text":"from math import sin, cos, pi\nimport rclpy\nfrom rclpy.node import Node\nfrom rclpy.qos import QoSProfile\nfrom sensor_msgs.msg import JointState\nfrom tf2_ros import TransformBroadcaster\n\nclass Ikin(Node):\n\n def __init__(self):\n\n rclpy.init()\n super().__init__('ikin')\n\n qos_profile = QoSProfile(depth=10)\n self.joint_pub = self.create_publisher(JointState, 'joint_states', qos_profile)\n self.broadcaster = TransformBroadcaster(self, qos=qos_profile)\n self.nodeName = self.get_name()\n self.get_logger().info(\"{0} started\".format(self.nodeName))\n\n loop_rate = self.create_rate(30)\n\n joint_state = JointState()\n\ndef main():\n node = Ikin()\n\nif __name__ == '__main__':\n main()\n","sub_path":"urdf_lab5/urdf_lab5/ikin.py","file_name":"ikin.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"128579747","text":"import os;\nfrom MonkeyPatch import *;\nimport xml.etree.ElementTree as ET;\nimport sys;\nsys.path.append('/home/nyadav/pyscr');\nimport ipVar, funcs;\nimport numpy as np;\nfrom scipy.interpolate import InterpolatedUnivariateSpline;\nclass CriticalRe:\n def __init__(self):\n self.bdFname='bd.xml';\n self.bdFPath='/home/nyadav/symm/0.675/bd';\n self.geomFname='geom.xml';\n self.FileList=['geom.xml','bd.xml','geomHplusD.fld'];\n self.RePath=os.getcwd();\n self.ReList=[];\n self.exe='/home/nyadav/nekNewton/dist/bin/IncNavierStokesSolver';\n self.FilePath='/home/nyadav/symm/ReC';\n self.BetaPath=os.getcwd();\n self.betaList=[];\n self.Re=0;\n self.beta=0;\n self.temp=0;\n #for i in range(0,2):\n #self.betaList.append(0.05+i*0.1);\n for i in range(0,8):\n self.betaList.append(0.3+i*0.05);\n #for i in range(0,2):\n #self.betaList.append(0.7+i*0.1);\n\n def IG(self,beta,ReNm):\n if not (self.bdFname=='0'):\n self.ReList=[];\n self.beta=beta;\n tree=ET.parse(self.bdFPath+'/'+self.bdFname,OrderedXMLTreeBuilder());\n root=tree.getroot();\n Re=root[1][1][5].text.split('=')[-1];\n self.ReList.append(int(Re));\n ReNew=float(Re)**(abs(beta-0.4)+1);\n self.ReList.append(int(ReNew));\n self.CritRe();\n [a,b]=ipVar.poptDir(self.RePath);\n #self.temp=Re;\n while(all(i<0 for i in a)):\n self.ReList=[];\n Re=float(Re)+0.1*(float(Re));\n self.ReList.append(Re);\n self.CritRe();\n [a,b]=ipVar.poptDir(self.RePath);\n while(all(i>0 for i in a)):\n self.ReList=[];\n Re=float(Re)-0.3*(float(Re));\n self.ReList.append(Re);\n self.CritRe();\n [a,b]=ipVar.poptDir(self.RePath);\n else:\n self.ReList=[];\n self.ReList.append(ReNm);\n ReNew=ReNm**(abs(beta-0.4)+1);\n self.ReList.append(ReNew);\n return self.ReList;\n\n def CritRe(self):\n for i in self.ReList:\n if not os.path.exists(str(i)):\n os.makedirs(str(i));\n os.chdir(str(i));\n funcs.CopyFileVal(self.FilePath,os.getcwd(),self.FileList,str(i),self.beta);\n funcs.incSolver(self.exe,self.FileList[:-1]);\n os.chdir(self.RePath);\n\n def ReIter(self):\n [a,b]=ipVar.poptDir(self.RePath);\n z=np.where(np.diff(np.sign(a)))[0];\n i=z[0];\n r1=b[i];r2=b[i+1];\n print(r1);print(r2);\n print(\"the value of the \");\n while(abs(r1-r2)>20):\n self.ReList=[];\n ReCr=funcs.calcReC(a,b);\n self.ReList.append(ReCr+0.3*abs(r1-r2));\n self.ReList.append(ReCr-0.3*abs(r1-r2));\n self.CritRe();\n print(r1);print(r2);\n [a,b]=ipVar.poptDir(self.RePath);\n z=np.where(np.diff(np.sign(a)))[0];\n r1=b[z[0]];r2=b[z[0]+1];\n [a,b]=ipVar.poptDir(self.RePath);\n if(len(a)>3):func=InterpolatedUnivariateSpline(b,a,k=3);\n ReC=func.roots();\n return ReC;\n \n def CreForBeta(self):\n os.chdir(self.BetaPath);\n for i in self.betaList:\n if not os.path.exists(str(i)):\n os.makedirs(str(i));\n os.chdir(str(i));\n self.RePath=os.getcwd();\n self.beta=i;\n self.IG(i,150);\n self.ReIter();\n os.chdir(self.BetaPath);\n\n\n\n\n\n\n\n\n\n\n","sub_path":"InitialGuess.py","file_name":"InitialGuess.py","file_ext":"py","file_size_in_byte":3639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"590921328","text":"import os\nfrom subprocess import Popen, PIPE\n\nimport handler\nimport osvcd_shared as shared\nimport rcExceptions as ex\nfrom rcUtilities import bdecode, drop_option\nfrom rcGlobalEnv import rcEnv\n\nclass Handler(handler.Handler):\n \"\"\"\n Execute a node action.\n \"\"\"\n routes = (\n (\"POST\", \"node_action\"),\n (None, \"node_action\"),\n )\n prototype = [\n {\n \"name\": \"sync\",\n \"desc\": \"Execute synchronously and return the outputs.\",\n \"required\": False,\n \"default\": True,\n \"format\": \"boolean\",\n },\n {\n \"name\": \"action_mode\",\n \"desc\": \"If true, adds --local if not already present in or .\",\n \"required\": False,\n \"default\": True,\n \"format\": \"boolean\",\n },\n {\n \"name\": \"cmd\",\n \"desc\": \"The command vector.\",\n \"required\": False,\n \"format\": \"list\",\n \"deprecated\": True,\n },\n {\n \"name\": \"action\",\n \"desc\": \"The action to execute.\",\n \"required\": False,\n \"format\": \"string\",\n },\n {\n \"name\": \"options\",\n \"desc\": \"The action options.\",\n \"required\": False,\n \"format\": \"dict\",\n \"default\": {},\n },\n ]\n\n def action(self, nodename, thr=None, **kwargs):\n options = self.parse_options(kwargs)\n\n if not options.cmd and not options.action:\n thr.log_request(\"node action ('action' not set)\", nodename, lvl=\"error\", **kwargs)\n return {\n \"status\": 1,\n }\n\n for opt in (\"node\", \"server\", \"daemon\"):\n if opt in options.options:\n del options.options[opt]\n if options.action_mode and options.options.get(\"local\"):\n if \"local\" in options.options:\n del options.options[\"local\"]\n for opt, ropt in ((\"jsonpath_filter\", \"filter\"),):\n if opt in options.options:\n options.options[ropt] = options.options[opt]\n del options.options[opt]\n options.options[\"local\"] = True\n pmod = __import__(\"nodemgr_parser\")\n popt = pmod.OPT\n\n def find_opt(opt):\n for k, o in popt.items():\n if o.dest == opt:\n return o\n if o.dest == \"parm_\" + opt:\n return o\n\n if options.cmd:\n cmd = [] + options.cmd\n cmd = drop_option(\"--node\", cmd, drop_value=True)\n cmd = drop_option(\"--server\", cmd, drop_value=True)\n cmd = drop_option(\"--daemon\", cmd)\n if options.action_mode and \"--local\" not in cmd:\n cmd += [\"--local\"]\n else:\n cmd = [options.action]\n for opt, val in options.options.items():\n po = find_opt(opt)\n if po is None:\n continue\n if val == po.default:\n continue\n if val is None:\n continue\n opt = po._long_opts[0] if po._long_opts else po._short_opts[0]\n if po.action == \"append\":\n cmd += [opt + \"=\" + str(v) for v in val]\n elif po.action == \"store_true\" and val:\n cmd.append(opt)\n elif po.action == \"store_false\" and not val:\n cmd.append(opt)\n elif po.type == \"string\":\n opt += \"=\" + val\n cmd.append(opt)\n elif po.type == \"integer\":\n opt += \"=\" + str(val)\n cmd.append(opt)\n fullcmd = rcEnv.python_cmd + [os.path.join(rcEnv.paths.pathlib, \"nodemgr.py\")] + cmd\n\n thr.log_request(\"run '%s'\" % \" \".join(fullcmd), nodename, **kwargs)\n if options.sync:\n proc = Popen(fullcmd, stdout=PIPE, stderr=PIPE, stdin=None, close_fds=True)\n out, err = proc.communicate()\n result = {\n \"status\": 0,\n \"data\": {\n \"out\": bdecode(out),\n \"err\": bdecode(err),\n \"ret\": proc.returncode,\n },\n }\n else:\n proc = Popen(fullcmd, stdin=None, close_fds=True)\n thr.push_proc(proc)\n result = {\n \"status\": 0,\n \"info\": \"started node action %s\" % \" \".join(cmd),\n }\n return result\n\n","sub_path":"lib/handlerPostNodeAction.py","file_name":"handlerPostNodeAction.py","file_ext":"py","file_size_in_byte":4547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"268781873","text":"import random\n\nclass lastword:\n\n def __init__(self):\n # 유저 총원\n self.UserCount = 0\n # 유저 닉네임\n self.UserList = []\n # 게임 중 발생한 단어들\n self.WordList = []\n\n # 유저 인원 수 입력 받기\n def userCount(self):\n while(True):\n Count = input(\"참여 인원 수 입력 (최대 10명): \")\n if Count.isdigit() == False:\n print(\"숫자만 입력해주세요.\")\n elif int(Count) > 10:\n print(\"최대 인원은 10명입니다.\")\n else:\n break\n self.UserCount = int(Count)\n print(\"========================================\")\n\n # 유저 이름 입력 받기\n def userName(self):\n # 유저 수만큼 반복\n for i in range(self.UserCount):\n while(True):\n name = input(\"{}번 인원 닉네임을 입력해주세요. : \".format(i + 1))\n if name in self.UserList:\n print(\"중복입니다.\")\n elif name.isalpha() == False:\n print(\"문자만 입력 가능합니다.\")\n else:\n self.UserList.append(name)\n break\n print(\"========================================\")\n\n # 게임 순서 정하기\n def Draw(self):\n print(\"순서 정하기 1. 랜덤 2. 입력순서 거꾸로 3. 입력순서\")\n while(True):\n draw = input(\"번호 입력 : \")\n if draw.isdigit() == False:\n print(\"숫자를 입력해주세��.\")\n elif draw != \"1\" and draw != \"2\" and draw != \"3\":\n print(\"입력 범위를 벗어 났습니다.\")\n else:\n draw = int(draw)\n break\n if draw == 1:\n print(\"랜덤을 선택했습니다.\")\n random.shuffle(self.UserList)\n print(\"순서는 \\n\", self.UserList)\n elif draw == 2:\n print(\"인력순서 거꾸로 선택했습니다.\")\n self.UserList.reverse()\n print(\"순서는 \\n\", self.UserList)\n else:\n print(\"ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ\")\n print(\"입력순서를 선택했습니다.\")\n print(\"순서는 \\n\", self.UserList)\n print(\"========================================\")\n\n # 게임 시작\n def Start(self):\n # 유저 리스트 저장\n UserList = self.UserList\n # 패배한 유저 저장\n LoserList = []\n print(\"게임을 시작합니다.\")\n print(\"========================================\")\n # 게임 턴 수 표현\n gameCount = 0\n # 게임 시작\n while(True):\n # 사람 한명 한명 지목\n for name in self.UserList:\n # 실패 측정을 위한 카운트\n LoseCount = 0\n # 지명된 사람 턴\n while(True):\n # 3회 실패 탈락\n if LoseCount == 3:\n print(\"실패 3회 초과 탈락입니다.\")\n print(\"\\\"{}\\\"님은 탈락입니다.\".format(name))\n LoserList.append(name)\n UserList.remove(name)\n gameCount += 1\n break\n print(\"ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ\")\n print(\"{}턴 \".format(gameCount + 1) + \"\\\"\" + name + \"\\\"\" + \"님 차레입니다.\")\n print(\"ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ\")\n word = input(\"단어를 입력하세요. : \")\n # 문자인지 1글자인지 판단\n if word.isalpha == False or len(word) <= 1:\n LoseCount += 1\n print(\"{}회 실패 단어를 정확하게 입력해주세요.\".format(LoseCount))\n else:\n # 단어가 있다면 탈락\n if word in self.WordList:\n print(\"========================================\")\n print(\"\\\"{}\\\"는 중복 문자입니다.\".format(word))\n print(\"\\\"{}\\\"님은 탈락입니다.\".format(name))\n LoserList.append(name)\n UserList.remove(name)\n print(\"========================================\")\n gameCount += 1\n break\n # 첫번째 턴이 아니라면\n elif gameCount != 0:\n # 앞에 단어를 Test에 삽입\n Test = self.WordList[gameCount - 1]\n # 앞에 단어 맨뒤와 지금 입력단어 맨앞을 비교 \n if Test[-1] != word[0]:\n print(\"========================================\")\n print(\"\\\"{}\\\"는 연결되지 않습니다.\".format(word))\n print(\"\\\"{}\\\"님은 탈락입니다.\".format(name))\n LoserList.append(name)\n UserList.remove(name)\n print(\"========================================\")\n gameCount += 1\n break\n else:\n print(\"통과\")\n self.WordList.append(word)\n gameCount += 1\n break\n # 정확하면\n else: \n print(\"통과\")\n self.WordList.append(word)\n gameCount += 1\n break\n \n if len(UserList) == 1:\n LoserList.append(UserList[0])\n print(\" 게 임 종 료 \")\n break\n \n \n print(\"========================================\")\n print(\" 순 위 \")\n LoserList.reverse()\n for i in range(len(LoserList)):\n print(\"{}등 {}님,\".format(i + 1, LoserList[i]),end=\" \")\n\nif __name__ == \"__main__\":\n Game = lastword()\n Game.userCount()\n Game.userName()\n Game.Draw()\n Game.Start()","sub_path":"끝말잇기/끝말.py","file_name":"끝말.py","file_ext":"py","file_size_in_byte":6555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"540666329","text":"import numpy\nfrom numpy.lib.function_base import average\nimport requests\nimport json\nfrom datetime import date\nimport re\nimport csv\nfrom requests.sessions import extract_cookies_to_jar\nimport pandas\nfrom sklearn import linear_model, preprocessing\nimport matplotlib.pyplot as plt\nfrom itertools import combinations\nfrom scipy.stats import ttest_ind\nfrom sklearn.decomposition import PCA\n\n\n\ndef findAvg(brands:list, prices:list, brand):\n\tcount, sum = 0, 0\n\tfor i in range(len(brands)):\n\t\tif brands[i] == brand:\n\t\t\tsum += prices[i]\n\t\t\tcount += 1\n\n\treturn sum/count\t\t\n\n\n\ndef changeNumToEnglish(tmpStr:str): # data cleaning\n\treturn tmpStr.replace('٫','').replace('۰','0').replace('۱','1').replace('۲','2').replace('۳','3').replace('۴','4').replace('۵','5').replace('۶','6').replace('۷','7').replace('۸','8').replace('۹','9').replace(' تومان', '').replace('توافقی', '0').replace('،' , ' ').replace('هستم', '0').replace('قبل از', '')\n\n\ndef findBrands(txt:str):\n\thold = txt.split('enumNames\":[')\n\tholdAll = hold[1].split(']')\n\tholdAll = holdAll[0].split(',')\n\tfor i in range(len(holdAll)):\n\t\tholdAll[i] = holdAll[i].replace('\\\"', '')\n\n\treturn holdAll\n\n\n\ninfo = \"{ \\\"phone\\\":\\\"9100039730\\\"}\"\nheaders = {'User-Agent': 'Mozilla/5.0', 'Content-Type': 'application/json', 'x-standard-divar-error': 'true', 'Cookie': 'city=tehran; multi-city=tehran%7C'}\nsession = requests.Session()\n\n\n# login = session.post(\"https://api.divar.ir/v5/auth/authenticate\", headers= headers, data=info)\n# print(login.text)\n\n# code = input(\"Enter Code: \")\n# tmp = \"{ \\\"phone\\\":\\\"9100039730\\\", \\\"code\\\":\\\"\"+code+\"\\\"}\"\n\n\n# giveCode = session.post(\"https://api.divar.ir/v5/auth/confirm\", headers=headers, data=tmp)\n\n# token = giveCode.text[10:len(giveCode.text)-2]\n\n# headers['Authorization'] = token\n# print('TOKEN:', token)\n\n\nurl = \"https://api.divar.ir/v8/search/1/motorcycles\"\npayload = json.dumps({\n\t\"json_schema\": {\n\t\t\"category\": {\n\t\t\"value\": \"motorcycles\"\n\t\t}\n\t},\n\t\"last-post-date\": 664444352522061\n\t})\nheaders = {\n'Content-Type': 'application/json',\n'Cookie': 'city=tehran; multi-city=tehran%7C'\n}\n\ntmpLast = '664444352522061'\n\nfile = open(\"C:/Users/Lenovo/Desktop/tamrin/Data_Divar/out.csv\", 'w', newline=\"\", encoding=\"utf-8\")\nwriteFile = csv.writer(file, quoting=csv.QUOTE_NONE)\nwriteFile.writerow(['title', ' kind of sale', 'brand', 'year', 'price', 'usage', 'explanation'])\n\ntmpToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiMDkxMDAwMzk3MzAiLCJleHAiOjE2Mjg0OTM2ODAuNDE0MjI3LCJ2ZXJpZmllZF90aW1lIjoxNjI3MTk3NjgwLjQxNDIyNSwidXNlci10eXBlIjoicGVyc29uYWwiLCJ1c2VyLXR5cGUtZmEiOiJcdTA2N2VcdTA2NDZcdTA2NDQgXHUwNjM0XHUwNjJlXHUwNjM1XHUwNmNjIn0.T528R8fW1HUErJKRBI-XlaJvpEOuBhdCAEXqIXw7P_o'\nheaders['Authorization'] = tmpToken # token for sign in to Divar.ir\n\n#eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiMDkxMDAwMzk3MzAiLCJleHAiOjE2Mjg1OTQ4NDEuOTkwMDg1LCJ2ZXJpZmllZF90aW1lIjoxNjI3Mjk4ODQxLjk5MDU0LCJ1c2VyLXR5cGUiOiJwZXJzb25hbCIsInVzZXItdHlwZS1mYSI6Ilx1MDY3ZVx1MDY0Nlx1MDY0NCBcdTA2MzRcdTA2MmVcdTA2MzVcdTA2Y2MifQ.C6EJfXaxDILThoWk7jgunG4NMPe0a_pnXPyfrdn3Qp0\n\nbrandExist = []\n\nallLinks = []\ncounter = 0\n\nallAdds = [] #all adds stored in file\n\nfor step in range(5):\n\n\tresponse = requests.request(\"POST\", url, headers=headers, data=payload)\n\ttxt = response.text\n\n\tbrands = findBrands(txt)\n\t\n\tfindLinkReg = \"\\\"token\\\":\\\"(.*?)\\\",\"\n\n\tlinks = re.findall(findLinkReg, txt) #find tokens of ads\n\t\t\t\n\tfor i in range(len(links)):\n\t\tlinks[i] = 'https://divar.ir/v/' + links[i]\n\n\ttitleReg = \"(.*)<\\/title>\"\n\tbaseInforeg2 = \"<p class=\\\"kt-unexpandable-row__value\\\">(.{1,50})<\\/p>\"\n\texplanationReg = \"<p class=\\\"kt-description-row__text post-description kt-description-row__text--primary\\\">([a-zA-Zا-ی\\s0-9۰-۹،-]+)\"\n\tphoneNumReg = \"<a class=\\\"kt-unexpandable-row__action kt-text-truncate ltr\\\" href=\\\"tel:09397777569\\\">(۰-۹)+<\\/a>\"\n\n\n\t#find pattern in data of url and write to csv file\n\tfor link in links:\n\t\tif link not in allLinks:\n\t\t\tallLinks.append(link)\n\t\telse:\n\t\t\tcontinue\t\n\t\tagahi = requests.get(link, headers)\n\t\tinfo = agahi.text\n\n\t\ttitleAgahi = re.findall(titleReg, info)\n\t\tbaseInfo2 = re.findall(baseInforeg2, info)\n\t\texp = re.findall(explanationReg, info)\n\n\t\ttry:\n\t\t\texp[0] = exp[0].replace('\\n', ' ')\n\t\texcept:\n\t\t\texp = exp \n\t\tallInfo = []\n\t\tallInfo.append(changeNumToEnglish(str(titleAgahi[0])))\n\n\t\tfor i in range(5):\n\t\t\tif len(baseInfo2) == 4:\n\t\t\t\tbaseInfo2.insert(1,'سایر')\n\t\t\ttmp = baseInfo2[i]\n\t\t\ttmp = list(tmp)\n\t\t\ttmp = ''.join(tmp[:]) \n\n\t\t\t# data cleaning\n\t\t\ttmp = changeNumToEnglish(tmp)\n\t\t\tallInfo.append(tmp)\n\n\n\t\tif baseInfo2[1] not in brandExist:\n\t\t\tbrandExist.append(baseInfo2[1])\n\n\t\ttmpExp = '' # cleamimg data\n\t\ttry:\n\t\t\ttmpExp = changeNumToEnglish(exp[0])\n\t\texcept:\n\t\t\ttmpExp = ' '\n\t\tallInfo.append(tmpExp)\n\t\twriteFile.writerow(allInfo) \n\t\tallAdds.append(allInfo)\n\t\tcounter += 1\n\t\tprint('OK '+ str(step+1) + '.' + str(links.index(link)+1))\t\n\n\tfindLastPostDateReg = \"\\\"last_post_date\\\":([0-9]+)\\,\" #update last post date to give new data\n\tlast = re.findall(findLastPostDateReg, txt)\n\ttmp = list(payload)\n\tfor i in range(15):\n\t\ttmp[i+74] = last[0][i]\n\ttmp = ''.join(tmp)\n\tpayload = tmp\t\n\n\n\ttmpLast = last\n\nprint(\"total:\", str(counter))\nfile.close()\n\n\nbrandExist.sort() # all brands we have in data\nallAdds.sort(key=lambda x: x[2])\n\nadsDict = {}\n\n\n# for i in range(len(brandExist)):\n# \ttempList = []\n# \tfor j in range(len(allAdds)):\n# \t\tif allAdds[j][2] == brandExist[i]:\n# \t\t\ttempList.append(allAdds[j])\n# \tadsDict[brandExist[i]] = tempList\t\t\n\n\n#--------------visualization-----------------\nusageTmp, yearTmp, brandTmp, priceTmp = [], [], [], []\nfor ad in allAdds:\n\tusageTmp.append(int(ad[5]))\n\tyearTmp.append(1400 - int(ad[3]))\n\tbrandTmp.append(brandExist.index(ad[2]))\n\tpriceTmp.append(int(ad[4]))\n\n\n# draw box plot of year, usage and brand and remove outlier data\nplt.boxplot(usageTmp)\nplt.title('usage')\nplt.show()\n\nq1 = numpy.quantile(usageTmp, 0.25)\nq3 = numpy.quantile(usageTmp, 0.75)\nmed = numpy.median(usageTmp)\niqr = q3-q1\nupper_bound = q3+(1.5*iqr)\nlower_bound = q1-(1.5*iqr)\n\ntmp = []\nfor i in range(len(usageTmp)):\n\tif usageTmp[i] > upper_bound or usageTmp[i] < lower_bound:\n\t\ttmp.append(usageTmp.index(usageTmp[i]))\ntmp.reverse()\t\t\nfor i in range(len(tmp)):\n\tn = usageTmp.pop(tmp[i])\n\tn = brandTmp.pop(tmp[i])\n\tn = yearTmp.pop(tmp[i])\n\tn = priceTmp.pop(tmp[i])\t\t\n#--------------------\nplt.boxplot(yearTmp)\nplt.title('year')\nplt.show()\n\nq1 = numpy.quantile(yearTmp, 0.25)\nq3 = numpy.quantile(yearTmp, 0.75)\nmed = numpy.median(yearTmp)\niqr = q3-q1\nupper_bound = q3+(1.5*iqr)\nlower_bound = q1-(1.5*iqr)\n\ntmp = []\nfor i in range(len(yearTmp)):\n\tif yearTmp[i] > upper_bound or yearTmp[i] < lower_bound:\n\t\ttmp.append(yearTmp.index(yearTmp[i]))\ntmp.reverse()\t\t\nfor i in range(len(tmp)):\n\tn = usageTmp.pop(tmp[i])\n\tn = brandTmp.pop(tmp[i])\n\tn = yearTmp.pop(tmp[i])\n\tn = priceTmp.pop(tmp[i])\n\n#--------------------\nplt.boxplot(brandTmp)\nplt.title('brand')\nplt.show()\n\nq1 = numpy.quantile(brandTmp, 0.25)\nq3 = numpy.quantile(brandTmp, 0.75)\nmed = numpy.median(brandTmp)\niqr = q3-q1\nupper_bound = q3+(1.5*iqr)\nlower_bound = q1-(1.5*iqr)\n\ntmp = []\nfor i in range(len(brandTmp)):\n\tif brandTmp[i] > upper_bound or brandTmp[i] < lower_bound:\n\t\ttmp.append(brandTmp.index(brandTmp[i]))\ntmp.reverse()\t\t\nfor i in range(len(tmp)):\n\tn = usageTmp.pop(tmp[i])\n\tn = brandTmp.pop(tmp[i])\n\tn = yearTmp.pop(tmp[i])\n\tn = priceTmp.pop(tmp[i])\n\n#--------------------\nprint(\"remove outliers\")\nprint('OK Data :', str(len(priceTmp)))\n\nfor i in range(len(yearTmp)):\n\tif priceTmp[i] > 30000000:\n\t\tplt.plot(yearTmp[i], usageTmp[i], 'go')\n\telif priceTmp[i] < 2500000:\n\t\tplt.plot(yearTmp[i], usageTmp[i], 'ro')\n\telse:\n\t\tplt.plot(yearTmp[i], usageTmp[i], 'yo')\t\t\nplt.xlabel('year') \nplt.ylabel('usage')\n#find linear equivalence of plot\nlinear_model=numpy.polyfit(yearTmp, usageTmp,1)\nlinear_model_fn=numpy.poly1d(linear_model)\nx_s=numpy.arange(min(yearTmp), max(yearTmp)+1)\nplt.plot(x_s,linear_model_fn(x_s),color=\"blue\")\n\nplt.title(numpy.poly1d(linear_model_fn))\nplt.show()\n\n\nfor i in range(len(yearTmp)):\n\tif priceTmp[i] > 30000000:\n\t\tplt.plot(brandTmp[i], usageTmp[i], 'go')\n\telif priceTmp[i] < 25000000:\n\t\tplt.plot(brandTmp[i], usageTmp[i], 'ro')\n\telse:\n\t\tplt.plot(brandTmp[i], usageTmp[i], 'yo')\t\nplt.xlabel('brand') \nplt.ylabel('usage')\n\nlinear_model=numpy.polyfit(brandTmp, usageTmp,1)\nlinear_model_fn=numpy.poly1d(linear_model)\nx_s=numpy.arange(min(brandTmp), max(brandTmp)+1)\nplt.plot(x_s,linear_model_fn(x_s),color=\"blue\")\n\nplt.title(numpy.poly1d(linear_model_fn))\nplt.show()\n\n\nfor i in range(len(yearTmp)):\n\tif priceTmp[i] > 30000000:\n\t\tplt.plot(brandTmp[i], yearTmp[i], 'go')\n\telif priceTmp[i] < 25000000:\n\t\tplt.plot(brandTmp[i], yearTmp[i], 'ro')\n\telse:\n\t\tplt.plot(brandTmp[i], yearTmp[i], 'yo')\nplt.xlabel('brand') \nplt.ylabel('year')\n\nlinear_model=numpy.polyfit(brandTmp, yearTmp,1)\nlinear_model_fn=numpy.poly1d(linear_model)\nx_s=numpy.arange(min(brandTmp), max(brandTmp)+1)\nplt.plot(x_s,linear_model_fn(x_s),color=\"blue\")\n\nplt.title(numpy.poly1d(linear_model_fn))\nplt.show()\n\n\nplot = plt.axes(projection = '3d')\ncolors = []\nfor i in range(len(yearTmp)):\n\tif priceTmp[i] > 3000000:\n\t\tcolors.append('green')\n\telif priceTmp[i] < 2500000:\n\t\tcolors.append('red')\n\telse:\n\t\tcolors.append('yellow')\t\t\ncolors = numpy.array(colors)\t\nplot.scatter(yearTmp, usageTmp, brandTmp, c = colors)\nplot.set_title('3d plot (year - usage - brand)')\nplt.show()\n\n\n#--------------normalization-----------------\n\n# usageTmp = numpy.asarray(usageTmp)\n# usageTmp = preprocessing.normalize([usageTmp])\n# usageTmp = (usageTmp.tolist())[0]\n\n# yearTmp = numpy.asarray(yearTmp)\n# yearTmp = preprocessing.normalize([yearTmp])\n# yearTmp = (yearTmp.tolist())[0]\n\n# brandTmp = numpy.asarray(brandTmp)\n# brandTmp = preprocessing.normalize([brandTmp])\n# brandTmp = (brandTmp.tolist())[0]\n\nfor i in range(len(usageTmp)): # normalize data formula = (x - xMin) / (xMax - xMin)\n\tusageTmp[i] = (usageTmp[i] - min(usageTmp)) / (max(usageTmp) - min(usageTmp))\n\tyearTmp[i] = (yearTmp[i] - min(yearTmp)) / (max(yearTmp) - min(yearTmp))\n\tbrandTmp[i] = (brandTmp[i] - min(brandTmp)) / (max(brandTmp) - min(brandTmp))\n\n\t\t#---------------------------\n\nfor i in range(len(yearTmp)):\n\tif priceTmp[i] > 30000000:\n\t\tplt.plot(yearTmp[i], usageTmp[i], 'go')\n\telif priceTmp[i] < 25000000:\n\t\tplt.plot(yearTmp[i], usageTmp[i], 'ro')\n\telse:\n\t\tplt.plot(yearTmp[i], usageTmp[i], 'yo')\t\nplt.xlabel('year') \nplt.ylabel('usage')\n\nlinear_model=numpy.polyfit(yearTmp, usageTmp,1)\nlinear_model_fn=numpy.poly1d(linear_model)\nx_s=numpy.arange(min(yearTmp), max(yearTmp)+1)\nplt.plot(x_s,linear_model_fn(x_s),color=\"blue\")\n\nplt.title('normalize' + str(numpy.poly1d(linear_model_fn)))\nplt.show()\n\nfor i in range(len(yearTmp)):\n\tif priceTmp[i] > 30000000:\n\t\tplt.plot(brandTmp[i], usageTmp[i], 'go')\n\telif priceTmp[i] < 25000000:\n\t\tplt.plot(brandTmp[i], usageTmp[i], 'ro')\n\telse:\n\t\tplt.plot(brandTmp[i], usageTmp[i], 'yo')\nplt.xlabel('brand') \nplt.ylabel('usage')\n\nlinear_model=numpy.polyfit(brandTmp, usageTmp,1)\nlinear_model_fn=numpy.poly1d(linear_model)\nx_s=numpy.arange(min(brandTmp), max(brandTmp)+1)\nplt.plot(x_s,linear_model_fn(x_s),color=\"blue\")\n\nplt.title('normalize' + str(numpy.poly1d(linear_model_fn)))\nplt.show()\n\nfor i in range(len(yearTmp)):\n\tif priceTmp[i] > 30000000:\n\t\tplt.plot(brandTmp[i], yearTmp[i], 'go')\n\telif priceTmp[i] < 25000000:\n\t\tplt.plot(brandTmp[i], yearTmp[i], 'ro')\n\telse:\n\t\tplt.plot(brandTmp[i], yearTmp[i], 'yo')\nplt.xlabel('brand') \nplt.ylabel('year')\n\nlinear_model=numpy.polyfit(brandTmp, yearTmp,1)\nlinear_model_fn=numpy.poly1d(linear_model)\nx_s=numpy.arange(min(brandTmp), max(brandTmp)+1)\nplt.plot(x_s,linear_model_fn(x_s),color=\"blue\")\n\nplt.title('normalize' + str(numpy.poly1d(linear_model_fn)))\nplt.show()\n\n\nplot = plt.axes(projection = '3d')\ncolors = []\nfor i in range(len(yearTmp)):\n\tif priceTmp[i] > 3000000:\n\t\tcolors.append('green')\n\telif priceTmp[i] < 2500000:\n\t\tcolors.append('red')\n\telse:\n\t\tcolors.append('yellow')\t\t\ncolors = numpy.array(colors)\t\t\nplot.scatter(yearTmp, usageTmp, brandTmp, c = colors)\nplot.set_title('Normalize 3d plot (year - usage - brand)')\nplt.show()\n\n# T-test and find two more similar groups\nT_test = []\nt, p = ttest_ind(usageTmp, yearTmp)\nT_test.append(p)\nt, p = ttest_ind(usageTmp, brandTmp)\nT_test.append(p)\nt, p = ttest_ind(yearTmp, brandTmp)\nT_test.append(p)\n\nind = T_test.index(max(T_test))\nif ind == 0: print('most similarity : usage & year')\nelif ind == 1: print('most similarity : usage & brand')\nelse: print('most similarity : year & brand')\n\n\n# calculate PCA\narr = [usageTmp, yearTmp, brandTmp]\npca = PCA(n_components=3)\np = pca.fit(arr)\nx = p.components_\n\ntemp = x.tolist()\nx1, x2, x3 = x[0], x[1], x[2]\n\n\nfor i in range(len(yearTmp)):\n\tif priceTmp[i] > average(priceTmp) + 3000000:\n\t\tplt.plot(x1[i], x2[i], 'go')\n\telif priceTmp[i] < average(priceTmp) - 3000000:\n\t\tplt.plot(x1[i], x2[i], 'ro')\n\telse:\n\t\tplt.plot(x1[i], x2[i], 'yo')\nplt.title('after PCA')\nlinear_model=numpy.polyfit(x1, x2,1)\nlinear_model_fn=numpy.poly1d(linear_model)\nx_s=numpy.arange(min(x1), max(x1)+1)\nplt.plot(x_s,linear_model_fn(x_s),color=\"blue\")\nplt.show()\n\nfor i in range(len(yearTmp)):\n\tif priceTmp[i] > average(priceTmp) + 3000000:\n\t\tplt.plot(x1[i], x3[i], 'go')\n\telif priceTmp[i] < average(priceTmp) - 3000000:\n\t\tplt.plot(x1[i], x3[i], 'ro')\n\telse:\n\t\tplt.plot(x1[i], x3[i], 'yo')\nplt.title('after PCA')\nlinear_model=numpy.polyfit(x1, x3,1)\nlinear_model_fn=numpy.poly1d(linear_model)\nx_s=numpy.arange(min(x1), max(x1)+1)\nplt.plot(x_s,linear_model_fn(x_s),color=\"blue\")\nplt.show()\n\nfor i in range(len(yearTmp)):\n\tif priceTmp[i] > average(priceTmp) + 3000000:\n\t\tplt.plot(x2[i], x3[i], 'go')\n\telif priceTmp[i] < average(priceTmp) - 3000000:\n\t\tplt.plot(x2[i], x3[i], 'ro')\n\telse:\n\t\tplt.plot(x2[i], x3[i], 'yo')\nplt.title('after PCA')\nlinear_model=numpy.polyfit(x2, x3,1)\nlinear_model_fn=numpy.poly1d(linear_model)\nx_s=numpy.arange(min(x2), max(x2)+1)\nplt.plot(x_s,linear_model_fn(x_s),color=\"blue\")\nplt.show()\n\n\n# for i in range(len(allAdds)):\n\t\n# \tusageTmp[i] = (usageTmp[i] - min(usageTmp))/(max(usageTmp) - min(usageTmp))\n# \tyearTmp[i] = (yearTmp[i] - min(yearTmp))/(max(yearTmp) - min(yearTmp))\n# \tbrandTmp[i] = (brandTmp[i] - min(brandTmp))/(max(brandTmp) - min(brandTmp))\n\n# data = pandas.read_csv('C:/Users/Lenovo/Desktop/tamrin/Data_Divar/out.csv')\n# X = data[['brand', 'year', 'usage']]\n# y = data[['price']]\n\n# regr = linear_model.LinearRegression()\n# regr.fit(X, y)\n\n# predictedPrice = regr.predict([['بنلی 300' , 1399, 1000]])\n\n","sub_path":"req.py","file_name":"req.py","file_ext":"py","file_size_in_byte":14488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"165314085","text":"# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP2_6_C&lang=jp\n# Lower Bound : python3\n# 2018.11.26 yonezawa\n\nimport sys\ninput = sys.stdin.readline\n\ndef LowerBound(d,l):\n max = len(l) -1\n min = 0\n mid = max // 2\n while True:\n if (l[mid] > d ):\n max = mid\n elif (l[mid] == d ):\n while l[mid] == d and mid >= 0:\n mid -= 1\n return mid + 1\n else:\n min = mid\n mid = (max + min ) // 2 \n\n if ( mid == max or mid == min ):\n if ( l[mid] == d or l[max] == d):\n while l[mid] == d and mid >= 0:\n mid -= 1\n return mid+1\n if ( l[max] < d ):\n return len(l)\n if ( l[mid] > d):\n return min\n return max\ndef main():\n nl = int(input())\n l = list(map(int,input().split()))\n\n for i in range(int(input())):\n n = int(input())\n result = LowerBound(n,l)\n print (result)\n\n\nif __name__ == '__main__':\n main()","sub_path":"ITP2/ITP2_6_C.py","file_name":"ITP2_6_C.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"415643752","text":"import sys\nimport file_parser as parser\nimport numpy as np\nimport random\nimport math\nfrom PIL import Image\n\n'''\n Perceptron object that has\n - weights[size_of_input]\n - bias\n - learning_rate\n The object can be trained with given input and then\n later make it guess on given input.\n'''\nclass Perceptron:\n def __init__(self, learn_rate, size_of_input):\n self.learning_rate = learn_rate\n self.weights = self.generate_random_weights(size_of_input)\n self.bias = 1\n\n # Returns dot-product of given input and weights + bias\n def calculate_sum(self, input_data):\n return np.dot(self.weights, input_data) + self.bias\n\n # Generates list with weights that are between 0 and 1\n def generate_random_weights(self, size):\n return [random.uniform(0, 1) for _ in range(size)]\n\n # Returns sigmoid of given input\n def sigmoid(self, x):\n return math.exp(-np.logaddexp(0, -x))\n\n # Returns weighted input data as sigmoid\n def calculate_output(self, input_data):\n return self.sigmoid(self.calculate_sum(input_data))\n\n # Perceptron will adjust weights depended on the error from its guess\n def learn_from_result(self, input_data, output_result, actual_result):\n error = actual_result - output_result\n for i in range(len(self.weights)):\n self.weights[i] = self.weights[i] + input_data[i] * error * self.learning_rate\n\n # Perceptron will calculate output for given input and then learn from results\n def train(self, input_data, desired_output):\n self.learn_from_result(input_data, self.calculate_output(input_data), desired_output)\n\n\n# Desired value for happy\ndef get_desired_val_for_happy(val):\n return 1 if val == 1 else 0\n\n\n# Desired value for sad\ndef get_desired_val_for_sad(val):\n return 1 if val == 2 else 0\n\n\n# Desired value for mischievous\ndef get_desired_val_for_mischievous(val):\n return 1 if val == 3 else 0\n\n\n# Desired value for mad\ndef get_desired_val_for_mad(val):\n return 1 if val == 4 else 0\n\n\n# Used only for debug purpose\ndef print_if_not_debug(debug, key, val):\n if not debug:\n print(str(key) + \" \" + str(val))\n\n\n# Sorts image list by the number\ndef sort_by_image_num(a):\n return int(a[5:])\n\n\n# Normalizes input data by setting every number to 1 if it's\n# above 10, else 0\ndef normalize_list(data):\n for key2 in data:\n for i in range(0, len(data[key2])):\n if data[key2][i] > 10:\n data[key2][i] = 1\n else:\n data[key2][i] = 0\n\n\n# Returns true if the bottom of image has number 31 in it\ndef should_rotate(list_to_rotate):\n return True if 31 in list_to_rotate[15 * 20:] else False\n\n\nif __name__ == \"__main__\":\n\n # For debug purposes\n debug = True\n\n train_data = parser.create_dictionary_for_images(sys.argv[1])\n training_answers = parser.create_dictionary_for_labels(sys.argv[2])\n if debug:\n test_answers = parser.create_dictionary_for_labels(\"test_answers.txt\")\n test_data = parser.create_dictionary_for_images(sys.argv[3])\n\n # Rotate train data\n for key in train_data:\n while should_rotate(train_data[key]):\n train_data[key] = np.reshape(train_data[key], (20, 20))\n train_data[key] = np.rot90(train_data[key], 1)\n train_data[key] = train_data[key].ravel()\n\n # Rotate test data\n for key in test_data:\n while should_rotate(test_data[key]):\n test_data[key] = np.reshape(test_data[key], (20, 20))\n test_data[key] = np.rot90(test_data[key], 1)\n test_data[key] = test_data[key].ravel()\n\n # Normalizes training data and test data\n normalize_list(train_data)\n normalize_list(test_data)\n\n learning_rate = 0.5\n size_of_data = 400\n\n # Creates one perceptron for each classification problem\n happy = Perceptron(learning_rate, size_of_data)\n sad = Perceptron(learning_rate, size_of_data)\n mischievous = Perceptron(learning_rate, size_of_data)\n mad = Perceptron(learning_rate, size_of_data)\n\n # Trains every perceptron 50 times with the same training data\n for _ in range(0, 50):\n for key in train_data:\n happy.train(train_data[key], get_desired_val_for_happy(training_answers[key]))\n sad.train(train_data[key], get_desired_val_for_sad(training_answers[key]))\n mischievous.train(train_data[key], get_desired_val_for_mischievous(training_answers[key]))\n mad.train(train_data[key], get_desired_val_for_mad(training_answers[key]))\n\n keys = test_data.keys()\n num_correct = 0\n correct_answer = 0\n\n # Test perceptrons on test data\n for key in sorted(keys, key=sort_by_image_num):\n\n num_happy = happy.calculate_output(test_data[key])\n num_sad = sad.calculate_output(test_data[key])\n num_mis = mischievous.calculate_output(test_data[key])\n num_mad = mad.calculate_output(test_data[key])\n\n # The perceptron with highest output wins\n if num_happy > max(num_sad, num_mis, num_mad):\n correct_answer = 1\n elif num_sad > max(num_mis, num_mad):\n correct_answer = 2\n elif num_mis > num_mad:\n correct_answer = 3\n else:\n correct_answer = 4\n\n print_if_not_debug(debug, key, correct_answer)\n if debug:\n if correct_answer == test_answers[key]:\n num_correct += 1\n if debug:\n print(\"percept was \", num_correct, \" out of\", len(test_data), \"correct after training.\")\n\n\n width = 20\n height = 20\n background = (255, 255, 255, 255)\n image = Image.new(\"RGBA\", (width, height), background)\n pixels = image.load()\n happyWeights = np.reshape(mischievous.weights, (20, 20))\n print(happyWeights)\n for i in range(20):\n for j in range(20):\n grayscale = int(round(255 - 255 * happyWeights[i, j]))\n pixels[i, j] = (grayscale, grayscale, grayscale)\n image.save(\"mis_image.png\")\n","sub_path":"faces.py","file_name":"faces.py","file_ext":"py","file_size_in_byte":6044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"77168584","text":"import logging\r\nlogger = logging.getLogger(\"Listener.modules.email\")\r\n\r\ndef send(script_name , error, documento):\r\n\r\n\timport time\r\n\timport smtplib\r\n\tfrom email.mime.text import MIMEText\r\n\r\n\thora = time.strftime(\"%d/%m/%Y-%H:%M:%S\")\r\n\r\n\t# define content\r\n\trecipients = [\"kevin.braga@jiveinvestments.com\"]\r\n\tsender = \"alerta.falhas@gmail.com\"\r\n\r\n\tsubject = \"ERRO - Execução\"\r\n\r\n\tbody = \"\"\"ERRO : {0}\r\n\tScript: {1} \r\n\tHorário: {2} \r\n\tRegistro : {3}\"\"\".format(error , script_name, hora, documento)\r\n\r\n\t# make up message\r\n\tmsg = MIMEText(body)\r\n\tmsg['Subject'] = subject\r\n\tmsg['From'] = sender\r\n\tmsg['To'] = \", \".join(recipients)\r\n\r\n\t# sending\r\n\ttry:\r\n\t\tsession = smtplib.SMTP(\"smtp.gmail.com:587\")\r\n\t\tsession.starttls()\r\n\t\tsession.login(sender, '.')\r\n\t\tsend_it = session.sendmail(sender, recipients, msg.as_string())\r\n\t\tsession.quit()\r\n\texcept Exception as error:\r\n\t\tlogger.error('<ERROR: %s>'%error)\r\n\r\n\r\n","sub_path":"modules/_email.py","file_name":"_email.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"57035439","text":"# Importing necessary libraries.\n\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\nimport torchvision\nfrom torchvision import datasets, transforms, models\nimport matplotlib.pyplot as plt\nimport os, random\nfrom PIL import Image\nimport argparse\nfrom extra import save_checkpoint, load_checkpoint\nfrom torchvision.datasets import ImageFolder\n\n\ndef parse_args():\n \n # For the coding parser function I referred to the python documentation \n # in this link \"https://docs.python.org/3/library/argparse.html\".\n # Using argparse module will help the user to input values through the command line during runtime.\n # It is not necessary to see the program while using it, as arguments were added for important values.\n \n par = argparse.ArgumentParser(description=\"Training process\")\n par.add_argument('--data_dir', action='store')\n par.add_argument('--arch', dest='arch', default='vgg16', choices=['vgg16', 'vgg19'])\n par.add_argument('--hidden_units', dest='hidden_units', default='512')\n par.add_argument('--epochs', dest='epochs', default='1')\n par.add_argument('--learning_rate', dest='learning_rate', default='0.0005')\n par.add_argument('--gpu', action=\"store_true\", default=True)\n return par.parse_args()\n\ndef main():\n \n args = parse_args()\n \n # For the code below I referred to the part8 Transfer learning solution in this module.\n # Directories assignment.\n \n data_dir = 'flowers'\n train_dir = data_dir + '/train'\n valid_dir = data_dir + '/valid'\n test_dir = data_dir + '/test'\n \n # Following transforms from the torchvision are used to modify the image. The rotation method helps to rotate the image,\n # crop method for cropping, resize method to resize the image, flip method for flipping the image, and \n # normalize method to set the standard deviation and mean values.\n \n train_transforms = transforms.Compose([transforms.RandomRotation(30),\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n \n valid_transforms = transforms.Compose([transforms.Resize(224),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n \n test_transforms = transforms.Compose([transforms.Resize(224),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n \n # The image_datasets take images from the directory and apply the above training,validation and testing transform.\n \n image_datasets = [ImageFolder(train_dir, transform=train_transforms),\n ImageFolder(valid_dir, transform=valid_transforms),\n ImageFolder(test_dir, transform=test_transforms)]\n \n # The dataloaders take data from image_datasets in the batch size of 64 and shuffles the remaining data.\n \n dataloaders = [torch.utils.data.DataLoader(image_datasets[0], batch_size=64, shuffle=True),\n torch.utils.data.DataLoader(image_datasets[1], batch_size=64),\n torch.utils.data.DataLoader(image_datasets[2], batch_size=64)]\n \n # User can select the model through argparse from two options, the default model is vgg16.\n \n model = getattr(models, args.arch)(pretrained=True)\n \n # Changes the device to GPU if it is available otherwise it will run in CPU mode.\n \n gorc = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") \n \n # To freeze the parameters.\n \n for param in model.parameters():\n param.requires_grad = False\n \n # The first line of code applies a linear transformation and passes the output to ReLU activation. \n # After applying dropout to prevent overfitting, output passed as input to the linear transformation.\n # The last line will apply the softmax function to the output unit.\n \n model.classifier = nn.Sequential(nn.Linear(25088, 1024),\n nn.ReLU(),\n nn.Dropout(0.5),\n nn.Linear(1024, 102),\n nn.LogSoftmax(dim=1))\n \n # If and elif statements help the user to choose the model provided in the argparse.\n \n if args.arch == \"vgg16\":\n \n feature_num = model.classifier[0].in_features\n model.classifier = nn.Sequential(nn.Linear(feature_num, 1024),\n nn.ReLU(),\n nn.Dropout(0.5),\n nn.Linear(1024, 102),\n nn.LogSoftmax(dim=1))\n\n elif args.arch == \"vgg19\":\n \n feature_num = model.classifier[0].in_features\n model.classifier = nn.Sequential(nn.Linear(feature_num, 1024),\n nn.ReLU(),\n nn.Dropout(0.5),\n nn.Linear(1024, 102),\n nn.LogSoftmax(dim=1))\n \n # Below statements call functions save_checkpoint function, argparse function, and optimizer (used\n # to update wieghts).\n \n criterion = nn.NLLLoss()\n optimizer = optim.Adam(model.classifier.parameters(), lr=float(args.learning_rate))\n model.to(gorc);\n epochs = int(args.epochs)\n class_index = image_datasets[0].class_to_idx\n gpu = args.gpu\n train(model, criterion, optimizer, dataloaders, epochs,gpu)\n model.class_to_idx = class_index\n save_checkpoint(model, optimizer, args, model.classifier)\n\ndef train(model, criterion, optimizer, dataloaders, epochs,gpu):\n \n # For the code below I referred to the part8 Transfer learning solution in this module. \n # Changes the device to GPU if it is available otherwise it will run in CPU mode.\n \n gorc = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") \n \n # Intializing values\n \n print_every = 5\n run_loss = 0\n step = 0\n \n for epoch in range(epochs):\n \n # Code for training data.\n \n for inputs, labels in dataloaders[0]:\n \n step += 1\n \n # Setting for the available device.\n \n inputs, labels = inputs.to(gorc), labels.to(gorc)\n \n # Multiple backward passes with the same parameters cause gradients to accumulate. \n # Setting the optimizer to zero_grad to prevent gradients from previous training batches.\n \n optimizer.zero_grad()\n \n # Forward pass backward pass and updating the weights.\n \n logps = model.forward(inputs)\n loss = criterion(logps, labels)\n loss.backward()\n optimizer.step()\n run_loss += loss.item()\n \n if step % print_every == 0:\n \n valid_loss = 0\n accuracy = 0\n \n # Setting the dropout probability to zero for validation.\n \n model.eval()\n \n # Turning off gradients.\n \n with torch.no_grad():\n \n # Code for validation data.\n \n for inputs, labels in dataloaders[1]:\n \n inputs, labels = inputs.to(gorc), labels.to(gorc)\n logps = model(inputs)\n batch_loss = criterion(logps, labels)\n valid_loss += batch_loss.item()\n\n # Calculate accuracy\n # Applying exponential to the probabilities.\n \n ps = torch.exp(logps)\n \n # Default value for topk is 5, which will help to display top 5 probabilities and indices.\n \n top_p, top_class = ps.topk(1, dim=1)\n \n # By using equals checking whether labels and top_class are matching. Applied (.view) \n # to labels to get the same shape as top_class.\n \n equals = top_class == labels.view(*top_class.shape)\n \n # Used mean to calculate the accuracy for the equals, here the equals is ByteTensor but the mean\n # is applied on floattensor so converting it into floattensor.\n # torch. mean returns scalar-tensor, to get the float values used the item().\n \n accuracy += torch.mean(equals.type(torch.FloatTensor)).item()\n \n # Printing epoch, training loss, testing loss, and test accuracy.\n \n print(f\"Epoch {epoch+1}/{epochs}.. \"\n f\"Train loss: {run_loss/print_every:.3f}.. \"\n f\"Valid loss: {valid_loss/len(dataloaders[1]):.3f}.. \"\n f\"valid accuracy: {accuracy/len(dataloaders[1]):.3f}\")\n \n # Resetting running loss to zero and changing to training mode.\n \n run_loss = 0\n model.train()\n \n test_loss = 0\n accuracy = 0\n \n # Setting the dropout probability to zero for testing.\n \n model.eval()\n \n # Turning off gradients.\n \n with torch.no_grad():\n \n # Code for testing data.\n \n for inputs, labels in dataloaders[2]:\n \n inputs, labels = inputs.to(gorc), labels.to(gorc)\n logps = model.forward(inputs)\n batch_loss = criterion(logps, labels)\n test_loss += batch_loss.item()\n \n # Calculate accuracy\n # Applying exponential to the probabilities.\n \n ps = torch.exp(logps)\n \n # Default value for topk is 5, which will help to display top 5 probabilities and indices.\n \n top_p, top_class = ps.topk(1, dim=1)\n \n # By using equals checking whether labels and top_class are matching. Applied (.view) \n # to labels to get the same shape as top_class.\n \n equals = top_class == labels.view(*top_class.shape)\n \n # Used mean to calculate the accuracy for the equals, here the equals is ByteTensor but the mean\n # is applied on floattensor so converting it into floattensor.\n # torch. mean returns scalar-tensor, to get the float values used the item().\n \n accuracy += torch.mean(equals.type(torch.FloatTensor)).item()\n \n # Printing testing loss, and test accuracy.\n \n print(f\"Test loss: {test_loss/len(dataloaders[2]):.3f}.. \"\n f\"Test accuracy: {accuracy/len(dataloaders[2]):.3f}\")\n\nif __name__ == \"__main__\":\n main()","sub_path":"Image Classifier/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":11695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"302116505","text":"from django.core.exceptions import ObjectDoesNotExist\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.urls import reverse\n\nfrom LEDApp.forms import DurationForm, CircleForm, GridForm, LineForm, ShapeForm, SquareForm\nfrom LEDApp.led_strip import LedStrip\nfrom LEDApp.models import Circle, Grid, Line, Shape, Square\n\nled_strip = LedStrip()\n\ndef change_shape(request):\n\t\"\"\"Clear shape database and load shape view\"\"\"\n\t\n\ttry:\n\t\ts = Shape.objects.get(pk =1 )\n\t\ts.delete()\n\texcept:\n\t\tpass\n\t\n\treturn HttpResponseRedirect(reverse('shape'))\n\ndef circle_settings(request):\n\t\"\"\"View function for circle settings form\"\"\"\n\t\n\t# Ensure that shape has been set to circle\n\ttry:\n\t\t# try and retrieve shape\n\t\tshape = Shape.objects.get(pk = 1)\n\t\t\n\t\t# test if the shape is not set to circle\n\t\tif shape.shape != 'C':\n\t\t\t# Redirect if the shape is not set to circle\n\t\t\tshape_url_names = {\n\t\t\t\t'G': \"grid-settings\",\n\t\t\t\t'L': \"line-settings\",\n\t\t\t\t'S': \"square-settings\",\n\t\t\t\t}\n\t\t\treturn HttpResponseRedirect(reverse(shape_url_names[shape.shape]))\n\t\n\texcept Shape.DoesNotExist:\n\t\t# The selected shape hasn't been set\n\t\treturn HttpResponseRedirect(reverse('shape'))\t\n\t\n\t# if this is a POST request then process the Form data\n\tif request.method == \"POST\":\n\t\t\n\t\t# Check if settings already were created. Will have PK of 1\n\t\ttry:\n\t\t\ts = Circle.objects.get(pk = 1)\n\t\t\tform = CircleForm(request.POST, instance = s)\n\t\t\t\n\t\texcept Circle.DoesNotExist:\n\t\t\t# First time creating settings. Load default form.\n\t\t\tform = CircleForm(request.POST)\n\t\t\n\t\t# Check if the form is valid:\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\tled_strip.reload_map(shape.shape)\n\t\t\treturn HttpResponseRedirect(reverse('home'))\n\t\n\telse:\n\t\ttry:\n\t\t\ts = Circle.objects.get(pk = 1)\n\t\t\tform = CircleForm(instance = s)\n\t\texcept ObjectDoesNotExist:\n\t\t\tform = CircleForm()\n\t\n\tcontext = {\n\t\t'form': form,\n\t\t} \n\t\n\treturn render(request, 'LEDApp/circle_settings.html', context)\n\ndef colours(request):\n\t\n\tif request.method == 'POST':\n\t\t\n\t\tform = DurationForm(request.POST)\n\t\t\n\t\tif form.is_valid():\n\t\t\trgb = request.POST.get('rgb')\n\t\t\tduration = request.POST.get('duration')\n\t\t\tled_strip.set_colour(rgb, duration)\n\t\t\t\n\t\t\treturn HttpResponseRedirect(reverse('colours'))\n\t\n\telse:\n\t\tform = DurationForm()\n\t\n\tcolours = (\n\t\t#hex, rgb\n\t\t(\"#ff0000\", \"255-0-0\"),\n\t\t(\"#ff4000\", \"255-64-0\"),\n\t\t(\"#ff8000\", \"255-128-0\"),\n\t\t(\"#ffbf00\", \"255-191-0\"),\n\t\t(\"#ffff00\", \"255-255-0\"),\n\t\t(\"#bfff00\",\t\"191-255-0\"),\n\t\t(\"#80ff00\",\t\"128-255-0\"),\n\t\t(\"#40ff00\",\t\"64-255-0\"),\n\t\t(\"#00ff00\",\t\"0-255-0\"),\n\t\t(\"#00ff40\", \"0-255-64\"),\n\t\t(\"#00ff80\",\t\"0-255-128\"),\n\t\t(\"#00ffbf\",\t\"0-255-191\"),\n\t\t(\"#00ffff\",\t\"0-255-255\"),\n\t\t(\"#00bfff\",\t\"0-191-255\"),\n\t\t(\"#0080ff\",\t\"0-128-255\"),\n\t\t(\"#0040ff\",\t\"0-64-255\"),\n\t\t(\"#0000ff\",\t\"0-0-255\"),\n\t\t(\"#4000ff\",\t\"64-0-255\"),\n\t\t(\"#8000ff\",\t\"128-0-255\"),\n\t\t(\"#bf00ff\",\t\"191-0-255\"),\n\t\t(\"#ff00ff\",\t\"255-0-255\"),\n\t\t(\"#ff00bf\",\t\"255-0-191\"),\n\t\t(\"#ff0080\",\t\"255-0-128\"),\n\t\t(\"#ff0040\",\t\"255-0-64\"),\n\t\t(\"#ff0000\", \"255-0-0\"),\n\t\t)\n\tcontext = {\n\t\t'form': form,\n\t\t'colours': colours,\n\t\t}\n\t\n\treturn render(request, 'LEDApp/colours.html', context)\n\t\ndef home(request):\n\t\"\"\"View function for home page of site\"\"\"\n\t\n\treturn render(request, 'home.html')\n\ndef line_settings(request):\n\t\"\"\"View function for line settings form\"\"\"\n\t\n\t# Ensure that shape has been set to line\n\ttry:\n\t\t# try and retrieve shape\n\t\tshape = Shape.objects.get(pk = 1)\n\t\t\n\t\t# test if the shape is not set to line\n\t\tif shape.shape != 'L':\n\t\t\t# Redirect if the shape is not set to line\n\t\t\tshape_url_names = {\n\t\t\t\t'G': \"grid-settings\",\n\t\t\t\t'C': \"circle-settings\",\n\t\t\t\t'S': \"square-settings\",\n\t\t\t\t}\n\t\t\treturn HttpResponseRedirect(reverse(shape_url_names[shape.shape]))\n\t\n\texcept Shape.DoesNotExist:\n\t\t# The selected shape hasn't been set\n\t\treturn HttpResponseRedirect(reverse('shape'))\t\n\t\n\t# if this is a POST request then process the Form data\n\tif request.method == \"POST\":\n\t\t\n\t\t# Check if settings already were created. Will have PK of 1\n\t\ttry:\n\t\t\ts = Line.objects.get(pk = 1)\n\t\t\tform = LineForm(request.POST, instance = s)\n\t\t\t\n\t\texcept Line.DoesNotExist:\n\t\t\t# First time creating settings. Load blank form.\n\t\t\tform = LineForm(request.POST)\n\t\t\n\t\t# Check if the form is valid:\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\tled_strip.reload_map(shape.shape)\n\t\t\treturn HttpResponseRedirect(reverse('home'))\n\t\n\telse:\n\t\ttry:\n\t\t\ts = Line.objects.get(pk = 1)\n\t\t\tform = LineForm(instance = s)\n\t\texcept ObjectDoesNotExist:\n\t\t\tform = LineForm()\n\t\n\tcontext = {\n\t\t'form': form,\n\t\t} \n\t\n\treturn render(request, 'LEDApp/line_settings.html', context)\n\ndef grid_settings(request):\n\t\"\"\"View function for grid settings form\"\"\"\n\t\n\t# Ensure that shape has been set to grid\n\ttry:\n\t\t# try and retrieve shape\n\t\tshape = Shape.objects.get(pk = 1)\n\t\t\n\t\t# test if the shape is not set to grid\n\t\tif shape.shape != 'G':\n\t\t\t# Redirect if the shape is not set to grid\n\t\t\tshape_url_names = {\n\t\t\t\t'C': \"circle-settings\",\n\t\t\t\t'L': \"line-settings\",\n\t\t\t\t'S': \"square-settings\",\n\t\t\t\t}\n\t\t\treturn HttpResponseRedirect(reverse(shape_url_names[shape.shape]))\n\t\n\texcept Shape.DoesNotExist:\n\t\t# The selected shape hasn't been set\n\t\treturn HttpResponseRedirect(reverse('shape'))\t\n\t\n\t# if this is a POST request then process the Form data\n\tif request.method == \"POST\":\n\t\t\n\t\t# Check if settings already were created. Will have PK of 1\n\t\ttry:\n\t\t\ts = Grid.objects.get(pk = 1)\n\t\t\tform = GridForm(request.POST, instance = s)\n\t\t\t\n\t\texcept Grid.DoesNotExist:\n\t\t\t# First time creating settings. Load blank form.\n\t\t\tform = GridForm(request.POST)\n\t\t\n\t\t# Check if the form is valid:\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\tled_strip.reload_map(shape.shape)\n\t\t\treturn HttpResponseRedirect(reverse('home'))\n\t\n\telse:\n\t\ttry:\n\t\t\ts = Grid.objects.get(pk = 1)\n\t\t\tform = GridForm(instance = s)\n\t\texcept ObjectDoesNotExist:\n\t\t\tform = GridForm()\n\t\n\tcontext = {\n\t\t'form': form,\n\t\t} \n\t\n\treturn render(request, 'LEDApp/grid_settings.html', context)\n\ndef shape(request):\n\t\"\"\"Select shape for LEDs\"\"\"\n\t\n\tshapes = {\n\t\t'C': 'circle-settings',\n\t\t'G': 'grid-settings',\n\t\t'L': 'line-settings',\n\t\t'S': 'square-settings',\n\t\t}\n\n\ttry:\n\t\ts = Shape.objects.get(pk = 1)\n\t\treturn HttpResponseRedirect(reverse(shapes[s.shape]))\n\texcept Shape.DoesNotExist:\t\n\t\n\t\t# if this is a POST request then process the Form data\n\t\tif request.method == \"POST\":\n\t\t\n\t\t\tform = ShapeForm(request.POST)\n\t\t\t\n\t\t\tif form.is_valid():\n\t\t\t\ts = form.save(commit = False)\n\t\t\t\ts.pk = 1\n\t\t\t\ts.save()\t\n\t\t\t\n\t\t\t\treturn HttpResponseRedirect(reverse(shapes[s.shape]))\n\t\t\t\n\t\telse:\n\t\t\tform = ShapeForm()\n\t\n\t\tcontext = {\n\t\t\t'form': form,\n\t\t\t}\n\t\t\n\t\treturn render(request, 'LEDApp/shape.html', context)\n\ndef square_settings(request):\n\t\"\"\"View function for square settings form\"\"\"\n\t\n\t# Ensure that shape has been set to square\n\ttry:\n\t\t# try and retrieve shape\n\t\tshape = Shape.objects.get(pk = 1)\n\t\t\n\t\t# test if the shape is not set to square\n\t\tif shape.shape != 'S':\n\t\t\t# Redirect if the shape is not set to circle\n\t\t\tshape_url_names = {\n\t\t\t\t'G': \"grid-settings\",\n\t\t\t\t'L': \"line-settings\",\n\t\t\t\t'C': \"circle-settings\",\n\t\t\t\t}\n\t\t\treturn HttpResponseRedirect(reverse(shape_url_names[shape.shape]))\n\t\n\texcept Shape.DoesNotExist:\n\t\t# The selected shape hasn't been set\n\t\treturn HttpResponseRedirect(reverse('shape'))\t\n\t\n\t# if this is a POST request then process the Form data\n\tif request.method == \"POST\":\n\t\t\n\t\t# Check if settings already were created. Will have PK of 1\n\t\ttry:\n\t\t\ts = Square.objects.get(pk = 1)\n\t\t\tform = SquareForm(request.POST, instance = s)\n\t\t\t\n\t\texcept Square.DoesNotExist:\n\t\t\t# First time creating settings. Load blank form.\n\t\t\tform = SquareForm(request.POST)\n\t\t\n\t\t# Check if the form is valid:\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\tled_strip.reload_map(shape.shape)\n\t\t\treturn HttpResponseRedirect(reverse('home'))\n\t\n\telse:\n\t\ttry:\n\t\t\ts = Square.objects.get(pk = 1)\n\t\t\tform = SquareForm(instance = s)\n\t\texcept ObjectDoesNotExist:\n\t\t\tform = SquareForm()\n\t\n\tcontext = {\n\t\t'form': form,\n\t\t} \n\t\n\treturn render(request, 'LEDApp/square_settings.html', context)\n\t","sub_path":"LEDApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"284470597","text":"class Solution:\n def angleClock(self, hour: int, minutes: int) -> float:\n hour = hour % 12\n hourArm = (hour * 30) + (minutes * 0.5)\n minuteArm = minutes * 6.0\n diff = abs(hourArm - minuteArm)\n return min(diff, 360 - diff)\n\n\ninput = [\n (1, 57, 76.5),\n (12, 30, 165),\n (3, 30, 75),\n (3, 15, 7.5),\n (4, 50, 155),\n (12, 0, 0),\n]\n\n\ndef getStr(i):\n return str(i[0]) + \":\" + str(i[1]) + \"\\t\" + str(i[2])\n\n\ns = Solution()\nfor i in input:\n an = s.angleClock(i[0], i[1])\n if an == i[2]:\n print(\"Test passed\\t\" + getStr(i))\n else:\n print(\"Test failed\\t\" + getStr(i) + \"\\t\" + str(an))\n","sub_path":"angle_between_clock_hands.py","file_name":"angle_between_clock_hands.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"92770683","text":"#!/usr/bin/env python3\n\nimport mytree\n\nnode = mytree.from_dict({\n \"root\": {\n \"child-1\": [\n \"leaf-1-1\",\n \"leaf-1-2\",\n ],\n \"child-2\": [\n \"leaf-2-1\",\n \"leaf-2-2\",\n ],\n }\n})\npattern = \"root/{child}/leaf-1-1\"\ntry:\n matched = node.match(pattern)\n print(matched.pretty_string())\nexcept AttributeError as e:\n print(\"Match failed because node was not of regex type -> Cast node to RegexNode\")\n regex_node = node.astype(mytree.RegexNode)\n matched = regex_node.match(pattern)\n print(matched.pretty_paths())\n","sub_path":"examples/casting.py","file_name":"casting.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"299683607","text":"import socket\nimport time\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nip = socket.gethostbyname('frpi.ddns.net')\nport = 80\n\nmessage = \"GET / HTTP/1.1\\r\\nHost: frpi.hopto.org\\r\\n\\r\\n\"\n\ns.connect((ip, port))\ns.send(message.encode())\n\ninfo = s.recv(2048)\n\nprint(info.decode('utf-8'))","sub_path":"sock_connect.py","file_name":"sock_connect.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"542633321","text":"def different(num1: list, num2: list):\n diff = []\n for i in num1:\n for j in num2:\n if i == j and i not in diff:\n diff.append(i)\n break\n print(diff)\n\n\ndifferent([1, 2, 3, 2, 3], [2, 3])\ndifferent([2, 4, 5, 9, 4, 2], [2, 2, 4, 4, 4])\n\n\ndef different(num1: list, num2: list):\n a = iter(set(num1))\n print(a)\n b = iter(set(num2))\n print(b)\n for i in b:\n if i in a:\n yield i\n else:\n continue\n # print(list(different()))\n\n\nprint(list(different([1, 2, 3, 2, 3], [2, 3])))\nprint(list(different([2, 4, 5, 9, 4, 2], [2, 2, 4, 4, 4, 8])))\n","sub_path":"python/leecode/求交集.py","file_name":"求交集.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"65269653","text":"from __future__ import annotations\n\nimport asyncio\nimport json\nimport logging\nimport os.path\nfrom pathlib import Path\nfrom typing import Optional, List, Union, Dict, Any\n\nimport requests\n\nfrom checkov.common.bridgecrew.platform_integration import bc_integration\nfrom checkov.common.bridgecrew.platform_key import bridgecrew_dir\nfrom checkov.common.bridgecrew.vulnerability_scanning.image_scanner import image_scanner, TWISTCLI_FILE_NAME\nfrom checkov.common.bridgecrew.vulnerability_scanning.integrations.docker_image_scanning import \\\n docker_image_scanning_integration\nfrom checkov.common.images.image_referencer import ImageReferencer, Image\nfrom checkov.common.output.report import Report, CheckType, merge_reports\nfrom checkov.common.runners.base_runner import filter_ignored_paths, strtobool\nfrom checkov.common.util.file_utils import compress_file_gzip_base64\nfrom checkov.dockerfile.utils import is_docker_file\nfrom checkov.runner_filter import RunnerFilter\nfrom checkov.sca_package.runner import Runner as PackageRunner\n\n\nclass Runner(PackageRunner):\n check_type = CheckType.SCA_IMAGE\n\n def __init__(self) -> None:\n super().__init__()\n self._check_class: Optional[str] = None\n self._code_repo_path: Optional[Path] = None\n self._check_class = f\"{image_scanner.__module__}.{image_scanner.__class__.__qualname__}\"\n self.raw_report: Optional[Dict[str, Any]] = None\n self.base_url = bc_integration.api_url\n self.image_referencers: set[ImageReferencer] | None = None\n\n def should_scan_file(self, filename: str) -> bool:\n return is_docker_file(os.path.basename(filename)) # type:ignore[no-any-return]\n\n def scan(\n self,\n image_id: str,\n dockerfile_path: str,\n runner_filter: RunnerFilter = RunnerFilter(),\n ) -> Dict[str, Any]:\n\n # skip complete run, if flag '--check' was used without a CVE check ID\n if runner_filter.checks and all(not check.startswith(\"CKV_CVE\") for check in runner_filter.checks):\n return {}\n\n if not bc_integration.bc_api_key:\n logging.info(\"The --bc-api-key flag needs to be set to run SCA package scanning\")\n return {}\n\n logging.info(f\"SCA image scanning is scanning the image {image_id}\")\n\n cached_results: Dict[str, Any] = image_scanner.get_scan_results_from_cache(image_id)\n if cached_results:\n logging.info(f\"Found cached scan results of image {image_id}\")\n return cached_results\n\n image_scanner.setup_scan(image_id, dockerfile_path, skip_extract_image_name=False)\n try:\n output_path = Path(f'results-{image_id}.json')\n scan_result = asyncio.run(self.execute_scan(image_id, output_path))\n self.upload_results_to_cache(output_path, image_id)\n logging.info(f\"SCA image scanning successfully scanned the image {image_id}\")\n return scan_result\n except Exception:\n raise\n\n async def execute_scan(\n self,\n image_id: str,\n output_path: Path,\n ) -> Dict[str, Any]:\n command = f\"{Path(bridgecrew_dir) / TWISTCLI_FILE_NAME} images scan --address {docker_image_scanning_integration.get_proxy_address()} --token {docker_image_scanning_integration.get_bc_api_key()} --details --output-file \\\"{output_path}\\\" {image_id}\"\n process = await asyncio.create_subprocess_shell(\n command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE\n )\n\n stdout, stderr = await process.communicate()\n\n # log output for debugging\n logging.debug(stdout.decode())\n\n exit_code = await process.wait()\n\n if exit_code:\n logging.error(stderr.decode())\n return {}\n\n # read the report file\n scan_result: Dict[str, Any] = json.loads(output_path.read_text())\n\n return scan_result\n\n def upload_results_to_cache(self, output_path: Path, image_id: str) -> None:\n image_id_sha = f\"sha256:{image_id}\" if not image_id.startswith(\"sha256:\") else image_id\n\n request_body = {\n \"compressedResult\": compress_file_gzip_base64(str(output_path)),\n \"compressionMethod\": \"gzip\",\n \"id\": image_id_sha\n }\n response = requests.request(\n \"POST\", f\"{self.base_url}/api/v1/vulnerabilities/scan-results\",\n headers=bc_integration.get_default_headers(\"POST\"), data=json.dumps(request_body)\n )\n\n if response.ok:\n logging.info(f\"Successfully uploaded scan results to cache with id={image_id}\")\n else:\n logging.info(f\"Failed to upload scan results to cache with id={image_id}\")\n\n output_path.unlink()\n\n def run(\n self,\n root_folder: Union[str, Path],\n external_checks_dir: Optional[List[str]] = None,\n files: Optional[List[str]] = None,\n runner_filter: RunnerFilter = RunnerFilter(),\n collect_skip_comments: bool = True,\n **kwargs: str\n ) -> Report:\n report = Report(self.check_type)\n\n if \"dockerfile_path\" in kwargs and \"image_id\" in kwargs:\n dockerfile_path = kwargs['dockerfile_path']\n image_id = kwargs['image_id']\n return self.get_image_id_report(dockerfile_path, image_id, runner_filter)\n\n if not strtobool(os.getenv(\"CHECKOV_EXPERIMENTAL_IMAGE_REFERENCING\", \"False\")):\n # experimental flag on running image referencers\n return report\n if not files and not root_folder:\n logging.debug(\"No resources to scan.\")\n return report\n if files:\n for file in files:\n self.iterate_image_files(file, report, runner_filter)\n\n if root_folder:\n for root, d_names, f_names in os.walk(root_folder):\n filter_ignored_paths(root, d_names, runner_filter.excluded_paths)\n filter_ignored_paths(root, f_names, runner_filter.excluded_paths)\n for file in f_names:\n abs_fname = os.path.join(root, file)\n self.iterate_image_files(abs_fname, report, runner_filter)\n\n return report\n\n def iterate_image_files(self, abs_fname: str, report: Report, runner_filter: RunnerFilter) -> None:\n \"\"\"\n Get workflow file, and get the list of images from every relevant imagereferencer, and create a unified vulnrability report\n :param abs_fname: file path to inspect\n :param report: unified report object\n :param runner_filter: filter for report\n \"\"\"\n if not self.image_referencers:\n return\n for image_referencer in self.image_referencers:\n if image_referencer.is_workflow_file(abs_fname):\n images = image_referencer.get_images(file_path=abs_fname)\n for image in images:\n image_report = self.get_image_report(dockerfile_path=abs_fname, image=image,\n runner_filter=runner_filter)\n merge_reports(report, image_report)\n\n def get_image_report(self, dockerfile_path: str, image: Image, runner_filter: RunnerFilter) -> Report:\n \"\"\"\n\n :param dockerfile_path: path of a file that might contain a container image\n :param image: Image object\n :param runner_filter:\n :return: vulnerability report\n \"\"\"\n report = Report(self.check_type)\n\n scan_result = self.scan(image.image_id, dockerfile_path, runner_filter)\n if scan_result is None:\n return report\n self.raw_report = scan_result\n result = scan_result.get('results', [{}])[0]\n vulnerabilities = result.get(\"vulnerabilities\") or []\n self.parse_vulns_to_records(report, result, f\"{dockerfile_path} ({image.name} lines:{image.start_line}-{image.end_line} ({image.image_id}))\", runner_filter, vulnerabilities,\n file_abs_path=os.path.abspath(dockerfile_path))\n return report\n\n def get_image_id_report(self, dockerfile_path: str, image_id: str, runner_filter: RunnerFilter) -> Report:\n \"\"\"\n THIS METHOD HANDLES CUSTOM IMAGE SCANNING THAT COMES DIRECTLY FROM CLI PARAMETERS\n \"\"\"\n report = Report(self.check_type)\n\n scan_result = self.scan(image_id, dockerfile_path, runner_filter)\n if scan_result is None:\n return report\n self.raw_report = scan_result\n result = scan_result.get('results', [{}])[0]\n vulnerabilities = result.get(\"vulnerabilities\") or []\n self.parse_vulns_to_records(report, result, f\"{dockerfile_path} ({image_id})\", runner_filter, vulnerabilities,\n file_abs_path=os.path.abspath(dockerfile_path))\n return report\n","sub_path":"checkov/sca_image/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":8888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"494798161","text":"from torch import optim, nn\nimport torch\nfrom .losses import Loss\nfrom ..utils import get_dict_values, detach_dict\n\n\nclass AdversarialJSDivergence(Loss):\n r\"\"\"\n Adversarial loss (Jensen-Shannon divergence).\n\n .. math::\n\n \\mathcal{L}_{adv} = 2 \\dot JS[p_{data}(x)||p(x)] + const.\n \"\"\"\n\n def __init__(self, p_data, p, discriminator, input_var=None, optimizer=optim.Adam, optimizer_params={},\n inverse_g_loss=True):\n super().__init__(p_data, p, input_var=input_var)\n self.loss_optimizer = optimizer\n self.loss_optimizer_params = optimizer_params\n self.d = discriminator\n\n params = discriminator.parameters()\n self.d_optimizer = optimizer(params, **optimizer_params)\n\n if len(list(p_data.parameters())) == 0:\n self._p1_no_params = True\n\n self.bce_loss = nn.BCELoss()\n self._inverse_g_loss = inverse_g_loss\n\n @property\n def loss_text(self):\n return \"mean(AdversarialJSDivergence[{}||{}])\".format(self._p1.prob_text,\n self._p2.prob_text)\n\n def estimate(self, x={}, discriminator=False):\n _x = super().estimate(x)\n batch_size = get_dict_values(_x, self._p1.input_var[0])[0].shape[0]\n\n # sample x from p1\n x_dict = get_dict_values(_x, self._p1.input_var, True)\n if self._p1_no_params:\n x1_dict = x_dict\n else:\n x1_dict = self._p1.sample(x_dict, batch_size=batch_size)\n x1_dict = get_dict_values(x1_dict, self.d.input_var, True)\n\n # sample x from p2\n x_dict = get_dict_values(_x, self._p2.input_var, True)\n x2_dict = self._p2.sample(x_dict, batch_size=batch_size)\n x2_dict = get_dict_values(x2_dict, self.d.input_var, True)\n\n if discriminator:\n # sample y from x1\n y1_dict = self.d.sample(detach_dict(x1_dict))\n y1 = get_dict_values(y1_dict, self.d.var)[0]\n\n # sample y from x2\n y2_dict = self.d.sample(detach_dict(x2_dict))\n y2 = get_dict_values(y2_dict, self.d.var)[0]\n\n return self.d_loss(y1, y2, batch_size)\n\n # sample y from x1\n y1_dict = self.d.sample(x1_dict)\n # sample y from x2\n y2_dict = self.d.sample(x2_dict)\n\n y1 = get_dict_values(y1_dict, self.d.var)[0]\n y2 = get_dict_values(y2_dict, self.d.var)[0]\n\n return self.g_loss(y1, y2, batch_size)\n\n def d_loss(self, y1, y2, batch_size):\n # set labels\n t1 = torch.ones(batch_size, 1).to(y1.device)\n t2 = torch.zeros(batch_size, 1).to(y1.device)\n return self.bce_loss(y1, t1) + self.bce_loss(y2, t2)\n\n def g_loss(self, y1, y2, batch_size):\n # set labels\n t1 = torch.ones(batch_size, 1).to(y1.device)\n t2 = torch.zeros(batch_size, 1).to(y1.device)\n\n if self._inverse_g_loss:\n y1_loss = self.bce_loss(y1, t2)\n y2_loss = self.bce_loss(y2, t1)\n else:\n y1_loss = -self.bce_loss(y1, t1)\n y2_loss = -self.bce_loss(y2, t2)\n\n if self._p1_no_params:\n y1_loss = y1_loss.detach()\n\n return y1_loss + y2_loss\n\n def train(self, train_x, **kwargs):\n self.d.train()\n\n self.d_optimizer.zero_grad()\n loss = self.estimate(train_x, discriminator=True)\n\n # backprop\n loss.backward()\n\n # update params\n self.d_optimizer.step()\n\n return loss\n\n def test(self, test_x, **kwargs):\n self.d.eval()\n\n with torch.no_grad():\n loss = self.estimate(test_x, discriminator=True)\n\n return loss\n\n\nclass AdversarialWassersteinDistance(AdversarialJSDivergence):\n r\"\"\"\n Adversarial loss (Wasserstein Distance).\n \"\"\"\n\n def __init__(self, p_data, p, discriminator,\n clip_value=0.01, **kwargs):\n super().__init__(p_data, p, discriminator, **kwargs)\n self._clip_value = clip_value\n\n @property\n def loss_text(self):\n return \"mean(AdversarialWassersteinDistance[{}||{}])\".format(self._p1.prob_text,\n self._p2.prob_text)\n\n def d_loss(self, y1, y2, *args, **kwargs):\n return - (torch.mean(y1) - torch.mean(y2))\n\n def g_loss(self, y1, y2, *args, **kwargs):\n if self._p1_no_params:\n y1 = y1.detach()\n return torch.mean(y1) - torch.mean(y2)\n\n def train(self, train_x, **kwargs):\n loss = super().train(train_x, **kwargs)\n # Clip weights of discriminator\n for params in self.d.parameters():\n params.data.clamp_(-self._clip_value, self._clip_value)\n\n return loss\n","sub_path":"pixyz/losses/adversarial_loss.py","file_name":"adversarial_loss.py","file_ext":"py","file_size_in_byte":4715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"653238341","text":"#!/usr/bin/env python\n# coding: utf8\n\nimport gtk\n\n\nclass ButtonBox(gtk.HBox):\n '''A ButtonBox used in Panel'''\n\n def __init__(self):\n\n gtk.HBox.__init__(self)\n\n\n def add_button(self, image_path, label_text):\n '''Add a new button in the ButtonBox.'''\n\n button = gtk.Button()\n\n vbox = gtk.VBox()\n button.add(vbox)\n\n frame = gtk.Frame()\n image = gtk.image_new_from_file(image_path)\n frame.add(image)\n vbox.pack_start(frame, False, False)\n\n label = gtk.Label()\n label.set_markup('<b>'+label_text+'</b>')\n vbox.pack_start(label, False, False)\n\n # button.connect('clicked', self.__button_clicked, image_path )\n self.pack_start(button, False, False)\n\n return button\n\n\n\n\n","sub_path":"story/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"502011063","text":"#!/usr/bin/env python\n'''\nSQL Introducción [Python]\nEjercicios de práctica\n---------------------------\nAutor: Inove Coding School\nVersion: 1.1\n\nDescripcion:\nPrograma creado para poner a prueba los conocimientos\nadquiridos durante la clase\n'''\n\n__author__ = \"Pedro Luis Lugo Garcia\"\n__email__ = \"pllugo@gmail.com\"\n__version__ = \"1.1\"\n\n\nimport os\nimport csv\nimport sqlite3\n\nimport sqlalchemy\nfrom sqlalchemy import Column, Integer, String, ForeignKey\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker, relationship\n\n# Crear el motor (engine) de la base de datos\nengine = sqlalchemy.create_engine(\"sqlite:///secundaria.db\")\nbase = declarative_base()\nsession = sessionmaker(bind=engine)()\n\nfrom config import config\n\n# Obtener la path de ejecución actual del script\nscript_path = os.path.dirname(os.path.realpath(__file__))\n\n# Obtener los parámetros del archivo de configuración\nconfig_path_name = os.path.join(script_path, 'config.ini')\ndataset = config('dataset', config_path_name)\n\nclass Autor(base):\n __tablename__ = \"autor\"\n id = Column(Integer, primary_key=True)\n name = Column(String)\n \n def __repr__(self):\n return f\"Autor: {self.name}\"\n\n\nclass Libro(base):\n __tablename__ = \"libro\"\n id = Column(Integer, primary_key=True)\n titulo = Column(String)\n cantidad_paginas = Column(Integer)\n autor_id = Column(Integer, ForeignKey(\"autor.id\"))\n\n autor = relationship(\"Autor\")\n\n def __repr__(self):\n return f\"Libro: {self.titulo}, cantidad_paginas {self.cantidad_paginas}, autor {self.autor.name}\"\n\n\ndef create_schema():\n # Borrar todos las tablas existentes en la base de datos\n # Esta linea puede comentarse sino se eliminar los datos\n base.metadata.drop_all(engine)\n\n # Crear las tablas\n base.metadata.create_all(engine)\n\n\ndef insert_autor(name):\n # Crear la session\n Session = sessionmaker(bind=engine)\n session = Session()\n\n # Crear una nueva nacionalidad\n autor = Autor(name=name)\n\n # Agregar la nacionalidad a la DB\n session.add(autor)\n session.commit()\n\ndef insert_libro(titulo, cantidad_paginas, autor):\n # Crear la session\n Session = sessionmaker(bind=engine)\n session = Session()\n\n # Buscar el autor del libro\n query = session.query(Autor).filter(Autor.name == autor)\n autor = query.first()\n\n if autor is None:\n # Podrá ver en este ejemplo que sucederá este error con la persona\n # de nacionalidad Inglaterra ya que no está definida en el archivo\n # de nacinoalidades\n print(f\"Error no existe el Autor {autor}\")\n return\n\n # Crear la persona\n book = Libro(titulo=titulo, cantidad_paginas=cantidad_paginas, autor=autor)\n book.autor = autor\n\n # Agregar la persona a la DB\n session.add(book)\n session.commit()\n\ndef fill():\n print('Completemos esta tablita!')\n # Insertar el archivo CSV de nacionalidades\n # Insertar fila a fila\n with open(dataset['autores']) as fi:\n data = list(csv.DictReader(fi))\n\n for row in data:\n insert_autor(row['autor'])\n\n # Insertar el archivo CSV de personas\n # Insertar todas las filas juntas\n with open(dataset['libros']) as fi:\n data = list(csv.DictReader(fi))\n\n for row in data:\n insert_libro(row['titulo'], int(row['cantidad_paginas']), row['autor_id'])\n\ndef fetch(id=0):\n print('Comprovemos su contenido, ¿qué hay en la tabla?')\n # Crear una query para imprimir en pantalla\n # todos los objetos creaods de la tabla estudiante.\n # Imprimir en pantalla cada objeto que traiga la query\n # Realizar un bucle para imprimir de una fila a la vez\n\n # Crear la session\n Session = sessionmaker(bind=engine)\n session = Session()\n\n # Buscar todas las personas\n query = session.query(Libro).order_by(Libro.cantidad_paginas.desc())\n\n # Si está definido el limite aplicarlo\n if id > 0:\n query = query.limit(id)\n\n # Leer una persona a la vez e imprimir en pantalla\n for libros in query:\n print(libros)\n\ndef search_author(titulo):\n print('Operación búsqueda!')\n # Esta función recibe como parámetro el nombre de un posible tutor.\n # Crear una query para imprimir en pantalla\n # aquellos estudiantes que tengan asignado dicho tutor.\n\n # Para poder realizar esta query debe usar join, ya que\n # deberá crear la query para la tabla estudiante pero\n # buscar por la propiedad de tutor.name\n\n # Crear la session\n Session = sessionmaker(bind=engine)\n session = Session()\n\n # Buscar el tutor en la base de datos\n resultado = session.query(Libro).join(Libro.autor).filter(Libro.titulo == titulo)\n\n for dato in resultado:\n author = dato.autor\n \n \n if author is None:\n # Podrá ver en este ejemplo que sucederá este error con la persona\n # de nacionalidad Inglaterra ya que no está definida en el archivo\n # de nacinoalidades\n print(f\"Error en este libro {titulo}\")\n return\n \n return author\n\nif __name__ == \"__main__\":\n # Crear DB\n create_schema()\n\n # Completar la DB con el CSV\n fill()\n\n # Leer filas\n fetch() # Ver todo el contenido de la DB\n fetch(3) # Ver la fila 3\n #fetch(20) # Ver la fila 20\n\n # Buscar autor\n print(search_author('Relato de un naufrago'))\n\n","sub_path":"ejercicio_de_profundizacion.py","file_name":"ejercicio_de_profundizacion.py","file_ext":"py","file_size_in_byte":5337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"200442490","text":"import logging\nfrom server.cache import cache, key_generator\nimport os\nimport json\nfrom server import mc\nfrom flask import send_from_directory\nfrom server.auth import is_user_logged_in\nimport datetime\nfrom slugify import slugify\n\nlogger = logging.getLogger(__name__)\n\nSORT_SOCIAL = 'social'\nSORT_INLINK = 'inlink'\nALL_MEDIA = '-1'\nDEFAULT_COLLECTION_IDS = [9139487]\n\n\ndef validated_sort(desired_sort, default_sort=SORT_SOCIAL):\n valid_sorts = [SORT_SOCIAL, SORT_INLINK]\n if (desired_sort is None) or (desired_sort not in valid_sorts):\n return default_sort\n return desired_sort\n\n\ndef topic_is_public(topics_id):\n topic = mc.topic(topics_id)\n is_public = topic['is_public']\n return int(is_public) == 1\n\n\ndef access_public_topic(topics_id):\n # check whether logged in here since it is a requirement for public access\n if (not is_user_logged_in()) and (topic_is_public(topics_id)):\n return True\n return False\n\n\n# helper for preview queries\n#tags_id is either a string or a list, which is handled in either case by the len() test. ALL_MEDIA is the exception\ndef concatenate_query_for_solr(solr_seed_query, media_ids, tags_ids):\n query = u'({})'.format(solr_seed_query)\n\n #if isinstance(tags_ids, basestring) or isinstance(tags_ids, list):\n if len(media_ids) > 0 or len(tags_ids) > 0:\n if tags_ids == [ALL_MEDIA] or tags_ids == ALL_MEDIA:\n return query\n query += \" AND (\"\n # add in the media sources they specified\n if len(media_ids) > 0:\n media_ids = media_ids.split(',') if isinstance(media_ids, basestring) else media_ids\n query_media_ids = u\" \".join([str(m) for m in media_ids])\n query_media_ids = u\" media_id:({})\".format(query_media_ids)\n query += '('+query_media_ids+')'\n\n # conjunction\n if len(media_ids) > 0 and len(tags_ids) > 0:\n query += \" OR \"\n\n # add in the collections they specified\n if len(tags_ids) == 0:\n tags_ids = []\n else:\n tags_ids = tags_ids.split(',') if isinstance(tags_ids, basestring) else tags_ids\n query_tags_ids = u\" \".join([str(t) for t in tags_ids])\n query_tags_ids = u\" tags_id_media:({})\".format(query_tags_ids)\n query += u'('+query_tags_ids+')'\n query += ')'\n\n return query\n\n\ndef concatenate_query_and_dates(start_date, end_date):\n date_query = u\"\"\n if start_date:\n testa = datetime.datetime.strptime(start_date, u'%Y-%m-%d').date()\n testb = datetime.datetime.strptime(end_date, u'%Y-%m-%d').date()\n date_query = mc.publish_date_query(testa, testb, True, True)\n return date_query\n\n\ndef parse_query_with_keywords(args):\n solr_q = ''\n solr_fq = None\n # default dates\n one_month_before_now = datetime.datetime.now() - datetime.timedelta(days=30)\n default_start_date = one_month_before_now.strftime(\"%Y-%m-%d\")\n default_end_date = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n # should I break this out into just a demo routine where we add in the start/end date without relying that the\n # try statement will fail?\n try: # if user arguments are present and allowed by the client endpoint, use them, otherwise use defaults\n current_query = args['q']\n if (current_query == ''):\n current_query = \"*\"\n if 'startDate' in args:\n start_date = args['startDate']\n elif 'start_date' in args:\n start_date = args['start_date']\n else:\n start_date = default_start_date\n if 'endDate' in args:\n end_date = args['endDate']\n elif 'end_date' in args:\n end_date = args['end_date']\n else:\n end_date = default_end_date\n media_ids = []\n\n if 'sources' in args:\n if isinstance(args['sources'], basestring):\n media_ids = args['sources'].split(',') if 'sources' in args and len(args['sources']) > 0 else []\n else:\n media_ids = args['sources']\n\n if 'collections' in args:\n if isinstance(args['collections'], basestring):\n if len(args['collections']) == 0:\n tags_ids = []\n else:\n tags_ids = args['collections'].split(',') # make a list\n else:\n tags_ids = args['collections']\n else:\n tags_ids = DEFAULT_COLLECTION_IDS\n\n solr_q = concatenate_query_for_solr(solr_seed_query=current_query,\n media_ids=media_ids,\n tags_ids=tags_ids)\n solr_fq = concatenate_query_and_dates(start_date, end_date)\n\n\n # otherwise, default\n except Exception as e:\n # tags_ids = args['collections'] if 'collections' in args and len(args['collections']) > 0 else []\n logger.warn(\"user custom query failed, there's a problem with the arguments \" + str(e))\n\n return solr_q, solr_fq\n\n\ndef _parse_query_for_sample_search(sample_search_id, query_id):\n sample_searches = load_sample_searches()\n current_query_info = sample_searches[int(sample_search_id)]['queries'][int(query_id)]\n solr_q = concatenate_query_for_solr(solr_seed_query=current_query_info['q'],\n media_ids=current_query_info['sources'],\n tags_ids=current_query_info['collections'])\n solr_fq = concatenate_query_and_dates(current_query_info['startDate'], current_query_info['endDate'])\n return solr_q, solr_fq\n\n\ndef parse_as_sample(search_id_or_query, query_id=None):\n try:\n if isinstance(search_id_or_query, int): # special handling for an indexed query\n sample_search_id = search_id_or_query\n return _parse_query_for_sample_search(sample_search_id, query_id)\n\n except Exception as e:\n logger.warn(\"error \" + str(e))\n\n\nsample_searches = None # use as singeton, not cache so that we can change the file and restart and see changes\n\n\ndef load_sample_searches():\n global sample_searches\n if sample_searches is None:\n json_file = os.path.join(os.path.dirname(__file__), '../..', 'static/data/sample_searches.json')\n # load the sample searches file\n with open(json_file) as json_data:\n d = json.load(json_data)\n sample_searches = d\n return sample_searches\n\n\ndef read_sample_searches():\n json_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..', 'static/data'))\n\n # load the sample searches file\n return send_from_directory(json_dir, 'sample_searches.json', as_attachment=True)\n\n\ndef file_name_for_download(label, type_of_download):\n length_limited_label = label\n if len(label) > 30:\n length_limited_label = label[:30]\n return u'{}-{}'.format(slugify(length_limited_label), type_of_download)\n","sub_path":"server/views/explorer/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"532948746","text":"# Copyright 2014 Hewlett-Packard\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport datetime\n\nimport model\nimport peewee\n\nfrom monasca.common.repositories import exceptions\nfrom monasca.common.repositories import notifications_repository\nfrom monasca.openstack.common import log\n\n\nLOG = log.getLogger(__name__)\n\n\nclass Notification_Method(model.Model):\n id = peewee.TextField(36)\n tenant_id = peewee.TextField(36)\n name = peewee.TextField()\n type = peewee.TextField()\n address = peewee.TextField()\n created_at = peewee.DateTimeField()\n updated_at = peewee.DateTimeField()\n\n\nclass NotificationsRepository(\n notifications_repository.NotificationsRepository):\n\n def notification_from_result(self, result):\n notification = dict(id=result.id,\n name=result.name,\n type=result.type,\n address=result.address)\n return notification\n\n def exists(self, tenant_id, name):\n try:\n return (Notification_Method.select().where(\n (Notification_Method.tenant_id == tenant_id) & (\n Notification_Method.name == name)).count() > 0)\n except Exception as ex:\n LOG.exception(ex)\n raise exceptions.RepositoryException(ex)\n\n def create_notification(\n self, id, tenant_id, name, notification_type, address):\n try:\n now = datetime.datetime.utcnow()\n Notification_Method.create(\n id=id,\n tenant_id=tenant_id,\n name=name,\n notification_type=notification_type,\n address=address,\n created_at=now,\n updated_at=now)\n except Exception as ex:\n LOG.exception(ex)\n raise exceptions.RepositoryException(ex)\n\n def list_notifications(self, tenant_id):\n try:\n q = Notification_Method.select().where(\n Notification_Method.tenant_id == tenant_id)\n results = q.execute()\n\n notifications = [\n self.notification_from_result(result) for result in results]\n return notifications\n except Exception as ex:\n LOG.exception(ex)\n raise exceptions.RepositoryException(ex)\n\n def delete_notification(self, tenant_id, notification_id):\n\n try:\n q = Notification_Method.delete().where(\n (Notification_Method.tenant_id == tenant_id) & (\n Notification_Method.id == notification_id))\n num_rows_deleted = q.execute()\n except Exception as ex:\n LOG.exception(ex)\n raise exceptions.RepositoryException(ex)\n\n if num_rows_deleted < 1:\n raise exceptions.DoesNotExistException()\n\n return\n\n def list_notification(self, tenant_id, notification_id):\n try:\n result = Notification_Method.get(\n (Notification_Method.tenant_id == tenant_id) & (\n Notification_Method.id == notification_id))\n return (self.notification_from_result(result))\n except Notification_Method.DoesNotExist as e:\n raise exceptions.DoesNotExistException(str(e))\n except Exception as ex:\n LOG.exception(ex)\n raise exceptions.RepositoryException(ex)\n\n def update_notification(\n self, id, tenant_id, name, notification_type, address):\n now = datetime.datetime.utcnow()\n try:\n q = Notification_Method.update(\n name=name,\n type=notification_type,\n address=address,\n created_at=now,\n updated_at=now).where(\n (Notification_Method.tenant_id == tenant_id) & (\n Notification_Method.id == id))\n # Execute the query, updating the database.\n num_rows_updated = q.execute()\n except Exception as ex:\n LOG.exception(ex)\n raise exceptions.RepositoryException(ex)\n else:\n if num_rows_updated == 0:\n raise exceptions.DoesNotExistException('Not Found')\n","sub_path":"monasca/common/repositories/mysql/notifications_repository.py","file_name":"notifications_repository.py","file_ext":"py","file_size_in_byte":4692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"312327664","text":"\"\"\"\nFind the contiguous subarray within an array (containing at least one number) which has the largest sum.\n\nFor example, given the array [-2,1,-3,4,-1,2,1,-5,4],\nthe contiguous subarray [4,-1,2,1] has the largest sum = 6.\n\nclick to show more practice.\n\nMore practice:\nIf you have figured out the O(n) solution,\ntry coding another solution using the divide and conquer approach, which is more subtle.\n\"\"\"\n\n\nclass Solution1(object):\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n def helper(lo, hi):\n if lo > hi: return float('-inf')\n\n mid = lo + (hi - lo) / 2\n left, right = helper(lo, mid - 1), helper(mid + 1, hi)\n inc_mid = max_inc_hi(lo, mid - 1) + nums[mid] + max_inc_lo(mid + 1, hi)\n return max(left, right, inc_mid)\n\n def max_inc_hi(lo, hi):\n max_num, curr_sum = 0, 0\n for i in range(hi, lo - 1, -1):\n curr_sum += nums[i]\n max_num = max(max_num, curr_sum)\n return max_num\n\n def max_inc_lo(lo, hi):\n max_num, curr_sum = 0, 0\n for i in range(lo, hi + 1):\n curr_sum += nums[i]\n max_num = max(max_num, curr_sum)\n return max_num\n\n if not nums: return 0\n return helper(0, len(nums) - 1)\n\n\n\n\nclass Solution(object):\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums: return -1\n\n maxSoFar, maxInc = nums[0], nums[0]\n for num in nums[1:]:\n maxInc = max(maxInc + num, num)\n maxSoFar = max(maxSoFar, maxInc)\n return maxSoFar\n","sub_path":"medium/MaximumSubarray.py","file_name":"MaximumSubarray.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"595892023","text":"import sys, gc\n\ndef GatherData():\n import weather_station\n result = weather_station.main()\n del sys.modules['weather_station']\n gc.collect()\n\n return result\n\ndef SendThingspeak(host, api_key, channel_id, data):\n import send_thingspeak\n send_thingspeak.SendToThingspeak(host, api_key, channel_id, data)\n del sys.modules['send_thingspeak']\n gc.collect()\n\ndef SendBlynk(blynk_auth, data):\n import send_blynk\n send_blynk.SendToBlynk(blynk_auth, data)\n del sys.modules['send_blynk']\n gc.collect()\n\ndef SendMQTT(CONF, data):\n import send_mqtt\n paused = send_mqtt.SendToMQTT(CONF, data)\n del sys.modules['send_mqtt']\n gc.collect()\n\n return paused\n\ndef WriteTimestamp(logfile, timestamp):\n f = open(logfile, 'w')\n f.write('%d\\n' % timestamp)\n f.close()\n\ndef main():\n from cycle_machine import GoToSleep\n \n result = GatherData()\n\n print('Free mem after W.S. unloaded in main(): %d' % gc.mem_free())\n\n if result['apps']['thingspeak']['enabled']:\n SendThingspeak(result['apps']['thingspeak']['host'],\n result['apps']['thingspeak']['api_key'],\n result['apps']['thingspeak']['channel_id'],\n result['values'])\n\n if result['apps']['blynk']['enabled']:\n SendBlynk(result['apps']['blynk']['auth'],\n result['values'])\n\n if result['apps']['mqtt']['enabled']:\n paused = SendMQTT(result['apps']['mqtt'],\n result['values'])\n\n WriteTimestamp(result['verify_file'],\n result['timestamp'])\n \n if not paused:\n GoToSleep(result['sleep_time_secs'])\n else:\n import sys\n sys.exit()\n\nmain()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"624195502","text":"# ----------------开发者信息--------------------------------\n# 开发者:姜媛\n# 开发日期:2020年6月23日\n# 修改日期:\n# 修改人:\n# 修改内容:\n# ----------------开发者信息--------------------------------\n\n\n# -------------------------- 1、导入需要包 -------------------------------\nimport gzip\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torchvision.models as models\nimport cv2\nimport matplotlib.pyplot as plt\n# -------------------------- 1、导入需要包 -------------------------------\n\n\n# --------------------- 2、读取数据及与图像预处理 ---------------------\npath = 'C:\\\\Users\\\\HP\\\\Desktop\\\\每周代码学习\\\\迁移学习\\\\数据集'\n# 函数:数据加载\ndef load_data():\n paths = [\n 'train-labels-idx1-ubyte.gz', 'train-images-idx3-ubyte.gz',\n 't10k-labels-idx1-ubyte.gz', 't10k-images-idx3-ubyte.gz'\n ]\n\n # 将文件解压并划分为数据集\n with gzip.open(paths[0], 'rb') as lbpath:\n y_train = np.frombuffer(lbpath.read(), np.uint8, offset=8)\n\n with gzip.open(paths[1], 'rb') as imgpath:\n x_train = np.frombuffer(\n imgpath.read(), np.uint8, offset=16).reshape(len(y_train), 28, 28, 1)\n\n with gzip.open(paths[2], 'rb') as lbpath:\n y_test = np.frombuffer(lbpath.read(), np.uint8, offset=8)\n\n with gzip.open(paths[3], 'rb') as imgpath:\n x_test = np.frombuffer(\n imgpath.read(), np.uint8, offset=16).reshape(len(y_test), 28, 28, 1)\n\n return (x_train, y_train), (x_test, y_test)\n\n\n(x_train, y_train), (x_test, y_test) = load_data() # 加载数据集\n# 由于mist的输入数据维度是(num, 28, 28),vgg16 需要三维图像,因为扩充一下mnist的最后一维\n'''\ncv2.resize:将原图放大到48*48\ncv2.cvtColor(p1,p2) :是颜色空间转换函数,p1是需要转换的图片,p2是转换成何种格式。\ncv2.COLOR_BGR2RGB 将BGR格式转换成RGB格式\ncv2.COLOR_GRAY2RGB 将灰度图片转化为格式\ncv2.COLOR_BGR2GRAY 将BGR格式转换成灰度图片\n'''\nX_train = [cv2.cvtColor(cv2.resize(i, (48, 48)), cv2.COLOR_GRAY2RGB) for i in x_train]\nX_test = [cv2.cvtColor(cv2.resize(i, (48, 48)), cv2.COLOR_GRAY2RGB) for i in x_test]\n\nx_train = np.asarray(X_train)\nx_test = np.asarray(X_test)\n\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\n\nx_train /= 255 # 归一化\nx_test /= 255 # 归一化\n\n# 转换为tensor形式\nx_train = torch.FloatTensor(x_train)\ny_train = torch.FloatTensor(y_train)\nx_test = torch.FloatTensor(x_test)\ny_test = torch.FloatTensor(y_test)\n# --------------------- 2、读取数据及与图像预处理 ---------------------\n\n\n# ---------------------------------3、参数定义 --------------------------------\nbatch_size = 32\nnum_classes = 10\nepochs = 5\nnum_predictions = 20\n# ----------------------------------- 3、参数定义---------------------------------------------\n\n\n# -------------------------------4、模型构建------------------------\nmodel = models.vgg16(pretrained=True) # 使用VGG16的权重\n\n# 特征层中参数都固定住,不会发生梯度的更新\nfor parma in model.parameters():\n parma.requires_grad = False\n\n# pytorch输入图片的尺寸必须是CxHxW,所以使用premute方法把[60000, 1, 28, 28]变为[60000, 28, 28, 1]\nx_train =x_train.permute(0, 3 , 2, 1)\n\n# 重新定义最后的三个全连接层,也就是分类层,7*7*512是vgg16最后一个卷积层的输出大小\nmodel.classifier = torch.nn.Sequential(torch.nn.Linear(7 * 7 * 512, 256),\n torch.nn.ReLU(),\n torch.nn.Dropout(0.5),\n torch.nn.Linear(256, 10),\n torch.nn.Softmax()\n )\n\nprint(model) # 查看模型\n# -------------------------------4、模型构建------------------------\n\n\n# -------------------------------5、模型训练------------------------\n# 使用gpu\nmodel = model.cuda(device='1')\nx_train = x_train.cuda()\ny_train = y_train.cuda()\n\noptimizer = torch.optim.Adam(model.parameters(), lr=1e-4) # 优化器\nloss_func = torch.nn.CrossEntropyLoss() # 损失函数\n\nprint(\"-----------训练开始-----------\")\n\nfor i in range(epochs):\n # 预测结果\n pred = model(x_train)\n # 计算损失\n loss = loss_func(pred, y_train.long())\n # 梯度归零\n optimizer.zero_grad()\n # 反向传播\n loss.backward()\n # 梯度更新\n optimizer.step()\n print(i, loss.item())\n\nprint(\"-----------训练结束-----------\")\ntorch.save(model.state_dict(), \"torch_transferlearning.pkl\") # 保存模型参数\n# -------------------------------5、模型训练------------------------\n\n\n# -------------------------- 6、模型测试 -------------------------------\nprint(\"-----------测试开始-----------\")\nmodel.load_state_dict(torch.load('torch_transferlearning.pkl')) # 加载训练好的模型参数\nfor i in range(epochs):\n # 预测结果\n pred = model(x_test)\n # 计算损失\n loss = loss_func(pred, y_test.long())\n # 打印迭代次数和损失\n print(i, loss.item())\nprint(\"-----------测试结束-----------\")\n# -------------------------------6、模型测试------------------------\n","sub_path":"jiangyuan/迁移学习/Pytorch/图像分类.py","file_name":"图像分类.py","file_ext":"py","file_size_in_byte":5289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"465539876","text":"\n# Django\nfrom django.conf.urls import url, patterns\n\n# Views\nfrom .views import (ArticuloCreate, ArticuloList, ArticuloUpdate,\n ArticuloDelete, MarcaCreate, MarcaList, PlatoCreate)\n\n\nurlpatterns = patterns('',\n url(r'^alta/$', ArticuloCreate.as_view(),\n name='Articulo-Alta'),\n\n url(r'^marca/alta/$', MarcaCreate.as_view(),\n name='Marca-Alta'),\n\n url(r'^rubro/alta/ajax/$',\n 'apps.articulos.views.rubro_create_ajax',\n name='Rubro-Alta-Ajax'),\n\n url(r'^marca/alta/ajax/$',\n 'apps.articulos.views.marca_create_ajax',\n name='Marca-Alta-Ajax'),\n\n url(r'^listado/$',\n ArticuloList.as_view(),\n name='Articulo-Listado'),\n\n url(r'^marca/listado/$',\n MarcaList.as_view(),\n name='Marca-Listado'),\n\n url(r'^editar/(?P<pk>\\d+)/$',\n ArticuloUpdate.as_view(),\n name='Articulo-Listado'),\n\n url(r'^eliminar/(?P<pk>\\d+)/$',\n ArticuloDelete.as_view(),\n name='Articulo-Eliminar'),\n\n url(r'^plato/alta/$',\n PlatoCreate.as_view(),\n name='Plato-Alta'),\n\n )\n","sub_path":"apps/articulos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"259545746","text":"import random\nfrom faker import Faker\nfrom factory.abstract.ConcreteFactory import HTTPFactory,AbstractFactory, MQTTFactory,AMQPFactory\n\n\nclass Connector(object):\n def __init__(self,factory):\n self.auth = factory.create_auth()\n self.port = factory.create_port()\n self.parser = factory.create_parser()\n self.person = Faker()\n self.machine = str(factory.machine_uid())\n def read(self,host,path):\n url = self.auth + '://' + host + ':' + str(self.port) + path + self.machine\n print(\"Connecting to {} on behalf {}\".format(url, self.person.name()))\n\n\nif __name__=='__main__':\n domain = 'service.vts.org'\n path = '/pub/'\n textual = Faker()\n is_secure = bool(random.getrandbits(1))\n\n for i in range(200):\n for name in [HTTPFactory,MQTTFactory,AMQPFactory]:\n factory = name(is_secure)\n abstract = isinstance(factory, AbstractFactory)\n print(\"Is {} instance of AbstractFactory? {} \".format(factory, abstract))\n connector = Connector(factory)\n content = connector.read(domain, path)\n\n\n\n","sub_path":"02Fabryka/Students/2018/mplawecki/abstract/Connector.py","file_name":"Connector.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"331962224","text":"# Посчитать, сколько раз встречается определенная цифра в введенной\n# последовательности чисел. Количество вводимых чисел и цифра,\n# которую необходимо посчитать, задаются вводом с клавиатуры.\n\nimport re\n\nsequence = input('Введите последовательноть: ')\nquery = input('Введите число для поиска: ')\ns_res = re.findall(query, sequence)\nprint(f'Найдено {len(s_res)} вхождений')\n","sub_path":"HW2/task8.py","file_name":"task8.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"187312606","text":"import tensorflow as tf\r\n\r\ndef load_cifar10():\r\n from tensorflow.keras.datasets import cifar10\r\n from tensorflow.keras.utils import to_categorical \r\n \r\n (x_train, y_train), (x_test, y_test) = cifar10.load_data()\r\n \r\n y_train = to_categorical(y_train, 10)\r\n y_test = to_categorical(y_test, 10)\r\n x_train = x_train.astype('float32')\r\n x_test = x_test.astype('float32')\r\n x_train /= 255\r\n x_test /= 255\r\n \r\n return x_train, y_train, x_test, y_test\r\n\r\ndef transform_dataset(x_train, y_train, x_test, y_test, batch_size):\r\n BATCH_SIZE = batch_size\r\n AUTOTUNE = tf.data.experimental.AUTOTUNE\r\n\r\n train_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train))\r\n train_ds = train_ds.shuffle(10000).batch(BATCH_SIZE).prefetch(buffer_size=AUTOTUNE)\r\n val_ds = tf.data.Dataset.from_tensor_slices((x_test,y_test))\r\n val_ds = val_ds.batch(BATCH_SIZE).prefetch(buffer_size=AUTOTUNE)\r\n\r\n return train_ds, val_ds\r\n\r\n\r\ndef load_data(dataset, batch_size):\r\n if dataset == \"cifar10\":\r\n x_train, y_train, x_test, y_test = load_cifar10()\r\n train_ds, val_ds = transform_dataset(x_train, y_train, x_test, y_test, batch_size) \r\n \r\n return train_ds, val_ds\r\n \r\nif __name__ == \"__main__\":\r\n x_train, y_train, x_test, y_test = load_cifar10()\r\n print(x_train.shape, y_train.shape)\r\n train_ds, val_ds = transform_dataset(x_train, y_train, x_test, y_test, 64)\r\n print(dir(train_ds))\r\n cnt = 0\r\n for obj in train_ds:\r\n cnt += 1\r\n print(cnt)\r\n for obj in train_ds.take(1):\r\n print(obj[0].shape[0])\r\n ","sub_path":"core/utils/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"397717242","text":"# Cloudlet Infrastructure for Mobile Computing\n# - Task Assistance\n#\n# Author: Zhuo Chen <zhuoc@cs.cmu.edu>\n# Roger Iyengar <iyengar@cmu.edu>\n#\n# Copyright (C) 2011-2013 Carnegie Mellon University\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 math\nimport instruction_pb2\nfrom gabriel_protocol import gabriel_pb2\nfrom collections import namedtuple\n\nENGINE_NAME = \"instruction\"\n\nLABELS = [\"bread\", \"ham\", \"cucumber\", \"lettuce\", \"cheese\", \"half\", \"hamwrong\",\n \"tomato\", \"full\"]\n\nHologram = namedtuple('Hologram', ['dist', 'x', 'y', 'label_index'])\n\nHAM_HOLO = Hologram(dist=6500, x=0.5, y=0.36, label_index=0)\nLETTUCE_HOLO = Hologram(dist=6800, x=0.5, y=0.32, label_index=1)\nBREAD_HOLO = Hologram(dist=7100, x=0.5, y=0.3, label_index=3)\nTOMATO_HOLO = Hologram(dist=7500, x=0.5, y=0.26, label_index=5)\nBREAD_TOP_HOLO = Hologram(dist=7800, x=0.5, y=0.22, label_index=7)\n\n\ndef _update_holo_location(objects, holo, engine_fields):\n # This modifies engine fields\n # TODO: Make this a method of an object that contains engine_fields as a\n # member\n objects = objects[objects[:, -1] == holo.label_index, :]\n x1, y1, x2, y2 = objects[0, :4]\n x = x1 * (1 - holo.x) + x2 * holo.x\n y = y1 * (1 - holo.y) + y2 * holo.y\n area = (y2 - y1) * (x2 - x1)\n\n depth = math.sqrt(holo.dist / float(area))\n engine_fields.sandwich.holo_x = x\n engine_fields.sandwich.holo_y = y\n engine_fields.sandwich.holo_depth = depth\n\n\ndef _result_with_update(\n image_path, instruction, engine_fields):\n engine_fields.update_count += 1\n\n result_wrapper = _result_without_update(engine_fields)\n\n result = gabriel_pb2.ResultWrapper.Result()\n result.payload_type = gabriel_pb2.PayloadType.IMAGE\n result.engine_name = ENGINE_NAME\n with open(image_path, 'rb') as f:\n result.payload = f.read()\n result_wrapper.results.append(result)\n\n result = gabriel_pb2.ResultWrapper.Result()\n result.payload_type = gabriel_pb2.PayloadType.TEXT\n result.engine_name = ENGINE_NAME\n result.payload = instruction.encode(encoding=\"utf-8\")\n result_wrapper.results.append(result)\n\n return result_wrapper\n\n\ndef _result_without_update(engine_fields):\n result_wrapper = gabriel_pb2.ResultWrapper()\n result_wrapper.engine_fields.Pack(engine_fields)\n return result_wrapper\n\n\ndef _start_result(engine_fields):\n engine_fields.sandwich.state = instruction_pb2.Sandwich.State.NOTHING\n return _result_with_update(\n \"images_feedback/bread.jpeg\", \"Now put a piece of bread on the table.\",\n engine_fields)\n\n\ndef _nothing_result(objects, object_counts, engine_fields):\n if object_counts[0] == 0:\n return _result_without_update(engine_fields)\n\n engine_fields.sandwich.state = instruction_pb2.Sandwich.State.BREAD\n _update_holo_location(objects, HAM_HOLO, engine_fields)\n return _result_with_update(\n \"images_feedback/ham.jpeg\", \"Now put a piece of ham on the bread.\",\n engine_fields)\n\n\ndef _bread_result(objects, object_counts, engine_fields):\n if object_counts[1] == 0:\n if object_counts[0] > 0:\n engine_fields.update_count += 1\n _update_holo_location(objects, HAM_HOLO, engine_fields)\n return _result_without_update(engine_fields)\n\n engine_fields.sandwich.state = instruction_pb2.Sandwich.State.HAM\n _update_holo_location(objects, LETTUCE_HOLO, engine_fields)\n return _result_with_update(\n \"images_feedback/lettuce.jpeg\", \"Now put a piece of lettuce on the \"\n \"ham.\", engine_fields)\n\n\ndef _lettuce_helper(objects, engine_fields):\n engine_fields.sandwich.state = instruction_pb2.Sandwich.State.LETTUCE\n _update_holo_location(objects, BREAD_HOLO, engine_fields)\n return _result_with_update(\n \"images_feedback/half.jpeg\", \"Now put a piece of bread on the lettuce.\",\n engine_fields)\n\n\ndef _ham_result(objects, object_counts, engine_fields):\n if object_counts[3] > 0:\n return _lettuce_helper(objects, engine_fields)\n elif object_counts[2] > 0:\n engine_fields.sandwich.state = instruction_pb2.Sandwich.State.CUCUMBER\n return _result_with_update(\n \"images_feedback/lettuce.jpeg\", \"This sandwich doesn't contain \"\n \"any cucumber. Replace the cucumber with lettuce.\", engine_fields)\n elif object_counts[0] > 0 and object_counts[1] == 0:\n return _nothing_result(objects, object_counts, engine_fields)\n\n if object_counts[1] > 0:\n engine_fields.update_count += 1\n _update_holo_location(objects, LETTUCE_HOLO, engine_fields)\n return _result_without_update(engine_fields)\n\n\ndef _half_helper(objects, engine_fields):\n engine_fields.sandwich.state = instruction_pb2.Sandwich.State.HALF\n _update_holo_location(objects, TOMATO_HOLO, engine_fields)\n return _result_with_update(\n \"images_feedback/tomato.jpeg\", \"You are half done. Now put a piece of \"\n \"tomato on the bread.\", engine_fields)\n\n\ndef _lettuce_result(objects, object_counts, engine_fields):\n if object_counts[5] > 0:\n return _half_helper(objects, engine_fields)\n elif object_counts[1] > 0 and object_counts[3] == 0:\n return _bread_result(objects, object_counts, engine_fields)\n\n if object_counts[3] > 0:\n _update_holo_location(objects, BREAD_HOLO, engine_fields)\n return _result_without_update(engine_fields)\n\n\ndef _cucumber_result(objects, object_counts, engine_fields):\n if object_counts[3] > 0:\n return _lettuce_helper(objects, engine_fields)\n elif object_counts[1] > 0 and object_counts[3] == 0:\n return _bread_result(objects, object_counts, engine_fields)\n\n return _result_without_update(engine_fields)\n\n\ndef _tomato_helper(objects, engine_fields):\n engine_fields.sandwich.state = instruction_pb2.Sandwich.State.TOMATO\n _update_holo_location(objects, BREAD_TOP_HOLO, engine_fields)\n return _result_with_update(\n \"images_feedback/full.jpeg\", \"Now put the bread on top and you will be \"\n \"done.\", engine_fields)\n\n\ndef _half_result(objects, object_counts, engine_fields):\n if object_counts[7] > 0:\n return _tomato_helper(objects, engine_fields)\n elif object_counts[6] > 0:\n engine_fields.sandwich.state = instruction_pb2.Sandwich.State.HAM_WRONG\n return _result_with_update(\n \"images_feedback/tomato.jpeg\", \"That's too much meat. Replace the \"\n \"ham with tomatoes.\", engine_fields)\n elif object_counts[3] > 0 and object_counts[5] == 0:\n return _lettuce_helper(objects, engine_fields)\n\n if object_counts[5] > 0:\n engine_fields.update_count += 1\n _update_holo_location(objects, TOMATO_HOLO, engine_fields)\n return _result_without_update(engine_fields)\n\n\ndef _tomato_result(objects, object_counts, engine_fields):\n if object_counts[8] > 0:\n engine_fields.sandwich.state = instruction_pb2.Sandwich.State.FULL\n return _result_with_update(\n \"images_feedback/full.jpeg\", \"Congratulations! You have made a \"\n \"sandwich!\", engine_fields)\n elif object_counts[5] > 0 and object_counts[7] == 0:\n return _half_helper(objects, engine_fields)\n\n if object_counts[7] > 0:\n engine_fields.update_count += 1\n _update_holo_location(objects, BREAD_TOP_HOLO, engine_fields)\n return _result_without_update(engine_fields)\n\n\ndef _ham_wrong_result(objects, object_counts, engine_fields):\n if object_counts[7] > 0:\n return _tomato_helper(objects, engine_fields)\n elif object_counts[5] > 0:\n return _half_helper(objects, engine_fields)\n\n return _result_without_update(engine_fields)\n\n\ndef get_instruction(engine_fields, objects):\n state = engine_fields.sandwich.state\n\n if state == instruction_pb2.Sandwich.State.START:\n return _start_result(engine_fields)\n\n if len(objects.shape) < 2:\n return _result_without_update(engine_fields)\n\n # get the count of detected objects\n object_counts = [sum(objects[:, -1] == i) for i in range(len(LABELS))]\n\n if state == instruction_pb2.Sandwich.State.NOTHING:\n return _nothing_result(objects, object_counts, engine_fields)\n elif state == instruction_pb2.Sandwich.State.BREAD:\n return _bread_result(objects, object_counts, engine_fields)\n elif state == instruction_pb2.Sandwich.State.HAM:\n return _ham_result(objects, object_counts, engine_fields)\n elif state == instruction_pb2.Sandwich.State.LETTUCE:\n return _lettuce_result(objects, object_counts, engine_fields)\n elif state == instruction_pb2.Sandwich.State.CUCUMBER:\n return _cucumber_result(objects, object_counts, engine_fields)\n elif state == instruction_pb2.Sandwich.State.HALF:\n return _half_result(objects, object_counts, engine_fields)\n elif state == instruction_pb2.Sandwich.State.TOMATO:\n return _tomato_result(objects, object_counts, engine_fields)\n elif state == instruction_pb2.Sandwich.State.HAM_WRONG:\n return _ham_wrong_result(objects, object_counts, engine_fields)\n elif state == instruction_pb2.Sandwich.State.FULL:\n return _result_without_update(engine_fields)\n\n raise Exception(\"Invalid state\")\n","sub_path":"instructions.py","file_name":"instructions.py","file_ext":"py","file_size_in_byte":9705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"652513205","text":"import tensorflow as tf\nimport tflearn\n\nfrom keras.datasets import imdb\nfrom keras.preprocessing import sequence\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation\nfrom keras.layers import Embedding\nfrom keras.layers import Conv1D, GlobalMaxPooling1D\n\n\nfrom keras.datasets import imdb\n# 每个例子包含一句电影评论和对应的标签,0或1。0代表负向评论,1代表正向评论。\n\n\ndef decode_review(text):\n # A dictionary mapping words to an integer index\n word_index = imdb.get_word_index()\n\n # The first indices are reserved\n word_index = {k: (v + 3) for k, v in word_index.items()}\n word_index[\"<PAD>\"] = 0\n word_index[\"<START>\"] = 1\n word_index[\"<UNK>\"] = 2 # unknown\n word_index[\"<UNUSED>\"] = 3\n\n reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])\n\n return ' '.join([reverse_word_index.get(i, '?') for i in text])\n\n#\n\n# set parameters:\n\nmax_features = 5000\n# 同一单条文本长度400, 不足的用0补齐\nmaxlen = 400\n\nbatch_size = 32\nembedding_dims = 50\n\nfilters = 250\nkernel_size = 3\nhidden_dims = 250\nepochs = 2\n\n\n# 训练测试数据,分别有25000条评论\n# 这里将文字转换为数字id\nprint('Loading data...')\n(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)\nprint(len(x_train), 'train sequences')\nprint(len(x_test), 'test sequences')\n\n# 编号转换为原文\n# print(decode_review(x_train[0]))\n\n# print('第0条长度',len(x_train[0]), x_train[0], y_train[0])\n# print('第5条长度',len(x_train[5]), x_train[5], y_train[5])\n\nprint(' 将每个评论补齐, 默认从前面补齐, Pad sequences (samples x time)')\nx_train = sequence.pad_sequences(x_train, maxlen=maxlen)\nx_test = sequence.pad_sequences(x_test, maxlen=maxlen)\n# print('第0条长度',len(x_train[0]), x_train[0], y_train[0])\n# print('第5条长度',len(x_train[5]), x_train[5], y_train[5])\n\nprint('Build model...')\nmodel = Sequential()\n\n# we start off with an efficient embedding layer which maps\n# our vocab indices into embedding_dims dimensions\nmodel.add(Embedding(max_features,\n embedding_dims,\n input_length=maxlen))\nmodel.add(Dropout(0.2))\n\n# we add a Convolution1D, which will learn filters\n# word group filters of size filter_length:\n# Conv1D 一维卷积,并不是说卷积核是一维的,而是说卷积操作只在纵列进行,得到的卷积层是一维的\n# 典型的就是自然语言相关的神经网络,序列数据的操作\n# Conv2D 二维卷积一般用于图像方面\nmodel.add(Conv1D(filters,\n kernel_size,\n padding='valid',\n activation='relu',\n strides=1))\n# we use max pooling:\nmodel.add(GlobalMaxPooling1D())\n\n# We add a vanilla hidden layer:\nmodel.add(Dense(hidden_dims))\nmodel.add(Dropout(0.2))\nmodel.add(Activation('relu'))\n\n# We project onto a single unit output layer, and squash it with a sigmoid:\nmodel.add(Dense(1))\nmodel.add(Activation('sigmoid'))\n\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=epochs,\n validation_data=(x_test, y_test))\n\n# trainX = pad_sequences(trainX, maxlen=100, value=0.)\n# testX = pad_sequences(testX, maxlen=100, value=0.)\n#\n# trainY = to_categorical(trainY)\n# testY = to_categorical(testY)\n#\n#\n# network = intput_data(shape=[None, 100], name='input')\n# network = tflearn.embedding(network, input_dim=10000, output_dim=128)\n#\n# branch1 = conv_1d(network, 128, 3 ,padding='valid', activation='relu',\n# regularizer='L2')\n#\n# branch2 = conv_1d(network, 128, 4 ,padding='valid', activation='relu',\n# regularizer='L2')\n#\n# branch3 = conv_1d(network, 128, 5 ,padding='valid', activation='relu',\n# regularizer='L2')\n#\n# network = merge([branch1, branch2, branch3], mode='concat', axis=1)\n# network = tf.expand_dims(network, 2)\n# network = global_max_pool(network)\n# network = dropout(network, 0.5)\n# network = fully_connected(network, 2, activation='softmax')\n#\n#\n","sub_path":"tensorflow_learn/keras_cnn_emotion_clf.py","file_name":"keras_cnn_emotion_clf.py","file_ext":"py","file_size_in_byte":4169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"446523267","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 6 17:37:46 2020\n\n@author: Aditya\n\"\"\"\n\n\nfrom flair.models import SequenceTagger\nfrom flair.data import Sentence\nimport re\n\ntagger = SequenceTagger.load(\"ner-ontonotes-fast\")\n\n\nFileName = []\nSections = []\n\n\ndef entityextraction(text):\n # for i in list1:\n # Starting_Ending_Index = []\n # Spacy_Data = []\n # with open(i, \"rb\") as f:\n # jsonfilename = i.split(\"\\\\\")[-1]\n # print (jsonfilename)\n # data = json.load(f)\n # for j in range(len(data)):\n # starting_position = 0\n # ending_position = 0\n # starting_text = \"\"\n # text = data[j][\"Paragraph_data\"][\"paragraph_value\"]\n # # data = text.split(\"\\\\r\\\\n\")\n starting_position = 0\n ending_position = 0\n starting_text = \"\"\n Starting_Ending_Index = []\n starting_string = \"<B-LAW>\"\n text = re.sub(r\"(Page\\s\\d\\sof\\s\\d+)\", \"\", text) \n sentence = Sentence(text)\n tagger.predict(sentence)\n tagged_data = sentence.to_tagged_string()\n links = re.findall(\n r\"((<B-LAW>)(.+?)(<E-LAW>))\",\n tagged_data,\n )\n #links = [(tuple(str(x) if len(x.strip())>0 else x for x in _ if x)) for _ in links]\n for link in links:\n link_text = sentence.to_tagged_string().split(\" \")\n for i in range(len(link_text)):\n if link_text[i] == starting_string:\n if link[0].split(\" \")[0] == link_text[i]:\n if i > starting_position and i > ending_position:\n starting_position = i\n starting_text = link_text[i-1]\n break\n Start_End_Index = {\n \"Txt\": re.sub(\n r\"<.*?>\",\n \"\",\n starting_text + link[0],\n ).strip()\n }\n Starting_Ending_Index.append(Start_End_Index)\n return Starting_Ending_Index","sub_path":"Legislation_Generator.py","file_name":"Legislation_Generator.py","file_ext":"py","file_size_in_byte":2469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"540846696","text":"from pylab import plt\nplt.style.use('seaborn')\nimport matplotlib as mpl\nmpl.rcParams['font.family'] = 'DejaVu Sans'\nimport warnings; warnings.simplefilter('ignore')\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom ipywidgets import widgets, interactive, interact, interactive_output\n\n# Vectorization with NumPy\n\ndef simulate(S0, u, d, p, T, N):\n '''\n S0 = 100 # initial price\n u = 1.1 # \"up\" factor\n d = 0.9 # \"down\" factor\n p = 0.4 # probability of \"up\"\n T = 30 # time-step size\n N = 50000 # sample size (no. of simulations) \n '''\n # Simulating I paths with M time steps\n S = np.zeros((T + 1, N))\n S[0] = S0\n for t in range(1, T + 1):\n z = np.random.rand(N) # pseudorandom numbers\n S[t] = S[t - 1] * ( (z<p)*u + (z>p)*d )\n # vectorized operation per time step over all paths\n return S\n \nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom matplotlib.ticker import FuncFormatter #, MultipleLocator, FormatStrFormatter, AutoMinorLocator\n\ndef animate(S0, u, d, p, T, N, P=10):\n '''\n S: data\n NumSims: simulation size\n numPaths: no. of simulated paths shown\n '''\n S = simulate(S0, u, d, p, T, N)\n fig, mainplot = plt.subplots(figsize=(10, 5))\n mainplot.plot(S[:, :P])\n plt.grid(True)\n plt.xlabel('time step')\n plt.ylabel('price')\n divider = make_axes_locatable(mainplot)\n axHist = divider.append_axes(\"right\", 2.5, pad=0.1, sharey=mainplot)\n axHist.hist(S[-1, :N], bins=15, orientation='horizontal', normed=True)\n axHist.yaxis.set_ticks_position(\"right\")\n axHist.xaxis.set_major_formatter(FuncFormatter('{0:.1%}'.format))\n plt.grid(True)\n plt.xlabel('probability')\n plt.show()\n\n \nS0=widgets.FloatSlider(min=100, max=500, step=100, value=100, description=\"$S_0$\")\nu=widgets.FloatSlider(min=1.0, max=2.0, step=0.01, value=1.05, description=\"u\")\nd=widgets.FloatSlider(min=0.1, max=1.0, step=0.1, value=0.95, description=\"d\")\np=widgets.FloatSlider(min=0.0, max=1.0, step=0.1, value=0.5, description=\"up prob\")\nT=widgets.IntSlider(min=5, max=100, step=5, value=25, description='Time steps')\nN=widgets.IntSlider(min=10000, max=100000, step=10000, value=5000, description='Sim. size')\nP=widgets.IntSlider(min=10, max=100, step=10, value=40, description='Paths displayed')\nui1 = widgets.HBox([S0, u, p, d])\nui2 = widgets.HBox([T, N, P])\nui = widgets.VBox([ui1, ui2])\n\nout = interactive_output(animate, {'S0': S0, 'u': u, 'd': d, 'p': p, 'T': T, 'N': N, 'P': P})\ndisplay(ui, out)\n","sub_path":"randomwalk.py","file_name":"randomwalk.py","file_ext":"py","file_size_in_byte":2552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"308643160","text":"import cv2 as cv\nimport numpy as np\nimport requests\n# if you are using ip webcam, then uncomment the following, other wise comment it\n# url= \"http://192.168.1.3:8080/shot.jpg\"\n\n# if you are using wired camera, uncomment the following, otherwise comment it\ncap = cv.VideoCapture(0)\n\nframe = None\nk = 0\nwhile(True):\n\t# if you are using ip webcam, then uncomment the following, other wise comment it\n\t# img_resp = requests.get(url)\n\t# im_arr = np.array(bytearray(img_resp.content), dtype=np.uint8)\n\t# frame = cv.imdecode(im_arr, -1)\n\n\t# if you are using wired camera, uncomment the following as well as cap.release() found at the end of the code, otherwise comment it\n\tret, frame = cap.read()\n\tif frame is not None and k==0:\n\t\timg1 = frame\n\t\tk=1\n\t\tcontinue\n\telif k==1:\n\t\tinput('press any key to capture second image...')\n\t\timg2 = frame\n\t\tbreak\n\n# Our operations on the frame come here\n\nimg1 = cv.resize(img1, (1080, 1080))\nimg2 = cv.resize(img2, (1080, 1080))\n\ndef preprocess(img):\n\tgray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n\tret, thresh = cv.threshold(gray, 180, 255, cv.THRESH_BINARY)\n\t_, cont, _ = cv.findContours(thresh, 1, 3)\n\t\n\tarea = 0\n\tfor i in range(len(cont)):\n\t\tif cv.contourArea(cont[i])>area:\n\t\t\tarea = cv.contourArea(cont[i])\n\t\t\tk=i\n\tM = cv.moments(cont[k])\n\tprint(cv.contourArea(cont[k]))\n\tcv.drawContours(img, [cont[k]], 0, (255,255,0), 5)\n\tcv.imshow('d', img)\n\tcv.waitKey(0)\n\tif M['m00']!=0:\n\t\tx = (M['m10']/M['m00'])\n\t\ty = (M['m01']/M['m00'])\n\t\treturn x,y\n\telse:\n\t\treturn None, None\nx1, y1 = preprocess(img1)\nx2, y2 = preprocess(img2)\ndist = np.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))\n\n\nprint('displacement of bright contour : '+str(dist))\nif dist> 0.15: \n\tshine=\"Shiny\"\n\tprint('This is a shiny object.')\nelse :\n\tshine=\"Dull\"\n\tprint('This is a dull object.')\n\n# When everything done, release the capture\ncap.release()\ncv.imwrite('img1.png', img1)\ncv.imwrite('img2.png',img2)\ncv.destroyAllWindows()","sub_path":"threshHold_blackbox.py","file_name":"threshHold_blackbox.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"636469848","text":"\"\"\"Crie um programa que declare uma matriz de dimensão 3x3\r\ne preencha com valores lidos pelo teclado. No final,\r\nmostre a matriz na tela, com a formatação correta.\"\"\"\r\nmatriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\r\nfor linha in range(0,3):\r\n for col in range(0,3):\r\n matriz[linha][col] = int(input(f'Digite um valor para: [{linha}, {col}]'))\r\nfor linha in range(0,3):\r\n for col in range(0,3):\r\n print(f'[{matriz[linha][col]:^5}]', end='')\r\n print()\r\n\r\n","sub_path":"ex086.py","file_name":"ex086.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"46751454","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 15 14:17:04 2021\n\n@author: blaise\n\"\"\"\nfrom DaLog import *\nfrom CircleDetection import *\nfrom Detection import *\nfrom Control import *\nfrom Connection import *\n\ncontrol = None\n\ndef doInstr(instr):\n if instr == 'F':\n control.forWard()\n elif instr == 'SL':\n control.setpLeft()\n elif instr == 'P':\n control.stop()\n time.sleep(0.1)\n elif instr == 'SR':\n control.setpRight()\n elif instr == 'TL':\n control.turnLeft()\n elif instr == 'TR':\n control.turnRight()\n elif instr == 'END':\n return True\n return False\n\ndef execInstructionList(instList):\n for i in instList:\n doInstr(i)\n\ndef turnBack():\n inst = [\"TR\",\"TR\",\"TR\",\"TR\",\"TR\",\"TR\",\"TR\",\"TR\",\"TR\",\"TR\",\"TR\",\"TR\",\"TR\",\"TR\",\"TR\",\"TR\",\"P\",\"SL\",\"SL\",\"SL\",\"P\",\"F\",\"F\"]\n inst.append(\"END\")\n execInstructionList(inst)\n\n\n'''\ndef passObstacle():\n \n def reverseOrder(order):\n if order==\"TR\":\n return \"TL\"\n else :\n return \"TR\"\n \n order = \"TR\"\n inst_size = 3\n inst = [\"TR\",\"TR\",\"TR\"]\n execInstructionList(inst)\n while detection.is_in_front_of_obstacle():\n order = reverseOrder(order)\n inst_size += 3 \n inst.clear()\n inst = [order for i in range(inst_size)]\n execInstructionList(inst)\n'''\ndef passObstacle():\n\n def reverseOrder(order):\n if order==\"TR\":\n return \"TL\"\n else :\n return \"TR\"\n\n order = \"TR\"\n numberOfLoops = 0 \n inst_size = 3\n inst = [\"TR\",\"TR\",\"TR\"]\n execInstructionList(inst)\n while detection.is_in_front_of_obstacle():\n order = reverseOrder(order)\n inst_size += 3 \n inst.clear()\n inst = [order for i in range(inst_size)]\n execInstructionList(inst)\n numberOfLoops += 1\n numberOfInstToWriteOnLog = len(inst) - (numberOfLoops//2)*3 \n for i in range (0,numberOfInstToWriteOnLog):\n log.write(order)\n \n \n\n#Da IA in da place \n\nrecognition = CircleDetection()\ndetection = Detection()\nlog = Log()\ncontrol = Control()\nbuzzer= Buzzer()\n\nc=Connection(\"192.168.43.171\")\n\nthreading.Thread(target=c.server).start()\n#threading.Thread(target=c.client).start()\n\nbuzzer.run_for(0.1)\n\nwhile not recognition.findBall() and not c.e.is_set() :\n if detection.is_in_front_of_obstacle():\n #do the obstacle trick\n passObstacle()\n else :\n doInstr(\"F\")\n log.write(\"F\")\n doInstr(\"F\")\n log.write(\"F\")\n \n\nc.send(\"DETECTED\")\nbuzzer.run_for(0.2)\nturnBack()\nlog.reverse()\nwhile not log.isEmpty:\n doInstr(log.getLastOrder)\n \n#Beep","sub_path":"Main_IA.py","file_name":"Main_IA.py","file_ext":"py","file_size_in_byte":2686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"421960154","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# hello.py - hello\n\n# Date : 2019/12/21\nimport ctypes\nimport struct\n\nlibrary = ctypes.cdll.LoadLibrary('/home/lyt/libhello.so')\n\nlibrary.hello()\nprint(library.fac(4))\nprint(library.fac(8))\n\n# argument\nlibrary.test.argtype = [ctypes.c_int, ctypes.c_float, ctypes.c_char_p]\nlibrary.test.restype = ctypes.c_void_p\na = ctypes.c_int(10)\nb = ctypes.c_float(12.34)\nc = ctypes.c_char_p(b'fine, thank you')\nlibrary.test(a, b, c)\n\n# struct\nclass stu(ctypes.Structure):\n _fields_ = [\n (\"id\", ctypes.c_int),\n (\"name\", ctypes.c_char * 128),\n (\"sex\", ctypes.c_int),\n (\"next\", ctypes.c_void_p)\n ]\n\n\ns = stu()\ns.id = 10\ns.name = b'liyunteng'\ns.sex = 1\ns.next = 0\nlibrary.setTest(ctypes.byref(s))\n\nlibrary.getTest.restype = ctypes.POINTER(stu)\nx = library.getTest(10)\nprint('id =', x.contents.id,\n 'name =', x.contents.name,\n 'sex =', x.contents.sex,\n 'next =', x.contents.next)\n\n# callback\ndef callback(a, b):\n print('v1 =',a, 'v2 =', b)\n return a*b\n\n\nc_callback = ctypes.CFUNCTYPE(ctypes.c_int,\n ctypes.c_int,\n ctypes.c_int)(callback)\nprint('idx =',library.register_callback(c_callback))\nprint('idx =',library.register_callback(c_callback))\nprint('idx =',library.register_callback(c_callback))\nlibrary.run_callback()\n\n# struct + callback\nclass py_callback_all(ctypes.Structure):\n _fields_ = [\n ('callback1', ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)),\n ('callback2', ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)),\n ('callback3', ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int))\n ]\n\ndef cb_1(a):\n print('cb_1:', a)\n return a * 1\n\ndef cb_2(a):\n print('cb_2:', a)\n return a * 2\n\ndef cb_3(a):\n print('cb_3:', a)\n return a * 3\n\ncb_all = py_callback_all()\ncb_all.callback1 = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)(cb_1)\ncb_all.callback2 = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)(cb_2)\ncb_all.callback3 = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)(cb_3)\nlibrary.run_callback_all.argtypes = [py_callback_all]\nlibrary.run_callback_all(cb_all)\n","sub_path":"my/python-core/extension/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"644508983","text":"#!python3\n\"\"\"\n###### Problem 1\nAsk the user to enter in the width and height of a box.\nThis should be an integer value less than 10\nDraw a box filled with \"*\" symbols that matches the\nwidth and height.\nYou will need 2 nested loops to draw the contents of\n1 row and the number of rows.\n\ninputs:\nint number\n\noutputs:\n\n\nexample:\nenter a number:4\n****\n****\n****\n****\n\n\"\"\"\n\ny=int(input(\"enter a number=>\"))\nd= (\"*\")\ns=y*d\n\nfor rows in range( y ):\n print(s)\n","sub_path":"problem1.py","file_name":"problem1.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"122124222","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport os\nimport json\nimport wx\nimport pprint\n\nclass FontSettings:\n\tdef __init__( self ):\n\t\tself.Size = 20\n\t\tself.Family = wx.FONTFAMILY_DEFAULT\n\t\tself.Style = wx.FONTSTYLE_NORMAL\n\t\tself.Weight = wx.FONTWEIGHT_NORMAL\n\t\tself.Underline = False\n\t\tself.Facename = 'Verdana'\n\t\tself.Encoding = wx.FONTENCODING_SYSTEM\n\n\t\tself.Color = '#AAAA00'\n\n\t\t#~ def __repr__(self):\n\t\t#~ return json.dumps(self.__dict__ ) #, cls=MyEncoder)\n\t\t\n\tdef GetFont( self ):\n\t\treturn wx.Font(\n\t\t\t\tself.Size, \n\t\t\t\tself.Family,\n\t\t\t\tself.Style,\n\t\t\t\tself.Weight,\n\t\t\t\tself.Underline,\n\t\t\t\tself.Facename,\n\t\t\t\tself.Encoding \n\t\t\t)\n \n\tdef FromDict( self, fontDict ):\n\t\tif( type( fontDict ) is not dict ):\n\t\t\treturn False\n\t\tif( len( set( self.__dict__.keys() ).difference( fontDict.keys() ) ) == 0 ):\n\t\t\tself.__dict__ = fontDict\n\t\t\treturn True\n\t\t\t\n\t\treturn False\n\nclass Settings:\n\t'''These are the settings of the mmedia'''\n\n\tFilename = 'settings.mmedia' #the file were the settings are saved\n\n\tdef __init__( self ):\n\t\t#self.device_ready_loaded_color = '#00FF00'\n\t\t#self.device_ready_not_loaded_color = '#FF0000'\n\t\tself.device_button_pressed_background_colour = 'black'\n\t\tself.device_button_unpressed_background_colour = wx.SystemSettings.GetColour( wx.SYS_COLOUR_BACKGROUND )\n\t\tself.device_button_pressed_text_colour = '#00FF00'\n\t\tself.device_button_unpressed_text_colour = wx.SystemSettings.GetColour( wx.SYS_COLOUR_BTNTEXT ) \n\t\t\n\t\tself.TXTFont = FontSettings() \n\t\tself.TXTFont.Size = 20\n\t\tself.TXTFont.Family = wx.FONTFAMILY_DEFAULT\n\t\tself.TXTFont.Style = wx.FONTSTYLE_NORMAL\n\t\tself.TXTFont.Weight = wx.FONTWEIGHT_NORMAL\n\t\tself.TXTFont.Underline = False\n\t\tself.TXTFont.Facename = 'Verdana'\n\t\tself.TXTFont.Encoding = wx.FONTENCODING_SYSTEM \n\t\tself.TXTFont.Color = '#AAAA00'\n\t\t\n\t\tself.SpeedDialUnassignedFont = FontSettings()\n\t\tself.SpeedDialUnassignedFont.Size = 11\n\t\tself.SpeedDialUnassignedFont.Family = wx.FONTFAMILY_DEFAULT\n\t\tself.SpeedDialUnassignedFont.Style = wx.FONTSTYLE_NORMAL\n\t\tself.SpeedDialUnassignedFont.Weight = wx.FONTWEIGHT_NORMAL\n\t\tself.SpeedDialUnassignedFont.Underline = False\n\t\tself.SpeedDialUnassignedFont.Facename = 'Arial'\n\t\tself.SpeedDialUnassignedFont.Encoding = wx.FONTENCODING_SYSTEM \n\t\tself.SpeedDialUnassignedFont.Color = '#888888'\n\t\t\n\t\tself.SpeedDialAssignedFont = FontSettings()\n\t\tself.SpeedDialAssignedFont.Size = 12\n\t\tself.SpeedDialAssignedFont.Family = wx.FONTFAMILY_DEFAULT\n\t\tself.SpeedDialAssignedFont.Style = wx.FONTSTYLE_NORMAL\n\t\tself.SpeedDialAssignedFont.Weight = wx.FONTWEIGHT_BOLD \n\t\tself.SpeedDialAssignedFont.Underline = True\n\t\tself.SpeedDialAssignedFont.Facename = 'Arial'\n\t\tself.SpeedDialAssignedFont.Encoding = wx.FONTENCODING_SYSTEM \n\t\tself.SpeedDialAssignedFont.Color = '#333333'\n\t\t\n\t\tself.NumericFreqFont = FontSettings()\n\t\tself.NumericFreqFont.Size = 25\n\t\tself.NumericFreqFont.Family = wx.FONTFAMILY_DEFAULT\n\t\tself.NumericFreqFont.Style = wx.FONTSTYLE_NORMAL\n\t\tself.NumericFreqFont.Weight = wx.FONTWEIGHT_BOLD \n\t\tself.NumericFreqFont.Underline = False\n\t\tself.NumericFreqFont.Facename = 'Arial'\n\t\tself.NumericFreqFont.Encoding = wx.FONTENCODING_SYSTEM \n\t\tself.NumericFreqFont.Color = '#FFFFFF'\n\t\t\n\t\tself.NumericFreqFontBackgroundColor = '#AAAAAA'\n\t\t\n\t\tself.StereoMonoBrightColor = '#FFFFFF'\n\t\tself.StereoMonoDimColor = '#666666'\n\n\t\tself.SetSpeedDialPressTimeSecs = 1\n\t\t# self.UnSetSpeedDialPressTimeSecs = 10\n\t\tself.CancelSpeedDialPressTimeSecs = 4\n\t\t#self.RefreshDisplayMillisecs = 1000\n\t\t\n\t\tself.offVolumeBackgroundColour = '#555555'\n\t\tself.onVolumeBackgroundColour = '#FFFF55'\n\n\t\tself.zappTimerMSecs = 5000\n\n\t\tself.FilelistFont = FontSettings()\n\t\tself.FilelistFont.Size = 12\n\t\tself.FilelistFont.Family = wx.FONTFAMILY_DEFAULT\n\t\tself.FilelistFont.Style = wx.FONTSTYLE_NORMAL\n\t\tself.FilelistFont.Weight = wx.FONTWEIGHT_NORMAL \n\t\tself.FilelistFont.Underline = False\n\t\tself.FilelistFont.Facename = 'Arial'\n\t\tself.FilelistFont.Encoding = wx.FONTENCODING_SYSTEM \n\t\tself.FilelistFont.Color = '#334455'\n\t\tself.FilelistDisabledFontColor = '#777788'\n\t\tself.FilelistPressColor = [120,120,120]\n\t\tself.FilelistBackgroundColour = '#DDDDDD'\n\t\tself.FilelistSelectedBackgroundColour = '#5555FF'\n\t\tself.FilelistSelectedForegroundColour = '#FFFFFF'\n\t\t\n\t\tself.FilelistFileIsPlaylistFont = FontSettings()\n\t\tself.FilelistFileIsPlaylistFont.Size = 12\n\t\tself.FilelistFileIsPlaylistFont.Family = wx.FONTFAMILY_DEFAULT\n\t\tself.FilelistFileIsPlaylistFont.Style = wx.FONTSTYLE_NORMAL\n\t\tself.FilelistFileIsPlaylistFont.Weight = wx.FONTWEIGHT_BOLD \n\t\tself.FilelistFileIsPlaylistFont.Underline = False\n\t\tself.FilelistFileIsPlaylistFont.Facename = 'Arial'\n\t\tself.FilelistFileIsPlaylistFont.Encoding = wx.FONTENCODING_SYSTEM \n\t\tself.FilelistFileIsPlaylistFont.Color = '#334455'\n\t\t\n\t\tself.PlaylistFont = FontSettings()\n\t\tself.PlaylistFont.Size = 12\n\t\tself.PlaylistFont.Family = wx.FONTFAMILY_DEFAULT\n\t\tself.PlaylistFont.Style = wx.FONTSTYLE_NORMAL\n\t\tself.PlaylistFont.Weight = wx.FONTWEIGHT_NORMAL \n\t\tself.PlaylistFont.Underline = False\n\t\tself.PlaylistFont.Facename = 'Arial'\n\t\tself.PlaylistFont.Encoding = wx.FONTENCODING_SYSTEM \n\t\tself.PlaylistFont.Color = '#334455'\n\t\tself.PlaylistDisabledFontColor = '#AAAAAA'\n\t\tself.PlaylistPressColor = [120,120,120]\n\t\tself.PlaylistBackgroundColour = '#DDDDDD'\n\t\tself.PlaylistSelectedBackgroundColour = '#5555FF'\n\t\tself.PlaylistSelectedForegroundColour = '#FFFFFF'\n\t\t\n\t\tself.PlaylistTitleFont = FontSettings()\n\t\tself.PlaylistTitleFont.Size = 14\n\t\tself.PlaylistTitleFont.Family = wx.FONTFAMILY_ROMAN #wx.FONTFAMILY_DEFAULT\n\t\tself.PlaylistTitleFont.Style = wx.FONTSTYLE_NORMAL\n\t\tself.PlaylistTitleFont.Weight = wx.FONTWEIGHT_BOLD #wx.FONTWEIGHT_NORMAL \n\t\tself.PlaylistTitleFont.Underline = False\n\t\tself.PlaylistTitleFont.Facename = 'Times'\n\t\tself.PlaylistTitleFont.Encoding = wx.FONTENCODING_SYSTEM \n\t\tself.PlaylistTitleFont.Color = '#FFFFFF'\n\t\tself.PlaylistTitleBackgroundColour = '#9999AA'\n\t\t\n\t\tself.samba_domain = 'WORKGROUP'\n\t\tself.samba_username = 'antonis'\n\t\tself.samba_password = '312ggp12'\n\t\t\n\tdef Load( self ):\n\t\tif( not os.path.isfile( Settings.Filename ) ):\n\t\t\treturn\n\t\twith open( Settings.Filename, mode='r' ) as f:\n\t\t\tsettingsDict = {}\n\t\t\tdict = json.load( f )\n\t\t\t#pprint.pprint( dict )\n\t\t\tfor key, value in dict.items():\n\t\t\t\tfs = FontSettings()\n\t\t\t\tif( fs.FromDict( value ) ):\n\t\t\t\t\tsettingsDict[key] = fs\n\t\t\t\telse:\n\t\t\t\t\tsettingsDict[key] = value\n\t\t\tself.__dict__ = settingsDict\n\n\tdef Save(self):\n\t\twith open( Settings.Filename, mode='w' ) as f:\n\t\t\tjson.dump( self.__dict__, f, indent=2, cls=MyEncoder )\n\t\t\t\nclass MyEncoder(json.JSONEncoder):\n def default(self, obj):\n if not isinstance(obj, FontSettings):\n return super(MyEncoder, self).default(obj)\n\n return obj.__dict__ \n \nif __name__ == \"__main__\":\n s = Settings()\n #s.Load()\n #json.dumps( s.__dict__, indent=2, cls=MyEncoder )\n # pprint.pprint( s.TXTFont.Size )\n # pprint.pprint( s.StationNameFont )\n # pprint.pprint( s.StationFreqFont )\n # pprint.pprint( s.NumericFreqFont )\n # pprint.pprint( s.SpeedDialUnassignedFont )\n # pprint.pprint( s.SpeedDialAssignedFont )\n # pprint.pprint( s.StationListFont )\n s.Save()\n","sub_path":"MMedia.bak/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":7200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"453201949","text":"#!/usr/bin/env python\n# coding: UTF-8\n\nimport sys\nimport subprocess\n\ncmd1 = \"scp stats.py 10.44.61.11:/root/\"\ncmd2 = \"scp stats.py 10.44.61.12:/root/\"\ncmd3 = \"scp stats.py 10.44.61.13:/root/\"\ncmd4 = \"scp stats.py 10.44.61.14:/root/\"\ncmd6 = \"scp stats.py 10.44.61.16:/root/\"\n\nsubprocess.call(cmd1,shell=True)\nsubprocess.call(cmd2,shell=True)\nsubprocess.call(cmd3,shell=True)\nsubprocess.call(cmd4,shell=True)\nsubprocess.call(cmd6,shell=True)\n\ncmd11 = \"ssh 10.44.61.11 \\\"ls -l |grep stats ; hostname\\\"\"\ncmd12 = \"ssh 10.44.61.12 \\\"ls -l |grep stats ; hostname\\\"\"\ncmd13 = \"ssh 10.44.61.13 \\\"ls -l |grep stats ; hostname\\\"\"\ncmd14 = \"ssh 10.44.61.14 \\\"ls -l |grep stats ; hostname\\\"\"\ncmd16 = \"ssh 10.44.61.16 \\\"ls -l |grep stats ; hostname\\\"\"\n\n\nprint\nsubprocess.call(cmd11,shell=True)\nprint\nsubprocess.call(cmd12,shell=True)\nprint\nsubprocess.call(cmd13,shell=True)\nprint\nsubprocess.call(cmd14,shell=True)\nprint\nsubprocess.call(cmd16,shell=True)\n\n","sub_path":"send-stats-script.py","file_name":"send-stats-script.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"219641499","text":"class Solution:\n \"\"\"\n @param nums: an array\n @param k: a target value\n @return: the maximum length of a subarray that sums to k\n \"\"\"\n def maxSubArrayLen(self, nums, k):\n # Write your code here\n # Sum from nums[i] to nums[j] is sums[j+1] - sums[i].\n sums = [0]\n sum_to_idx = dict()\n for i, n in enumerate(nums):\n sums.append(sums[-1] + n)\n sum_to_idx[sums[-1]] = i + 1\n max_len = 0\n for i, s0 in enumerate(sums):\n s1 = k + s0\n if s1 in sum_to_idx:\n len = sum_to_idx[s1] - i\n max_len = max(max_len, len)\n return max_len\n","sub_path":"python3/l0325_maximum_size_subarray_sum_equals_k.py","file_name":"l0325_maximum_size_subarray_sum_equals_k.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"344284806","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dashboard', '0002_auto_20170603_1512'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='ZabbixHost',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('hostid', models.IntegerField(null=True, db_index=True)),\n ('host', models.CharField(max_length=50, null=True, db_index=True)),\n ('ip', models.CharField(max_length=50, null=True, db_index=True)),\n ('updatetime', models.DateTimeField(auto_now=True)),\n ('server', models.OneToOneField(null=True, to='dashboard.Server')),\n ],\n options={\n 'db_table': 'resources_zabbix_cache',\n },\n ),\n ]\n","sub_path":"day9/opsweb/dashboard/migrations/0003_zabbixhost.py","file_name":"0003_zabbixhost.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"351590021","text":"from base import Base\r\nimport globals\r\nfrom globals import HouseModes, PEOPLE\r\nimport datetime\r\nfrom datetime import timedelta, date\r\n\r\nclass LightSchedule(Base):\r\n def initialize(self):\r\n \"\"\"Initialize.\"\"\"\r\n super().initialize()\r\n\r\n self.lights_at_dark = \"scene.lights_at_dark\"\r\n self.dark_lights_off = \"script.dark_lights_off\"\r\n self.run_at_sunset(self.lights_on, offset = datetime.timedelta(minutes = -45).total_seconds())\r\n self.scheduler.run_on_evening_before_weekday(self.lights_out, self.parse_time(\"23:59:00\"))\r\n self.scheduler.run_on_night_before_weekend_day(self.lights_out, self.parse_time(\"00:30:00\"))\r\n\r\n if (self.sun_down()):\r\n self.scheduler.run_on_weekdays(self.lights_on, self.parse_time(\"06:30:00\"))\r\n self.run_at_sunrise(self.lights_out, offset = datetime.timedelta(minutes = 45).total_seconds())\r\n\r\n def lights_on(self, kwargs):\r\n self.turn_on_device(self.lights_at_dark)\r\n self.log(\"Turned on dark lights\")\r\n \r\n def lights_out(self, kwargs):\r\n self.turn_off_device(self.dark_lights_off)\r\n self.log(\"Turned off dark lights\")","sub_path":"appdaemon/apps/lights/light_schedule.py","file_name":"light_schedule.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"603146565","text":"# Copyright (c) 2018 Robin Jarry\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport os\nimport unittest\n\nfrom libyang import Context\nfrom libyang.schema import Module\nfrom libyang.schema import Rpc\nfrom libyang.util import LibyangError\n\n\nYANG_DIR = os.path.join(os.path.dirname(__file__), 'yang')\n\n\n#------------------------------------------------------------------------------\nclass ContextTest(unittest.TestCase):\n\n def test_ctx_no_dir(self):\n ctx = Context()\n self.assertIsNot(ctx, None)\n\n def test_ctx_dir(self):\n ctx = Context(YANG_DIR)\n self.assertIsNot(ctx, None)\n\n def test_ctx_invalid_dir(self):\n ctx = Context('/does/not/exist')\n self.assertIsNot(ctx, None)\n\n def test_ctx_missing_dir(self):\n ctx = Context(os.path.join(YANG_DIR, 'yolo'))\n self.assertIsNot(ctx, None)\n with self.assertRaises(LibyangError):\n ctx.load_module('yolo-system')\n\n def test_ctx_env_search_dir(self):\n try:\n os.environ['YANGPATH'] = ':'.join([\n os.path.join(YANG_DIR, 'omg'),\n os.path.join(YANG_DIR, 'wtf'),\n ])\n ctx = Context(os.path.join(YANG_DIR, 'yolo'))\n mod = ctx.load_module('yolo-system')\n self.assertIsInstance(mod, Module)\n finally:\n del os.environ['YANGPATH']\n\n def test_ctx_load_module(self):\n ctx = Context(YANG_DIR)\n mod = ctx.load_module('yolo-system')\n self.assertIsInstance(mod, Module)\n\n def test_ctx_get_module(self):\n ctx = Context(YANG_DIR)\n ctx.load_module('yolo-system')\n mod = ctx.get_module('wtf-types')\n self.assertIsInstance(mod, Module)\n\n def test_ctx_get_invalid_module(self):\n ctx = Context(YANG_DIR)\n ctx.load_module('wtf-types')\n with self.assertRaises(LibyangError):\n ctx.get_module('yolo-system')\n\n def test_ctx_load_invalid_module(self):\n ctx = Context(YANG_DIR)\n with self.assertRaises(LibyangError):\n ctx.load_module('invalid-module')\n\n def test_ctx_find_path(self):\n ctx = Context(YANG_DIR)\n ctx.load_module('yolo-system')\n node = next(ctx.find_path('/yolo-system:format-disk'))\n self.assertIsInstance(node, Rpc)\n\n def test_ctx_iter_modules(self):\n ctx = Context(YANG_DIR)\n ctx.load_module('yolo-system')\n modules = list(iter(ctx))\n self.assertGreater(len(modules), 0)\n","sub_path":"tests/test_context.py","file_name":"test_context.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"311449086","text":"#apse1\nimport requests\nimport json\nimport zipfile\nimport io\nimport os\n\ndef putjson(filename,data):\n with open(filename, 'w') as f:\n json.dump(data, f)\n\ndef getjson(filepath):\n with open((filepath),'r') as fp:\n return json.load(fp)\n#login--------------------------------------------------------------------------------------------------------------------------------\nvalues = {\"username\":\"farmanshaikh2009@gmail.com\",\"password\":\"Qwerty@123\"}\nheaders={'content-type':'application/json','accept':'application/json'}\nurl1='https://dm-ap.informaticacloud.com/saas/public/core/v3/login'\nr = requests.post(url1,data=json.dumps(values),headers=headers)\nprint(r.status_code)\n\n#convert r into json format\ndata = r.json()\n#formatting d json in beautified form\nd=json.dumps(data,indent=2)\n#print(d)\n\n#putting in *.json file\nputjson('1)loginData.json',data)\n#retrieving data from that file\nmyobj=getjson('./1)loginData.json')\n\nics=myobj['userInfo']['sessionId']#NOTE WE ARE SENDING AND THEN RECEIVING THEN PRINTING WE CAN DIRECTLY PRINT ALSO\n#as ics=data['userInfo']['sessionId']\nprint(ics)\n\n\n#lookup----------------------------------------------------------------------------------------------------------------------------------\nvalues={\n\t\"objects\": [ {'path' : \"Default/farmanMapping\",\n \"type\" : \"Mapping\" },\n \n {\"path\" : \"testFarmanProject\",\n \"type\" : \"Project\" \n },\n \n {\"path\" : \"testFarmanProject/insideTestFarmanFolder\",\n \"type\" : \"Folder\" \n }\n]}\nheaders={'content-type':'application/json','INFA-SESSION-ID':ics}\nr=requests.post('https://apse1.dm-ap.informaticacloud.com/saas/public/core/v3/lookup',data=json.dumps(values),headers=headers)\nprint(r.status_code)\n\ndata=r.json()\nd=json.dumps(data,indent=2)\nprint(d)\n\n#putting in *.json file\nputjson('2)lookup.json',data)\n#retrieving data from that file\nmyobj=getjson('./2)lookup.json')\n\n\n#export of all ids-------------------------------------------------------------------------------------------------------------------------------------\n#getting all the ids of objects dynamically\nnumberOfObjects=len(myobj['objects'])\n#just for printing ids if will reomove then also no problem\n\nids=[]\nidsArray=[]\nfor i in range(numberOfObjects):\n key=[\"id\"]\n ids.append(myobj['objects'][i]['id'])\n value=[myobj['objects'][i]['id']]\n idsArray.append(dict(zip(key,value)))\nprint(ids)\nprint(idsArray)\n\n#idsArray is storing a dict od key : value pairs of id : ids\nvalues={\n \"objects\": idsArray\n }\nheaders={'content-type':'application/json','accept':'application/json','INFA-SESSION-ID':ics}\nr=requests.post('https://apse1.dm-ap.informaticacloud.com/saas/public/core/v3/export',data=json.dumps(values),headers=headers)\nprint(r.status_code)\n\ndata= r.json()\n#putting in *.json file\nputjson('3)export.json',data)\n#retrieving data from that file\nmyobj=getjson('./3)export.json')\nprint(json.dumps(myobj,indent=2))\nexportId=myobj[\"id\"]\nprint(exportId)\n\n#get status of export with id (note: its exported id)---------------------------------------------------------------------------------------------------------\nheaders={'content-type':'application/json','accept':'application/json','INFA-SESSION-ID':ics}\nr=requests.get('https://apse1.dm-ap.informaticacloud.com/saas/public/core/v3/export/'+exportId,headers=headers)\nprint(r.status_code)\ndata=r.json()\nputjson('4)export_status.json',data)\nmyobj=getjson('./4)export_status.json')\nprint(json.dumps(myobj,indent=2))\n\n#download export package----------------------------------------------------------------------------------------------------------------------------------\nr=requests.get('https://apse1.dm-ap.informaticacloud.com/saas/public/core/v3/export/'+exportId+'/package',headers=headers)\nprint(r.status_code)\n\nz = zipfile.ZipFile(io.BytesIO(r.content))\nz.extractall('./export_file')\n\nfzip = zipfile.ZipFile('C:\\\\Users\\\\moabbasi\\\\Desktop\\\\PythonProjects\\\\export_file.zip','w')\n \nfor folder, subfolders, files in os.walk('C:\\\\Users\\\\moabbasi\\\\Desktop\\\\PythonProjects\\\\export_file'):\n \n for file in files:\n \n fzip.write(os.path.join(folder, file), os.path.relpath(os.path.join(folder,file),'C:\\\\Users\\\\moabbasi\\\\Desktop\\\\PythonProjects\\\\export_file'),compress_type = zipfile.ZIP_DEFLATED)\n \nfzip.close()\n\n\n\n#logout-----------------------------------------------------------------------------------------------------------------------------------------------\nheaders={'content-type':'application/json','INFA-SESSION-ID':ics}\nr=requests.post('https://dm-ap.informaticacloud.com/saas/public/core/v3/logout',headers)\nprint(r.status_code)\n\n\n\n","sub_path":"PythonProjects/IICS/iicsMe.py","file_name":"iicsMe.py","file_ext":"py","file_size_in_byte":4757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"361241768","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass IotHubCapacity(Model):\n \"\"\"IoT Hub capacity information.\n\n Variables are only populated by the server, and will be ignored when\n sending a request.\n\n :ivar minimum: The minimum number of units.\n :vartype minimum: long\n :ivar maximum: The maximum number of units.\n :vartype maximum: long\n :ivar default: The default number of units.\n :vartype default: long\n :ivar scale_type: The type of the scaling enabled. Possible values\n include: 'Automatic', 'Manual', 'None'\n :vartype scale_type: str or :class:`IotHubScaleType\n <azure.mgmt.iothub.models.IotHubScaleType>`\n \"\"\"\n\n _validation = {\n 'minimum': {'readonly': True, 'maximum': 1, 'minimum': 1},\n 'maximum': {'readonly': True},\n 'default': {'readonly': True},\n 'scale_type': {'readonly': True},\n }\n\n _attribute_map = {\n 'minimum': {'key': 'minimum', 'type': 'long'},\n 'maximum': {'key': 'maximum', 'type': 'long'},\n 'default': {'key': 'default', 'type': 'long'},\n 'scale_type': {'key': 'scaleType', 'type': 'IotHubScaleType'},\n }\n\n def __init__(self):\n self.minimum = None\n self.maximum = None\n self.default = None\n self.scale_type = None\n","sub_path":"azure-mgmt-iothub/azure/mgmt/iothub/models/iot_hub_capacity.py","file_name":"iot_hub_capacity.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"411633931","text":"\r\n\r\nminUpperLetter = 65\r\nmaxUpperLetter = 90\r\n\r\nminLowerLetter = 97\r\nmaxLowerLetter = 122\r\n\r\n\r\ndef getMessage(m):\r\n \"\"\"\r\n recupere une chaine de caractères et le transforme en message pour le chiffre César: uniquement des majuscules et pas d'autres caractères comme les espaces ou autre\r\n \"\"\"\r\n\r\n newm = []\r\n\r\n for letter in m:\r\n l = ord(letter)\r\n if (l >= minUpperLetter) & (l <= maxUpperLetter):\r\n newm.append(letter)\r\n #...\r\n\r\n if (l >= minLowerLetter) & (l <= maxLowerLetter):\r\n newm.append(letter.upper())\r\n # ...\r\n # ...\r\n\r\n return ''.join(newm)\r\n# ...\r\n\r\n\r\ndef isValidMessage(m):\r\n \"\"\"\r\n verifie si le message ne contient que des lettre majuscules\r\n \"\"\"\r\n\r\n for letter in m:\r\n l = ord(letter)\r\n if (l < minUpperLetter) | (l > maxUpperLetter):\r\n return False\r\n # ...\r\n # ...\r\n return True\r\n# ...\r\n\r\ndef findOppositeKeyCesar(k):\r\n \"\"\"\r\n Donne la cle symmetrique a la cle passe en argument\r\n \"\"\"\r\n k = k % 26\r\n oppk = 26 - k\r\n\r\n return oppk\r\n\r\ndef setCryptogrammeByBloc(c, nl):\r\n\r\n newc = []\r\n\r\n n = len(c)\r\n nbloc = int(n/nl)\r\n\r\n for i in range(0,nbloc):\r\n newc.append(c[i*nl:(i+1)*nl])\r\n # ...\r\n\r\n if n/nl > nbloc:\r\n newc.append(c[nbloc*nl:])\r\n # ...\r\n\r\n return ' '.join(newc)\r\n# ...\r\n\r\n\r\ndef chiffrementCesar(m, kc, nl):\r\n \"\"\"\r\n renvoie le cryptogramme pour le message m avec la clé kc par le chiffre César\r\n \"\"\"\r\n\r\n if not isValidMessage(m):\r\n m = getMessage(m)\r\n # ...\r\n\r\n # on reduit potentiellement kc\r\n kc = kc % 26\r\n\r\n c = []\r\n for letter in m:\r\n l = ord(letter) - minUpperLetter\r\n c_i = (l + kc) % 26\r\n c_i = c_i + minUpperLetter\r\n c.append(chr(c_i))\r\n #...\r\n return setCryptogrammeByBloc(''.join(c), nl)\r\n# ...\r\n\r\ndef dechiffrementCesar(c, kc):\r\n \"\"\"\r\n dechiffre le cryptogramme donne dont on connait la cle de chiffrement kc\r\n \"\"\"\r\n if not isValidMessage(c):\r\n c = getMessage(c)\r\n # ...\r\n\r\n # on reduit kc\r\n kc = kc % 26\r\n\r\n # on en deduit kd\r\n kd = 26 - kc\r\n\r\n\r\n m = []\r\n for letter in c:\r\n l = ord(letter) - minUpperLetter\r\n m_i = (l + kd) % 26\r\n m_i = m_i + minUpperLetter\r\n m.append(chr(m_i))\r\n #...\r\n return ''.join(m)\r\n\r\ndef decryptCesarCryptogrammeSeul(c):\r\n \"\"\"\r\n Teste l'ensemble des cles possibles pour retrouver le message en clair\r\n\r\n Renvoie une liste de 26 chaines de caractères.\r\n \"\"\"\r\n\r\n dicoSol = [c]\r\n print(\"CLE:\\tMESSAGE:\")\r\n for i in range(1,26):\r\n tmp = dechiffrementCesar(c, i)\r\n print('{0}\\t{1}'.format(i, tmp))\r\n dicoSol.append(tmp)\r\n # ...\r\n\r\n return dicoSol \r\n# ...\r\n\r\n\r\ndef decryptCesarCouplesConnus(m, c):\r\n \"\"\"\r\n un message en clair et son cryptogramme. \r\n\r\n Renvoie la clé de chiffrement\r\n \"\"\"\r\n\r\n\r\n if not isValidMessage(m):\r\n m = getMessage(m)\r\n # ...\r\n\r\n if not isValidMessahe(c):\r\n c = getMessage(c)\r\n # ...\r\n\r\n # Il nous suffit ici d'observer le premier element de chacune des deux chaines de caractères\r\n m0 = m[0]\r\n c0 = c[0]\r\n\r\n m0 = ord(m0) - minUpperLetter\r\n c0 = ord(c0) - minUpperLetter\r\n\r\n kc = m0 - c0\r\n if kc < 0:\r\n kc = kc + 26\r\n # ... \r\n\r\n return kc\r\n#...\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n m = 'Salut je viens de Villetaneuse'\r\n c = chiffrementCesar(m, 8, 5)\r\n print(m)\r\n print(c)\r\n print(dechiffrementCesar(c, 8))\r\n #decryptCesarCryptogrammeSeul(c)\r\n\r\n# ...","sub_path":"cesar.py","file_name":"cesar.py","file_ext":"py","file_size_in_byte":3328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"468467682","text":"#!/usr/bin/env python3\nfrom kubernetes import client, config\nimport subprocess\nimport os\nimport signal\nimport gi\ngi.require_version('Gtk', '3.0')\ngi.require_version('AppIndicator3', '0.1')\nfrom gi.repository import Gtk, AppIndicator3\ncurrpath = os.path.dirname(os.path.realpath(__file__))\n\nclass Indicator():\n def __init__(self):\n self.app = 'k8s_context_switcher'\n iconpath = currpath+\"/icon.png\"\n self.indicator = AppIndicator3.Indicator.new(\n self.app, iconpath,\n AppIndicator3.IndicatorCategory.SYSTEM_SERVICES)\n self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)\n self.indicator.set_menu(self.create_menu())\n def refresh_menu(self):\n # k8s cluster \n self.menu = Gtk.Menu()\n contexts, current = self.list_contexts()\n for c in contexts:\n if c['name'] == current['name']:\n c['name'] = '* ' + c['name']\n menu_item = Gtk.MenuItem(c['name'].strip())\n menu_item.connect(\"activate\", self.run_script, c['name'])\n self.menu.append(menu_item) \n def create_menu(self):\n self.menu = Gtk.Menu()\n self.refresh_menu()\n # quit\n item_quit = Gtk.MenuItem('Quit')\n sep = Gtk.SeparatorMenuItem()\n self.menu.append(sep)\n item_quit.connect('activate', self.stop)\n self.menu.append(item_quit)\n self.menu.show_all()\n return self.menu\n def run_script(self, widget, context):\n self.change_context(context)\n self.indicator.set_menu(self.create_menu())\n def stop(self, source):\n Gtk.main_quit()\n \n def change_context(self,context):\n subprocess.check_output(['kubectl', 'config','use-context', context])\n\n def list_contexts(self):\n config.load_kube_config()\n contexts , current = config.list_kube_config_contexts()\n return contexts, current \n \nIndicator()\nsignal.signal(signal.SIGINT, signal.SIG_DFL)\nGtk.main()","sub_path":"run_k8s_indicator.py","file_name":"run_k8s_indicator.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"626001299","text":"import socket\nimport threading\nfrom dashboard.models import RawData\nfrom manage_devices.models import Node\nfrom datetime import datetime\nimport os\nimport django\n\n\nclass ThreadedServer(object):\n def __init__(self, host, port):\n self.host = host\n self.port = port\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.sock.bind((self.host, self.port))\n\n def listen(self):\n print(\"Server is listening !\")\n self.sock.listen(5)\n while True:\n client, address = self.sock.accept()\n client.settimeout(60)\n threading.Thread(target=self.listen_to_client, args=(client, address)).start()\n\n def listen_to_client(self, client, address):\n size = 1024\n while True:\n try:\n data = client.recv(size)\n if data:\n # Set the response to echo back the recieved data\n response = data\n client.send(response)\n # handle data here\n co, oxi, node = data.split(';')\n node_id = Node.objects.get(node)\n new_data = RawData(oxi=oxi,\n co=co,\n node=node_id,\n node_identification=node_id.name,\n measuring_date=datetime.now())\n new_data.save(force_insert=True)\n print('Adding successfully !')\n else:\n print('Client disconnected')\n except:\n client.close()\n return False\n\n\nThreadedServer('localhost', 1995).listen()\n\n\n\n","sub_path":"airpollutionmearsuring/airmeasuring/tcp_socket.py","file_name":"tcp_socket.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"223833341","text":"from markdown_it import MarkdownIt\nimport pytest\n\nfrom mdformat._renderer import MDRenderer\n\nSTYLE_CASES = (\n {\n \"name\": \"strip paragraph lines\",\n \"input_md\": \"trailing whitespace \\n\"\n \"at the end of paragraph lines \\n\"\n \"should be stripped \\n\",\n \"output_md\": \"trailing whitespace\\n\"\n \"at the end of paragraph lines\\n\"\n \"should be stripped\\n\",\n },\n {\n \"name\": \"strip quotes\",\n \"input_md\": \"> Paragraph 1\\n\" \"> \\n\" \"> Paragraph 2\\n\",\n \"output_md\": \"> Paragraph 1\\n\" \">\\n\" \"> Paragraph 2\\n\",\n },\n {\n \"name\": \"no escape ampersand\",\n \"input_md\": \"R&B, rock & roll\\n\",\n \"output_md\": \"R&B, rock & roll\\n\",\n },\n {\n \"name\": \"list whitespaces\",\n \"input_md\": \"- item one\\n \\n- item two\\n - sublist\\n \\n - sublist\\n\",\n \"output_md\": \"- item one\\n\\n- item two\\n\\n - sublist\\n\\n - sublist\\n\",\n },\n {\n \"name\": \"convert setext to ATX heading\",\n \"input_md\": \"Top level heading\\n=========\\n\\n2nd level heading\\n---------\",\n \"output_md\": \"# Top level heading\\n\\n## 2nd level heading\\n\",\n },\n)\n\n\n@pytest.mark.parametrize(\"entry\", STYLE_CASES, ids=[c[\"name\"] for c in STYLE_CASES])\ndef test_renderer_style(entry):\n \"\"\"Test Markdown renderer renders expected style.\"\"\"\n md_original = entry[\"input_md\"]\n md_new = MarkdownIt(renderer_cls=MDRenderer).render(md_original)\n expected_md = entry[\"output_md\"]\n assert md_new == expected_md\n","sub_path":"tests/test_renderer_style.py","file_name":"test_renderer_style.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"521856994","text":"#ipython3\n#%matplotlib\nimport pickle\nimport numpy as np\nimport pyproj\nimport glob\nfrom scipy.stats import circmean, circstd #for mean wind/wave direction and spread\nimport os\n\n#=====================================================\n# recast time vector into swan iso style\ndef time2isotime(times):\n isotimes = []\n for k in times:\n newk = k.split(':')[0].replace('-','').replace('T','.')\n newk = newk.replace('.'+newk.split('.')[1], '.'+str(int(newk.split('.')[1])/24).replace('0.',''))\n isotimes.append(newk)\n return isotimes\n\n\n##http://spatialreference.org/ref/epsg/nad83-utm-zone-10n/\ntrans = pyproj.Proj(init=\"epsg:26910\")\n\n# west. lon, lat: 28, 20\n# east. lon, lat: 29, 20\n# south. lon, lat: 28, 19\n\n#input directory\ndirec = 10\n\nprojname = 'd'+str(direc)\nswnfile = './d'+str(direc)+'/'+projname+'.swn'\n\n## multiplier on standard deviation\nmult = 2\n\n#=====================================================\n## wave direction\n#infile = 'noaa_ww3_wc Primary_wave_direction_surface Fri_Jan_27_21:39:27_2017 output.pkl'\ninfile = glob.glob('d'+str(direc)+os.sep+'Primary_wave_direction_surface*.pkl')[0]\n\nwith open(infile,'rb') as f:\n wavdir = pickle.load(f)\n\nf.close()\ntmp = wavdir[1]\ntimes = sorted(tmp.keys())\n\nWD = []\nfor k in times:\n WD.append(tmp[k].as_matrix())\n\nlon = np.asarray(tmp[k].columns)\nlat = np.asarray(tmp[k].index)\n\nwd_w = np.asarray(WD)[:,28,20]\nwd_e = np.asarray(WD)[:,29,20]\nwd_s = np.asarray(WD)[:,28,19]\n\n\n#=====================================================\n## wave direction spread\nwdlocal = np.asarray(WD)[:,26:31,17:22]\n\nwdsp_w = np.ones(len(wd_s))*np.rad2deg(circstd(np.deg2rad(wdlocal)))*mult #pd.rolling_std(wd_w, 3)*mult\nwdsp_e = np.ones(len(wd_s))*np.rad2deg(circstd(np.deg2rad(wdlocal)))*mult #pd.rolling_std(wd_e, 3)*mult\nwdsp_s = np.ones(len(wd_s))*np.rad2deg(circstd(np.deg2rad(wdlocal)))*mult #pd.rolling_std(wd_s, 3)*mult\n\n#wdsp_w[np.isnan(wdsp_w)] = wdsp_w[2]\n#wdsp_e[np.isnan(wdsp_e)] = wdsp_e[2]\n#wdsp_s[np.isnan(wdsp_s)] = wdsp_s[2]\n\n\n#=====================================================\n## wave height\n#infile = 'noaa_ww3_wc Significant_height_of_combined_wind_waves_and_swell_surface Fri_Jan_27_21:37:45_2017 output.pkl'\ninfile = glob.glob('d'+str(direc)+'/Significant_height_of_combined_wind_waves_and_swell_surface*.pkl')[0]\n\nwith open(infile,'rb') as f:\n wavh = pickle.load(f)\n\nf.close()\ntmp = wavh[1]\n\nWH = []\nfor k in times:\n WH.append(tmp[k].as_matrix())\n\nwh_w = np.asarray(WH)[:,28,20]\nwh_e = np.asarray(WH)[:,29,20]\nwh_s = np.asarray(WH)[:,28,19]\n\n\n#=====================================================\n## wave period\n#infile = 'noaa_ww3_wc Primary_wave_mean_period_surface Fri_Jan_27_21:38:36_2017 output.pkl'\ninfile = glob.glob('d'+str(direc)+'/Primary_wave_mean_period_surface*.pkl')[0]\n\nwith open(infile,'rb') as f:\n wavp = pickle.load(f)\n\nf.close()\ntmp = wavp[1]\n\nWP = []\nfor k in times:\n WP.append(tmp[k].as_matrix())\n\nwp_w = np.asarray(WP)[:,28,20]\nwp_e = np.asarray(WP)[:,29,20]\nwp_s = np.asarray(WP)[:,28,19]\n\n\n#=====================================================\n## wind speed\n#infile = 'noaa_ww3_wc Wind_speed_surface Fri_Jan_27_21:40:19_2017 output.pkl'\ninfile = glob.glob('d'+str(direc)+'/Wind_speed_surface*.pkl')[0]\n\nwith open(infile,'rb') as f:\n wins = pickle.load(f)\n\nf.close()\ntmp = wins[1]\n\nWS = []\nfor k in times:\n WS.append(tmp[k].as_matrix())\n\nwins_w = np.asarray(WS)[:,28,20]\nwins_e = np.asarray(WS)[:,29,20]\nwins_s = np.asarray(WS)[:,28,19]\n\n\n#=====================================================\n## wind direc\n#infile = 'noaa_ww3_wc Wind_direction_from_which_blowing_surface Fri_Jan_27_21:41:12_2017 output.pkl'\ninfile = glob.glob('d'+str(direc)+'/Wind_direction_from_which_blowing_surface*.pkl')[0]\n\nwith open(infile,'rb') as f:\n wind = pickle.load(f)\n\nf.close()\ntmp = wind[1]\n\nWD = []\nfor k in times:\n WD.append(tmp[k].as_matrix())\n\nwind_w = np.asarray(WD)[:,28,20]\nwind_e = np.asarray(WD)[:,29,20]\nwind_s = np.asarray(WD)[:,28,19]\n\n\n#x, y = np.meshgrid(lon, lat)\n#x,y = trans(x,y)\n#xyz = np.genfromtxt('/home/filfy/Downloads/SWAN/lostcoast/2009bathy/H11972_10m_xyz.txt', delimiter=' ')\n\n\n#========================================\n\n# now we need to write out the SWAN files\n\n#==========================================\n# variables\n\nisotimes = time2isotime(times)\n\nn = len(times)\n\n# just 1st day\n#isotimes = isotimes[:9]\n\nlevel = '0.0'\nwinddir = str(np.rad2deg(circmean(np.deg2rad(wind_s[:n]))))[:5] #str(np.mean(wins_s[:9]))[:5]\nwindspeed = str(np.mean(wins_s[:n]))[:5]\nstarttime = isotimes[0]\nendtime = isotimes[-1]\nfileS = './TPAR_S7.txt'\nfileE = './TPAR_E7.txt'\nfileW = './TPAR_W7.txt'\ncomptstep = '5 MIN'\nmaxiter = '50'\noutfreq = '1 HR'\nbotfile = '../H11972_10mall.bot'\nnproc = '20'\n\n#==========================================\n# write swanfile\nfile = open(swnfile, 'w')\n\nfile.write(\"PROJECT '\"+projname+\"' '1'\\n\")\nfile.write(\"SET LEVEL \"+level+\" NAUT\\n\")\nfile.write(\"MODE NONSTATIONARY TWODIMENSIONAL\\n\")\n\nfile.write(\"COORDINATES CART\\n\")\nfile.write(\"CGRID REG 0. 0. 0. 4000 5590 399 558 CIRcle 36 0.02 1. 31\\n\")\nfile.write(\"INPGRID BOTTOM 0. 0. 0. 399 558 10. 10. EXC -99.\\n\")\nfile.write(\"READINP BOTTOM 1. '\"+botfile+\"' 3 0 FREE\\n\")\n\nfile.write(\"WIND \"+windspeed+\" \"+winddir+\" DRAG WU\\n\")\n\nfile.write(\"BOU SHAP JON 3.3 PEAK DSPR DEGR\\n\")\n\nfile.write(\"BOUNDSPEC SIDE S CCW VARIABLE FILE 0 '\"+fileS+\"'\\n\")\nfile.write(\"BOUNDSPEC SIDE W CCW VARIABLE FILE 0 '\"+fileW+\"'\\n\")\nfile.write(\"BOUNDSPEC SIDE E CCW VARIABLE FILE 0 '\"+fileE+\"'\\n\")\n\nfile.write(\"GEN3\\n\")\nfile.write(\"FRICTION\\n\")\nfile.write(\"TRIADS\\n\")\nfile.write(\"WCAP\\n\")\nfile.write(\"QUAD\\n\")\nfile.write(\"BREAKING\\n\")\nfile.write(\"TURB\\n\")\nfile.write(\"SETUP\\n\")\n\nfile.write(\"INIT DEF\\n\")\n\nfile.write(\"BLOCK 'COMPGRID' NOHEAD '\"+projname+\"_Pparams.mat' LAY 3 XP YP BOTLEV TIME DEPTH\\n\")\n\nfile.write(\"BLOCK 'COMPGRID' NOHEAD '\"+projname+\"_Hs.mat' LAY 3 HS OUTPUT \"+starttime+\" \"+outfreq+\"\\n\")\nfile.write(\"BLOCK 'COMPGRID' NOHEAD '\"+projname+\"_Hswell.mat' LAY 3 HSWELL OUTPUT \"+starttime+\" \"+outfreq+\"\\n\")\nfile.write(\"BLOCK 'COMPGRID' NOHEAD '\"+projname+\"_Force.mat' LAY 3 FORCE OUTPUT \"+starttime+\" \"+outfreq+\"\\n\")\nfile.write(\"BLOCK 'COMPGRID' NOHEAD '\"+projname+\"_Ubot.mat' LAY 3 UBOT OUTPUT \"+starttime+\" \"+outfreq+\"\\n\")\nfile.write(\"BLOCK 'COMPGRID' NOHEAD '\"+projname+\"_Urms.mat' LAY 3 URMS OUTPUT \"+starttime+\" \"+outfreq+\"\\n\")\n\nfile.write(\"BLOCK 'COMPGRID' NOHEAD '\"+projname+\"_Tm01.mat' LAY 3 TM01 OUTPUT \"+starttime+\" \"+outfreq+\"\\n\")\nfile.write(\"BLOCK 'COMPGRID' NOHEAD '\"+projname+\"_Dspr.mat' LAY 3 DSPR OUTPUT \"+starttime+\" \"+outfreq+\"\\n\")\nfile.write(\"BLOCK 'COMPGRID' NOHEAD '\"+projname+\"_Dir.mat' LAY 3 DIR OUTPUT \"+starttime+\" \"+outfreq+\"\\n\")\nfile.write(\"BLOCK 'COMPGRID' NOHEAD '\"+projname+\"_Rtp.mat' LAY 3 RTP OUTPUT \"+starttime+\" \"+outfreq+\"\\n\")\nfile.write(\"BLOCK 'COMPGRID' NOHEAD '\"+projname+\"_Wlen.mat' LAY 3 WLEN OUTPUT \"+starttime+\" \"+outfreq+\"\\n\")\n\nfile.write(\"BLOCK 'COMPGRID' NOHEAD '\"+projname+\"_dissip.mat' LAY 3 DISSIP OUTPUT \"+starttime+\" \"+outfreq+\"\\n\")\nfile.write(\"BLOCK 'COMPGRID' NOHEAD '\"+projname+\"_disbot.mat' LAY 3 DISBOT OUTPUT \"+starttime+\" \"+outfreq+\"\\n\")\nfile.write(\"BLOCK 'COMPGRID' NOHEAD '\"+projname+\"_diswcap.mat' LAY 3 DISWCAP OUTPUT \"+starttime+\" \"+outfreq+\"\\n\")\n\nfile.write(\"BLOCK 'COMPGRID' NOHEAD '\"+projname+\"_prop.mat' LAY 3 PROPAGAT OUTPUT \"+starttime+\" \"+outfreq+\"\\n\")\nfile.write(\"BLOCK 'COMPGRID' NOHEAD '\"+projname+\"_genat.mat' LAY 3 GENERAT OUTPUT \"+starttime+\" \"+outfreq+\"\\n\")\nfile.write(\"BLOCK 'COMPGRID' NOHEAD '\"+projname+\"_genwind.mat' LAY 3 GENWIND OUTPUT \"+starttime+\" \"+outfreq+\"\\n\")\n\nfile.write(\"TEST 1,0\\n\")\nfile.write(\"NUM ACCUR STAT \"+maxiter+\" 0.01\\n\")\nfile.write(\"PROP BSBT\\n\")\n\nfile.write(\"COMPUTE NONSTAT \"+starttime+\" \"+comptstep+\" \"+endtime+\"\\n\")\n\n#file.write(\"HOTFile '\"+hotfile+\"' FREE\\n\")\nfile.write(\"STOP\\n\")\nfile.close()\n\n#==========================================\n# write bash file\n\nfile = open('./d'+str(direc)+'/'+projname+'.sh', 'w')\nfile.write(\"swanrun -input \"+swnfile.split('/')[-1]+\" -omp \"+nproc+\"\\n\")\nfile.close()\n\n#==========================================\n# write wave input files\n\nfileS = './d'+str(direc)+'/TPAR_S7.txt'\nfileE = './d'+str(direc)+'/TPAR_E7.txt'\nfileW = './d'+str(direc)+'/TPAR_W7.txt'\n\nfile = open(fileS, 'w')\nfile.write(\"TPAR\\n\")\nfor n in range(len(isotimes)):\n file.write(isotimes[n]+\" \"+str(wh_s[n])[:5]+\" \"+str(wp_s[n])[:5]+\" \"+str(wd_s[n])[:5]+\" \"+str(wdsp_s[n])[:5]+\"\\n\")\nfile.close()\n\nfile = open(fileW, 'w')\nfile.write(\"TPAR\\n\")\nfor n in range(len(isotimes)):\n file.write(isotimes[n]+\" \"+str(wh_w[n])[:5]+\" \"+str(wp_w[n])[:5]+\" \"+str(wd_w[n])[:5]+\" \"+str(wdsp_w[n])[:5]+\"\\n\")\nfile.close()\n\nfile = open(fileE, 'w')\nfile.write(\"TPAR\\n\")\nfor n in range(len(isotimes)):\n file.write(isotimes[n]+\" \"+str(wh_e[n])[:5]+\" \"+str(wp_e[n])[:5]+\" \"+str(wd_e[n])[:5]+\" \"+str(wdsp_e[n])[:5]+\"\\n\")\nfile.close()\n","sub_path":"ww3model/runswan_timestep.py","file_name":"runswan_timestep.py","file_ext":"py","file_size_in_byte":8802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"431977603","text":"import sys,os,time\nprevPath = os.path.abspath(os.getcwd())\nsys.path.insert(0,prevPath)\nimport jwt\nfrom Modules.FaceRecognition import Recognition\nimport Modules.gaze_tracking\nfrom App.MongoDBConnection import db\nimport eel\neel.init('Panel')\n\n\n@eel.expose\ndef login(a,b):\n user = 1\n \n if user is not None :\n jwt_encode = jwt.encode({'user': {'username':'msanli14','name':'Mustafa','surname':'Sanlı','phone':'05457120478'}}, 'Hacklemigelkeklemi', algorithm='HS256')\n return str(jwt_encode)\n else:\n return \"error\"\n \n@eel.expose\ndef showDashboard():\n os.system('python3 '+os.path.abspath(os.getcwd())+'/App/admin/dashboard.py')\n\n\n\n\n\n\neel.start('admin/login.html')\n\n\n\n\n\n\n \n\n","sub_path":"App/admin/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"44027500","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nfrom builtins import *\nfrom future.utils import raise_from\nfrom termcolor import colored\nimport ttmake.private.metadata as metadata\nimport ttmake.private.messages as messages\nfrom ttmake.private.exceptionclasses import ColoredError, CritError\nfrom ttmake.private.utility import convert_to_list, norm_path, format_message, format_traceback\n\nimport os\nimport sys\nif (sys.version_info < (3, 0)) and (os.name == 'nt'):\n import ttmake.private.subprocess_nt as subprocess\nelse:\n import subprocess\nimport zipfile\nimport traceback\nimport glob\n\nimport colorama\ncolorama.init()\n\n\ndef remove_path(path, option='', quiet=False):\n \"\"\".. Remove path using system command.\n\n Remove path ``path`` using system command. Safely removes symbolic links.\n Path can be specified with the * shell pattern\n (see `here <https://www.gnu.org/software/findutils/manual/html_node/find_html/Shell-Pattern-Matching.html>`__).\n\n Parameters\n ----------\n path : str\n Path to remove.\n option : str, optional\n Options for system command. Defaults to ``-rf`` for POSIX and ``/s /q`` for NT.\n quiet : bool, optional\n Suppress printing of path removed. Defaults to ``False``.\n\n Returns\n -------\n None\n\n Example\n -------\n The following code removes path ``path``.\n\n .. code-block:: python\n\n remove_path('path')\n\n The following code removes all paths beginning with ``path``.\n\n .. code-block:: python\n\n remove_path('path*')\n \"\"\"\n\n path = norm_path(path)\n\n if not option:\n option = metadata.default_options[os.name]['rmdir']\n\n command = metadata.commands[os.name]['rmdir'] % (option, path)\n process = subprocess.Popen(command,\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n universal_newlines=True)\n stdout, stderr = process.communicate()\n\n if process.returncode != 0:\n error_message = messages.crit_error_remove_path_command % command\n error_message += format_traceback(stderr)\n raise_from(CritError(error_message), None)\n else:\n if not quiet:\n message = 'Removed: `%s`' % path\n print(colored(message, metadata.color_success))\n\n\ndef remove_dir(dir_list, quiet=False):\n \"\"\".. Remove directory using system command.\n\n Remove directories in list ``dir_list`` using system command.\n Safely removes symbolic links. Directories can be specified with the * shell pattern\n (see `here <https://www.gnu.org/software/findutils/manual/html_node/find_html/Shell-Pattern-Matching.html>`__).\n Non-existent paths in list ``dir_list`` are ignored.\n\n Parameters\n ----------\n dir_list : str, list\n Directory or list of directories to remove.\n quiet : bool, optional\n Suppress printing of directories removed. Defaults to ``False``.\n\n Returns\n -------\n None\n\n Example\n -------\n The following code removes directories ``dir1`` and ``dir2``.\n\n .. code-block:: python\n\n remove_dir(['dir1', 'dir2'])\n\n The following code removes directories beginning with ``dir``.\n\n .. code-block:: python\n\n remove_dir(['dir1*'])\n \"\"\"\n\n try:\n dir_list = convert_to_list(dir_list, 'dir')\n dir_list = [norm_path(dir_path) for dir_path in dir_list]\n dir_list = [d for directory in dir_list for d in glob.glob(directory)]\n\n for dir_path in dir_list:\n if os.path.isdir(dir_path):\n remove_path(dir_path, quiet=quiet)\n elif os.path.isfile(dir_path):\n raise_from(TypeError(messages.type_error_not_dir %\n dir_path), None)\n except:\n error_message = messages.error_message % 'remove_dir'\n error_message = format_message(error_message)\n raise_from(ColoredError(error_message, traceback.format_exc()), None)\n\n\ndef clear_dir(dir_list):\n \"\"\".. Clear directory. Create directory if nonexistent.\n\n Clears all directories in list ``dir_list`` using system command.\n Safely clears symbolic links. Directories can be specified with the * shell pattern\n (see `here <https://www.gnu.org/software/findutils/manual/html_node/find_html/Shell-Pattern-Matching.html>`__).\n\n Note\n ----\n To clear a directory means to remove all contents of a directory.\n If the directory is nonexistent, the directory is created,\n unless the directory is specified via shell pattern.\n\n Parameters\n ----------\n dir_list : str, list\n Directory or list of directories to clear.\n\n Returns\n -------\n None\n\n Example\n -------\n The following code clears directories ``dir1`` and ``dir2``.\n\n .. code-block:: python\n\n clear_dir(['dir1', 'dir2'])\n\n The following code clears directories beginning with ``dir``.\n\n .. code-block:: python\n\n clear_dir(['dir*'])\n \"\"\"\n\n try:\n dir_list = convert_to_list(dir_list, 'dir')\n dir_glob = []\n\n for dir_path in dir_list:\n expand = glob.glob(dir_path)\n expand = expand if expand else [dir_path]\n dir_glob.extend(expand)\n\n remove_dir(dir_glob, quiet=True)\n\n for dir_path in dir_glob:\n option = metadata.default_options[os.name]['mkdir']\n command = metadata.commands[os.name]['mkdir'] % (option, dir_path)\n process = subprocess.Popen(command,\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n universal_newlines=True)\n stdout, stderr = process.communicate()\n\n if process.returncode != 0:\n error_message = messages.crit_error_mkdir_command % command\n error_message += format_traceback(stderr)\n raise_from(CritError(error_message), None)\n else:\n message = 'Cleared: `%s`' % dir_path\n print(colored(message, metadata.color_success))\n except:\n error_message = messages.error_message % 'clear_dir'\n error_message = format_message(error_message)\n raise_from(ColoredError(error_message, traceback.format_exc()), None)\n\n\ndef unzip(zip_path, output_dir):\n \"\"\".. Unzip file to directory.\n\n Unzips file ``zip_path`` to directory ``output_dir``.\n\n Parameters\n ----------\n zip_path : str\n Path of file to unzip.\n output_dir : str\n Directory to write outputs of unzipped file.\n\n Returns\n -------\n None\n \"\"\"\n\n try:\n with zipfile.ZipFile(zip_path, allowZip64=True) as z:\n z.extractall(output_dir)\n except:\n error_message = messages.error_message % 'zip_path'\n error_message = format_message(error_message)\n raise_from(ColoredError(error_message, traceback.format_exc()), None)\n\n\ndef zip_dir(source_dir, zip_dest):\n \"\"\".. Zip directory to file.\n\n Zips directory ``source_dir`` to file ``zip_dest``.\n\n Parameters\n ----------\n source_dir : str\n Path of directory to zip.\n zip_dest : str\n Destination of zip file.\n\n Returns\n -------\n None\n \"\"\"\n\n try:\n with zipfile.ZipFile('%s' % (zip_dest), 'w', zipfile.ZIP_DEFLATED, allowZip64=True) as z:\n source_dir = norm_path(source_dir)\n\n for root, dirs, files in os.walk(source_dir):\n for f in files:\n file_path = os.path.join(root, f)\n file_name = os.path.basename(file_path)\n z.write(file_path, file_name)\n\n message = 'Zipped: `%s` as `%s`' % (file_path, file_name)\n print(colored(message, metadata.color_success))\n except:\n error_message = messages.error_message % 'zip_dir'\n error_message = format_message(error_message)\n raise_from(ColoredError(error_message, traceback.format_exc()), None)\n\n\n__all__ = ['remove_dir', 'clear_dir', 'unzip', 'zip_dir']\n","sub_path":"lib/ttmake/modify_dir.py","file_name":"modify_dir.py","file_ext":"py","file_size_in_byte":8211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"486092762","text":"'''\nFor your reference:\n\nclass LinkedListNode:\n def __init__(self, node_value):\n self.val = node_value\n self.next = None\n'''\ndef reverse_linked_list_in_groups_of_k(head, k):\n p = head\n prev = None\n new_head = None\n node = None\n while p:\n i = 0\n q = []\n while i < k and p:\n q.append(p)\n p = p.next\n i += 1\n\n if not new_head:\n new_head = q[-1]\n\n for node in q[::-1]:\n if prev:\n prev.next = node\n\n prev = node\n\n node.next = None\n\n return new_head\n","sub_path":"2019Nov/linked_lists/list_groupk_reverse_own_pass.py","file_name":"list_groupk_reverse_own_pass.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"613019379","text":"# IMPORTS\nimport time\nimport os\nimport sys\nfrom os import system\nsys.path.append(os.path.abspath('.'))\n\nfrom src.models.game_logic import GameLogic\n\n# GAME FUNCTIONS\ndef init_game(game):\n '''\n Initialize the game. Ask for number of players and get player names.\n :param game: GameLogic object.\n :return dealer: Dealer object.\n :return player_list: List of player objects.\n '''\n game.welcome()\n game.set_player_names()\n dealer = game.get_dealer()\n player_list = game.get_players()\n \n return dealer, player_list\n\ndef dealer_blackjack(dealer, player_list, table):\n '''\n Check if dealer has blackjack and end round if they do.\n :param dealer: Dealer object.\n :param player_list: List of player objects.\n :return: True if dealer has blackjack, False otherwise.\n '''\n dealer_blackjack_flag = False\n \n if dealer.showing_ace() or dealer.showing_face():\n if dealer.has_blackjack():\n # Player ties if they also have blackjack, loses otherwise.\n table.draw_table(face_down=False)\n print(\"\\nDealer BlackJack.\")\n for player in player_list:\n if player.has_blackjack():\n player.push()\n \n else:\n player.lose_hand()\n\n dealer_blackjack_flag = True\n \n return dealer_blackjack_flag\n\ndef dealer_bust(player_list, test=False):\n '''\n All players who haven't busted win their bets.\n :param player_list: List of player objects.\n '''\n for player in player_list:\n if player.is_split():\n if not player.split_hand.is_bust():\n player.split_hand.win_hand()\n player.payout_split()\n \n if not player.is_bust():\n player.win_hand()\n\n else:\n player.lose_hand()\n\n if not test:\n time.sleep(1)\n\ndef compare_hands_and_payout(dealer, player_list, test=False):\n '''\n Compare each player's hand to the dealer hand and pay out winnings.\n :param dealer: Dealer object.\n :param player_list: List of player objects.\n '''\n dealer_hand = dealer.count_hand()\n for player in player_list:\n if player.is_split():\n check_player_hand(player.split_hand, dealer_hand)\n player.payout_split()\n\n check_player_hand(player, dealer_hand)\n \n if not test:\n time.sleep(1)\n\n\ndef check_player_hand(player, dealer_hand):\n '''\n Compare the player's hand against the dealer's hand.\n :param player: Player object.\n :param dealer_hand: The dealer's hand.\n '''\n player_hand = player.count_hand()\n \n if player.is_bust():\n player.lose_hand()\n\n else:\n if player_hand > dealer_hand:\n player.win_hand()\n \n elif player_hand < dealer_hand:\n player.lose_hand()\n\n else:\n player.push()\n\ndef perform_user_action(user_input, player, deck):\n '''\n Perform the action chosen by the user.\n :param user_input: String used to determine user action.\n :param player: Player object for user.\n :return stay_flag: Flag used to determine whether or not user decided to stay and end their turn.\n :return stay_flag: Flag used to determine whether or not user decided to split.\n '''\n stay_flag = False\n \n if user_input == 'h':\n player.draw_card(deck)\n\n elif user_input == 'd':\n player.double_down(deck)\n stay_flag = True\n\n elif user_input == 'sp':\n player.split(deck)\n\n else:\n stay_flag = True\n\n return stay_flag\n\ndef print_title():\n '''\n Print the title of the game.\n '''\n system('cls')\n print(\"BLACKJACK\\n\".center(100))\n\ndef remove_players_without_money(player_list, min_bet):\n '''\n Remove players from the game that no longer have enough money to play.\n :param player_list: List of player objects in the game.\n :param min_bet: Minimum bet at the table.\n :return: List of player objects with players without enough money removed.\n '''\n for player in player_list.copy():\n if player.get_balance() < min_bet:\n print(f\"\\n{player.name}: Sorry, you don't have enough money to play.\")\n player_list.remove(player)\n\n return player_list\n\ndef end_of_round(player_list):\n '''\n Print a message at the end of the round.\n :param player_list: List of player objects in the game.\n '''\n if len(player_list) == 0:\n input(\"\\nThanks for playing.\")\n else:\n input(\"\\nPress enter to play another hand.\")","sub_path":"src/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":4594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"270494939","text":"\"\"\"\nPlease refer to the following tutorial in the documentation at www.opendeep.org\n\nTutorial: Classifying Handwritten MNIST Images\n\"\"\"\n# standard libraries\nimport logging\n# third party libraries\nfrom opendeep.log.logger import config_root_logger\nfrom opendeep.models.container import Prototype\nfrom opendeep.models.single_layer.basic import BasicLayer, SoftmaxLayer\nfrom opendeep.optimization.stochastic_gradient_descent import SGD\nfrom opendeep.data.standard_datasets.image.mnist import MNIST\n\n# grab a log to output useful info\nconfig_root_logger()\nlog = logging.getLogger(__name__)\n\ndef sequential_add_layers():\n # This method is to demonstrate adding layers one-by-one to a Prototype container.\n # As you can see, inputs_hook are created automatically by Prototype so we don't need to specify!\n mlp = Prototype()\n mlp.add(BasicLayer(input_size=28*28, output_size=512, activation='rectifier', noise='dropout'))\n mlp.add(BasicLayer(output_size=512, activation='rectifier', noise='dropout'))\n mlp.add(SoftmaxLayer(output_size=10))\n\n return mlp\n\ndef add_list_layers():\n # You can also add lists of layers at a time (or as initialization) to a Prototype! This lets you specify\n # more complex interactions between layers!\n hidden1 = BasicLayer(input_size=28*28,\n output_size=512,\n activation='rectifier',\n noise='dropout')\n\n hidden2 = BasicLayer(inputs_hook=(512, hidden1.get_outputs()),\n output_size=512,\n activation='rectifier',\n noise='dropout')\n\n class_layer = SoftmaxLayer(inputs_hook=(512, hidden2.get_outputs()),\n output_size=10)\n\n mlp = Prototype([hidden1, hidden2, class_layer])\n return mlp\n\n\nif __name__ == '__main__':\n mlp = sequential_add_layers()\n optimizer = SGD(model=mlp,\n dataset=MNIST(concat_train_valid=False),\n n_epoch=500,\n batch_size=600,\n learning_rate=.01,\n momentum=.9,\n nesterov_momentum=True)\n optimizer.train()","sub_path":"opendeep/tutorials/tutorial03_mnist_mlp.py","file_name":"tutorial03_mnist_mlp.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"532703824","text":"import re\nfrom pprint import pprint\nfrom collections import defaultdict\n\nwith open('./words.mhtml') as stuff:\n page = stuff.read()\n\n # We want the second <table>...</table> block, ignoring line endings\n pieces = re.findall('(?s)<table.*?</table>', page)\n body = pieces[1]\n\n pattern = ( '(?s)' + # turn off line separation\n '<tr>.*?' + # each row is a <tr>...</tr>\n '<td.*?' + # discard first cell\n '<td.*?>(?: |\\s)*(?P<word>\\w*)</td>.*?' + # collect word\n '<td.*?' + # discard third cell\n '<td.*?>(?P<freq>\\d+)</td>.*?' + # collect frequency\n '.*?</tr>' # discard rest of row\n )\n content = re.findall(pattern, body)\n dig_freq = defaultdict(int)\n for word, freq in content:\n word = word.lower()\n freq = int(freq)\n for index in range(0, len(word) - 1):\n pair = word[index:index + 2]\n dig_freq[pair] += freq\n dig_freq = dig_freq.items()\n dig_freq = sorted(dig_freq, key = lambda entry: -entry[1])\n\n pprint(dig_freq)","sub_path":"digraphs.py","file_name":"digraphs.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"146742220","text":"from PIL import Image\r\nimport sys\r\nimport pyocr\r\nimport pyocr.builders\r\n\r\ntools = pyocr.get_available_tools()\r\nif len(tools) == 0:\r\n print(\"No OCR tool found\")\r\n sys.exit(1)\r\ntool = tools[0] #取得可用工具\r\n\r\ntxt = tool.image_to_string(\r\n Image.open('test.jpg'),\r\n builder=pyocr.builders.TextBuilder()\r\n)\r\nprint(\"result=\",txt)","sub_path":"pyocr1.py","file_name":"pyocr1.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"232891371","text":"import copy\nimport logging\nimport os\nimport shutil\nimport tempfile\nimport time\nfrom typing import Optional, List, Dict\n\nfrom dedoc.attachment_extractors.abstract_attachment_extractor import AbstractAttachmentsExtractor\nfrom dedoc.attachments_handler.attachments_handler import AttachmentsHandler\nfrom dedoc.converters.file_converter import FileConverterComposition\nfrom dedoc.common.exceptions.bad_file_exception import BadFileFormatException\nfrom dedoc.data_structures.document_content import DocumentContent\nfrom dedoc.data_structures.parsed_document import ParsedDocument\nfrom dedoc.data_structures.unstructured_document import UnstructuredDocument\nfrom dedoc.metadata_extractor.metadata_extractor_composition import MetadataExtractorComposition\nfrom dedoc.readers.reader_composition import ReaderComposition\nfrom dedoc.structure_constructor.structure_constructor_composition import StructureConstructorComposition\nfrom dedoc.utils import get_unique_name, get_empty_content\n\n\nclass DedocManager:\n\n def __init__(self,\n converter: FileConverterComposition,\n attachments_handler: AttachmentsHandler,\n reader: ReaderComposition,\n structure_constructor: StructureConstructorComposition,\n document_metadata_extractor: MetadataExtractorComposition,\n logger: logging.Logger,\n version: str):\n self.version = version\n self.converter = converter\n self.attachments_handler = attachments_handler\n self.reader = reader\n self.structure_constructor = structure_constructor\n self.document_metadata_extractor = document_metadata_extractor\n self.logger = logger\n\n @staticmethod\n def from_config(version: str, manager_config: dict, *, config: dict) -> \"DedocManager\":\n \"\"\"\n this method helps to construct dedoc manager from config\n :param version: str, actual version of dedoc (or your lib, based on dedoc) Lay in file VERSION\n :param manager_config: dict, you may get example of managers config dict in manager_config.py\n :param config: any additional parameters for dedoc lay in config, see config.py\n :return: DedocManager\n \"\"\"\n\n logger = config.get(\"logger\")\n logger = logger if logger is not None else logging.getLogger(__name__)\n manager = DedocManager(\n converter=manager_config[\"converter\"],\n attachments_handler=manager_config[\"attachments_extractor\"],\n reader=manager_config[\"reader\"],\n structure_constructor=manager_config[\"structure_constructor\"],\n document_metadata_extractor=manager_config[\"document_metadata_extractor\"],\n logger=logger,\n version=version\n )\n\n return manager\n\n def parse_file(self,\n file_path: str,\n parameters: Dict[str, str],\n original_file_name: Optional[str] = None) -> ParsedDocument:\n \"\"\"\n Function of complete parsing document with 'filename' with attachment files analyze\n :param file_path: full path where file lay\n :param parameters: any parameters, specify how we want to parse file\n :param original_file_name: name of original file (None if file was not ranamed)\n :return:\n \"\"\"\n warnings = []\n if not os.path.isfile(path=file_path):\n raise FileNotFoundError()\n self.logger.info(\"start handle {}\".format(file_path))\n if original_file_name is None:\n original_file_name = os.path.basename(file_path)\n filename = get_unique_name(file_path)\n with tempfile.TemporaryDirectory() as tmp_dir:\n shutil.copy(file_path, os.path.join(tmp_dir, filename))\n\n # Step 1 - Converting\n filename_convert = self.converter.do_converting(tmp_dir, filename, parameters=parameters)\n self.logger.info(\"finish conversion {} -> {}\".format(filename, filename_convert))\n # Step 2 - Parsing content of converted file\n unstructured_document = self.reader.parse_file(\n tmp_dir=tmp_dir,\n filename=filename_convert,\n parameters=parameters\n )\n warnings.extend(unstructured_document.warnings)\n self.logger.info(\"parse file {}\".format(filename_convert))\n structure_type = parameters.get(\"structure_type\")\n document_content = self.structure_constructor.structure_document(document=unstructured_document,\n structure_type=structure_type,\n parameters=parameters)\n warnings.extend(document_content.warnings)\n self.logger.info(\"get document content {}\".format(filename_convert))\n # Step 3 - Adding meta-information\n parsed_document = self.__parse_file_meta(document_content=document_content,\n directory=tmp_dir,\n filename=filename,\n converted_filename=filename_convert,\n original_file_name=original_file_name,\n parameters=parameters)\n warnings.extend(parsed_document.warnings)\n self.logger.info(\"get structure and metadata {}\".format(filename_convert))\n\n if AbstractAttachmentsExtractor.with_attachments(parameters):\n self.logger.info(\"start handle attachments\")\n parsed_attachment_files = self.__handle_attachments(document=unstructured_document,\n parameters=parameters,\n tmp_dir=tmp_dir)\n self.logger.info(\"get attachments {}\".format(filename_convert))\n parsed_document.add_attachments(parsed_attachment_files)\n else:\n parsed_document.attachments = None\n parsed_document.version = self.version\n parsed_document.warnings.extend(warnings)\n self.logger.info(\"finish handle {}\".format(filename))\n return parsed_document\n\n def __parse_file_meta(self,\n document_content: Optional[DocumentContent],\n directory: str,\n filename: str,\n converted_filename: str,\n original_file_name: str,\n parameters: dict) -> ParsedDocument:\n \"\"\"\n Decorator with metainformation\n document_content - None for unsupported document in attachments\n \"\"\"\n parsed_document = self.document_metadata_extractor.add_metadata(doc=document_content,\n directory=directory,\n filename=filename,\n converted_filename=converted_filename,\n original_filename=original_file_name,\n parameters=parameters)\n return parsed_document\n\n def __handle_attachments(self,\n document: UnstructuredDocument,\n parameters: dict,\n tmp_dir: str) -> List[ParsedDocument]:\n parsed_attachment_files = []\n self.attachments_handler.handle_attachments(document=document, parameters=parameters)\n previous_log_time = time.time()\n for i, attachment in enumerate(document.attachments):\n current_time = time.time()\n if current_time - previous_log_time > 3:\n previous_log_time = current_time # not log too often\n self.logger.info(\"Handle attachment {} of {}\".format(i, len(document.attachments)))\n parameters_copy = copy.deepcopy(parameters)\n parameters_copy[\"is_attached\"] = True\n parameters_copy[\"attachment\"] = attachment\n try:\n if attachment.need_content_analysis:\n file_path = os.path.join(tmp_dir, attachment.get_filename_in_path())\n parsed_file = self.parse_file(file_path,\n parameters=parameters_copy,\n original_file_name=attachment.get_original_filename()\n )\n else:\n parsed_file = self.__parse_file_meta(document_content=get_empty_content(),\n directory=tmp_dir,\n filename=attachment.get_filename_in_path(),\n converted_filename=attachment.get_filename_in_path(),\n original_file_name=attachment.get_original_filename(),\n parameters=parameters_copy)\n except BadFileFormatException:\n # return empty ParsedDocument with Meta information\n parsed_file = self.__parse_file_meta(document_content=get_empty_content(),\n directory=tmp_dir,\n filename=attachment.get_filename_in_path(),\n converted_filename=attachment.get_filename_in_path(),\n original_file_name=attachment.get_original_filename(),\n parameters=parameters_copy)\n parsed_file.metadata.set_uid(attachment.uid)\n parsed_attachment_files.append(parsed_file)\n return parsed_attachment_files\n","sub_path":"dedoc/manager/dedoc_manager.py","file_name":"dedoc_manager.py","file_ext":"py","file_size_in_byte":10269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"29150863","text":"import os\nimport time\nimport re\n\nstart = time.time()\n\nexp_time = \"41\"\nlocaltime = time.asctime( time.localtime(time.time()) )\nprojects_dir = \"/root/repos/repos\"+exp_time\nmvn_log_dir = \"/root/git/extract_code/mvn_log\"\nall_projects_count = len(os.listdir(projects_dir))\nmvn_projects_count = 0\ndelete_projects = []\nanalyzed_projects = []\nfor project_name in os.listdir(projects_dir):\n project_dir = os.path.join(projects_dir, project_name)\n if not \"pom.xml\" in os.listdir(project_dir):\n delete_projects.append(project_name)\n os.system(\"rm -r \" + project_dir)\n else:\n mvn_projects_count += 1\n analyzed_projects.append(project_name)\n print(\">>>>>>>>>>>>>>>>>>>>>>>>>>mvn package\",project_name+\">>>>>>>>>>>>>>\")\n os.system(\"cd \" +project_dir + \"; mvn package -DskipTests\") \nend = time.time()\n\nprint(\"=================================\")\nprint(\"all projects count:\", all_projects_count)\nprint(\"package projects count:\", mvn_projects_count)\nprint(\"package projects :\", ' '.join(analyzed_projects))\nprint(\"delete no maven projects:\", ' '.join(delete_projects))\nprint(\"time used:\", end - start)\nprint(\"=================================\")\n\nwith open(os.path.join(mvn_log_dir, \"all_mvn_infomation.txt\"), \"a+\") as f:\n f.write(\"===============================\\n\")\n f.write(\"experiment NO: \" + exp_time + \"\\n\")\n f.write(\"experiment time: \" + str(localtime) + \"\\n\")\n f.write(\"all projects count: \" + str(all_projects_count) + \"\\n\")\n f.write(\"package projects count: \" + str(mvn_projects_count) + \"\\n\")\n f.write(\"package projects: \" + ' '.join(analyzed_projects) + \"\\n\")\n f.write(\"delete no maven projects: \" + ' '.join(delete_projects)+ \"\\n\")\n f.write(\"all time used: \" + str(end - start) + \"s\\n\" )\n f.write(\"===============================\\n\")\n#sss\n","sub_path":"map_code/mvn_package.py","file_name":"mvn_package.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"279699282","text":"\"\"\"Module containing `Archive` class.\"\"\"\n\n\nfrom __future__ import print_function\n\nfrom collections import namedtuple\nimport datetime\nimport os.path\n\nimport numpy as np\nimport pytz\nimport sqlite3 as sqlite\n\nfrom vesper.archive.clip_class import ClipClass\nfrom vesper.archive.detector import Detector\nfrom vesper.archive.station import Station\nfrom vesper.util.audio_file_utils import \\\n WAVE_FILE_NAME_EXTENSION as _CLIP_FILE_NAME_EXTENSION\nfrom vesper.util.bunch import Bunch\nfrom vesper.util.preferences import preferences as prefs\nfrom vesper.util.instantaneous_frequency_analysis import \\\n InstantaneousFrequencyAnalysis\nfrom vesper.util.spectrogram import Spectrogram\nimport vesper.util.data_windows as data_windows\nimport vesper.util.sound_utils as sound_utils\n\n\n'''\nQuestions regarding cloud archives:\n\n* What should GAE entity groups be?\n* How do we support classification histories?\n* How do we support aggregate statistics?\n* What indexes do we need?\n* Should we require login, perhaps just for certain functionality?\n* Do we provide just sounds, or spectrograms, too?\n* How soon could we have multiple people classifying?\n* How can we automate uploading?\n'''\n\n\n_CLIP_DATABASE_FILE_NAME = 'ClipDatabase.db'\n \n# named tuple classes for database tables\n_StationTuple = namedtuple(\n '_StationTuple', ('id', 'name', 'long_name', 'time_zone_name'))\n_DetectorTuple = namedtuple('_DetectorTuple', ('id', 'name'))\n_ClipClassTuple = namedtuple('_ClipClassTuple', ('id', 'name'))\n_ClipClassNameComponentTuple = \\\n namedtuple('_ClipClassNameComponentTuple', ('id', 'component'))\n_ClipTuple = namedtuple(\n '_ClipTuple',\n ('id', 'station_id', 'detector_id', 'time', 'night', 'duration',\n 'clip_class_id', 'clip_class_name_0_id', 'clip_class_name_1_id',\n 'clip_class_name_2_id'))\n\n\n_CREATE_STATION_TABLE_SQL = '''\n create table Station (\n id integer primary key,\n name text,\n long_name text,\n time_zone_name text,\n unique(name) on conflict rollback)'''\n \n \n_CREATE_DETECTOR_TABLE_SQL = '''\n create table Detector (\n id integer primary key,\n name text,\n unique(name) on conflict rollback)'''\n \n \n_CREATE_CLIP_CLASS_TABLE_SQL = '''\n create table ClipClass (\n id integer primary key,\n name text,\n unique(name) on conflict rollback)'''\n \n \n_CREATE_CLIP_CLASS_NAME_COMPONENT_TABLE_SQL = '''\n create table ClipClassNameComponent (\n id integer primary key,\n component text,\n unique(component) on conflict rollback)'''\n \n \n_CREATE_CLIP_TABLE_SQL = '''\n create table Clip (\n id integer primary key,\n station_id integer,\n detector_id integer,\n time datetime,\n night integer,\n duration real,\n clip_class_id integer,\n clip_class_name_0_id integer,\n clip_class_name_1_id integer,\n clip_class_name_2_id integer,\n unique(station_id, detector_id, time) on conflict rollback)'''\n \n_CREATE_CLIP_TABLE_MULTICOLUMN_INDEX_SQL = '''\n create index ClipIndex on Clip(station_id, detector_id, night)\n'''\n\n_CREATE_CLIP_TABLE_NIGHT_DATE_INDEX_SQL = '''\n create index NightIndex on Clip(night)\n'''\n\n_INSERT_CLIP_SQL = \\\n 'insert into Clip values (' + \\\n ', '.join(['?'] * len(_ClipTuple._fields)) + ')'\n\n\n_SELECT_CLIP_SQL = \\\n 'select * from Clip where station_id = ? and detector_id = ? and time = ?'\n \n \n_CLASSIFY_CLIP_SQL = (\n 'update Clip set clip_class_id = ?, clip_class_name_0_id = ?, '\n 'clip_class_name_1_id = ?, clip_class_name_2_id = ? where id = ?')\n\n\nclass Archive(object):\n \n \n CLIP_CLASS_NAME_COMPONENT_SEPARATOR = '.'\n CLIP_CLASS_NAME_WILDCARD = '*'\n CLIP_CLASS_NAME_UNCLASSIFIED = 'Unclassified'\n\n\n @staticmethod\n def create(dir_path, stations=None, detectors=None, clip_classes=None):\n \n # TODO: Validate arguments, for example to make sure that\n # clip class names do not have more than three components?\n \n if stations is None:\n stations = []\n \n if detectors is None:\n detectors = []\n \n if clip_classes is None:\n clip_classes = []\n \n # Create archive directory, along with any needed directories above,\n # if needed.\n if not os.path.exists(dir_path):\n os.makedirs(dir_path)\n \n archive = Archive(dir_path)\n archive._open_db()\n archive._create_tables(stations, detectors, clip_classes)\n archive._close_db()\n \n return archive\n \n \n def __init__(self, dir_path):\n self._archive_dir_path = dir_path\n self._name = os.path.basename(dir_path)\n self._db_file_path = os.path.join(dir_path, _CLIP_DATABASE_FILE_NAME)\n \n \n @property\n def name(self):\n return self._name\n \n \n def open(self, cache_db=False):\n self._open_db(cache_db)\n self._create_dicts()\n self._clip_dir_paths = set()\n\n\n def _open_db(self, cache_db=False):\n \n self._cache_db = cache_db\n \n if self._cache_db:\n file_conn = self._open_db_file()\n self._conn = sqlite.connect(':memory:')\n _copy_db(file_conn, self._conn)\n file_conn.close()\n \n else:\n self._conn = self._open_db_file()\n\n self._cursor = self._conn.cursor()\n\n\n def _open_db_file(self):\n \n path = self._db_file_path\n \n try:\n return sqlite.connect(path)\n \n except:\n \n if not os.path.exists(path):\n raise ValueError(\n 'Database file \"{:s}\" does not exist'.format(path))\n else:\n m = 'Database file \"{:s}\" exists but could not be opened.'\n raise ValueError(m.format(path))\n\n\n def close(self):\n self._close_db()\n \n \n def _close_db(self):\n \n if self._cache_db:\n \n path = self._db_file_path + ' new'\n \n # write memory database to new file\n file_conn = sqlite.connect(path)\n _copy_db(self._conn, file_conn)\n file_conn.close()\n \n # delete old database file if it exists\n if os.path.exists(self._db_file_path):\n os.remove(self._db_file_path)\n \n # rename new database file\n os.rename(path, self._db_file_path)\n \n self._conn.close()\n \n \n def _drop_tables(self):\n self._drop_table('Station')\n self._drop_table('Detector')\n self._drop_table('ClipClass')\n self._drop_table('ClipClassNameComponent')\n self._drop_table('Clip')\n \n \n def _drop_table(self, name):\n \n try:\n self._cursor.execute('drop table ' + name)\n \n except sqlite.OperationalError:\n \n # TODO: Recover gracefully here.\n pass\n \n \n def _create_tables(self, stations, detectors, clip_classes):\n self._create_station_table(stations)\n self._create_detector_table(detectors)\n self._create_clip_class_table(clip_classes)\n self._create_clip_class_name_component_table(clip_classes)\n self._create_clip_table()\n \n \n def _create_station_table(self, stations):\n self._create_table(\n 'Station', _CREATE_STATION_TABLE_SQL, stations,\n self._create_station_tuple)\n \n \n def _create_table(self, name, create_sql, objects=(), tuple_creator=None):\n \n self._cursor.execute(create_sql)\n \n if len(objects) > 0:\n \n if tuple_creator is None:\n tuples = objects\n else:\n tuples = [tuple_creator(obj) for obj in objects]\n \n marks = ', '.join(['?'] * len(tuples[0]))\n sql = 'insert into {:s} values ({:s})'.format(name, marks)\n \n self._cursor.executemany(sql, tuples)\n \n self._conn.commit()\n \n \n def _create_station_tuple(self, station):\n return _StationTuple(\n id=None, name=station.name, long_name=station.long_name,\n time_zone_name=station.time_zone.zone)\n \n \n def _create_detector_table(self, detectors):\n self._create_table(\n 'Detector', _CREATE_DETECTOR_TABLE_SQL, detectors,\n self._create_detector_tuple)\n \n \n def _create_detector_tuple(self, detector):\n return _DetectorTuple(id=None, name=detector.name)\n \n \n def _create_clip_class_table(self, clip_classes):\n self._create_table(\n 'ClipClass', _CREATE_CLIP_CLASS_TABLE_SQL, clip_classes,\n self._create_clip_class_tuple)\n \n \n def _create_clip_class_tuple(self, clip_class):\n return _ClipClassTuple(id=None, name=clip_class.name)\n \n \n def _create_clip_class_name_component_table(self, clip_classes):\n components = _get_name_components(clip_classes)\n tuples = [_ClipClassNameComponentTuple(None, c) for c in components]\n self._create_table(\n 'ClipClassNameComponent',\n _CREATE_CLIP_CLASS_NAME_COMPONENT_TABLE_SQL,\n tuples)\n \n \n def _create_clip_table(self):\n \n self._create_table('Clip', _CREATE_CLIP_TABLE_SQL)\n \n self._cursor.execute(_CREATE_CLIP_TABLE_MULTICOLUMN_INDEX_SQL)\n self._cursor.execute(_CREATE_CLIP_TABLE_NIGHT_DATE_INDEX_SQL)\n \n self._conn.commit()\n \n \n def _create_dicts(self):\n aux = self._create_dicts_aux\n (self._station_ids, self._stations) = aux(self.stations)\n (self._detector_ids, self._detectors) = aux(self.detectors)\n (self._clip_class_ids, self._clip_classes) = \\\n aux(self.clip_classes)\n self._clip_class_name_component_ids = \\\n dict((o.component, o.id)\n for o in self._get_clip_class_name_components())\n \n \n def _create_dicts_aux(self, objects):\n ids_dict = dict((o.name, o.id) for o in objects)\n objects_dict = dict((o.id, o) for o in objects)\n return (ids_dict, objects_dict)\n \n \n def _get_clip_class_name_components(self):\n sql = 'select * from ClipClassNameComponent order by id'\n self._cursor.execute(sql)\n rows = self._cursor.fetchall()\n return self._create_bunches(_ClipClassNameComponentTuple, rows)\n \n \n def _create_bunches(self, cls, rows):\n return [Bunch(**dict(zip(cls._fields, r))) for r in rows]\n \n\n @property\n def stations(self):\n return self._create_objects_from_db_table(Station)\n \n \n def _create_objects_from_db_table(self, cls):\n sql = 'select * from {:s} order by id'.format(cls.__name__)\n self._cursor.execute(sql)\n rows = self._cursor.fetchall()\n objects = [_create_with_id(cls, *r) for r in rows]\n objects.sort(key=lambda o: o.name)\n return objects\n \n \n @property\n def detectors(self):\n return self._create_objects_from_db_table(Detector)\n \n \n @property\n def clip_classes(self):\n return self._create_objects_from_db_table(ClipClass)\n \n \n @property\n def start_night(self):\n return self._get_extremal_night('min')\n \n \n def _get_extremal_night(self, function_name):\n sql = 'select {:s}(night) from Clip'.format(function_name)\n self._cursor.execute(sql)\n date_int = self._cursor.fetchone()[0]\n return _int_to_date(date_int)\n \n \n @property\n def end_night(self):\n return self._get_extremal_night('max')\n \n \n def add_clip(\n self, station_name, detector_name, time, sound,\n clip_class_name=None):\n \n \"\"\"\n Adds a clip to this archive.\n \n :Parameters:\n \n station_name : `str`\n the name of the station of the clip.\n \n detector_name : `str`\n the name of the detector of the clip.\n \n time : `datetime`\n the UTC start time of the clip.\n \n To help ensure archive data quality, the start time is\n required to have the `pytz.utc` time zone.\n \n sound : `object`\n the clip sound.\n \n The clip sound must include a `samples` attribute\n whose value is a NumPy array containing the 16-bit\n two's complement samples of the sound, and a\n `sample_rate` attribute specifying the sample rate\n of the sound in hertz.\n \n clip_class_name : `str`\n the clip class name, or `None` if the class is not known.\n \n :Returns:\n the inserted clip, of type `Clip`.\n \n :Raises ValueError:\n if the specified station name, detector name, or clip\n class name is not recognized, or if there is already a\n clip in the archive with the specified station name,\n detector name, and time.\n \"\"\"\n \n \n station_id = self._check_station_name(station_name)\n detector_id = self._check_detector_name(detector_name)\n clip_class_id = self._check_clip_class_name(clip_class_name)\n \n if time.tzinfo is not pytz.utc:\n raise ValueError('Clip time zone must be `pytz.utc`.')\n \n station = self._stations[station_id]\n night = _date_to_int(station.get_night(time))\n \n duration = len(sound.samples) / float(sound.sample_rate)\n ids = self._get_clip_class_name_component_ids(clip_class_name)\n \n clip_tuple = _ClipTuple(\n id=None,\n station_id=station_id,\n detector_id=detector_id,\n time=_format_clip_time(time),\n night=night,\n duration=duration,\n clip_class_id=clip_class_id,\n clip_class_name_0_id=ids[0],\n clip_class_name_1_id=ids[1],\n clip_class_name_2_id=ids[2])\n \n try:\n self._cursor.execute(_INSERT_CLIP_SQL, clip_tuple)\n \n except sqlite.IntegrityError:\n f = ('There is already a clip in the archive for station \"{:s}\", '\n 'detector \"{:s}\", and UTC time {:s}.')\n raise ValueError(\n f.format(station_name, detector_name, _format_clip_time(time)))\n \n clip_id = self._cursor.lastrowid\n \n clip = _Clip(\n self, clip_id, station, detector_name, time, duration,\n clip_class_name)\n \n self._create_clip_dir_if_needed(clip.file_path)\n \n sound_utils.write_sound_file(clip.file_path, sound)\n \n # We wait until here to commit since we don't want to commit if\n # the sound file write fails.\n self._conn.commit()\n \n return clip\n\n\n def _get_clip_class_name_component_ids(self, class_name):\n components = class_name.split('.') if class_name is not None else []\n ids = [self._clip_class_name_component_ids[c] for c in components]\n return ids + [None] * (3 - len(components))\n \n \n def _check_station_name(self, name):\n try:\n return self._station_ids[name]\n except KeyError:\n raise ValueError('Unrecognized station name \"{:s}\".'.format(name))\n \n \n def _check_detector_name(self, name):\n try:\n return self._detector_ids[name]\n except KeyError:\n raise ValueError('Unrecognized detector name \"{:s}\".'.format(name))\n \n \n def _check_clip_class_name(self, name):\n \n if name is None:\n return None\n \n else:\n \n try:\n return self._clip_class_ids[name]\n except KeyError:\n raise ValueError(\n 'Unrecognized clip class name \"{:s}\".'.format(name))\n \n \n def get_clip_counts(\n self, station_name=None, detector_name=None, start_night=None,\n end_night=None, clip_class_name=None):\n \n \"\"\"\n Counts the archived clips matching the specified criteria.\n \n :Returns:\n Per-night clip counts in a dictionary that maps start\n night dates (of type `Date`) to clip counts (of type\n `int`).\n \"\"\"\n \n\n where = self._create_where_clause(\n station_name, detector_name, start_night, end_night,\n clip_class_name)\n \n sql = 'select night, count(*) from Clip' + where + \\\n ' group by night'\n \n# print('Archive.get_clip_counts:', sql)\n \n self._cursor.execute(sql)\n \n return dict((_int_to_date(d), c) for (d, c) in self._cursor)\n \n \n def _create_where_clause(\n self, station_name, detector_name, start_night, end_night,\n clip_class_name):\n \n conds = []\n \n conds += self._get_station_conditions(station_name)\n conds += self._get_detector_conditions(detector_name)\n conds += self._get_night_conditions(start_night, end_night)\n conds += self._get_clip_class_conditions(clip_class_name)\n \n return ' where ' + ' and '.join(conds) if len(conds) != 0 else ''\n \n\n def _get_station_conditions(self, station_name):\n \n if station_name is None:\n return []\n \n else:\n self._check_station_name(station_name)\n id_ = self._station_ids[station_name]\n return ['station_id = {:d}'.format(id_)]\n \n \n def _get_detector_conditions(self, detector_name):\n \n if detector_name is None:\n return []\n \n else:\n self._check_detector_name(detector_name)\n id_ = self._detector_ids[detector_name]\n return ['detector_id = {:d}'.format(id_)]\n \n \n def _get_night_conditions(self, start_night, end_night):\n \n if start_night != end_night:\n aux = self._get_night_conditions_aux\n return aux(start_night, '>=') + aux(end_night, '<=')\n \n elif start_night is not None:\n # start date and end date are equal and not `None`\n \n return ['night = {:d}'.format(_date_to_int(start_night))]\n \n else:\n # start date and end date are both `None`\n \n return []\n\n \n def _get_night_conditions_aux(self, date, operator):\n \n if date is None:\n return []\n \n else:\n return ['night {:s} {:d}'.format(operator, _date_to_int(date))]\n \n \n def _get_clip_class_conditions(self, class_name):\n \n if class_name is None or \\\n class_name == Archive.CLIP_CLASS_NAME_WILDCARD:\n \n return []\n \n else:\n \n include_subclasses = False\n \n if class_name.endswith(Archive.CLIP_CLASS_NAME_WILDCARD):\n include_subclasses = True\n n = len(Archive.CLIP_CLASS_NAME_WILDCARD)\n class_name = class_name[:-n]\n \n if class_name == Archive.CLIP_CLASS_NAME_UNCLASSIFIED:\n return ['clip_class_id is null']\n \n else:\n \n self._check_clip_class_name(class_name)\n\n if include_subclasses:\n \n components = class_name.split('.')\n \n ids = [self._clip_class_name_component_ids[c]\n for c in components]\n \n return ['clip_class_name_{:d}_id = {:d}'.format(*p)\n for p in enumerate(ids)]\n \n else:\n id_ = self._clip_class_ids[class_name]\n return ['clip_class_id = {:d}'.format(id_)]\n \n \n def get_clips(\n self, station_name=None, detector_name=None, night=None,\n clip_class_name=None):\n \n \"\"\"\n Gets the archived clips matching the specified criteria.\n \n :Returns:\n Per-night clip lists in a dictionary that maps start\n night dates (of type `Date`) to lists of `Clip` objects.\n \"\"\"\n \n where = self._create_where_clause(\n station_name, detector_name, night, night, clip_class_name)\n \n sql = 'select * from Clip' + where + ' order by time'\n \n# print('Archive.get_clips', sql)\n \n# planSql = 'explain query plan ' + sql\n# print('Archive.get_clips', planSql)\n# self._cursor.execute(planSql)\n# rows = self._cursor.fetchall()\n# print(rows)\n \n # TODO: Try to speed this up. Are we using indices effectively?\n self._cursor.execute(sql)\n \n return self._create_clips()\n \n \n def _create_clips(self):\n # rows = self._cursor.fetchall()\n # return [self._create_clip(_ClipTuple._make(row)) for row in rows]\n # TODO: Try to speed this up. The iteration is slow.\n return [self._create_clip(_ClipTuple._make(row))\n for row in self._cursor]\n \n \n def _create_clip(self, clip):\n \n station = self._stations[clip.station_id]\n detector_name = self._detectors[clip.detector_id].name\n \n class_id = clip.clip_class_id\n try:\n clip_class_name = self._clip_classes[class_id].name\n except KeyError:\n clip_class_name = None\n \n time = self._parse_clip_time(clip.time)\n \n return _Clip(\n self, clip.id, station, detector_name, time,\n clip.duration, clip_class_name)\n \n \n def _parse_clip_time(self, time):\n time = datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S.%f')\n time = pytz.utc.localize(time)\n return time\n \n \n def get_clip(self, station_name, detector_name, time):\n \n station_id = self._check_station_name(station_name)\n detector_id = self._check_detector_name(detector_name)\n \n if time.tzinfo is not pytz.utc:\n raise ValueError('Clip time zone must be `pytz.utc`.')\n \n time = _format_clip_time(time)\n clip_info = (station_id, detector_id, time)\n self._cursor.execute(_SELECT_CLIP_SQL, clip_info)\n \n row = self._cursor.fetchone()\n \n if row is None:\n return None\n \n else:\n return self._create_clip(_ClipTuple._make(row))\n \n \n def _classify_clip(self, clip_id, clip_class_name):\n \n class_id = self._check_clip_class_name(clip_class_name)\n component_ids = self._get_clip_class_name_component_ids(\n clip_class_name)\n \n values = [class_id] + component_ids + [clip_id]\n self._cursor.execute(_CLASSIFY_CLIP_SQL, values)\n self._conn.commit()\n \n \n def _create_clip_dir_if_needed(self, path):\n \n dir_path = os.path.dirname(path)\n \n if dir_path not in self._clip_dir_paths:\n # directory either doesn't exist or hasn't yet been\n # added to `_clip_dir_paths`\n \n try:\n os.makedirs(dir_path)\n \n except OSError:\n \n if not (os.path.exists(dir_path) and os.path.isdir(dir_path)):\n # makedirs did not fail because directory\n # already existed\n \n raise\n \n # If we get here, makedirs either succeeded or failed\n # because the directory already existed.\n self._clip_dir_paths.add(dir_path)\n \n \n def _create_clip_file_path(self, station, detector_name, time):\n dir_path = self._create_clip_dir_path(station, time)\n file_name = _create_clip_file_name(station.name, detector_name, time)\n return os.path.join(dir_path, file_name)\n \n \n def _create_clip_dir_path(self, station, time):\n n = station.get_night(time)\n month_name = _create_month_dir_name(n.year, n.month)\n day_name = _create_day_dir_name(n.year, n.month, n.day)\n return os.path.join(\n self._archive_dir_path, station.name, month_name, day_name)\n \n \ndef _copy_db(from_conn, to_conn):\n _create_db_tables(to_conn)\n _copy_db_tables(from_conn, to_conn)\n \n \ndef _copy_db_tables(from_conn, to_conn):\n _copy_db_table('Station', from_conn, to_conn)\n _copy_db_table('Detector', from_conn, to_conn)\n _copy_db_table('ClipClass', from_conn, to_conn)\n _copy_db_table('ClipClassNameComponent', from_conn, to_conn)\n _copy_db_table('Clip', from_conn, to_conn)\n\n \ndef _copy_db_table(name, from_conn, to_conn):\n \n from_cursor = from_conn.cursor()\n to_cursor = to_conn.cursor()\n \n sql = 'select * from {:s} order by id'.format(name)\n from_cursor.execute(sql)\n \n sql = None\n \n while True:\n \n rows = from_cursor.fetchmany(1000)\n \n if len(rows) == 0:\n break\n \n if sql is None:\n num_columns = len(rows[0])\n question_marks = ', '.join(['?'] * num_columns)\n sql = 'insert into {:s} values ({:s})'.format(name, question_marks)\n \n to_cursor.executemany(sql, rows)\n \n to_conn.commit()\n \n \ndef _create_db_tables(conn):\n \n cursor = conn.cursor()\n \n # tables\n cursor.execute(_CREATE_STATION_TABLE_SQL)\n cursor.execute(_CREATE_DETECTOR_TABLE_SQL)\n cursor.execute(_CREATE_CLIP_CLASS_TABLE_SQL)\n cursor.execute(_CREATE_CLIP_CLASS_NAME_COMPONENT_TABLE_SQL)\n cursor.execute(_CREATE_CLIP_TABLE_SQL)\n \n # indices\n cursor.execute(_CREATE_CLIP_TABLE_MULTICOLUMN_INDEX_SQL)\n cursor.execute(_CREATE_CLIP_TABLE_NIGHT_DATE_INDEX_SQL)\n \n conn.commit()\n \n \ndef _date_to_int(date):\n return ((date.year * 100 + date.month) * 100) + date.day\n\n\ndef _int_to_date(night):\n year = night // 10000\n month = (night % 10000) // 100\n day = night % 100\n return datetime.date(year, month, day)\n\n\ndef _format_clip_time(time):\n millisecond = int(round(time.microsecond / 1000.))\n return time.strftime('%Y-%m-%d %H:%M:%S') + '.{:03d}'.format(millisecond)\n\n\ndef _create_with_id(cls, id_, *args, **kwds):\n obj = cls(*args, **kwds)\n obj.id = id_\n return obj\n \n\ndef _get_name_components(clip_classes):\n \n components = set()\n components.update(*[c.name_components for c in clip_classes])\n \n components = list(components)\n components.sort()\n\n return components\n \n \n# TODO: Figure out a better way to manage clip spectrograms, especially\n# one that supports clients that use spectrograms computed with different\n# spectrogram parameters. Some sort of general facility for computing\n# and managing derived data (not just spectrograms) for a collection of\n# clips may be the way to go.\n# TODO: Confine code that reads `clipFigure` preferences to the\n# `clips_window` module. This can happen after we figure out how to\n# support clients that use spectrograms computed with different\n# parameters.\n_window_type_name = prefs['clipFigure.spectrogram.windowType']\n_window_size = prefs['clipFigure.spectrogram.windowSize']\n_window = data_windows.create_window(_window_type_name, _window_size)\nSPECTROGRAM_PARAMS = Bunch(\n window=_window,\n hop_size=prefs['clipFigure.spectrogram.hopSize'],\n dft_size=prefs['clipFigure.spectrogram.dftSize'],\n ref_power=1)\n\n\n_MIN_CLIP_DURATION = .05\n\"\"\"\nthe minimum clip duration in seconds.\n\nClips shorter than this duration are padded with zeros to make them\nlong enough. This is part of a temporary \"fix\" to GitHub issue 30.\n\"\"\"\n\n\nclass _Clip(object):\n \n \n def __init__(\n self, archive, clip_id, station, detector_name, time, duration,\n clip_class_name=None):\n \n self._archive = archive\n self._id = clip_id\n self.station = station\n self.detector_name = detector_name\n self.time = time\n self._duration = duration\n self._clip_class_name = clip_class_name\n \n self._file_path = None\n self._sound = None\n self._spectrogram = None\n self._instantaneous_frequencies = None\n \n \n @property\n def file_path(self):\n \n if self._file_path is None:\n self._file_path = self._archive._create_clip_file_path(\n self.station, self.detector_name, self.time)\n \n return self._file_path\n \n \n @property\n def night(self):\n return self.station.get_night(self.time)\n \n \n @property\n def sound(self):\n \n if self._sound is None:\n # sound not yet read from file\n \n self._sound = sound_utils.read_sound_file(self.file_path)\n \n # Pad sound with zeros to make it at least `_MIN_CLIP_DURATION`\n # seconds long. This is part of a temporary \"fix\" to GitHub\n # issue 30.\n if self._duration < _MIN_CLIP_DURATION:\n min_length = \\\n int(round(_MIN_CLIP_DURATION * self._sound.sample_rate))\n n = min_length - len(self._sound.samples)\n if n > 0:\n self._sound.samples = \\\n np.hstack((self._sound.samples, np.zeros(n)))\n \n return self._sound\n \n \n @property\n def spectrogram(self):\n \n if self._spectrogram is None:\n # have not yet computed spectrogram\n \n self._spectrogram = Spectrogram(self.sound, SPECTROGRAM_PARAMS)\n \n return self._spectrogram\n \n \n @property\n def instantaneous_frequencies(self):\n \n if self._instantaneous_frequencies is None:\n # have not yet computed instantaneous frequencies\n \n self._instantaneous_frequencies = \\\n InstantaneousFrequencyAnalysis(self.sound, SPECTROGRAM_PARAMS)\n \n return self._instantaneous_frequencies\n \n \n @property\n def duration(self):\n return max(self._duration, _MIN_CLIP_DURATION)\n \n \n @property\n def clip_class_name(self):\n return self._clip_class_name\n \n \n @clip_class_name.setter\n def clip_class_name(self, name):\n self._archive._classify_clip(self._id, name)\n self._clip_class_name = name\n\n\n def play(self):\n sound_utils.play_sound_file(self.file_path)\n \n\ndef _create_month_dir_name(year, month):\n return '{:02d}'.format(month)\n\n\ndef _create_day_dir_name(year, month, day):\n return '{:02d}'.format(day)\n\n\ndef _create_clip_file_name(station_name, detector_name, time):\n ms = int(round(time.microsecond / 1000.))\n time = time.strftime('%Y-%m-%d_%H.%M.%S') + '.{:03d}'.format(ms) + '_Z'\n return '{:s}_{:s}_{:s}{:s}'.format(\n station_name, detector_name, time, _CLIP_FILE_NAME_EXTENSION)\n","sub_path":"src/vesper/archive/archive.py","file_name":"archive.py","file_ext":"py","file_size_in_byte":31790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"362732419","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.http import HttpResponse\nfrom .models.product import Product\nfrom .models.category import Category\n\n\n\ndef Home(request):\n products = None\n categories = Category.get_all_categories()\n catgoryID= request.GET.get('category')\n if catgoryID:\n products = Product.get_all_products_by_id(catgoryID)\n else:\n products = Product.get_all_products();\n\n data= {products: products, categories: categories}\n return render(request, 'Home.html', {'categories': categories})\n\n\n\ndef category(request):\n products = None\n categories = Category.get_all_categories()\n catgoryID = request.GET.get('category')\n if catgoryID:\n products = Product.get_all_products_by_id(catgoryID)\n else:\n products = Product.get_all_products();\n\n data = {products: products, categories: categories}\n\n\n return render(request, 'category.html', {'products':products})\n\n\ndef bookpage(request):\n name=request.GET.get('name')\n if name:\n products = Product.get_products_by_name(name)\n else:\n products = Product.get_all_products();\n\n return render(request,'bookpage.html',{'products': products})\n\n\ndef booksdownload(request):\n products=Product.get_all_products()\n return render(request,'booksdownload.html',{'products':products})","sub_path":"wadapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"296501693","text":"from gevent import monkey\nmonkey.patch_all()\nimport json\nfrom multiprocessing import Process\nfrom multiprocessing import JoinableQueue\nimport gevent\nimport requests\nfrom gevent.pool import Pool\n# from multiprocessing.dummy import Pool\nfrom queue import Queue\n\nimport time\nfrom lxml import etree\n\n\nclass QiuShi(object):\n def __init__(self):\n self.url_madel = \"https://www.qiushibaike.com/8hr/page/{}/\"\n self.headers = {\n \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36\",\n }\n self.url_queue = Queue()\n self.response_queue = Queue()\n self.data_queue = Queue()\n self.pool = Pool(6)\n\n def add_url_to_queue(self):\n # url_list = [self.url_madel.format(i) for i in range(1, 14)]\n # return url_list\n for i in range(1, 14):\n self.url_queue.put(self.url_madel.format(i))\n\n def add_page_to_queue(self):\n while True:\n url = self.url_queue.get()\n response = requests.get(url, headers=self.headers)\n print(response.status_code)\n if response.status_code != 200:\n # url_queue的unfinished_tasks 增加1\n self.url_queue.put(url)\n else:\n # 把响应内容添加到响应列表\n self.response_queue.put(response.content)\n # 到这儿,当前这个url的任务已经处理完成了\n # 饶昂url_queue的unfinished_tasks减少1\n self.url_queue.task_done()\n\n def add_data_to_queue(self):\n while True:\n page = self.response_queue.get()\n element = etree.HTML(page)\n dz_s = element.xpath('//div[@id=\"content-left\"]/div')\n data_list = []\n\n for dz in dz_s:\n item = {}\n item[\"head_url\"] = self.get_first_from_list(dz.xpath('./div[1]/a[1]/img/@src'))\n item['nick_name'] = self.get_first_from_list(dz.xpath('./div[1]/a[2]/h2/text()'))\n gender_class = self.get_first_from_list(dz.xpath(\"./div[1]/div/@class\"))\n if gender_class is not None:\n item['gender'] = \"man\" if gender_class.find('man') != -1 else 'women'\n else:\n item['gender'] = None\n item['dz_content'] = dz.xpath('./a[1]/div/span[1]/text()')[0]\n item['funny_count'] = dz.xpath('./div/span[1]/i/text()')[0]\n item['comment_count'] = dz.xpath('./div/span/a/i/text()')[0]\n # 把段子信息添加列表中\n data_list.append(item)\n self.data_queue.put(data_list)\n self.response_queue.task_done()\n\n def save_data(self):\n while True:\n data_list = self.data_queue.get()\n with open(\"协程.text\", \"a\", encoding=\"utf8\")as f:\n for data in data_list:\n json.dump(data, f, ensure_ascii=False)\n f.write(\"\\n\")\n self.data_queue.task_done()\n\n def excute_more_tasks(self, target, count):\n for i in range(0, count):\n self.pool.apply_async(target)\n\n def run(self):\n\n self.excute_more_tasks(self.add_url_to_queue, 1)\n self.excute_more_tasks(self.add_page_to_queue, 2)\n self.excute_more_tasks(self.add_data_to_queue, 3)\n self.excute_more_tasks(self.save_data, 1)\n time.sleep(1)\n self.url_queue.join()\n self.response_queue.join()\n self.data_queue.join()\n # self.url_queue.join()\n # self.response_queue.join()\n # self.data_queue.join()\n # for url in url_list:\n # data = self.get_data_from_url(url)\n # data_list = self.get_dz_list_from_data(data)\n #\n # self.save_data(data_list)\n\n def get_first_from_list(self, ls):\n return ls[0] if len(ls) != 0 else None\n\n\nif __name__ == '__main__':\n qss = QiuShi()\n qss.run()\n","sub_path":"33,协程版糗百.py","file_name":"33,协程版糗百.py","file_ext":"py","file_size_in_byte":3995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"369017808","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\"\"\"\n@Author : yangwei.li\n@Create date : 2019-09-23\n@FileName : 0000.py\n\"\"\"\n\"\"\"\n**第 0000 题:**将你的 QQ 头像(或者微博头像)右上角加上红色的数字,\n类似于微信未读信息数量那种提示效果。 \n\"\"\"\n\nfrom PIL import Image, ImageDraw, ImageFont, ImageColor\n\n\ndef add_num_to_img(img):\n # img = Image.open(img_path,'rb') # 打开图片\n font = ImageFont.truetype('C:\\Windows\\Fonts\\Arial.ttf',36) # 创建Font对象\n color = ImageColor.getrgb(\"#ff0000\")\n draw = ImageDraw.Draw(img) # 创建画图对象\n # 在画图对象上添加数字\n draw.text((img.width-40, 40), '8', color, font)\n # 保存\n img.save('new.png')\n\n\nif __name__ == \"__main__\":\n img = Image.open(\"1.png\") # 打开图片\n print(img.width,img.height)\n add_num_to_img(img)\n img.show()\n\n","sub_path":"0000/0000.py","file_name":"0000.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"169817547","text":"\"\"\"\nModule: DMS Browser Django URLs\n\nProject: Adlibre DMS\nCopyright: Adlibre Pty Ltd 2011\nLicense: See LICENSE for license information\n\"\"\"\n\nfrom django.conf.urls.defaults import *\n\nurlpatterns = patterns('browser.views',\n url(r'^$', 'index', name='home'),\n url(r'^settings/plugins$', 'plugins', name='plugins'),\n url(r'^upload/$', 'upload', name='upload'),\n url(r'^get/(?P<code>[\\w_-]+)$', 'get_file', name='get_file'),\n url(r'^get/(?P<code>[\\w_-]+)\\.(?P<suggested_format>[\\w_-]+)$', 'get_file', name='get_file'),\n url(r'^files/$', 'files_index', name='files_index'),\n url(r'^files/(?P<id_rule>\\d+)/$', 'files_document', name='files_document'),\n url(r'^revision/(?P<document>.+)$', 'revision_document', name='revision_document'),\n)\n","sub_path":"adlibre_dms/apps/browser/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"485056977","text":"from sys import stdin\r\ndef score(a):\r\n con = 0\r\n res=0\r\n for i in a:\r\n if i == \"O\":\r\n con+=1\r\n res+=con\r\n else:\r\n con = 0\r\n return res\r\n\r\n\r\ndef main():\r\n n=int(stdin.readline().strip())\r\n for i in range(n):\r\n a = stdin.readline().strip()\r\n z=score(a)\r\n print(z)\r\nmain()\r\n","sub_path":"1585Score.py","file_name":"1585Score.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"468331879","text":"import uuid\nfrom django.http import response\nfrom django.shortcuts import render\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework import status\nfrom rest_framework.parsers import JSONParser\nfrom django.http.response import JsonResponse\nimport re\nimport random\n\n\nfrom UserApp.models import UserData, Otp\nfrom UserApp.serializers import UserSerialiser, OtpSerialiser\nfrom Helper.sendotp import sendOtpHelper, verifyOtpHelper\n\n\ndef isValid(s):\n Pattern = re.compile(\"(0|91)?[7-9][0-9]{9}\")\n return Pattern.match(s)\n\n\n@csrf_exempt\ndef userverify_otp(request, number=0, code=0):\n otpValid = None\n print(number, code)\n fullnumber = '+'+number\n if request.method == 'GET':\n # result = verifyOtpHelper(fullnumber, code)\n # if result['status'] == 'approved':\n # int_number = int(number)\n valid = isValid(number)\n\n if valid:\n\n try:\n otpUser = Otp.objects.get(number=number[2:])\n\n if code == otpUser.otp:\n\n otpValid = True\n if otpValid:\n try:\n user = UserData.objects.get(PhoneNumber=number[2:])\n userserialiser = UserSerialiser(user)\n if userserialiser.data['PhoneNumber']:\n return JsonResponse({'Status': True, 'Message': 'Otp verified successfully', 'User': {'UserId': userserialiser.data['UserId'], 'UserStatus': userserialiser.data['UserStatus']}}, safe=False)\n\n except Exception as e:\n er = str(e)\n print(er, e)\n if er == 'UserData matching query does not exist.':\n userdata_serializer = UserSerialiser(\n data={'PhoneNumber': number[2:]})\n if userdata_serializer.is_valid():\n userdata_serializer.save()\n user = UserData.objects.get(\n PhoneNumber=number[2:])\n userdata_serializer = UserSerialiser(user)\n return JsonResponse({'Status': True, 'Message': 'Otp verified successfully', 'User': {'UserId': userdata_serializer.data['UserId'], 'UserStatus': userdata_serializer.data['UserStatus']}}, safe=False, status=200)\n return JsonResponse({'Status': False, 'Message': 'Failed to Update'}, safe=False, status=400)\n return JsonResponse({'Status': False, 'Message': 'Something wrong'}, safe=False, status=500)\n else:\n return JsonResponse({'Status': False, 'Message': 'Verification failed!'}, safe=False, status=400)\n except:\n return JsonResponse({'Status': False, 'Message': 'Phone number is wrong'}, safe=False, status=400)\n\n # elif result['status'] == 'expired' or result['status'] == 'when the max attempts to check a code have been reached':\n # return JsonResponse({'Status': False, 'Message': result['status']}, safe=False)\n # else:\n # return JsonResponse({'Status': False, 'Message': 'Phone number or OTP is wrong'}, safe=False)\n else:\n return JsonResponse({'Status': False, 'Message': 'Phone number or OTP is wrong'}, safe=False, status=400)\n\n\n@csrf_exempt\ndef usersend_otp(request, id=0):\n\n if request.method == 'GET':\n fullnumber = '+'+id\n # result = sendOtpHelper(fullnumber)\n # return JsonResponse(result, safe=False)\n if isValid(id):\n code = random.randint(1000, 9999)\n otpUser = None\n\n try:\n\n otpUser = Otp.objects.get(number=id[2:])\n otp_Seriyalizer = OtpSerialiser(\n otpUser, {'number': id[2:], 'otp': code})\n otp_Seriyalizer.save()\n\n return JsonResponse({'Status': True, 'Message': 'OTP sent to your given number +'+id, 'OtpCode': code}, safe=False)\n except Exception as e:\n otp_Seriyalizer = OtpSerialiser(\n otpUser, data={'number': id[2:], 'otp': code})\n if otp_Seriyalizer.is_valid():\n otp_Seriyalizer.save()\n return JsonResponse({'Status': True, 'Message': 'OTP sent to your given number +'+id, 'OtpCode': code}, safe=False)\n else:\n return JsonResponse({'Status': False, 'Message': 'Phone number is not valid'}, safe=False)\n\n\n@csrf_exempt\ndef User_data(request, id=0):\n try:\n if request.method == 'GET':\n if id != 0:\n users = UserData.objects.get(UserId=id)\n users_serializer = UserSerialiser(users)\n return JsonResponse(users_serializer.data, safe=False)\n else:\n users = UserData.objects.all()\n users_serializer = UserSerialiser(users, many=True)\n return JsonResponse(users_serializer.data, safe=False)\n\n elif request.method == 'PUT':\n users_data = JSONParser().parse(request)\n user = UserData.objects.get(UserId=id)\n if user.UserStatus == 1 and user.Name == '':\n uniqueId = str(uuid.uuid4())\n selaId = 'SELA-'+uniqueId\n updatedData = {'SelaId': selaId,\n 'Name': users_data['Name'], 'UserStatus': 0}\n user_serializer = UserSerialiser(user, data=updatedData)\n if user_serializer.is_valid():\n user_serializer.save()\n user = UserData.objects.get(UserId=id)\n user_serializer = UserSerialiser(user)\n return JsonResponse({'Status': True, 'Message': 'Data updated successfully', 'User': user_serializer.data}, safe=False)\n return JsonResponse({'Status': False, 'Message': 'Failed to Update'}, safe=False, status=400)\n\n else:\n user_serializer = UserSerialiser(\n user, data={'Name': users_data['Name']})\n if user_serializer.is_valid():\n user_serializer.save()\n return JsonResponse({'Status': True, 'Message': 'Data updated successfully'}, safe=False)\n return JsonResponse({'Status': False, 'Message': 'Failed to Update'}, safe=False, status=400)\n\n elif request.method == 'DELETE':\n user = UserData.objects.get(UserId=id)\n user.delete()\n return JsonResponse({'Status': True, 'Message': 'Data Deleted successfully'}, safe=False)\n\n except Exception as e:\n er_str = str(e)\n return JsonResponse({'Status': False, 'Message': 'Failed to update', 'Error': er_str}, safe=False, status=400)\n","sub_path":"UserApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"466514119","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n#\n################################################################\n#\n# Question 8\n# Level 2\n#\n################################################################\n#\n# Question:\n# Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically.\n# Suppose the following input is supplied to the program:\n# without,hello,bag,world\n# Then, the output should be:\n# bag,hello,without,world\n#\n# Hints:\n# In case of input data being supplied to the question, it should be assumed to be a console input.\n#\n################################################################\n\n# items = [x for x in input('P>>').split(',')]\nitems = ['without','hello','bag','world']\nitems.sort()\nprint(items)\n\n\nres = items[2][::-1]\nprint(res)","sub_path":"my_exercises/question_8.py","file_name":"question_8.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"249419521","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# File : grader.py\n# Author : INMAK <jchrys@me.com>\n# Date : 04.11.2019\n# Last Modified Date: 04.11.2019\n# Last Modified By : INMAK <jchrys@me.com>\n\nimport os\nimport json\nfrom mwt import settings\ndef cleaned_data(string):\n string = string.replace('\\r\\n', '\\n')\n string = string.replace('\\r', '\\n')\n return bytes(string, 'utf8').strip()\n\nclass Grader:\n def __init__(self, problem):\n self.ans_file = os.path.join(settings.PRB_DIR, problem, 'outs', '0001')\n self.ins_file = os.path.join(settings.PRB_DIR, problem, 'ins', '0001')\n def run(self, subs):\n with open(self.ans_file) as ans:\n with open(self.ins_file) as ins:\n ans = ans.read()\n ans = cleaned_data(ans)\n ins = ins.read()\n ins = cleaned_data(ins)\n ans_lines = ans.splitlines() \n ins_lines = ins.splitlines()\n subs_lines = subs.splitlines()\n ret_ans = [] \n ret_subs = []\n for i in range(len(ans_lines)):\n #print(ans_lines[i], subs_lines[i], ins_lines[i+1])\n ret_ans.append(ans_lines[i].decode('utf-8'))\n ret_subs.append(subs_lines[i].decode('utf-8'))\n return json.dumps({\"ans\": ret_ans, \"subs\": ret_subs})\n\n\n\nif __name__ == '__main__':\n grader = Grader('sum') \n grader.run('1')\n","sub_path":"judge/mwt/engine/grader.py","file_name":"grader.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"310752192","text":"# coding:utf-8\nimport requests\nfrom bs4 import BeautifulSoup\nfrom requests.exceptions import RequestException\nimport re\nfrom multiprocessing.dummy import Pool as ThreadPool\nfrom pymongo import MongoClient\n\n\nhome_pageUrl='http://www.51hao.cc/'\nuser_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'\nheaders = {'User-Agent': user_agent}\nall_cityUrl=\"http://www.51hao.cc/all.html\"\ncityList=[]\nphoneNumber={}\n\ndef download(url):\n try:\n r = requests.get(url,headers=headers)\n r.encoding = 'gb2312' #设置编码,不设置中文会乱码\n return r\n except RequestException as e:\n print(\"The problem is {}!\".format(e))\n\ndef getCity(url):\n r = download(url)\n Soup = BeautifulSoup(r.text,'lxml')\n\n for province in Soup.find_all('a',href=re.compile(r'city/\\w+$')):\n print(province.text)\n for city in Soup.find_all('a',href=re.compile(province['href']+r'/\\w+.php')):\n print(city.text,city['href'])\n\n cityList.append(home_pageUrl+city['href'])\n\n p.map(getNumber,cityList)\n\ndef getNumber(url):\n r=download(url)\n Soup=BeautifulSoup(r.text,'lxml')\n title =Soup.select('div[class~=title] > span')[0].text\n ProvincePattern=re.compile(u\"[\\u4e00-\\u9fa5]+\") #用来匹配省份\n Province_City=title[:-10]\n Province=re.search(ProvincePattern,Province_City).group().strip()\n City=Province_City[4:].strip()\n for cuc in Soup.find_all('div',class_='ab_menu cuc'):\n cucList=cuc.find_next('ul')\n for num in cucList.find_all('a',href=re.compile(r'../../mobile/')):\n db.liantong.insert_one({'号码':num.text,'省/直辖市':Province,'市':City,'运营商':'中国联通'})\n for ctc in Soup.find_all('div',class_='ab_menu ctc'):\n ctcList=ctc.find_next('ul')\n for num in ctcList.find_all('a',href=re.compile(r'../../mobile/')):\n db.dianxin.insert_one({'号码': num.text, '省/直辖市': Province, '市': City, '运营商': '中国电信'})\n for cm in Soup.find_all('div',class_='ab_menu cm'):\n\n cmList=cm.find_next('ul')\n for num in cmList.find_all('a',href=re.compile(r'../../mobile/')):\n db.yidong.insert_one({'号码': num.text, '省/直辖市': Province, '市': City, '运营商': '中国移动'})\n\n\nclient=MongoClient()\ndb=client.PhoneNumber\np=ThreadPool(4)\ngetCity(all_cityUrl)\np.close()\np.join()\n# print(cityList)\n","sub_path":"craw_51hao.py","file_name":"craw_51hao.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"475650881","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport json\nfrom pprint import pprint\n\nimport requests\n\nfrom wenshu_utils.docid.decrypt import decrypt_doc_id\nfrom wenshu_utils.docid.runeval import decrypt_runeval\nfrom wenshu_utils.document.parse import parse_detail\nfrom wenshu_utils.vl5x.args import Vjkl5, Vl5x, Number, Guid\nfrom wenshu_utils.wzws.decrypt import decrypt_wzws\nfrom wenshu_utils.method import Para\nfrom wenshu_utils.redis_ip_pool import RedisPara\n\n\nclass Demo:\n def __init__(self):\n self.session = requests.Session()\n self.session.headers.update({\n \"User-Agent\": Para().user_agent,\n })\n self.proxy = \"212.64.51.13:8888\"\n\n def list_page(self):\n \"\"\"文书列表页\"\"\"\n url = \"http://wenshu.court.gov.cn/List/ListContent\"\n data = {\n \"Param\": \"全文检索:合同纠纷\",\n \"Index\": 1,\n \"Page\": 10,\n \"Order\": \"法院层级\",\n \"Direction\": \"asc\",\n \"vl5x\": Vl5x(self.session.cookies.setdefault(\"vjkl5\", Vjkl5())),\n # \"number\": Number(),\n \"number\": \"&gui\",\n \"guid\": Guid(),\n }\n response = self.session.post(url, data=data, proxies={\"http\": \"http://{}\".format(self.proxy)}) # 请求1\n text = response.content.decode()\n\n if \"请开启JavaScript并刷新该页\" in text:\n # 如果使用代理,确保请求1和请求2的ip为同一个,否则将继续返回\"请开启JavaScript并刷新该页\"\n dynamic_url = decrypt_wzws(text)\n response = self.session.post(dynamic_url, data=data) # 请求2\n if response.status_code != 200:\n print(response.text)\n raise ValueError(\"获取信息失败\")\n print(response.text)\n json_data = json.loads(response.json())\n print(\"列表数据:\", json_data)\n\n runeval = json_data.pop(0)[\"RunEval\"]\n try:\n key = decrypt_runeval(runeval)\n except ValueError as e:\n raise ValueError(\"返回脏数据\") from e\n else:\n print(\"RunEval解析完成:\", key, \"\\n\")\n\n key = key.encode()\n for item in json_data:\n cipher_text = item[\"文书ID\"]\n print(\"解密:\", cipher_text)\n plain_text = decrypt_doc_id(doc_id=cipher_text, key=key)\n print(\"成功, 文书ID:\", plain_text, \"\\n\")\n\n def detail_page(self):\n \"\"\"文书详情页\"\"\"\n url = \"http://wenshu.court.gov.cn/CreateContentJS/CreateContentJS.aspx\"\n params = {\n \"DocID\": \"029bb843-b458-4d1c-8928-fe80da403cfe\",\n # \"DocID\": \"d461337d-1e9d-475d-8c76-01e2e3a5c90e\",\n }\n response = self.session.get(url, params=params, proxies={\"http\": \"http://{}\".format(self.proxy)}) # 请求1\n text = response.content.decode()\n\n if \"请开启JavaScript并刷新该页\" in text:\n # 如果使用代理,确保请求1和请求2的ip为同一个,否则将继续返回\"请开启JavaScript并刷新该页\"\n dynamic_url = decrypt_wzws(text)\n response = self.session.get(dynamic_url) # 请求2\n if response.status_code != 200:\n raise ValueError(\"获取信息失败\")\n detail_dict = parse_detail(response.text)\n return detail_dict\n\n\nif __name__ == '__main__':\n demo = Demo()\n data = demo.list_page()\n # # data = demo.detail_page()\n print(data)\n # from wenshu_utils.main import StartSpider\n # test = StartSpider(\"全文检索:合同纠纷\")\n # print(test.get_keyword_all_document())\n","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":3591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"126589593","text":"from django.shortcuts import render, get_object_or_404\nfrom .models import Measure\nfrom .forms import MeasureModelForm\nfrom geopy.geocoders import Nominatim\nfrom geopy.distance import geodesic\nfrom .utils import get_geo, get_center_cordinates, get_zoom, get_ip_address\nimport folium\n\n\ndef distance_calculate_view(request):\n distance = None\n destination = None\n obj = get_object_or_404(Measure, id=1)\n form = MeasureModelForm(request.POST or None)\n geolocator = Nominatim(user_agent='measure')\n\n ip_ = get_ip_address(request)\n # print(ip_)\n ip = ip_\n country, city, lat, lon = get_geo(ip)\n\n location = geolocator.geocode(city)\n\n # Location Cordinates\n l_lat = lat\n l_lon = lon\n pointA = (l_lat, l_lon)\n\n # Initial Folium map Setup\n m = folium.Map(width=1100, height=600, location=get_center_cordinates(l_lat, l_lon), zoom_start=2)\n # location Marker\n folium.Marker([l_lat, l_lon], tooltip='click here for more', popup=city['city'],\n icon=folium.Icon(color='purple')).add_to(m)\n\n if form.is_valid():\n instance = form.save(commit=False)\n destination_ = form.cleaned_data.get('destination')\n destination = geolocator.geocode(destination_)\n\n # Destinates Coordinates\n d_lat = destination.latitude\n d_lon = destination.longitude\n pointB = (d_lat, d_lon)\n\n # Distance Calculation\n distance = round(geodesic(pointA, pointB).km, 2)\n\n # Map Modifications\n m = folium.Map(width=1100, height=600, location=get_center_cordinates(l_lat, l_lon, d_lat, d_lon),\n zoom_start=get_zoom(distance))\n # location Marker\n folium.Marker([l_lat, l_lon], tooltip='this is your location', popup=city['city'],\n icon=folium.Icon(color='purple')).add_to(m)\n # Destination Marker\n folium.Marker([d_lat, d_lon], tooltip='this is your destination', popup=destination,\n icon=folium.Icon(color='red', icon='cloud')).add_to(m)\n\n # Draw a line\n line = folium.PolyLine(locations=[pointA, pointB], weight=5, color='blue')\n m.add_child(line)\n instance.location = location\n instance.distance = distance\n instance.save()\n\n m = m._repr_html_()\n\n context = {\n 'distance': distance,\n 'destination': destination,\n 'form': form,\n 'map': m\n }\n return render(request, 'measures/index.html', context)\n","sub_path":"measure/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"38895163","text":"__author__ = 'adri'\nimport threading\nimport time\n\n\nclass Clock(threading.Thread):\n\n def __init__(self, aDelayInSeconds = 1, aNumberOfHits = -1):\n threading.Thread.__init__(self)\n self.listeners = []\n self.delayInSeconds = aDelayInSeconds\n self.numberOfHits = aNumberOfHits\n\n def run(self):\n currentHit = 1\n while(self.numberOfHits < 0 or self.numberOfHits >= currentHit):\n currentHit = currentHit +1\n time.sleep(self.delayInSeconds)\n\n self.notify()\n\n def register(self, listener):\n self.listeners.append(listener)\n\n def notify(self):\n for listener in self.listeners:\n listener()\n'''\nclass Example:\n\n def __init__(self):\n self.index = 0\n\n def execute(self):\n self.index = self.index +1\n print(self.index)\n\nclass cpu:\n init(irqManager)\n\n fetcInt:\n ....irqManager.Hanldle(kill)\n\nclass IrqManager:\n\n def __init__(self):\n self.pendingIrqs = []\n\n def handle(self, irq):\n\n self.pendingIrqs.append(irq)\n\n def execute(self):\n for irq in self.pendingIrqs:\n ...\nirqManager = irqManager\ncpu = Cpu(irqManager)\nclock = Clock(aNumberOfHits=3)\nclock.register(cpu.execute)\nclock.start()\n\ntime.sleep(5)\n'''\n","sub_path":"HardWare/Clock.py","file_name":"Clock.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"62470445","text":"import os.path\r\nfrom os import listdir\r\n\r\n'''\r\ndef getTournamentId(path_file)\r\nParameters\r\n\tpath_file: is the Tournament's path file\r\nReturn\r\n\tReturns a integer Tournament's Id \r\n'''\r\ndef getTournamentId(path_file):\r\n\tif os.path.isfile(path_file):\r\n\t\ttournamentTxt = open(path_file, encoding=\"utf8\")\r\n\t\ttext = tournamentTxt.read()\r\n\t\ttarget = \"PokerStars Tournament #\"\r\n\t\tstartPosition = text.find(target)\r\n\t\tif startPosition!=-1:\r\n\t\t\tstartPosition += len(target)\r\n\t\t\tendPosition = text.find(\", No Limit\")\r\n\t\t\ttournamentID = int(text[startPosition:endPosition])\r\n\t\t\ttournamentTxt.close()\r\n\t\t\treturn int(tournamentID)\r\n\t\telse:\r\n\t\t\tprint(\"Can't get Tournament Id. No Id in the file \"+path_file)\r\n\t\ttournamentTxt.close()\r\n\telse:\r\n\t\tprint(\"Can't get Tournament Id. Error while opening \"+path_file)\r\n\treturn None\r\n\r\n'''\r\ndef getTournamentList(path_dir)\r\nParameters\r\n\tpath_dir: is the path of the directory that contains the tournament files\r\nReturn\r\n\tReturns a list of tournament file names\r\n'''\r\ndef getTournamentList(path_dir):\r\n\tif os.path.isdir(path_dir):\r\n\t\ttournamentFileNames = [path_dir+name for name in listdir(path_dir) if os.path.isfile(path_dir+name)]\r\n\t\treturn tournamentFileNames\r\n\telse:\r\n\t\tprint(\"Can't get list of files.\")\r\n\treturn None\r\n\r\n'''\r\ndef getTournamentBuyIn(path_file)\r\nParameters\r\n\tpath_file: is the path of the tournament file\r\nReturn\r\n\tReturns float buy-in\r\n'''\r\ndef getTournamentBuyIn(path_file):\r\n\tif os.path.isfile(path_file):\r\n\t\ttournamentTxt = open(path_file, encoding=\"utf8\")\r\n\t\ttext = tournamentTxt.read()\r\n\t\ttarget = \"Buy-In: \"\r\n\t\tstartPosition = text.find(target)\r\n\t\tif startPosition!=-1:\r\n\t\t\tstartPosition += len(target)\r\n\t\t\tendPosition = text.find(\" USD\")\r\n\t\t\ttournamentBuyIn = text[startPosition:endPosition]\r\n\t\t\ttournamentBuyIn = tournamentBuyIn.replace(\"$\",\"\")\r\n\t\t\tslashPosition = tournamentBuyIn.find(\"/\")\r\n\t\t\tbuyin = float(tournamentBuyIn[:slashPosition])\r\n\t\t\trake = float(tournamentBuyIn[slashPosition+1:])\r\n\t\t\ttournamentTxt.close()\r\n\t\t\treturn buyin+rake\r\n\t\telse:\r\n\t\t\tprint(\"Can't get Tournament Buy-In. No Buy-In in the file \"+path_file)\r\n\t\ttournamentTxt.close()\r\n\telse:\r\n\t\tprint(\"Can't get Tournament Buy-In. Error while opening \"+path_file)\r\n\treturn None","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"265148337","text":"from website.views import IndexTemplateView, PessoasListView, PessoasUpdateView, PessoasCreateView, \\\n PessoasDeleteView\n\nfrom django.urls import path\n\napp_name = 'website'\n\nurlpatterns = [\n # GET /\n path('', IndexTemplateView.as_view(), name=\"index\"),\n\n # GET /Pessoas/cadastrar\n path('Pessoas/cadastrar', PessoasCreateView.as_view(), name=\"cadastra_Pessoas\"),\n\n # GET /Pessoas\n path('Pessoas/', PessoasListView.as_view(), name=\"lista_Pessoas\"),\n\n # GET/POST /Pessoas/{pk}\n path('Pessoas/<pk>', PessoasUpdateView.as_view(), name=\"atualiza_Pessoas\"),\n\n # GET/POST /Pessoas/excluir/{pk}\n path('Pessoas/excluir/<pk>', PessoasDeleteView.as_view(), name=\"deleta_Pessoas\"),\n]\n","sub_path":"MF/mf/website/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"493196873","text":"''' Dapricot Style urls module\n'''\nfrom django.urls import path\nfrom dapricot.style.views import ExampleView, ExampleGridView\n\napp_name = 'dastyle'\n\nurlpatterns = [\n path('', ExampleView.as_view(), name='home'),\n path('grid/', ExampleGridView.as_view(), name='grid'),\n]\n","sub_path":"dapricot/style/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"144515111","text":"import datetime\nimport json\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport shutil\nfrom auvsi_suas.models import AerialPosition\nfrom auvsi_suas.models import GpsPosition\nfrom auvsi_suas.models import haversine\nfrom auvsi_suas.models import kilometersToFeet\nfrom auvsi_suas.models import knotsToFeetPerSecond\nfrom auvsi_suas.models import MovingObstacle\nfrom auvsi_suas.models import Obstacle\nfrom auvsi_suas.models import ObstacleAccessLog\nfrom auvsi_suas.models import ServerInfo\nfrom auvsi_suas.models import ServerInfoAccessLog\nfrom auvsi_suas.models import StationaryObstacle\nfrom auvsi_suas.models import UasTelemetry\nfrom auvsi_suas.models import Waypoint\nfrom django.contrib.auth.models import User\nfrom django.core.urlresolvers import reverse\nfrom django.test import TestCase\nfrom django.test.client import Client\n\n\n# (lon1, lat1, lon2, lat2, dist_actual)\nTESTDATA_ZERO_DIST = [\n (0, 0, 0, 0, 0),\n (1, 1, 1, 1, 0),\n (-1, -1, -1, -1, 0),\n (1, -1, 1, -1, 0),\n (-1, 1, -1, 1, 0),\n (76, 42, 76, 42, 0),\n (-76, 42, -76, 42, 0)\n]\nTESTDATA_HEMISPHERE_DIST = [\n (-73, 40, -74, 41, 139.6886345468666),\n (73, 40, 74, 41, 139.6886345468667),\n (73, -40, 74, -41, 139.6886345468667),\n (-73, -40, -74, -41, 139.68863454686704)\n]\nTESTDATA_COMPETITION_DIST = [\n (-76.428709, 38.145306, -76.426375, 38.146146, 0.22446),\n (-76.428537, 38.145399, -76.427818, 38.144686, 0.10045),\n (-76.434261, 38.142471, -76.418876, 38.147838, 1.46914)\n]\n\n# (km, ft_actual)\nTESTDATA_KM_TO_FT = [\n (0, 0),\n (1, 3280.84),\n (1.5, 4921.26),\n (100, 328084)\n]\n\n# (knots, fps)\nTESTDATA_KNOTS_TO_FPS = [\n (0.1, 0.168781),\n (1, 1.68781),\n (10, 16.8781),\n (100, 168.781)\n]\n\n# (lon1, lat1, alt1, lon2, lat2, alt2, dist_actual)\nTESTDATA_ZERO_3D_DIST = [\n (0, 0, 0, 0, 0, 0, 0),\n (1, 2, 3, 1, 2, 3, 0),\n (-30, 30, 100, -30, 30, 100, 0)\n]\nTESTDATA_COMPETITION_3D_DIST = [\n (-76.428709, 38.145306, 0, -76.426375, 38.146146, 0, 0.22446),\n (-76.428537, 38.145399, 0, -76.427818, 38.144686, 100, 0.10497),\n (-76.434261, 38.142471, 100, -76.418876, 38.147838, 800, 1.48455)\n]\n\nTESTDATA_MOVOBST_PATHS = [\n [(38.142233, -76.434082, 300),\n (38.141878, -76.425198, 700),\n (38.144599, -76.428186, 100)],\n [(38.145574, -76.428492, 100),\n (38.149164, -76.427113, 750),\n (38.148662, -76.431517, 300),\n (38.146143, -76.426727, 500)],\n [(38.145405, -76.428310, 100),\n (38.146582, -76.424099, 200),\n (38.144662, -76.427634, 300),\n (38.147729, -76.419185, 200),\n (38.147573, -76.420832, 100),\n (38.148522, -76.419507, 750)]\n]\n\n\nclass TestHaversine(TestCase):\n \"\"\"Tests the haversine code correctness.\"\"\"\n\n def distance_close_enough(self, distance_actual, distance_received):\n \"\"\"Determines whether the km distances given are close enough.\"\"\"\n distance_thresh = 0.003048 # 10 feet in km\n return abs(distance_actual - distance_received) <= distance_thresh\n\n def evaluate_input(self, lon1, lat1, lon2, lat2, distance_actual):\n \"\"\"Evaluates the haversine code for the given input.\"\"\"\n distance_received = haversine(lon1, lat1, lon2, lat2)\n return self.distance_close_enough(distance_actual, distance_received)\n\n def evaluate_inputs(self, input_output_list):\n \"\"\"Evaluates a list of inputs and outputs.\"\"\"\n for (lon1, lat1, lon2, lat2, distance_actual) in input_output_list:\n if not self.evaluate_input(lon1, lat1, lon2, lat2, distance_actual):\n return False\n return True\n\n def test_zero_distance(self):\n \"\"\"Tests various latitudes and longitudes which have zero distance.\"\"\"\n self.assertTrue(self.evaluate_inputs(\n TESTDATA_ZERO_DIST))\n\n def test_hemisphere_distances(self):\n \"\"\"Tests distances in each hemisphere.\"\"\"\n self.assertTrue(self.evaluate_inputs(\n TESTDATA_HEMISPHERE_DIST))\n\n def test_competition_distances(self):\n \"\"\"Tests distances representative of competition amounts.\"\"\"\n self.assertTrue(self.evaluate_inputs(\n TESTDATA_COMPETITION_DIST))\n\n\nclass TestKilometersToFeet(TestCase):\n \"\"\"Tests the conversion from kilometers to feet.\"\"\"\n\n def evaluate_conversion(self, km, ft_actual):\n \"\"\"Tests the conversion of the given input to feet.\"\"\"\n convert_thresh = 5\n return abs(kilometersToFeet(km) - ft_actual) < convert_thresh\n\n def test_km_to_ft(self):\n \"\"\"Performs a data-driven test of the conversion.\"\"\"\n for (km, ft_actual) in TESTDATA_KM_TO_FT:\n self.assertTrue(self.evaluate_conversion(km, ft_actual))\n\n\nclass TestKnotsToFeetPerSecond(TestCase):\n \"\"\"Tests the conversion from knots to feet per second.\"\"\"\n\n def evaluate_conversion(self, knots, fps_actual):\n \"\"\"Tests the conversion of the given input/output pair.\"\"\"\n convert_thresh = 5\n return abs(knotsToFeetPerSecond(knots) - fps_actual) < convert_thresh\n\n def test_knots_to_fps(self):\n \"\"\"Performs a data-drive test of the conversion.\"\"\"\n for (knots, fps_actual) in TESTDATA_KNOTS_TO_FPS:\n self.assertTrue(self.evaluate_conversion(knots, fps_actual))\n\n\nclass TestGpsPositionModel(TestCase):\n \"\"\"Tests the GpsPosition model.\"\"\"\n\n def eval_distanceTo_input(self, lon1, lat1, lon2, lat2, distance_actual):\n \"\"\"Evaluates the distanceTo functionality for the given inputs.\"\"\"\n wpt1 = GpsPosition()\n wpt1.latitude = lat1\n wpt1.longitude = lon1\n wpt2 = GpsPosition()\n wpt2.latitude = lat2\n wpt2.longitude = lon2\n dist12 = wpt1.distanceTo(wpt2)\n dist21 = wpt2.distanceTo(wpt1)\n dist_actual_ft = kilometersToFeet(distance_actual)\n diffdist12 = abs(dist12 - dist_actual_ft)\n diffdist21 = abs(dist21 - dist_actual_ft)\n dist_thresh = 10.0\n return diffdist12 <= dist_thresh and diffdist21 <= dist_thresh\n\n def eval_distanceTo_inputs(self, input_output_list):\n \"\"\"Evaluates the distanceTo function on various inputs.\"\"\"\n for (lon1, lat1, lon2, lat2, distance_actual) in input_output_list:\n if not self.eval_distanceTo_input(lon1, lat1, lon2, lat2,\n distance_actual):\n return False\n return True\n\n def test_distanceTo_zero(self):\n \"\"\"Tests distance calc for same position.\"\"\"\n self.assertTrue(self.eval_distanceTo_inputs(\n TESTDATA_ZERO_DIST))\n\n def test_distanceTo_competition_amounts(self):\n \"\"\"Tests distance calc for competition amounts.\"\"\"\n self.assertTrue(self.eval_distanceTo_inputs(\n TESTDATA_COMPETITION_DIST))\n\n\nclass TestAerialPositionModel(TestCase):\n \"\"\"Tests the AerialPosition model.\"\"\"\n\n def eval_distanceTo_input(self, lon1, lat1, alt1, lon2, lat2, alt2,\n dist_actual):\n \"\"\"Evaluates the distanceTo calc with the given inputs.\"\"\"\n pos1 = AerialPosition()\n pos1.gps_position = GpsPosition()\n pos1.gps_position.latitude = lat1\n pos1.gps_position.longitude = lon1\n pos1.altitude_msl = alt1\n pos2 = AerialPosition()\n pos2.gps_position = GpsPosition()\n pos2.gps_position.latitude = lat2\n pos2.gps_position.longitude = lon2\n pos2.altitude_msl = alt2\n dist12 = pos1.distanceTo(pos2)\n dist21 = pos2.distanceTo(pos1)\n dist_actual_ft = kilometersToFeet(dist_actual)\n diffdist12 = abs(dist12 - dist_actual_ft)\n diffdist21 = abs(dist21 - dist_actual_ft)\n dist_thresh = 10.0\n return diffdist12 <= dist_thresh and diffdist21 <= dist_thresh\n\n def eval_distanceTo_inputs(self, input_output_list):\n \"\"\"Evaluates the distanceTo calc with the given input list.\"\"\"\n for (lon1, lat1, alt1,\n lon2, lat2, alt2, dist_actual) in input_output_list:\n if not self.eval_distanceTo_input(lon1, lat1, alt1, lon2, lat2,\n alt2, dist_actual):\n return False\n return True\n\n def test_distanceTo_zero(self):\n \"\"\"Tests distance calc for same position.\"\"\"\n self.assertTrue(self.eval_distanceTo_inputs(\n TESTDATA_ZERO_3D_DIST))\n\n def test_distanceTo_competition_amounts(self):\n \"\"\"Tests distance calc for competition amounts.\"\"\"\n self.assertTrue(self.eval_distanceTo_inputs(\n TESTDATA_COMPETITION_3D_DIST))\n\n\nclass TestServerInfoModel(TestCase):\n \"\"\"Tests the ServerInfo model.\"\"\"\n\n def test_toJSON(self):\n \"\"\"Tests the JSON serialization method.\"\"\"\n TEST_MSG = 'Hello, world.'\n TEST_TIME = datetime.datetime.now()\n\n server_info = ServerInfo()\n server_info.timestamp = TEST_TIME\n server_info.team_msg = TEST_MSG\n json_data = server_info.toJSON()\n\n self.assertTrue('message' in json_data)\n self.assertEqual(json_data['message'], TEST_MSG)\n self.assertTrue('message_timestamp' in json_data)\n self.assertEqual(json_data['message_timestamp'], str(TEST_TIME))\n\n\nclass TestStationaryObstacleModel(TestCase):\n \"\"\"Tests the StationaryObstacle model.\"\"\"\n\n def test_toJSON(self):\n \"\"\"Tests the JSON serialization model.\"\"\"\n TEST_LAT = 100.10\n TEST_LONG = 200.20\n TEST_RADIUS = 150.50\n TEST_HEIGHT = 75.30\n\n gps_position = GpsPosition()\n gps_position.latitude = TEST_LAT\n gps_position.longitude = TEST_LONG\n obstacle = StationaryObstacle()\n obstacle.gps_position = gps_position\n obstacle.cylinder_radius = TEST_RADIUS\n obstacle.cylinder_height = TEST_HEIGHT\n json_data = obstacle.toJSON()\n\n self.assertTrue('latitude' in json_data)\n self.assertEqual(json_data['latitude'], TEST_LAT)\n self.assertTrue('longitude' in json_data)\n self.assertEqual(json_data['longitude'], TEST_LONG)\n self.assertTrue('cylinder_radius' in json_data)\n self.assertEqual(json_data['cylinder_radius'], TEST_RADIUS)\n self.assertTrue('cylinder_height' in json_data)\n self.assertEqual(json_data['cylinder_height'], TEST_HEIGHT)\n\n\nclass TestMovingObstacle(TestCase):\n \"\"\"Tests the MovingObstacle model.\"\"\"\n\n def setUp(self):\n \"\"\"Create the obstacles for testing.\"\"\"\n # Obstacle with no waypoints\n obst_no_wpt = MovingObstacle()\n obst_no_wpt.speed_avg = 1\n obst_no_wpt.sphere_radius = 1\n obst_no_wpt.save()\n self.obst_no_wpt = obst_no_wpt\n\n # Obstacle with single waypoint\n self.single_wpt_lat = 40\n self.single_wpt_lon = 76\n self.single_wpt_alt = 100\n obst_single_wpt = MovingObstacle()\n obst_single_wpt.speed_avg = 1\n obst_single_wpt.sphere_radius = 1\n obst_single_wpt.save()\n single_gpos = GpsPosition()\n single_gpos.latitude = self.single_wpt_lat\n single_gpos.longitude = self.single_wpt_lon\n single_gpos.save()\n single_apos = AerialPosition()\n single_apos.gps_position = single_gpos\n single_apos.altitude_msl = self.single_wpt_alt\n single_apos.save()\n single_wpt = Waypoint()\n single_wpt.position = single_apos\n single_wpt.name = 'Waypoint'\n single_wpt.order = 1\n single_wpt.save()\n obst_single_wpt.waypoints.add(single_wpt)\n self.obst_single_wpt = obst_single_wpt\n\n # Obstacles with predefined path\n self.obstacles = list()\n for path in TESTDATA_MOVOBST_PATHS:\n cur_obst = MovingObstacle()\n cur_obst.name = 'MovingObstacle'\n cur_obst.speed_avg = 68\n cur_obst.sphere_radius = 10\n cur_obst.save()\n for pt_id in range(len(path)):\n (lat, lon, alt) = path[pt_id]\n cur_gpos = GpsPosition()\n cur_gpos.latitude = lat\n cur_gpos.longitude = lon\n cur_gpos.save()\n cur_apos = AerialPosition()\n cur_apos.gps_position = cur_gpos\n cur_apos.altitude_msl = alt\n cur_apos.save()\n cur_wpt = Waypoint()\n cur_wpt.position = cur_apos\n cur_wpt.name = 'Waypoint'\n cur_wpt.order = pt_id\n cur_wpt.save()\n cur_obst.waypoints.add(cur_wpt)\n cur_obst.save()\n self.obstacles.append(cur_obst)\n\n def tearDown(self):\n \"\"\"Tear down the obstacles created.\"\"\"\n MovingObstacle.objects.all().delete()\n Waypoint.objects.all().delete()\n AerialPosition.objects.all().delete()\n GpsPosition.objects.all().delete()\n\n def test_getWaypointTravelTime_invalid_inputs(self):\n \"\"\"Tests proper invalid input handling.\"\"\"\n obstacle = MovingObstacle()\n obstacle.speed_avg = 1\n\n self.assertIsNone(obstacle.getWaypointTravelTime(None, 1, 1))\n self.assertIsNone(obstacle.getWaypointTravelTime([], 1, 1))\n self.assertIsNone(obstacle.getWaypointTravelTime([None], 1, 1))\n self.assertIsNone(obstacle.getWaypointTravelTime(\n [None, None], None, 1))\n self.assertIsNone(obstacle.getWaypointTravelTime(\n [None, None], 1, None))\n self.assertIsNone(obstacle.getWaypointTravelTime(\n [None, None], -1, 0))\n self.assertIsNone(obstacle.getWaypointTravelTime(\n [None, None], 0, -1))\n self.assertIsNone(obstacle.getWaypointTravelTime(\n [None, None], 2, 0))\n self.assertIsNone(obstacle.getWaypointTravelTime(\n [None, None], 0, 2))\n obstacle.speed_avg = 0\n self.assertIsNone(obstacle.getWaypointTravelTime(\n [None, None], 0, 1))\n\n def eval_travel_time(self, time_actual, time_received):\n \"\"\"Evaluates whether the travel times are close enough.\"\"\"\n EVAL_THRESH = time_actual * 0.1\n return abs(time_actual - time_received) < EVAL_THRESH\n\n def test_getWaypointTravelTime(self):\n \"\"\"Tests travel time calc.\"\"\"\n test_spds = [1, 10, 100, 500]\n for (lon2, lat2, lon1, lat1, dist_km) in TESTDATA_COMPETITION_DIST:\n dist_ft = kilometersToFeet(dist_km)\n for speed in test_spds:\n speed_fps = knotsToFeetPerSecond(speed)\n time = dist_ft / speed_fps\n wpt1 = Waypoint()\n apos1 = AerialPosition()\n gpos1 = GpsPosition()\n gpos1.latitude = lat1\n gpos1.longitude = lon1\n apos1.gps_position = gpos1\n apos1.altitude_msl = 0\n wpt1.position = apos1\n wpt2 = Waypoint()\n apos2 = AerialPosition()\n gpos2 = GpsPosition()\n gpos2.latitude = lat2\n gpos2.longitude = lon2\n apos2.gps_position = gpos2\n apos2.altitude_msl = 0\n wpt2.position = apos2\n waypoints = [wpt1, wpt2]\n obstacle = MovingObstacle()\n obstacle.speed_avg = speed\n self.assertTrue(self.eval_travel_time(\n obstacle.getWaypointTravelTime(waypoints, 0, 1),\n time))\n\n def test_getPosition_no_waypoints(self):\n \"\"\"Tests position calc on no-waypoint.\"\"\"\n self.assertIsNone(self.obst_no_wpt.getPosition())\n\n def test_getPosition_one_waypoint(self):\n \"\"\"Tests position calc on single waypoints.\"\"\"\n (lat, lon, alt) = self.obst_single_wpt.getPosition()\n self.assertEqual(lat, self.single_wpt_lat)\n self.assertEqual(lon, self.single_wpt_lon)\n self.assertEqual(alt, self.single_wpt_alt)\n\n def test_getPosition_waypoints_plot(self):\n \"\"\"Tests position calculation by saving plots of calculation.\n\n Saves plots to testOutput/auvsi_suas-MovingObstacle-getPosition-x.jpg.\n On each run it first deletes the existing folder. This requires manual\n inspection to validate correctness.\n \"\"\"\n # Create directory for plot output\n if os.path.exists('testOutput'):\n shutil.rmtree('testOutput')\n os.mkdir('testOutput')\n\n # Create plot for each path\n for obst_id in range(len(self.obstacles)):\n cur_obst = self.obstacles[obst_id]\n\n # Get waypoint positions as numpy array\n waypoints = cur_obst.waypoints.order_by('order')\n waypoint_travel_times = cur_obst.getInterWaypointTravelTimes(\n waypoints)\n waypoint_times = cur_obst.getWaypointTimes(waypoint_travel_times)\n total_time = waypoint_times[len(waypoint_times)-1]\n num_waypoints = len(waypoints)\n wpt_latitudes = np.zeros(num_waypoints+1)\n wpt_longitudes = np.zeros(num_waypoints+1)\n wpt_altitudes = np.zeros(num_waypoints+1)\n for waypoint_id in range(num_waypoints+1):\n cur_id = waypoint_id % num_waypoints\n wpt_latitudes[waypoint_id] = (\n waypoints[cur_id].position.gps_position.latitude)\n wpt_longitudes[waypoint_id] = (\n waypoints[cur_id].position.gps_position.longitude)\n wpt_altitudes[waypoint_id] = (\n waypoints[cur_id].position.altitude_msl)\n\n # Create time series to represent samples at 10 Hz for 1.5 trips\n time_pos = np.arange(0, 1.5*total_time, 0.10)\n # Sample position for the time series\n latitudes = np.zeros(len(time_pos))\n longitudes = np.zeros(len(time_pos))\n altitudes = np.zeros(len(time_pos))\n epoch = datetime.datetime.utcfromtimestamp(0)\n for time_id in range(len(time_pos)):\n cur_time_offset = time_pos[time_id]\n cur_samp_time = (epoch +\n datetime.timedelta(seconds=cur_time_offset))\n (lat, lon, alt) = cur_obst.getPosition(cur_samp_time)\n latitudes[time_id] = lat\n longitudes[time_id] = lon\n altitudes[time_id] = alt\n\n # Create plot\n plt.figure()\n plt.subplot(311)\n plt.plot(time_pos, latitudes, 'b',\n waypoint_times, wpt_latitudes, 'rx')\n plt.subplot(312)\n plt.plot(time_pos, longitudes, 'b',\n waypoint_times, wpt_longitudes, 'rx')\n plt.subplot(313)\n plt.plot(time_pos, altitudes, 'b',\n waypoint_times, wpt_altitudes, 'rx')\n plt.savefig(('testOutput/auvsi_suas-MovingObstacle-getPosition-%d.jpg' %\n obst_id))\n\n\n def test_toJSON(self):\n \"\"\"Tests the JSON serialization model.\"\"\"\n for cur_obst in self.obstacles:\n json_data = cur_obst.toJSON()\n self.assertTrue('latitude' in json_data)\n self.assertTrue('longitude' in json_data)\n self.assertTrue('altitude_msl' in json_data)\n self.assertTrue('sphere_radius' in json_data)\n self.assertEqual(json_data['sphere_radius'], cur_obst.sphere_radius)\n obst = self.obst_single_wpt\n json_data = obst.toJSON()\n self.assertEqual(json_data['latitude'],\n obst.waypoints.all()[0].position.gps_position.latitude)\n self.assertEqual(json_data['longitude'],\n obst.waypoints.all()[0].position.gps_position.longitude)\n self.assertEqual(json_data['altitude_msl'],\n obst.waypoints.all()[0].position.altitude_msl)\n\n\nclass TestLoginUserView(TestCase):\n \"\"\"Tests the loginUser view.\"\"\"\n\n def setUp(self):\n \"\"\"Sets up the test by creating a test user.\"\"\"\n self.user = User.objects.create_user(\n 'testuser', 'testemail@x.com', 'testpass')\n self.user.save()\n self.client = Client()\n self.loginUrl = reverse('auvsi_suas:login')\n\n def tearDown(self):\n \"\"\"Deletes users for the view.\"\"\"\n self.user.delete()\n\n def test_invalid_request(self):\n \"\"\"Tests an invalid request by mis-specifying parameters.\"\"\"\n client = self.client\n loginUrl = self.loginUrl\n\n # Test GET instead of POST\n response = client.get(loginUrl)\n self.assertEqual(response.status_code, 400)\n\n # Test POST with no parameters\n response = client.post(loginUrl)\n self.assertEqual(response.status_code, 400)\n\n # Test POST with a missing parameter\n response = client.post(loginUrl, {'username': 'test'})\n self.assertEqual(response.status_code, 400)\n response = client.post(loginUrl, {'password': 'test'})\n self.assertEqual(response.status_code, 400)\n\n\n def test_invalid_credentials(self):\n \"\"\"Tests invalid credentials for login.\"\"\"\n client = self.client\n loginUrl = self.loginUrl\n response = client.post(loginUrl, {'username': 'a', 'password': 'b'})\n self.assertEqual(response.status_code, 400)\n\n def test_correct_credentials(self):\n \"\"\"Tests correct credentials for login.\"\"\"\n client = self.client\n loginUrl = self.loginUrl\n response = client.post(\n loginUrl, {'username': 'testuser', 'password': 'testpass'})\n self.assertEqual(response.status_code, 200)\n\n\nclass TestGetServerInfoView(TestCase):\n \"\"\"Tests the getServerInfo view.\"\"\"\n\n def setUp(self):\n \"\"\"Sets up the client, server info URL, and user.\"\"\"\n self.user = User.objects.create_user(\n 'testuser', 'testemail@x.com', 'testpass')\n self.user.save()\n self.info = ServerInfo()\n self.info.team_msg = 'test message'\n self.info.save()\n self.client = Client()\n self.loginUrl = reverse('auvsi_suas:login')\n self.infoUrl = reverse('auvsi_suas:server_info')\n\n def tearDown(self):\n \"\"\"Destroys the user.\"\"\"\n self.user.delete()\n ServerInfo.objects.all().delete()\n ServerInfoAccessLog.objects.all().delete()\n\n def test_not_authenticated(self):\n \"\"\"Tests requests that have not yet been authenticated.\"\"\"\n client = self.client\n infoUrl = self.infoUrl\n\n response = client.get(infoUrl)\n self.assertEqual(response.status_code, 400)\n\n def test_invalid_request(self):\n \"\"\"Tests an invalid request by mis-specifying parameters.\"\"\"\n client = self.client\n loginUrl = self.loginUrl\n infoUrl = self.infoUrl\n\n client.post(loginUrl, {'username': 'testuser', 'password': 'testpass'})\n response = client.post(infoUrl)\n self.assertEqual(response.status_code, 400)\n\n def test_correct_log_and_response(self):\n \"\"\"Tests that access is logged and returns valid response.\"\"\"\n client = self.client\n loginUrl = self.loginUrl\n infoUrl = self.infoUrl\n client.post(loginUrl, {'username': 'testuser', 'password': 'testpass'})\n\n response = client.get(infoUrl)\n self.assertEqual(response.status_code, 200)\n self.assertTrue(len(ServerInfoAccessLog.objects.all()) == 1)\n access_log = ServerInfoAccessLog.objects.all()[0]\n self.assertEqual(access_log.user, self.user)\n json_data = json.loads(response.content)\n self.assertTrue('server_info' in json_data)\n self.assertTrue('server_time' in json_data)\n\n def test_loadtest(self):\n \"\"\"Tests the max load the view can handle.\"\"\"\n client = self.client\n loginUrl = self.loginUrl\n infoUrl = self.infoUrl\n client.post(loginUrl, {'username': 'testuser', 'password': 'testpass'})\n\n total_ops = 0\n min_time = 10.0\n start_time = datetime.datetime.now()\n while (datetime.datetime.now() - start_time).total_seconds() < min_time:\n client.get(infoUrl)\n total_ops += 1\n end_time = datetime.datetime.now()\n total_time = (end_time - start_time).total_seconds()\n op_rate = total_ops / total_time\n\n OP_RATE_THRESH = 10 * 3 * 2\n self.assertTrue(op_rate >= OP_RATE_THRESH)\n\n\nclass TestGetObstaclesView(TestCase):\n \"\"\"Tests the getObstacles view.\"\"\"\n\n def setUp(self):\n \"\"\"Sets up the client, obstacle URL, obstacles, and user.\"\"\"\n # Setup user\n self.user = User.objects.create_user(\n 'testuser', 'testemail@x.com', 'testpass')\n self.user.save()\n # Setup the obstacles\n for path in TESTDATA_MOVOBST_PATHS:\n # Stationary obstacle\n (stat_lat, stat_lon, _) = path[0]\n stat_gps = GpsPosition()\n stat_gps.latitude = stat_lat\n stat_gps.longitude = stat_lon\n stat_gps.save()\n stat_obst = StationaryObstacle()\n stat_obst.gps_position = stat_gps\n stat_obst.cylinder_radius = 100\n stat_obst.cylinder_height = 200\n stat_obst.save()\n # Moving obstacle\n mov_obst = MovingObstacle()\n mov_obst.speed_avg = 40\n mov_obst.sphere_radius = 100\n mov_obst.save()\n for pt_id in range(len(path)):\n # Obstacle waypoints\n (wpt_lat, wpt_lon, wpt_alt) = path[pt_id]\n gpos = GpsPosition()\n gpos.latitude = wpt_lat\n gpos.longitude = wpt_lon\n gpos.save()\n apos = AerialPosition()\n apos.altitude_msl = wpt_alt\n apos.gps_position = gpos\n apos.save()\n wpt = Waypoint()\n wpt.name = 'test waypoint'\n wpt.order = pt_id\n wpt.position = apos\n wpt.save()\n mov_obst.waypoints.add(wpt)\n mov_obst.save()\n # Setup test objs\n self.client = Client()\n self.loginUrl = reverse('auvsi_suas:login')\n self.obstUrl = reverse('auvsi_suas:obstacles')\n\n def tearDown(self):\n \"\"\"Destroys the user.\"\"\"\n self.user.delete()\n ObstacleAccessLog.objects.all().delete()\n StationaryObstacle.objects.all().delete()\n MovingObstacle.objects.all().delete()\n\n def test_not_authenticated(self):\n \"\"\"Tests requests that have not yet been authenticated.\"\"\"\n client = self.client\n obstUrl = self.obstUrl\n response = client.get(obstUrl)\n self.assertEqual(response.status_code, 400)\n\n def test_invalid_request(self):\n \"\"\"Tests an invalid request by mis-specifying parameters.\"\"\"\n client = self.client\n loginUrl = self.loginUrl\n obstUrl = self.obstUrl\n\n client.post(loginUrl, {'username': 'testuser', 'password': 'testpass'})\n response = client.post(obstUrl)\n self.assertEqual(response.status_code, 400)\n\n def test_correct_log_and_response(self):\n \"\"\"Tests that access is logged and returns valid response.\"\"\"\n client = self.client\n loginUrl = self.loginUrl\n obstUrl = self.obstUrl\n client.post(loginUrl, {'username': 'testuser', 'password': 'testpass'})\n\n response = client.get(obstUrl)\n self.assertEqual(response.status_code, 200)\n json_data = json.loads(response.content)\n self.assertTrue('stationary_obstacles' in json_data)\n self.assertTrue('moving_obstacles' in json_data)\n self.assertEqual(len(ObstacleAccessLog.objects.all()), 1)\n\n def test_loadtest(self):\n \"\"\"Tests the max load the view can handle.\"\"\"\n client = self.client\n loginUrl = self.loginUrl\n obstUrl = self.obstUrl\n client.post(loginUrl, {'username': 'testuser', 'password': 'testpass'})\n\n total_ops = 0\n min_time = 10.0\n start_time = datetime.datetime.now()\n while (datetime.datetime.now() - start_time).total_seconds() < min_time:\n client.get(obstUrl)\n total_ops += 1\n end_time = datetime.datetime.now()\n total_time = (end_time - start_time).total_seconds()\n op_rate = total_ops / total_time\n\n OP_RATE_THRESH = 10 * 3 * 1.5\n self.assertTrue(op_rate >= OP_RATE_THRESH)\n\n\nclass TestPostUasPosition(TestCase):\n \"\"\"Tests the postUasPosition view.\"\"\"\n\n def setUp(self):\n \"\"\"Sets up the client, server info URL, and user.\"\"\"\n self.user = User.objects.create_user(\n 'testuser', 'testemail@x.com', 'testpass')\n self.user.save()\n self.client = Client()\n self.loginUrl = reverse('auvsi_suas:login')\n self.uasUrl = reverse('auvsi_suas:uas_telemetry')\n\n def tearDown(self):\n \"\"\"Destroys the user.\"\"\"\n self.user.delete()\n UasTelemetry.objects.all().delete()\n AerialPosition.objects.all().delete()\n GpsPosition.objects.all().delete()\n\n def test_not_authenticated(self):\n \"\"\"Tests requests that have not yet been authenticated.\"\"\"\n client = self.client\n uasUrl = self.uasUrl\n response = client.get(uasUrl)\n self.assertEqual(response.status_code, 400)\n\n def test_invalid_request(self):\n \"\"\"Tests an invalid request by mis-specifying parameters.\"\"\"\n client = self.client\n loginUrl = self.loginUrl\n uasUrl = self.uasUrl\n\n client.post(loginUrl, {'username': 'testuser', 'password': 'testpass'})\n response = client.post(uasUrl)\n self.assertEqual(response.status_code, 400)\n response = client.post(uasUrl,\n {'longitude': 0,\n 'altitude_msl': 0,\n 'uas_heading': 0})\n self.assertEqual(response.status_code, 400)\n response = client.post(uasUrl,\n {'latitude': 0,\n 'altitude_msl': 0,\n 'uas_heading': 0})\n self.assertEqual(response.status_code, 400)\n response = client.post(uasUrl,\n {'latitude': 0,\n 'longitude': 0,\n 'uas_heading': 0})\n self.assertEqual(response.status_code, 400)\n response = client.post(uasUrl,\n {'latitude': 0,\n 'longitude': 0,\n 'altitude_msl': 0})\n self.assertEqual(response.status_code, 400)\n\n def eval_request_values(self, lat, lon, alt, heading):\n client = self.client\n uasUrl = self.uasUrl\n response = client.post(uasUrl,\n {'latitude': lat,\n 'longitude': lon,\n 'altitude_msl': alt,\n 'uas_heading': heading})\n return response.status_code\n\n def test_invalid_request_values(self):\n \"\"\"Tests by specifying correct parameters with invalid values.\"\"\"\n client = self.client\n loginUrl = self.loginUrl\n client.post(loginUrl, {'username': 'testuser', 'password': 'testpass'})\n\n TEST_DATA = [\n (-100, 0, 0, 0),\n (100, 0, 0, 0),\n (0, -190, 0, 0),\n (0, 190, 0, 0),\n (0, 0, 0, -10),\n (0, 0, 0, 370)]\n for (lat, lon, alt, heading) in TEST_DATA:\n self.assertEqual(400,\n self.eval_request_values(lat, lon, alt, heading))\n\n def test_upload_and_store(self):\n \"\"\"Tests correct upload and storage of data.\"\"\"\n client = self.client\n loginUrl = self.loginUrl\n client.post(loginUrl, {'username': 'testuser', 'password': 'testpass'})\n uasUrl = self.uasUrl\n\n lat = 10\n lon = 20\n alt = 30\n heading = 40\n response = client.post(uasUrl,\n {'latitude': lat,\n 'longitude': lon,\n 'altitude_msl': alt,\n 'uas_heading': heading})\n self.assertEqual(response.status_code, 200)\n self.assertEqual(len(UasTelemetry.objects.all()), 1)\n obj = UasTelemetry.objects.all()[0]\n self.assertEqual(obj.user, self.user)\n self.assertEqual(obj.uas_heading, heading)\n self.assertEqual(obj.uas_position.altitude_msl, alt)\n self.assertEqual(obj.uas_position.gps_position.latitude, lat)\n self.assertEqual(obj.uas_position.gps_position.longitude, lon)\n\n def test_loadtest(self):\n \"\"\"Tests the max load the view can handle.\"\"\"\n client = self.client\n loginUrl = self.loginUrl\n uasUrl = self.uasUrl\n client.post(loginUrl, {'username': 'testuser', 'password': 'testpass'})\n\n lat = 10\n lon = 20\n alt = 30\n heading = 40\n total_ops = 0\n min_time = 10.0\n start_time = datetime.datetime.now()\n while (datetime.datetime.now() - start_time).total_seconds() < min_time:\n client.post(uasUrl,\n {'latitude': lat,\n 'longiutde': lon,\n 'altitude_msl': alt,\n 'uas_heading': heading})\n total_ops += 1\n end_time = datetime.datetime.now()\n total_time = (end_time - start_time).total_seconds()\n op_rate = total_ops / total_time\n\n OP_RATE_THRESH = 10 * 3 * 1.5\n self.assertTrue(op_rate >= OP_RATE_THRESH)\n","sub_path":"src/auvsi_suas_server/auvsi_suas/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":33152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"578787820","text":"\"\"\"Tests for the data module.\"\"\"\n\nfrom collections import OrderedDict\nimport csv\nimport os\nimport tempfile\nimport uuid\n\nimport pandas as pd\nimport psycopg2\nimport pytest\n\nimport dallinger\nfrom dallinger.config import get_config\nfrom dallinger.utils import generate_random_id\n\n\nclass TestData(object):\n\n data_path = os.path.join(\n \"tests\",\n \"datasets\",\n \"12eee6c6-f37f-4963-b684-da585acd77f1-data.zip\"\n )\n\n config = get_config()\n\n def test_connection_to_s3(self):\n conn = dallinger.data._s3_connection()\n assert conn\n\n def test_user_s3_bucket_first_time(self):\n conn = dallinger.data._s3_connection()\n bucket = dallinger.data.user_s3_bucket(\n canonical_user_id=generate_random_id(),\n )\n assert bucket\n conn.delete_bucket(bucket)\n\n def test_user_s3_bucket_thrice(self):\n conn = dallinger.data._s3_connection()\n id = generate_random_id()\n for i in range(3):\n bucket = dallinger.data.user_s3_bucket(\n canonical_user_id=id,\n )\n assert bucket\n conn.delete_bucket(bucket)\n\n def test_user_s3_bucket_no_id_provided(self):\n bucket = dallinger.data.user_s3_bucket()\n assert bucket\n\n def test_dataset_creation(self):\n \"\"\"Load a dataset.\"\"\"\n dallinger.data.Data(self.data_path)\n\n def test_conversions(self):\n data = dallinger.data.Data(self.data_path)\n assert data.networks.csv\n assert data.networks.dict\n assert data.networks.df.shape\n assert data.networks.html\n assert data.networks.latex\n assert data.networks.list\n assert data.networks.ods\n assert data.networks.tsv\n assert data.networks.xls\n assert data.networks.xlsx\n assert data.networks.yaml\n\n def test_dataframe_conversion(self):\n data = dallinger.data.Data(self.data_path)\n assert data.networks.df.shape == (1, 13)\n\n def test_csv_conversion(self):\n data = dallinger.data.Data(self.data_path)\n assert data.networks.csv[0:3] == \"id,\"\n\n def test_tsv_conversion(self):\n data = dallinger.data.Data(self.data_path)\n assert data.networks.tsv[0:3] == \"id\\t\"\n\n def test_list_conversion(self):\n data = dallinger.data.Data(self.data_path)\n assert type(data.networks.list) is list\n\n def test_dict_conversion(self):\n data = dallinger.data.Data(self.data_path)\n assert type(data.networks.dict) is OrderedDict\n\n def test_df_conversion(self):\n data = dallinger.data.Data(self.data_path)\n assert type(data.networks.df) is pd.DataFrame\n\n def test_data_loading(self):\n data = dallinger.data.load(\"3b9c2aeb-0eb7-4432-803e-bc437e17b3bb\")\n assert data\n assert data.networks.csv\n\n def test_export_of_nonexistent_database(self):\n nonexistent_local_db = str(uuid.uuid4())\n with pytest.raises(psycopg2.OperationalError):\n dallinger.data.copy_local_to_csv(nonexistent_local_db, \"\")\n\n def test_export_of_dallinger_database(self):\n export_dir = tempfile.mkdtemp()\n dallinger.data.copy_local_to_csv(\"dallinger\", export_dir)\n assert os.path.isfile(os.path.join(export_dir, \"network.csv\"))\n\n def test_exported_database_includes_headers(self):\n export_dir = tempfile.mkdtemp()\n dallinger.data.copy_local_to_csv(\"dallinger\", export_dir)\n network_table_path = os.path.join(export_dir, \"network.csv\")\n assert os.path.isfile(network_table_path)\n with open(network_table_path, 'rb') as f:\n reader = csv.reader(f, delimiter=',')\n header = next(reader)\n assert \"creation_time\" in header\n\n def test_scrub_pii(self):\n path_to_data = os.path.join(\"tests\", \"datasets\", \"pii\")\n dallinger.data._scrub_participant_table(path_to_data)\n with open(os.path.join(path_to_data, \"participant.csv\"), 'rb') as f:\n reader = csv.reader(f, delimiter=',')\n next(reader) # Skip the header\n for row in reader:\n assert \"PII\" not in row\n","sub_path":"tests/test_data.py","file_name":"test_data.py","file_ext":"py","file_size_in_byte":4138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"347930763","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport sbb_rs485\n\nLOG_OK = 1\nLOG_FAIL = 4\n\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n\ndef log(level, message):\n if (level == 1):\n pf = \"[{0}{1}{2}] \".format(bcolors.OKGREEN, \"OK\", bcolors.ENDC)\n if (level == 4):\n pf = \"[{0}{1}{2}]\".format(bcolors.FAIL, \"FAIL\", bcolors.ENDC)\n print(\"{0} {1}\".format(pf, message))\n\n\ndef fmt_ser(ser):\n ss = \"{0}{1}{2}{3}\".format(\n str(hex(ser[0]))[2:].upper(),\n str(hex(ser[1]))[2:].upper(),\n str(hex(ser[2]))[2:].upper(),\n str(hex(ser[3]))[2:].upper(),\n )\n return ss\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Get serial number from SBB panel\",\n )\n parser.add_argument(\n '--port',\n '-p',\n help=\"Serial port\",\n type=str,\n default='/dev/ttyUSB0',\n )\n parser.add_argument(\n '--address',\n '-a',\n help=\"Address\",\n type=int,\n default=0,\n )\n args = parser.parse_args()\n\n cc = sbb_rs485.PanelControl(port=args.port)\n cc.connect()\n cc.serial.timeout = 0.1\n\n serial = cc.get_serial_number(args.address)\n if len(serial) == 4:\n log(LOG_OK, \"reading serial ({0})\".format(fmt_ser(serial)))\n else:\n log(LOG_FAIL, \"reading serial\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"python/get_serial.py","file_name":"get_serial.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"28993780","text":"\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import uic\nimport ctypes.wintypes\nimport ctypes, ctypes.wintypes, sys\nimport py1win0 as win0\n\n\n\nclass COPYDATASTRUCT(ctypes.Structure):\n _fields_ = [\n ('dwData', ctypes.wintypes.LPARAM),\n ('cbData', ctypes.wintypes.DWORD),\n ('lpData', ctypes.c_void_p)\n ]\nPCOPYDATASTRUCT = ctypes.POINTER(COPYDATASTRUCT)\n\n\nform_class = uic.loadUiType(\"main_window.ui\")[0]\n\nclass MyWindow(QMainWindow, form_class):\n def __init__(self):\n super().__init__()\n self.setupUi(self)\n self.setWindowTitle(\"MainWindow\")\n\n def nativeEvent(self, eventType, message):\n msg = ctypes.wintypes.MSG.from_address(message.__int__())\n if eventType == \"windows_generic_MSG\":\n if msg.message == 74:\n print(msg.lParam)\n pCDS = ctypes.cast(msg.lParam, PCOPYDATASTRUCT)\n print(\"dwData=%d cbData=0x%x lpData=0x%x\" % (pCDS.contents.dwData, pCDS.contents.cbData, pCDS.contents.lpData))\n\n yHdr = ctypes.string_at(pCDS.contents.lpData,255)\n stringToReturn = win0.s_yHdr(yHdr)\n QMessageBox.about(self,\"message\", stringToReturn.decode(\"utf-8\"))\n\n\n return False, 0\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n myWindow = MyWindow()\n myWindow.show()\n app.exec_()","sub_path":"pywin/py1win7cds.py","file_name":"py1win7cds.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"349679269","text":"from flask import Flask\napp = Flask(__name__)\n\nfrom flask import make_response\n\n@app.route('/')\ndef index():\n response = make_response('<h1> 잘 따라 치시오!! </h1>')\n response.set_cookie('answer','42') # 'answer' :쿠키의 이름 / '42' : 값\n return response\n\nif __name__ == '__main__':\n app.run(host='127.0.0.1', port=5000, debug=False)\n\n''' cookie session\n------------------------------------------\n저장위치 : 클라이언트 / 서버\n저장형식 : 텍스트 형식 / object형\n종료시점 : 쿠키 저장 시 설정 / 브라우저 종료시\n (기간 만료시 삭제)/ 삭제\n / (기간 지정 가능)\n 자원 : 클라이언드의 / 서버 자원 사용\n 자원 사용 \n 속도 : 빠름 / 느림 : 상대적\n 보안 : 나쁨 / 좋음 : 상대적\n\n'''","sub_path":"flask/fk04_response.py","file_name":"fk04_response.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"264020183","text":"import discord\nfrom discord.ext import commands, vbu\n\n\nCSUPPORT_MESSAGE = (\"\\u200b\\n\" * 28) + \"\"\"\nPlease give a detailed report of:\n* What you thought would happen vs what actually happened\n* How you cause the issue to happen\n* Any extra details (like screenshots)\n\nPing `@Support Team` for a faster response\n\"\"\"\nCSUPPORT_COMPONENTS = discord.ui.MessageComponents(\n discord.ui.ActionRow(\n discord.ui.Button(label=\"See the FAQs\", custom_id=\"FAQ\")\n )\n)\nFAQ_COMPONENTS = discord.ui.MessageComponents(\n discord.ui.ActionRow(\n discord.ui.Button(label=\"MarriageBot FAQs ->\", custom_id=\"_\", disabled=True),\n discord.ui.Button(label=\"I can't disown my child\", custom_id=\"FAQ CANT_DISOWN\", style=discord.ui.ButtonStyle.secondary),\n discord.ui.Button(label=\"None of the commands work\", custom_id=\"FAQ NO_COMMANDS_WORK\", style=discord.ui.ButtonStyle.secondary),\n discord.ui.Button(label=\"Gold doesn't have my family tree\", custom_id=\"FAQ COPY_FAMILY_TO_GOLD\", style=discord.ui.ButtonStyle.secondary),\n ),\n)\n\n\nclass FAQHandler(vbu.Cog):\n\n NO_COMMANDS_WORK = 729049284129062932 # setprefix\n CANT_DISOWN = 729049343260229652 # useid\n COPY_FAMILY_TO_GOLD = 729050839502553089\n NEED_TO_BE_MODERATOR = 729051025184653413 # create a role called marriagebot moderator\n\n FAQ_CHANNEL_ID = 689189625356746755\n SUPPORT_CHANNEL_ID = 689189589776203861\n\n def __init__(self, bot: vbu.Bot):\n super().__init__(bot)\n self.cached_messages = {}\n\n async def get_output(self, key: str) -> dict:\n \"\"\"\n Get a message from the API or the cache.\n \"\"\"\n\n if key in self.cached_messages:\n return self.cached_messages[key]\n message_id: int = getattr(self, key)\n faq_message: discord.Message = await self.bot.get_channel(self.FAQ_CHANNEL_ID).fetch_message(message_id)\n data = {\n \"content\": faq_message.content,\n \"embeds\": faq_message.embeds,\n }\n self.cached_messages[key] = data\n return data\n\n @commands.command(hidden=True)\n async def csupport(self, ctx: vbu.Context):\n \"\"\"\n Post the csupport message wew.\n \"\"\"\n\n if ctx.channel.id != self.SUPPORT_CHANNEL_ID:\n return\n await ctx.send(CSUPPORT_MESSAGE, components=CSUPPORT_COMPONENTS)\n\n @commands.command(hidden=True)\n async def faq(self, ctx: vbu.Context):\n \"\"\"\n Post the FAQ message for people who don't want to look in the support channel.\n \"\"\"\n\n return await ctx.send(\"Click a button to see the FAQ response.\", components=FAQ_COMPONENTS)\n\n @vbu.Cog.listener()\n async def on_component_interaction(self, payload):\n \"\"\"\n See if an FAQ component was clicked.\n \"\"\"\n\n if not payload.component.custom_id.startswith(\"FAQ\"):\n return\n try:\n _, asking_for = payload.component.custom_id.split(\" \")\n except ValueError:\n return await payload.respond(\"Click a button to see the FAQ response.\", components=FAQ_COMPONENTS, ephemeral=True)\n data = await self.get_output(asking_for)\n return await payload.respond(**data, ephemeral=True)\n\n\ndef setup(bot: vbu.Bot):\n x = FAQHandler(bot)\n bot.add_cog(x)\n","sub_path":"cogs/faq_handler.py","file_name":"faq_handler.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"351229807","text":"# Copyright 2014-2015 PUNCH Cyber Analytics Group\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\"\"\"\nOverview\n========\n\nPublish messages to single or multiple queues for processing\n\n\"\"\"\n\nimport os\nimport argparse\n\nfrom stoq.scan import get_sha1\nfrom stoq.args import StoqArgs\nfrom stoq.plugins import StoqWorkerPlugin\n\n\nclass PublisherWorker(StoqWorkerPlugin):\n\n def __init__(self):\n super().__init__()\n\n def activate(self, stoq):\n\n self.stoq = stoq\n\n parser = argparse.ArgumentParser()\n parser = StoqArgs(parser)\n worker_opts = parser.add_argument_group(\"Plugin Options\")\n worker_opts.add_argument(\"-O\", \"--comment\",\n dest='user_comments',\n default=\"\",\n help=\"Comment associated with sample \\\n submission\")\n worker_opts.add_argument(\"-w\", \"--worker\",\n dest='submission_list',\n action='append',\n help=\"Worker queues that should process \\\n sample. May be used multiple times\")\n\n options = parser.parse_args(self.stoq.argv[2:])\n\n super().activate(options=options)\n\n # Activate the appropriate plugin so we can publish messages,\n # if needed.\n self.publish_connector = self.stoq.load_plugin(self.publisher,\n 'source')\n\n return True\n\n def scan(self, payload, **kwargs):\n \"\"\"\n Publish messages to single or multiple RabbitMQ queues for processing\n\n :param bytes payload: Payload to be published\n :param **kwargs path: Path to file being ingested\n :param **kwargs user_comments: Comments associated with payload\n :param **kwargs submission_list: List of queues to publish to\n\n :returns: Results from scan\n :rtype: True\n\n \"\"\"\n\n super().scan()\n\n self.stoq.log.info(\"Ingesting: %s\" % kwargs['uuid'])\n\n # For every file we ingest we are going to assign a unique\n # id so we can link everything across the scope of the ingest.\n # This will be assigned to submissions within archive files as well\n # in order to simplify correlating files post-ingest.\n if 'uuid' not in kwargs:\n kwargs['uuid'] = self.stoq.get_uuid\n\n if payload and 'sha1' not in kwargs:\n kwargs['sha1'] = get_sha1(payload)\n\n if 'path' in kwargs:\n kwargs['path'] = os.path.abspath(kwargs['path'])\n\n if self.user_comments:\n kwargs['user_comments'] = self.user_comments\n\n if 'submission_list' in kwargs:\n self.submission_list = kwargs['submission_list']\n kwargs.pop('submission_list')\n\n # Using self.stoq.worker.archive_connector in case this plugin is\n # called from another plugin. This will ensure that the correct\n # archive connector is defined when the message is published.\n if self.stoq.worker.archive_connector:\n kwargs['archive'] = self.archive_connector\n else:\n kwargs['archive'] = \"file\"\n\n for routing_key in self.submission_list:\n self.publish_connector.publish(kwargs, routing_key)\n\n return True\n","sub_path":"worker/publisher/publisher/publisher.py","file_name":"publisher.py","file_ext":"py","file_size_in_byte":3892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"11848847","text":"# _*_ coding:utf-8 _*_\n# import urllib.request, urllib.error, urllib.parse\n# import urllib.request, urllib.parse, urllib.error\nimport sys\n\nfrom Task import TK_TerminalHandle\nfrom common import dataprovide, sql_normal,stringHelper\nfrom element_locator import papaandroid\nimport imp\nimport requests\nsys.path.append(\"..\")\nimport unittest,time\nfrom time import sleep\nfrom selenium.webdriver.common.by import By\nimport random\n\n# imp.reload(sys)\n# sys.setdefaultencoding('utf-8')\n\nclass Task(TK_TerminalHandle.TerminalHandle,unittest.TestCase):\n\n #弹出框关闭\n def pop_close(self):\n sleep(15)\n if self.isElement(papaandroid.b_Pop) == True:\n self.click_button(papaandroid.b_Pop_close)\n sleep(3)\n\n #用户登录\n def login(self,casekey):\n self.click_button(papaandroid.b_My)\n x=self.get_login_number(casekey)\n user=dataprovide.fetchTestData(4,'login',0,x,'')\n if self.isElement(papaandroid.b_login)==False:\n print('用户已登录')\n self.driver.back()\n else:\n self.click_button(papaandroid.b_login)\n self.send_keys(papaandroid.edit_iphone, dataprovide.dict_gen(user)[1]['iphone'])\n self.click_button(papaandroid.b_next)\n self.send_keys(papaandroid.edit_pwd, dataprovide.dict_gen(user)[1]['pwd'])\n sleep(3)\n self.click_button(papaandroid.b_loginsure)\n if self.isElement(papaandroid.tx_papa)==True:\n print('用户登录成功,跳转页面正确')\n sleep(3)\n else:\n self.back()\n\n #退出登录\n def loginout(self):\n self.click_button(papaandroid.b_WoDe)\n if self.isElement(papaandroid.b_DengLu_ZhuCe) == False:\n sleep(3)\n self.click_button(papaandroid.b_More)\n self.click_button(papaandroid.b_loginout)\n sleep(2)\n self.click_button(papaandroid.b_loginout_sure)\n print (\"退出登录成功\")\n sleep(1)\n else:\n self.back()\n\n\n #点击排序:默认\n def orderby_default(self):\n self.click_button((By.XPATH, papaandroid.b_MoRen[1]))\n\n\n def get_login_number(self,casekey):\n list1=[]\n for i in range(len(dataprovide.fetchTestData(3,'login',0))):\n if casekey==dataprovide.fetchTestData(3,'login',0)[i]['Casekey']:\n list1.append(i+1)\n else:\n pass\n return list1[0]\n\n def user(self,casekey):\n x=self.get_login_number(casekey)\n return dataprovide.fetchTestData(4,'login',0,x,'')\n\n # 支付回调\n def order(self, ordernum):\n now = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(time.time()))\n a = random.randint(0, 999999)\n # 模拟回调代码\n params = \"service=alipay.wap.trade.create.direct&v=1.0&sec_id=MD5¬ify_data=<notify><payment_type>1</payment_type><subject>\" \\\n + \"[寿全斋]红糖姜冲泡茶纸盒装12g*10条/盒\" + \"</subject><trade_no>\" + \"2016030821001004360263\" + str(a) + \"\\\n </trade_no><buyer_email>13738171756</buyer_email><gmt_create>\" \\\n + now + \"</gmt_create><notify_type>trade_status_sync</notify_type><quantity>1</quantity><out_trade_no>\" + str(\n ordernum) + \\\n \"</out_trade_no><notify_time>\" + now + \\\n \"</notify_time><seller_id>2088021886187623</seller_id><trade_status>TRADE_SUCCESS</trade_status>\\\n <is_total_fee_adjust>N</is_total_fee_adjust><total_fee>\" \\\n + str(0.01) + \"</total_fee><gmt_payment>\" \\\n + now + \"</gmt_payment><seller_email>zhuzhu@wansecheng.com</seller_email><price>\" + str(0.01) \\\n + \"</price><buyer_id>\" + \"2088122051790362\" + \"</buyer_id><notify_id></notify_id><use_coupon>N</use_coupon></notify>\"\n secid = \"3ieev5tm0zfma78up2kp9gaz1dln1kmb\"\n sign = self.md5(params + secid)\n # 将参数post到指定接口\n url = 'http://tt5.ewanse.com/pay-callback/alipay'\n payload = {'service': 'alipay.wap.trade.create.direct', 'v': '1.0', 'sec_id': 'MD5', 'sign': sign,\n 'notify_data': \\\n \"<notify><payment_type>1</payment_type><subject>\" \\\n + \"[寿全斋]红糖姜冲泡茶纸盒装12g*10条/盒\" + \"</subject><trade_no>2016030821001004360263\" + str(a) + \"</trade_no>\\\n <buyer_email>13738171756</buyer_email><gmt_create>\" + \\\n now + \"</gmt_create><notify_type>trade_status_sync</notify_type><quantity>1</quantity><out_trade_no>\" + \\\n str(ordernum) + \"</out_trade_no><notify_time>\" + \\\n now + \"</notify_time><seller_id>2088021886187623</seller_id><trade_status>TRADE_SUCCESS</trade_status>\\\n <is_total_fee_adjust>N</is_total_fee_adjust><total_fee>\" \\\n + str(\n 0.01) + \"</total_fee><gmt_payment>\" + now + \"</gmt_payment><seller_email>zhuzhu@wansecheng.com</seller_email><price>\" \\\n + str(\n 0.01) + \"</price><buyer_id>2088122051790362</buyer_id><notify_id></notify_id><use_coupon>N</use_coupon></notify>\"}\n test_data_urlencode = urllib.parse.urlencode(payload)\n r = urllib.request.Request(url=url, data=test_data_urlencode)\n res_data = urllib.request.urlopen(r)\n res = res_data.read()\n print(res, res_data)\n\n # 获取订单号并支付\n def get_order_num(self):\n sleep(6)\n self.my_swipe_to_down()\n sleep(4)\n status1 = self.driver.find_element_by_id(papaandroid.tx_DingdanZhuangTai[1]).text\n status2 = status1[5:]\n status3 = status1.encode(encoding='UTF-8')\n self.assertEqual(status3, papaandroid.wait_pay)\n print(\"等待买家支付状态正确\")\n self.my_swipe_to_up()\n self.my_swipe_to_up()\n sleep(6)\n order_num = self.driver.find_element_by_id(papaandroid.tx_DingDanHao[1]).text\n myms = sql_normal.mysql_connect(sql_normal.db_info)\n myms.sql_assign_exec(\"update gzseed_vancelle_order.gss_weidian_order set order_amount=0.01 where order_sn='\" \\\n + order_num + \"'\")\n order_amount_num = myms.sql_assign_exec(\"SELECT gzseed_vancelle_order.gss_weidian_order.order_amount\\\n FROM gzseed_vancelle_order.gss_weidian_order where order_sn='\" + order_num + \"'\")\n order_amount = str(myms.fetchone())\n order_id_num = myms.sql_assign_exec(\"SELECT gzseed_vancelle_order.gss_weidian_order.order_id \\\n FROM gzseed_vancelle_order.gss_weidian_order where order_sn ='\" + order_num + \"'\")\n order_id = str(myms.fetchone())\n self.order(order_num)\n myms.sql_assign_exec(\"update gzseed_vancelle_order.gss_packages set notify_time=UNIX_TIMESTAMP(NOW()) \\\n where bill_id in (SELECT order_id from gzseed_vancelle_order.gss_order_info where order_sn='\" + order_num + \"')\")\n r = requests.get(papaandroid.payment)\n # 修改备货中状态���改为已发货\n myms.sql_assign_exec(\"update gzseed_vancelle_order.gss_packages set delivery_time=UNIX_TIMESTAMP(NOW()) , \\\n shipping_status=50 where bill_id in (SELECT order_id from gzseed_vancelle_order.gss_order_info where order_sn='\" \\\n + order_num + \"')\")\n r = requests.get(papaandroid.delivered)\n sleep(3)\n print(r)\n # self.click_button(klmandroid.b_FuKuan)\n # self.assertTrue(self.isElement(By.XPATH,(klmandroid.order_fail)[1]))\n print(\"通过接口付款成功\")\n # self.click_button(klmandroid.order_sure)\n # self.driver.get(klmandroid.rebate)\n # rebate=myms.sql_exec_normal_all(\"select amount FROM gzseed_vancelle_user.gss_weidian_rebates WHERE order_sn='\" \\\n # +order_num+\"'\")[0][0]\n # self.assertTrue(rebate!=0)\n # print '有返利数据,正确'","sub_path":"UIAutoTestCase_papa_rf-master-3a2007d0a93fb0f06581fd16d2e2ba40dd2e3837/UIAutoTestCase_papa_rf-master-3a2007d0a93fb0f06581fd16d2e2ba40dd2e3837/Task/TK_papaandroid.py","file_name":"TK_papaandroid.py","file_ext":"py","file_size_in_byte":8312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"346342503","text":"import os\nfrom time import perf_counter\nfrom functools import wraps\n\nimport requests\nfrom scrapy import Selector\n\n\n\ndef timer(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n start_time = perf_counter()\n result = func(*args, **kwargs)\n end_time = perf_counter()\n cls_name = func.__name__\n fmt = '{cls_name} {args} spend time: {time:.5f}'\n print(fmt.format(cls_name=cls_name, args=args, time=end_time - start_time))\n return result\n return wrapper\n\n\ndef get_content_css(url):\n req = requests.get(url)\n content = req.content.decode('gbk')\n selector = Selector(text=content)\n return selector\n\n\ndef get_page_items(*, start_page_num: int=1, end_page_num: int=5, step: int=1):\n items = []\n for page_num in range(start_page_num, end_page_num, step):\n base_url = 'http://www.meizitu.com/a/{genre}_{page_num}.html'\n selector = get_content_css(base_url.format(genre='cute', page_num=page_num))\n item_urls = list(set(selector.css('#maincontent a::attr(href)').extract()))\n items.extend(url for url in item_urls if url.startswith('http://www.meizitu.com/a/'))\n return items\n\ndef get_images(item):\n selector = get_content_css(item)\n image_urls = list(set(selector.css('#maincontent p img::attr(src)').extract()))\n dir_name = selector.css('#maincontent div.metaRight h2 a::text').extract_first()\n 'ok' if os.path.exists(dir_name) else os.mkdir(dir_name)\n for url in image_urls:\n download_image(dir_name, url)\n\n@timer\ndef download_image(dir_name, image_url):\n headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_0) '\n 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}\n req = requests.get(image_url, headers=headers)\n image = req.content\n filename = image_url.rsplit('/', 1)[-1]\n save_path = os.path.join(dir_name, filename)\n with open(save_path, 'wb') as f:\n f.write(image)\n\n\nif __name__ == \"__main__\":\n start = perf_counter()\n for item in get_page_items():\n get_images(item)\n end = perf_counter()\n print(format('end', '*^100'))\n print('download all images cost time:{:.3f}'.format(end - start))","sub_path":"mytest/tu/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"238010692","text":"from typing import List\nfrom collections import deque\n\n\nclass TreeNode:\n def __init__(self, x, left=None, right=None):\n self.val = x\n self.left = left\n self.right = right\n\n\nclass Solution:\n def levelOrder(self, root: TreeNode) -> List[List[int]]:\n if root is None:\n return []\n\n queue = deque([root, None])\n result = []\n temp = []\n left_to_right = False\n while len(queue) > 0:\n r = queue.popleft()\n if r is None:\n result.append(temp)\n temp = []\n left_to_right = not left_to_right\n if len(queue) > 0:\n queue.append(None)\n else:\n temp.append(r.val)\n self._appendIfNonNone(r.left, queue)\n self._appendIfNonNone(r.right, queue)\n if len(temp) > 0:\n result.append(temp)\n return result\n\n def _appendIfNonNone(self, t, q):\n if t is not None:\n q.append(t)\n\n\nroot = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))\n# root = TreeNode(1, TreeNode(2, TreeNode(4)), TreeNode(3, None, TreeNode(5)))\nsol = Solution()\nresult = sol.zigzagLevelOrder(root)\nprint(result)\n","sub_path":"binary_tree_level_traversal.py","file_name":"binary_tree_level_traversal.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"571781407","text":"import os\n\nfrom webarchive.application import create_app\n\nenvironment_type = os.getenv(\"WEBARCHIVE_ENV_TYPE\", \"production\")\n\nsettings_file = os.getenv(\"WEBARCHIVE_SETTINGS\")\n\nif settings_file is None:\n print(\"The environment variable WEBARCHIVE_SETTINGS is not set\")\n exit(1)\n\napp = create_app(settings_file, environment_type)\n","sub_path":"wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"361066967","text":"\"\"\"Pastoral URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom .views import tres, seis, registrar_usuario, index2, listar_usuarios, privacidad, usabilidad, eliminar\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.views.generic import RedirectView\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('index2/', index2, name=\"inicio\"),\n path('accounts/', include('django.contrib.auth.urls')),\n path('tres/', tres),\n path('seis/',seis),\n path('oauth/', include('social_django.urls', namespace='social')),\n path('accounts/', include('allauth.urls')),\n path('registro/', registrar_usuario, name=\"registrar\"),\n path('listar_usuarios/', listar_usuarios, name=\"listar\"),\n path('', index2),\n path('privacidad/', privacidad),\n path('usabilidad/', usabilidad),\n path('eliminar/', eliminar),\n\n] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n","sub_path":"Pastoral/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"572668903","text":"'''Module 'main_test' : Fonctions utilitaires pour les tests réalisés\ndans le shell directement depuis les scripts. Celles-ci incluent :\n- Lecture de fichiers de grilles\n- Initialisation de grilles\n- Initialisation d'interface GUI\nGrâce à ces fonctions la \"plate-forme\" de test est rapidement prête. Il ne\nreste plus qu'à écrire le code de test spécifique à chaque module.\n'''\n\nfrom sudosimu.sudogame import *\nfrom sudosimu import sudotestall\nfrom sudosimu.sudogrid import SudoGrid\n\nfrom test_modules import *\n\n#interface\ntestlev(0)\ntestMakeUI()\n#données de jeu\ngrid = None\ngridInit = None\nmem = None\nthink = None\nview = None\ngame = None\nparams = None\n#fonctions de jeu\ndef newGrid():\n '''Demande à l'utilisateur (console) de choisir une nouvelle grille, puis\n initialise une partie avec cette grille.\n '''\n global gridInit\n gridInit = testNewGrid()\n return newGame()\ndef resetGrid():\n '''Prépare ou réinitialise la grille de jeu comme copie de la grille\n choisie. ResetGrid() est utilisée quand une nouvelle grille est chargée,\n ainsi que quand une nouvelle partie est initialisée pour la même grille.\n '''\n global grid\n global gridInit\n if not isinstance(gridInit, SudoGrid):\n print(\"Erreur, il n'y a pas de grille chargée.\")\n return False\n grid = gridInit.copy()\n testShowGrid(grid)\n return True\ndef newGame():\n '''Initialise une nouvelle partie sur la grille déjà chargée.'''\n global grid\n global mem\n global think\n global view\n global game\n if not resetGrid():\n return False\n mem = SudoMemory()\n think = SudoThinking(mem)\n view = SudoGridView(grid)\n game = SudoGame(mem, think, view)\n return True\ndef play(newParams=None):\n global params\n if newParams is None:\n r = game.play(params)\n else:\n r = game.play(newParams)\n return r\ndef resume():\n return game.resume()\ndef again():\n return game.again()\ndef step():\n return game.step()\ndef observe():\n return game.observe()\ndef place():\n return game.place()\n\n#Initialisation des tests et de la partie\nTEST.level(\"main\", 1)\nTEST.display(\"main\", 1, \"\\nTest du module sudogame\")\nTEST.display(\"main\", 1, \"----------------------------\\n\")\nnewGrid()\nui.display(\"Création et initialisation de la partie\")\nnewGame()\n#Niveaux de commentaires pour la partie\nTEST.level(\"thinkai\", 1)\n\n#Paramètres de la partie\nparams = None\n#jeu\nTEST.display(\"main\", 1, \"Prêt à jouer.\")\nprint(\"\\n...>>> game.play(params) \\nou >>> go()\")\n\n#ui.sudoPause()\n#go()\n \n\n\n## #TEST \n## import sudotestall\n## from sudogrid import SudoGrid, SudoBloc\n## testlevel = 3\n## TEST.levelAll(testlevel)\n## ui.display(\"Tous les niveaux de test sont à {0}\".format(testlevel))\n##\n## #mode GUI\n## ui.UImode(ui.GUI)\n## TEST.displayUImode(MODE_BOTH, 1)\n##\n## TEST.display(\"main\", 1, \"\\nCréation de la grille.\")\n## grid = SudoGrid()\n## gridInit = SudoGrid()\n## newGrid()\n## ui.displayGridAll(grid)\n##\n## TEST.display(\"main\", 1, \"\\nCréation de la partie.\")\n## mem = None\n## think = None\n## view = None\n## game = None\n## gameParam = (mem, think, view, game)\n## #newGame(grid)\n## (mem, think, view, game) = newGame(grid)\n## \n## TEST.display(\"main\", 1, \"Ok prêt à jouer\")\n##\n## TEST.levelAll(0)\n## TEST.level(\"thinkai\", 1)\n### TEST.level(\"game\", 1)\n## \n\n","sub_path":"test_sudogame.py","file_name":"test_sudogame.py","file_ext":"py","file_size_in_byte":3412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"293358532","text":"#take commits from all_commits by year, along with new_event_features and updated_labels, and create time-sorted commits with new adopted_libs field and commit_id\n\n#save the same augmented commits to user_commits, chunked by user id\n\nimport json\nimport os.path\nfrom collections import defaultdict\nimport pickle\nfrom datetime import datetime\n\n#stream json data one object at a time (generator function)\ndef stream(f):\n\tobj_str = ''\n\tf.read(1) \t#eat first [\n\twhile True:\n\t\tc = f.read(1)\t#read one character at a time\n\t\t#end of file, quit\n\t\tif not c:\n\t\t\t#print('EOF')\n\t\t\tbreak\n\t\t#skip newline characters\n\t\tif c == '\\n':\n\t\t\tcontinue\n\t\t#remove backslashes\n\t\tif c == '\\'':\n\t\t\tc = '\"'\n\t\tobj_str = obj_str + c\t#add character to current object string\n\t\t#when reach end of object, parse json and return resulting object\n\t\tif c == '}':\n\t\t\tobj_str = obj_str.replace('u\"', '\"')\t#remove all unicode prefixes\n\t\t\tyield json.loads(obj_str)\t\t#return json object\n\t\t\tobj_str = ''\t#clear for next read\n\t\t\tc = f.read(1) \t#eat comma between objects\n#end stream\n\n#given a filepath, load pickled data\ndef load_pickle(filename):\n\twith open(filename, \"rb\") as f:\n\t\tdata = pickle.load(f)\n\treturn data\n#end load_pickle\n\n#dump all currently cached data (for a single month) to file\ndef dump_month_commit_list(data, name):\n\t#save commits_list to file\n\tpik = (\"data_files/augmented_commits/%s_commits.pkl\" % name)\n\twith open(pik, \"wb\") as f:\n\t\tpickle.dump(data, f)\n#end dump_list\n\n#dump all currently cached data (for a single user_chunk) to file\ndef dump_user_chunk_dict(chunk, name):\n\t#save dictionary chunk to file\n\tpik = (\"data_files/user_commits/%s_commits.pkl\" % name)\n\twith open(pik, \"wb\") as f:\n\t\tpickle.dump(chunk, f)\n\n\tprint (\"saved %s users for %s user-ids\" % (len(chunk), name))\n#end dump_dict\n\n#return pre-computed feature vector one at a time (generator function)\ndef next_feature(year, month):\n\tevents = load_pickle(\"data_files/new_event_features/%s/%s_events.pkl\" % (year, month))\n\tfor event in events:\n\t\tyield event\n#end next_feature\n\n#return pre-computed event labels one at a time (generator function)\ndef next_label(year, month):\n\tlabels = load_pickle(\"data_files/new_event_features/%s/%s_updated_labels.pkl\" % (year, month))\n\tfor label in labels:\n\t\tyield label\n#end next_label\n\n\n#--- MAIN EXECUTION BEGINS HERE---#\n\nif __name__ == \"__main__\":\n\t\n\tdata_month = -1\n\tdata_year = -1\n\tevent = [-1]\n\tevent_label = -1\n\n\t#list of augmented commits, where each commit is a dictionary\n\tnew_commits = []\n\n\t#dictionary of dictionary of commits by user\n\t#first key: user id / 1000\n\t#second key: user id\n\t#value: list of commits by this user, in time-sorted order\n\tby_user = defaultdict(lambda: defaultdict(list))\n\n\t#make sure directories for files exist\n\tif os.path.isdir(\"data_files/user_commits\") == False:\n\t\tos.makedirs(\"data_files/user_commits\")\n\tif os.path.isdir(\"data_files/augmented_commits\") == False:\n\t\tos.makedirs(\"data_files/augmented_commits\")\n\n\tcommit_count = 0\n\n\t#stream data from sorted json files\n\tfor year in range(1990, 2019):\t\t#read and process 1993 through 2018\n\n\t\tprint(\"Streaming\", year)\n\n\t\t#stream from current year's commit output file (commits only, no features/labels)\n\t\tf = open('data_files/all_commits_by_year/%s_commits_SUB_sorted.json' % year)\n\t\tcommits = stream(f)\n\n\t\t#process all commits in date order\t\t\n\t\tfor c in commits:\n\n\t\t\tdate = datetime.fromtimestamp(c['time'])\t\t#grab date of current commit\n\n\t\t\t#is this commit from a different month than the current feature data? if so, new feature file stream\n\t\t\tif date.month != data_month or date.year != data_year:\n\t\t\t\tprint(\" moving to\", str(date.month)+\"-\"+str(date.year))\n\n\t\t\t\t#dump this month's data (if actually data) to augmented_commits\n\t\t\t\tif data_month != -1:\n\t\t\t\t\t#gen correct filename (date) for this month of data\n\t\t\t\t\tfilename = \"%s-%s\" % (data_year, str(data_month) if len(str(data_month)) == 2 else \"0\" + str(data_month))\n\t\t\t\t\tdump_month_commit_list(new_commits, filename)\n\n\t\t\t\t#reset month commit list and date tracking\n\t\t\t\tnew_commits = []\n\t\t\t\tdata_month = date.month\n\t\t\t\tdata_year = date.year\n\t\t\t\t#init new generators for new month: features and labels\n\t\t\t\tevents = next_feature(data_year, data_month)\t\n\t\t\t\tevent_labels = next_label(data_year, data_month)\n\n\t\t\t#short circuit the processing: if hit March 2018, quit - since we don't want those\n\t\t\tif date.month == 3 and date.year == 2018:\n\t\t\t\tprint(\" Reached March 2018, all done\")\n\t\t\t\tbreak\n\n\t\t\t#remove duplicate libraries from lists by converting them to sets\n\t\t\tadded_libs = set(c['add_libs'])\n\t\t\tdeleted_libs = set(c['del_libs'])\n\n\t\t\t#change added/deleted_libs so that \"moved libs\" i.e., libs that are added and deleted in the same commit are not considered for adoptions\n\t\t\tadded_and_deleted = added_libs.intersection(deleted_libs)\n\t\t\tdeleted_libs = [item for item in deleted_libs if item not in added_and_deleted]\n\t\t\tadded_libs = [item for item in added_libs if item not in added_and_deleted]\n\n\t\t\t#update commit added/deleted libs fields\n\t\t\tc['add_libs'] = added_libs\n\t\t\tc['del_libs'] = deleted_libs\n\n\t\t\t#build list of adopted libraries from this commit\n\n\t\t\t#first, skip any event features/labels that are not part of this commit\n\t\t\twhile commit_count > event[0]:\t\t\t#event[0] = commit id\n\t\t\t\ttry:\n\t\t\t\t\tevent = next(events)\n\t\t\t\t\tevent_label = next(event_labels)\n\t\t\t\texcept StopIteration:\n\t\t\t\t\t#finished the current month, but no match for this commit - must be empty event\n\t\t\t\t\tevent = [-1]\n\t\t\t\t\tevent_label = -1\t\n\t\t\t\t\tbreak\n\n\t\t\t#match up event features/labels to build list of adopted libraries\n\t\t\tadopted = []\n\t\t\twhile commit_count == event[0]:\t\t\t#loop as long as commits match\t\n\t\t\t\t#if event is adoption, add library/package name to list of adopted libraries\n\t\t\t\tif event_label == 1:\t\n\t\t\t\t\tadopted.append(event[19])\n\t\t\t\t#if event flagged as added library but package not in commit added libs, or user ids \n\t\t\t\t#don't match, or repo names don't match, something has gone wrong - quit\n\t\t\t\tif (event[20] == 1 and event[19] not in c['add_libs']) or event[1] != c['user'] or event[2] != c['repo']:\n\t\t\t\t\tprint(\"FAIL\")\n\t\t\t\t\tprint(commit_count, c)\n\t\t\t\t\tprint(event, event_label)\n\t\t\t\t\texit(0)\n\t\t\t\t\t\n\t\t\t\t#get next event/label pair to continue loop\n\t\t\t\ttry:\n\t\t\t\t\tevent = next(events)\n\t\t\t\t\tevent_label = next(event_labels)\n\t\t\t\texcept StopIteration:\n\t\t\t\t\t#finished the current month, stop\n\t\t\t\t\tevent = [-1]\n\t\t\t\t\tevent_label = -1\n\n\t\t\t#grab user from commit\n\t\t\tif c['user'] == '':\n\t\t\t\tuser = 0\n\t\t\telse:\n\t\t\t\tuser = int(c['user'])\n\n\t\t\t#get user id / 1000 (integer divide)\n\t\t\tmod = user // 1000\n\n\t\t\t#add list of adopted libs and commit id to commit before saving\n\t\t\tc['adopted_libs'] = adopted\n\t\t\tc['id'] = commit_count\n\n\t\t\t#add this commit to month list\n\t\t\tnew_commits.append(c)\n\n\t\t\t#add this commit to user's list\n\t\t\tby_user[mod][user].append(c)\n\n\t\t\tcommit_count += 1\n\t\t\t\n\t\tf.close()\n\n\tprint(\"\\nProcessed\", commit_count, \"commits\")\n\n\t#finished processing, save each \"chunk\" (defined by /1000 key) as a separate pickle\n\tfor key in by_user:\n\t\tdump_user_chunk_dict(by_user[key], key)\n\n\tprint(\"Updated commits saved to data_files/augmented_commits and data_files/user_commits\")\n","sub_path":"augment_and_divide_commits.py","file_name":"augment_and_divide_commits.py","file_ext":"py","file_size_in_byte":7089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"366298480","text":"from female import Mother\nfrom human import Human\nfrom male import Father\n\n\nclass Child(Human):\n\n def __init__(self, name, age, father, mother):\n Human.__init__(self, name, age)\n if isinstance(father, Father):\n self.father = father\n else:\n raise ValueError('Father must be of a type Father')\n if isinstance(mother, Mother):\n self.mother = mother\n else:\n raise ValueError('Mother must be of a type Mother')\n\n def __str__(self):\n return f'{Human.__str__(self)}, Father: {self.father.name}, Mother: {self.mother.name}'\n","sub_path":"sessions/20/pavel_shchegolevatykh/child.py","file_name":"child.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"296132605","text":"def layout(request):\n\treturn render(request, 'layout.html')\n\ndef products(request):\n products = Product.find_all()\n brands = Brand.find_all()\n categories = Category.find_all()\n featured = Collection.find_by_name(\"featured\")\n cart = ShoppingCart.get()\n return render(request, \"shop/products.html\", {\"brands\": brands, \"categories\": categories, \"products\": products,\n \"featured\": featured, \"cart\": cart})\n","sub_path":"layout/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"599331860","text":"## STAGE FOUR : Contract REGISTRATION\n\"\"\"\nTesting:\nneo> build varimi/smartFarmContracts.py test 0710 05 True False query [\"Name\"]\nneo> build varimi/smartFarmContracts.py test 0710 05 True False register [\"Name\",\"AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y\"]\nneo> build varimi/smartFarmContracts.py test 0710 05 True False delete [\"Name\"]\nneo> build varimi/smartFarmContracts.py test 0710 05 True False transfer [\"Name\",\"AK2nJJpJr6o664CWJKi1QRXjqeic\"]\nImporting:\nneo> import contract varimi/smartFarmContracts.avm 0710 05 True False\nimport contract varimi/smartFarmContracts.avm 0710 05 True False\nneo> contract search ...\nUsing:\nneo> testinvoke c4e31aa5d66d7c9e8a4afa3a92be7e8a3ca49f76 query [\"name\"]\ned72a3d1e35420a8208f3f32e8e2815370ed1ed3\n\nExamples\n\n\ntestinvoke 0x76c40b9b03316acaad4b0acd02dd67981785e749 RegisterFarmer [\"Name\",\"AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y\"]\ntestinvoke 0x76c40b9b03316acaad4b0acd02dd67981785e749 QueryFarmer [\"Name\"]\n\n\"\"\"\nfrom boa.interop.Neo.Runtime import Log, Notify, GetTrigger, CheckWitness\nfrom boa.interop.Neo.Action import RegisterAction\n\nfrom boa.interop.Neo.TransactionType import InvocationTransaction\nfrom boa.interop.Neo.Transaction import *\n\nfrom boa.interop.System.ExecutionEngine import InvocationTransaction\nfrom boa.interop.Neo.TriggerType import Application, Verification\nfrom boa.interop.Neo.Output import GetScriptHash, GetValue, GetAssetId\nfrom boa.interop.Neo.Storage import Get, Put,Delete, GetContext\n\nfrom boa.builtins import concat\n\n\ndef Main(operation, args):\n nargs = len(args)\n if nargs == 0:\n print(\"No Farmer name supplied\")\n return 0\n ##Contract \n elif operation == 'QueryContract':\n Contract_name = args[0]\n return QueryContract(Contract_name)\n\n elif operation == 'DeleteContract':\n Contract_name = args[0]\n return DeleteContract(Contract_name)\n\n elif operation == 'RegisterContract':\n if nargs < 2:\n print(\"required arguments: [Contract_name] [owner]\")\n return 0\n Contract_name = args[0]\n owner = args[1]\n return RegisterContract(Contract_name, owner)\n \n## STAGE FOUR : Contract REGISTRATION : PYTHON CODE COMPLETE \n## THIS CODE IS TO REGISTER A DIRECT Contract ON THE BLOCKCHAIN WITH ABILITY TO ADD/DELETE/QUERY \ndef QueryContract(Contract_name):\n msg = concat(\"QueryContract: \", Contract_name)\n Notify(msg)\n\n context = GetContext()\n owner = Get(context, Contract_name)\n if not owner:\n Notify(\"This Contract is not yet registered\")\n return False\n\n Notify(owner)\n return owner\n\ndef RegisterContract(Contract_name, owner):\n msg = concat(\"RegisterContract: \", Contract_name)\n Notify(msg)\n\n if not CheckWitness(owner):\n Notify(\"Owner argument is not the same as the person who registered\")\n return False\n\n context = GetContext()\n exists = Get(context, Contract_name)\n if exists:\n Notify(\"Contract is already registered\")\n return False\n\n Put(context, Contract_name, owner)\n return True\n\ndef DeleteContract(Contract_name):\n msg = concat(\"DeleteContract: \", Contract_name)\n Notify(msg)\n\n context = GetContext()\n owner = Get(context, Contract_name)\n if not owner:\n Notify(\"Contract is not yet registered\")\n return False\n\n if not CheckWitness(owner):\n Notify(\"This person is not the owner of the contract, the Contract cannot be deleted\")\n return False\n\n Delete(context, Contract_name)\n return True\n","sub_path":"python/v2/bsfc/farmContractRegistry.py","file_name":"farmContractRegistry.py","file_ext":"py","file_size_in_byte":3503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"221840874","text":"from __future__ import print_function\nimport time\nimport boto3\nimport urllib.request\nimport json\n\ndemo_name = 'speech-to-text-classified'\nbucket_name = 'sgfdevs-demo-2018'\n\ns3 = boto3.client('s3')\nfilename = demo_name+'.wav'\ns3.upload_file(filename, bucket_name, filename, ExtraArgs={'ACL':'public-read'})\n\ntranscribe = boto3.client('transcribe')\njob_name = demo_name+'-'+str(time.time())\njob_uri = \"https://s3.amazonaws.com/\"+bucket_name+\"/\"+filename\ntranscribe.start_transcription_job(\n TranscriptionJobName=job_name,\n Media={'MediaFileUri': job_uri},\n MediaFormat='wav',\n LanguageCode='en-US',\n Settings={'MaxSpeakerLabels': 2, 'ShowSpeakerLabels': True}\n)\nwhile True:\n status = transcribe.get_transcription_job(TranscriptionJobName=job_name)\n if status['TranscriptionJob']['TranscriptionJobStatus'] in ['COMPLETED', 'FAILED']:\n break\n print(\"Not ready yet...\")\n time.sleep(5)\n#print(status)\n\ntranscript_url = status['TranscriptionJob']['Transcript']['TranscriptFileUri']\n#print(transcript_url)\n\n# Download Transcription Results to JSON File\ntranscript_file = demo_name+'.json'\nurllib.request.urlretrieve(transcript_url, transcript_file)\n\nwith open(transcript_file, 'r') as transcript_file:\n transcript_json=transcript_file.read().replace('\\n', '')\n\n# Display Transcription\ntranscript_data = json.loads(transcript_json)\ntranscript_text = transcript_data['results']['transcripts'][0]['transcript']\nprint(transcript_text)\n\n# NOTE: This was a failed attempt to identify two separate speakers in dialog.\n","sub_path":"05-speech-to-text/speech-to-text-classified.py","file_name":"speech-to-text-classified.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"253213215","text":"import textwrap\n\nimport tsrc.config\n\n\ndef test_read_config(tmp_path):\n tsrc_yml_path = tmp_path.joinpath(\"tsrc.yml\")\n tsrc_yml_path.write_text(\n textwrap.dedent(\n \"\"\"\\\n auth:\n gitlab:\n token: MY_SECRET_TOKEN\n \"\"\")\n )\n config = tsrc.config.read(config_path=tsrc_yml_path)\n assert config[\"auth\"][\"gitlab\"][\"token\"] == \"MY_SECRET_TOKEN\"\n","sub_path":"tsrc/test/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"632799758","text":"import math\nri, k, N = [3.2, 3.8, 1.2, 4, 2.8], 5, 5\nalpha, F_test_threshold = 0.05, 3.007\nq_alpha = 2.728 # for Nemenyi Test\n\ntau_chi_square = 0\nfor i in ri:\n tau_chi_square += i * i\ntau_chi_square = 12 * N / k / (k + 1) * (tau_chi_square - k * (k + 1) * (k + 1) / 4)\n\ntau_F = (N - 1) * tau_chi_square / (N * (k - 1) - tau_chi_square)\nprint(\"\\\\tau_F = {}\".format(tau_F))\n\nassert k == 5 and N == 5 and alpha == 0.05\n\nif tau_F <= F_test_threshold:\n print(\"Above algorithms have the same performance (fail to reject H0)\")\nelse:\n print(\"Above algorithms have different performance (reject H0)\")\n print(\"Continue to Nemenyi Test..\")\n CD = q_alpha * math.sqrt(k * (k + 1) / 6 / N)\n\n diffTrue, diffFalse = [], []\n maxRiIndex = ri.index(max(ri))\n print(\"The best performing algorithms is {}, whose r_i = {}\".format(maxRiIndex + 1, ri[maxRiIndex]))\n for i in range(len(ri)):\n if i != maxRiIndex:\n if abs(ri[i] - ri[maxRiIndex]) <= CD:\n diffTrue.append(i + 1)\n else:\n diffFalse.append(i + 1)\n\n print(\"The best performing algorithms differ significantly from the following: \")\n print(diffTrue)\n print(\"The best performing algorithms are not significantly different from the following: \")\n print(diffFalse)\n print(\"The index starts at one\")","sub_path":"机器学习_Machine Learning_NJUCS_2020spring_homework/1/Problem_4.py","file_name":"Problem_4.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"27824506","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom sklearn.base import RegressorMixin, BaseEstimator\nfrom sklearn.linear_model.base import LinearModel, LinearClassifierMixin\nfrom sklearn.utils import check_X_y,check_array\nfrom sklearn.utils.multiclass import check_classification_targets\nfrom sklearn.utils.extmath import pinvh,log_logistic\nfrom sklearn.metrics.pairwise import pairwise_kernels\nfrom sklearn.utils.validation import check_is_fitted\nfrom scipy.special import expit\nfrom scipy.optimize import fmin_l_bfgs_b\nfrom scipy.linalg import solve_triangular\nfrom scipy.stats import logistic\nfrom sklearn.utils.optimize import newton_cg\nimport scipy.sparse\nimport warnings\n\n\ndef update_precisions(Q,S,q,s,A,active,tol, clf_bias = True):\n '''\n Selects one feature to be added/recomputed/deleted to model based on \n effect it will have on value of log marginal likelihood.\n '''\n # initialise vector holding changes in log marginal likelihood\n deltaL = np.zeros(Q.shape[0])\n \n # identify features that can be added , recomputed and deleted in model\n theta = q**2 - s \n add = (theta > 0) * (active == False)\n recompute = (theta > 0) * (active == True)\n delete = ~(add + recompute)\n \n # compute sparsity & quality parameters corresponding to features in \n # three groups identified above\n Qadd,Sadd = Q[add], S[add]\n Qrec,Srec,Arec = Q[recompute], S[recompute], A[recompute]\n Qdel,Sdel,Adel = Q[delete], S[delete], A[delete]\n \n # compute new alpha's (precision parameters) for features that are \n # currently in model and will be recomputed\n Anew = s[recompute]**2/theta[recompute]\n delta_alpha = (1./Anew - 1./Arec)\n \n # compute change in log marginal likelihood \n deltaL[add] = ( Qadd**2 - Sadd ) / Sadd + np.log(Sadd/Qadd**2 )\n deltaL[recompute] = Qrec**2 / (Srec + 1. / delta_alpha) - np.log(1 + Srec*delta_alpha)\n deltaL[delete] = Qdel**2 / (Sdel - Adel) - np.log(1 - Sdel / Adel)\n \n \n # find feature which caused largest change in likelihood\n feature_index = np.argmax(deltaL)\n \n # no deletions or additions\n same_features = np.sum( theta[~recompute] > 0) == 0\n \n # changes in precision for features already in model is below threshold\n no_delta = np.sum( abs( Anew - Arec ) > tol ) == 0\n \n # check convergence: if features to add or delete and small change in \n # precision for current features then terminate\n converged = False\n if same_features and no_delta:\n converged = True\n return [A,converged]\n \n # if not converged update precision parameter of weights and return\n if theta[feature_index] > 0:\n A[feature_index] = s[feature_index]**2 / theta[feature_index]\n if active[feature_index] == False:\n active[feature_index] = True\n else:\n if not clf_bias:\n active_min = 1\n else:\n active_min = 2\n if active[feature_index] == True and np.sum(active) > active_min:\n active[feature_index] = False\n A[feature_index] = np.PINF\n return [A,converged]\n\n\n###############################################################################\n# ARD REGRESSION AND CLASSIFICATION\n###############################################################################\n\n\n#-------------------------- Regression ARD ------------------------------------\n\n\nclass RegressionARD(LinearModel,RegressorMixin):\n '''\n Regression with Automatic Relevance Determination. \n \n \n Parameters\n ----------\n n_iter: int, optional (DEFAULT = 100)\n Maximum number of iterations\n \n tol: float, optional (DEFAULT = 1e-3)\n If absolute change in precision parameter for weights is below threshold\n algorithm terminates.\n \n perfect_fit_tol: float, optional (DEFAULT = 1e-4)\n Algortihm terminates in case MSE on training set is below perfect_fit_tol.\n Helps to prevent overflow of precision parameter for noise in case of\n nearly perfect fit.\n\n fit_intercept : boolean, optional (DEFAULT = True)\n whether to calculate the intercept for this model. If set\n to false, no intercept will be used in calculations\n (e.g. data is expected to be already centered).\n \n normalize : boolean, optional (DEFAULT = False)\n If True, the regressors X will be normalized before regression\n \n copy_X : boolean, optional (DEFAULT = True)\n If True, X will be copied; else, it may be overwritten.\n \n verbose : boolean, optional (DEFAULT = True)\n Verbose mode when fitting the model\n \n \n Attributes\n ----------\n coef_ : array, shape = (n_features)\n Coefficients of the regression model (mean of posterior distribution)\n \n alpha_ : float\n estimated precision of the noise\n \n active_ : array, dtype = np.bool, shape = (n_features)\n True for non-zero coefficients, False otherwise\n \n lambda_ : array, shape = (n_features)\n estimated precisions of the coefficients\n \n sigma_ : array, shape = (n_features, n_features)\n estimated covariance matrix of the weights, computed only\n for non-zero coefficients \n\n\n Examples\n --------\n >>> clf = RegressionARD()\n >>> clf.fit([[0,0], [1, 1], [2, 2]], [0, 1, 2])\n ... # doctest: +NORMALIZE_WHITESPACE\n RegressionARD(compute_score=False, copy_X=True, fit_intercept=True, n_iter=100,\n normalize=False, perfect_fit_tol=0.001, verbose=False)\n >>> clf.predict([[1, 1]])\n array([ 1.])\n \n '''\n \n def __init__( self, n_iter = 300, tol = 1e-1, perfect_fit_tol = 1e-3, \n fit_intercept = True, normalize = False, copy_X = True,\n verbose = False):\n self.n_iter = n_iter\n self.tol = tol\n self.perfect_fit_tol = perfect_fit_tol\n self.scores_ = list()\n self.fit_intercept = fit_intercept\n self.normalize = normalize\n self.copy_X = copy_X\n self.verbose = verbose\n \n \n def fit(self,X,y):\n '''\n Fits ARD Regression with Sequential Sparse Bayes Algorithm.\n \n Parameters\n -----------\n X: {array-like, sparse matrix} of size [n_samples, n_features]\n Training data, matrix of explanatory variables\n \n y: array-like of size [n_samples, n_features] \n Target values\n \n Returns\n -------\n self : object\n Returns self.\n '''\n X, y = check_X_y(X, y, dtype=np.float64, y_numeric=True)\n n_samples, n_features = X.shape\n\n \n X, y, X_mean, y_mean, X_std = self._center_data(X, y, self.fit_intercept,\n self.normalize, self.copy_X)\n self._x_mean_ = X_mean\n self._y_mean = y_mean\n self._x_std = X_std\n\n # precompute X'*Y , X'*X for faster iterations & allocate memory for\n # sparsity & quality vectors\n XY = np.dot(X.T,y)\n XX = np.dot(X.T,X)\n XXd = np.diag(XX)\n\n # initialise precision of noise & and coefficients\n var_y = np.var(y)\n # check that variance is non zero !!!\n if var_y == 0 :\n beta = 1e-2\n else:\n beta = 1. / np.var(y)\n \n A = np.PINF * np.ones(n_features)\n active = np.zeros(n_features , dtype = np.bool)\n \n # in case of perfect multicollinearity start from first feature\n if np.sum(XXd==0) > 0:\n A[0] = 1e-3\n active[0] = True\n else:\n # start from a single basis vector with largest projection on targets\n proj = XY**2 / XXd\n start = np.argmax(proj)\n active[start] = True\n A[start] = XXd[start]/( proj[start] - var_y)\n\n\n for i in range(self.n_iter):\n \n XXa = XX[active,:][:,active]\n XYa = XY[active]\n Aa = A[active]\n \n # mean & covariance of posterior distribution\n Mn,Ri = self._posterior_dist(Aa,beta,XXa,XYa)\n Sdiag = np.sum(Ri**2,0)\n \n # compute quality & sparsity parameters \n s,q,S,Q = self._sparsity_quality(XX,XXd,XY,XYa,Aa,Ri,active,beta)\n \n # update precision parameter for noise distribution\n rss = np.sum( ( y - np.dot(X[:,active] , Mn) )**2 )\n # if near perfect fit , them terminate\n if rss / n_samples < self.perfect_fit_tol:\n warnings.warn('Early termination due to near perfect fit')\n break\n beta = n_samples - np.sum(active) + np.sum(Aa * Sdiag )\n beta /= rss\n\n # update precision parameters of coefficients\n A,converged = update_precisions(Q,S,q,s,A,active,self.tol,True)\n \n if self.verbose:\n print(('Iteration: {0}, number of features '\n 'in the model: {1}').format(i,np.sum(active)))\n \n if converged or i == self.n_iter - 1:\n if converged and self.verbose:\n print('Algorithm converged !')\n break\n \n # after last update of alpha & beta update parameters\n # of posterior distribution\n XXa,XYa,Aa = XX[active,:][:,active],XY[active],A[active]\n Mn, Sn = self._posterior_dist(Aa,beta,XXa,XYa,True)\n self.coef_ = np.zeros(n_features)\n self.coef_[active] = Mn\n self.sigma_ = Sn\n self.active_ = active\n self.lambda_ = A\n self.alpha_ = beta\n self._set_intercept(X_mean,y_mean,X_std)\n return self\n \n \n def predict_dist(self,X):\n '''\n Computes predictive distribution for test set.\n Predictive distribution for each data point is one dimensional\n Gaussian and therefore is characterised by mean and standard\n deviation.\n \n Parameters\n -----------\n X: {array-like, sparse} [n_samples_test, n_features]\n Test data, matrix of explanatory variables\n \n Returns\n -------\n y_hat: numpy array of size [n_samples_test]\n Estimated values of targets on test set (Mean of predictive distribution)\n \n std_hat: numpy array of size [n_samples_test]\n Error bounds (Standard deviation of predictive distribution)\n '''\n x = (X - self._x_mean_) / self._x_std\n y_hat = np.dot(x,self.coef_) + self._y_mean \n var_hat = self.alpha_\n var_hat += np.sum( np.dot(x[:,self.active_],self.sigma_) * x[:,self.active_], axis = 1)\n std_hat = np.sqrt(var_hat)\n return y_hat, std_hat\n\n\n def _posterior_dist(self,A,beta,XX,XY,full_covar = False):\n '''\n Calculates mean and covariance matrix of posterior distribution\n of coefficients.\n '''\n # precision matrix \n Sinv = beta * XX\n np.fill_diagonal(Sinv, np.diag(Sinv) + A)\n R = np.linalg.cholesky(Sinv)\n Z = solve_triangular(R,beta*XY, check_finite = False, lower = True)\n Mn = solve_triangular(R.T,Z,check_finite = False, lower = False)\n Ri = solve_triangular(R,np.eye(A.shape[0]), check_finite = False, lower = True)\n if full_covar:\n Sn = np.dot(Ri.T,Ri)\n return Mn,Sn\n else:\n return Mn,Ri\n \n \n def _sparsity_quality(self,XX,XXd,XY,XYa,Aa,Ri,active,beta):\n '''\n Calculates sparsity and quality parameters for each feature\n \n Theoretical Note:\n -----------------\n Here we used Woodbury Identity for inverting covariance matrix\n of target distribution \n C = 1/beta + 1/alpha * X' * X\n C^-1 = beta - beta^2 * X' * Sn * X\n '''\n bxy = beta*XY\n bxx = beta*XXd\n xr = np.dot(XX[:,active],Ri.T)\n S = bxx - beta**2 * np.sum( xr**2, axis=1)\n Q = bxy - beta**2 * np.dot( xr, np.dot(Ri,XYa))\n qi = np.copy(Q)\n si = np.copy(S) \n Qa,Sa = Q[active], S[active]\n qi[active] = Aa * Qa / (Aa - Sa )\n si[active] = Aa * Sa / (Aa - Sa )\n return [si,qi,S,Q]\n \n \n#----------------------- Classification ARD -----------------------------------\n \n \ndef _logistic_cost_grad(X,Y,w,diagA, penalise_intercept):\n '''\n Calculates cost and gradient for logistic regression\n '''\n n = X.shape[0]\n Xw = np.dot(X,w)\n s = expit(Xw)\n wdA = w*diagA\n if not penalise_intercept:\n wdA[0] = 0\n cost = np.sum( -Xw*Y - log_logistic(-Xw)) + np.sum(w*wdA)/2 \n grad = np.dot(X.T, s - Y) + wdA\n return [cost/n,grad/n]\n \n\n# TODO: cost, grad , hessian function for Newton CG\ndef _logistic_cost_grad_hess(X,Y,w,diagA):\n '''\n Calculates cost, gradient and hessian for logistic regression\n '''\n raise NotImplementedError('to be done')\n\n \n \n \nclass ClassificationARD(BaseEstimator,LinearClassifierMixin):\n '''\n Logistic Regression with Automatic Relevance determination\n \n Parameters\n ----------\n n_iter: int, optional (DEFAULT = 100)\n Maximum number of iterations before termination\n \n tol: float, optional (DEFAULT = 1e-3)\n If absolute change in precision parameter for weights is below threshold\n algorithm terminates.\n \n solver: str, optional (DEFAULT = 'lbfgs_b')\n Optimization method that is used for finding parameters of posterior\n distribution ['lbfgs_b','newton_cg']\n \n n_iter_solver: int, optional (DEFAULT = 20)\n Maximum number of iterations before termination of solver\n \n tol_solver: float, optional (DEFAULT = 1e-5)\n Convergence threshold for solver (it is used in estimating posterior\n distribution), \n\n fit_intercept : bool, optional ( DEFAULT = True )\n If True will use intercept in the model. If set\n to false, no intercept will be used in calculations\n \n penalise_intercept: bool, optional ( DEFAULT = False)\n If True uses prior distribution on bias term (penalises intercept)\n \n normalize : boolean, optional (DEFAULT = False)\n If True, the regressors X will be normalized before regression\n \n verbose : boolean, optional (DEFAULT = True)\n Verbose mode when fitting the model\n \n \n Attributes\n ----------\n coef_ : array, shape = (n_features)\n Coefficients of the regression model (mean of posterior distribution)\n \n lambda_ : float\n estimated precisions of weights\n \n active_ : array, dtype = np.bool, shape = (n_features)\n True for non-zero coefficients, False otherwise\n\n sigma_ : array, shape = (n_features, n_features)\n estimated covariance matrix of the weights, computed only\n for non-zero coefficients\n\n '''\n def __init__(self, n_iter = 100, tol = 1e-4, solver = 'lbfgs_b', \n n_iter_solver = 15, tol_solver = 1e-4, fit_intercept = True,\n penalise_intercept = False, normalize = False, verbose = False):\n self.n_iter = n_iter\n self.tol = tol\n self.solver = solver\n self.n_iter_solver = n_iter_solver\n self.tol_solver = tol_solver\n self.fit_intercept = fit_intercept\n self.penalise_intercept = penalise_intercept\n self.normalize = normalize\n self.verbose = verbose\n \n \n def fit(self,X,y):\n '''\n Fits Logistic Regression with ARD\n \n Parameters\n ----------\n X: array-like of size [n_samples, n_features]\n Training data, matrix of explanatory variables\n \n y: array-like of size [n_samples] \n Target values\n \n Returns\n -------\n self : object\n Returns self.\n '''\n X, y = check_X_y(X, y, accept_sparse = None, dtype=np.float64)\n n_samples, n_features = X.shape\n\n # preprocess features\n self._X_mean = np.zeros(n_features)\n self._X_std = np.ones(n_features)\n if self.normalize:\n self._X_mean, self._X_std = np.mean(X,0), np.std(X,0)\n X = (X - self._X_mean) / self._X_std\n if self.fit_intercept:\n X = np.concatenate((np.ones([n_samples,1]),X),1)\n n_features += 1\n \n # preprocess targets\n check_classification_targets(y)\n self.classes_ = np.unique(y)\n n_classes = len(self.classes_)\n if n_classes < 2:\n raise ValueError(\"Need samples of at least 2 classes\"\n \" in the data, but the data contains only one\"\n \" class: %r\" % self.classes_[0])\n \n # if multiclass use OVR (i.e. fit classifier for each class)\n self.coef_,self.active_ ,self.lambda_= list(),list(),list()\n self.intercept_, self.sigma_ = list(),list() \n for pos_class in self.classes_:\n if n_classes == 2:\n pos_class = self.classes_[1]\n mask = (y == pos_class)\n y_bin = np.zeros(y.shape, dtype=np.float64)\n y_bin[mask] = 1\n coef_, intercept_, active_ , sigma_ , A = self._fit(X,y_bin,\n n_samples,n_features)\n self.coef_.append(coef_)\n self.active_.append(active_)\n self.intercept_.append(intercept_)\n self.sigma_.append(sigma_)\n self.lambda_.append(A)\n # in case of binary classification fit only one classifier \n if n_classes == 2:\n break\n \n return self\n \n \n def _fit(self,X,y,n_samples,n_features):\n '''\n Fits binary classification\n '''\n A = np.PINF * np.ones(n_features)\n active = np.zeros(n_features , dtype = np.bool)\n # this is done for RVC (so that to have at least one rv in worst case)\n if n_features > 1:\n active[1] = True\n A[1] = 1e-3\n else:\n active[1] = True\n A[1] = 1e-3\n \n penalise = self.fit_intercept and self.penalise_intercept\n for i in range(self.n_iter):\n Xa = X[:,active]\n Aa = A[active]\n penalise_intercept = active[0] and penalise\n \n # mean & covariance of posterior distribution\n Mn,Sn,B,t_hat = self._posterior_dist(Xa,y, Aa, penalise_intercept)\n \n # compute quality & sparsity parameters\n s,q,S,Q = self._sparsity_quality(X,Xa,t_hat,B,A,Aa,active,Sn)\n\n # update precision parameters of coefficients\n A,converged = update_precisions(Q,S,q,s,A,active,self.tol,self.fit_intercept)\n\n # terminate if converged\n if converged or i == self.n_iter - 1:\n break\n \n penalise_intercept = penalise and active[0]\n Xa,Aa = X[:,active], A[active]\n Mn,Sn,B,t_hat = self._posterior_dist(Xa,y,Aa,penalise_intercept)\n intercept_ = 0\n if self.fit_intercept:\n n_features -= 1\n if active[0] == True:\n intercept_ = Mn[0]\n Mn = Mn[1:] \n active = active[1:]\n coef_ = np.zeros([1,n_features])\n coef_[0,active] = Mn \n return coef_, intercept_, active, Sn, A\n \n \n def decision_function(self,X):\n '''\n Decision function\n '''\n check_is_fitted(self, 'coef_') \n X = check_array(X, accept_sparse=None, dtype = np.float64)\n n_features = self.coef_[0].shape[1]\n if X.shape[1] != n_features:\n raise ValueError(\"X has %d features per sample; expecting %d\"\n % (X.shape[1], n_features))\n x = (X - self._X_mean) / self._X_std\n decision = np.array([ (np.dot(x,w.T) + c)[:,0] for w,c \n in zip(self.coef_,self.intercept_) ]).T\n if decision.shape[1] == 1:\n return decision[:,0]\n return decision\n \n \n def predict(self,X):\n '''\n Calculates estimated target values on test set\n \n Parameters\n ----------\n X: array-like of size [n_samples_test, n_features]\n Matrix of explanatory variables (test set)\n \n Returns\n -------\n y_pred: numpy arra of size [n_samples_test]\n Predicted values of targets\n '''\n probs = self.predict_proba(X)\n indices = np.argmax(probs, axis = 1)\n y_pred = self.classes_[indices]\n return y_pred\n\n \n\n def predict_proba(self,X):\n '''\n Predicts probabilities of targets for test set\n Uses probit function to approximate convolution \n of sigmoid and Gaussian.\n \n Parameters\n ----------\n X: array-like of size [n_samples_test,n_features]\n Matrix of explanatory variables (test set)\n\n Returns\n -------\n probs: numpy array of size [n_samples_test]\n Estimated probabilities of target classes\n '''\n y_hat = self.decision_function(X)\n X = check_array(X, accept_sparse = None)\n x = (X - self._X_mean) / self._X_std\n if self.fit_intercept:\n x = np.concatenate((np.ones([x.shape[0],1]), x),1)\n if y_hat.ndim == 1:\n pr = self._predict_proba(x[:,self.lambda_[0]!=np.PINF],\n y_hat,self.sigma_[0])\n prob = np.vstack([1 - pr, pr]).T\n else:\n pr = [self._predict_proba(x[:,idx != np.PINF],y_hat[:,i],\n self.sigma_[i]) for i,idx in enumerate(self.lambda_) ]\n pr = np.asarray(pr).T\n prob = pr / np.reshape(np.sum(pr, axis = 1), (pr.shape[0],1))\n return prob\n\n\n def _predict_proba(self,X,y_hat,sigma):\n '''\n Calculates predictive distribution\n '''\n var = np.sum(np.dot(X,sigma)*X,1)\n ks = 1. / ( 1. + np.pi * var/ 8)**0.5\n pr = expit(y_hat * ks)\n return pr\n\n\n def _sparsity_quality(self, X, Xa, y, B, A, Aa, active, Sn):\n '''Calculates sparsity & quality parameters for each feature.'''\n XB = X.T*B\n XSX = np.dot(Xa, Sn)\n XSX = np.dot(XSX, Xa.T)\n\n S = np.dot(XB, XSX)\n del XSX\n\n Q = -np.dot(S, y*B)\n Q += np.dot(XB, y)\n\n S *= XB\n S = -np.sum(S, 1)\n S += np.sum(XB*X.T, 1)\n del XB\n\n qi = np.copy(Q)\n si = np.copy(S)\n Qa, Sa = Q[active], S[active]\n qi[active] = Aa * Qa / (Aa - Sa)\n si[active] = Aa * Sa / (Aa - Sa)\n\n return [si, qi, S, Q]\n\n\n def _posterior_dist(self,X,y,A,intercept_prior):\n '''\n Uses Laplace approximation for calculating posterior distribution\n '''\n if self.solver == 'lbfgs_b':\n f = lambda w: _logistic_cost_grad(X,y,w,A,intercept_prior)\n w_init = np.random.random(X.shape[1])\n Mn = fmin_l_bfgs_b(f, x0 = w_init, pgtol = self.tol_solver,\n maxiter = self.n_iter_solver)[0]\n Xm = np.dot(X,Mn)\n s = expit(Xm)\n B = logistic._pdf(Xm) # avoids underflow\n S = np.dot(X.T*B,X)\n np.fill_diagonal(S, np.diag(S) + A)\n t_hat = Xm + (y - s) / B\n Sn = pinvh(S)\n elif self.solver == 'newton_cg':\n # TODO: Implement Newton-CG\n raise NotImplementedError(('Newton Conjugate Gradient optimizer '\n 'is not currently supported'))\n return [Mn,Sn,B,t_hat]\n \n\n\n###############################################################################\n# Relevance Vector Machine: RVR and RVC\n###############################################################################\n\n\n\ndef get_kernel( X, Y, gamma, degree, coef0, kernel, kernel_params ):\n '''\n Calculates kernelised features for RVR and RVC\n '''\n if callable(kernel):\n params = kernel_params or {}\n else:\n params = {\"gamma\": gamma,\n \"degree\": degree,\n \"coef0\": coef0 }\n return pairwise_kernels(X, Y, metric=kernel,\n filter_params=True, **params)\n \n \n \ndef decision_function(estimator , active_coef_ , X , intercept_,\n relevant_vectors_, gamma, degree, coef0,\n kernel,kernel_params):\n '''\n Computes decision function for regression and classification.\n '''\n K = get_kernel( X, relevant_vectors_, gamma, degree, coef0, \n kernel, kernel_params)\n return np.dot(K,active_coef_) + intercept_\n \n\n\nclass RVR(RegressionARD):\n '''\n Relevance Vector Regression is ARD regression with kernelised features\n \n Parameters\n ----------\n n_iter: int, optional (DEFAULT = 300)\n Maximum number of iterations\n\n fit_intercept : boolean, optional (DEFAULT = True)\n whether to calculate the intercept for this model. If set\n to false, no intercept will be used in calculations\n (e.g. data is expected to be already centered)\n \n tol: float, optional (DEFAULT = 1e-3)\n If absolute change in precision parameter for weights is below threshold\n algorithm terminates.\n \n perfect_fit_tol: float, optional (DEFAULT = 1e-4)\n Algortihm terminates in case MSE on training set is below perfect_fit_tol.\n Helps to prevent overflow of precision parameter for noise in case of\n nearly perfect fit.\n \n copy_X : boolean, optional (DEFAULT = True)\n If True, X will be copied; else, it may be overwritten.\n \n verbose : boolean, optional (DEFAULT = True)\n Verbose mode when fitting the model \n \n kernel: str, optional (DEFAULT = 'poly')\n Type of kernel to be used (all kernels: ['rbf' | 'poly' | 'sigmoid', 'linear']\n \n degree : int, (DEFAULT = 3)\n Degree for poly kernels. Ignored by other kernels.\n \n gamma : float, optional (DEFAULT = 1/n_features)\n Kernel coefficient for rbf and poly kernels, ignored by other kernels\n \n coef0 : float, optional (DEFAULT = 1)\n Independent term in poly and sigmoid kernels, ignored by other kernels\n \n kernel_params : mapping of string to any, optional\n Parameters (keyword arguments) and values for kernel passed as\n callable object, ignored by other kernels\n \n \n Attributes\n ----------\n coef_ : array, shape = (n_features)\n Coefficients of the regression model (mean of posterior distribution)\n \n alpha_ : float\n estimated precision of the noise\n \n active_ : array, dtype = np.bool, shape = (n_features)\n True for non-zero coefficients, False otherwise\n \n lambda_ : array, shape = (n_features)\n estimated precisions of the coefficients\n \n sigma_ : array, shape = (n_features, n_features)\n estimated covariance matrix of the weights, computed only\n for non-zero coefficients\n \n relevant_vectors_ : array \n Relevant Vectors\n \n '''\n def __init__(self, n_iter=300, tol = 1e-3, perfect_fit_tol = 1e-4, \n fit_intercept = True, copy_X = True,verbose = False,\n kernel = 'poly', degree = 3, gamma = 1,\n coef0 = 1, kernel_params = None):\n # !!! do not normalise kernel matrix\n normalize = False\n super(RVR,self).__init__(n_iter, tol, perfect_fit_tol, \n fit_intercept, normalize, copy_X, verbose)\n self.kernel = kernel\n self.degree = degree\n self.gamma = gamma\n self.coef0 = coef0\n self.kernel_params = kernel_params\n \n \n def fit(self,X,y):\n '''\n Fit Relevance Vector Regression Model\n \n Parameters\n -----------\n X: {array-like,sparse matrix} of size [n_samples, n_features]\n Training data, matrix of explanatory variables\n \n y: array-like of size [n_samples, n_features] \n Target values\n \n Returns\n -------\n self: object\n self\n '''\n X,y = check_X_y(X,y, accept_sparse = ['csr','coo','bsr'], dtype = np.float64)\n # kernelise features\n K = get_kernel( X, X, self.gamma, self.degree, self.coef0, \n self.kernel, self.kernel_params)\n # use fit method of RegressionARD\n _ = super(RVR,self).fit(K,y)\n # convert to csr (need to use __getitem__)\n convert_tocsr = [scipy.sparse.coo.coo_matrix, scipy.sparse.dia.dia_matrix,\n scipy.sparse.bsr.bsr_matrix]\n if type(X) in convert_tocsr:\n X = X.tocsr()\n self.relevant_ = np.where(self.active_== True)[0]\n if X.ndim == 1:\n self.relevant_vectors_ = X[self.relevant_]\n else:\n self.relevant_vectors_ = X[self.relevant_,:]\n return self\n \n \n def predict(self,X):\n '''\n Predicts targets on test set\n \n Parameters\n ----------\n X: {array-like,sparse_matrix} of size [n_samples_test, n_features]\n Matrix of explanatory variables (test set)\n \n Returns\n --------\n : numpy array of size [n_samples_test]\n Estimated target values on test set \n '''\n X = check_array(X, accept_sparse=['csr', 'csc', 'coo'])\n return self._decision_function(X)\n \n \n def predict_dist(self,X):\n '''\n Computes predictive distribution for test set.\n Predictive distribution for each data point is one dimensional\n Gaussian and therefore is characterised by mean and standard\n deviation.\n \n Parameters\n ----------\n X: {array-like,sparse matrix} of size [n_samples_test, n_features]\n Matrix of explanatory variables (test set)\n \n Returns\n -------\n y_hat: array of size [n_samples_test]\n Estimated values of targets on test set (Mean of predictive distribution)\n \n std_hat: array of size [n_samples_test]\n Error bounds (Standard deviation of predictive distribution)\n '''\n check_is_fitted(self, \"coef_\")\n # mean of predictive distribution\n K = get_kernel( X, self.relevant_vectors_, self.gamma, self.degree, \n self.coef0, self.kernel, self.kernel_params)\n y_hat = decision_function(self,self.coef_[self.active_], X, \n self.intercept_,self.relevant_vectors_, \n self.gamma, self.degree, self.coef0,\n self.kernel,self.kernel_params)\n K = (K - self._x_mean_[self.active_])\n var_hat = self.alpha_\n var_hat += np.sum( np.dot(K,self.sigma_) * K, axis = 1)\n std_hat = np.sqrt(var_hat)\n return y_hat,std_hat\n \n \n def _decision_function(self,X):\n '''\n Decision function, calculates mean of predicitve distribution\n '''\n check_is_fitted(self, \"coef_\")\n return decision_function(self , self.coef_[self.active_] ,\n X , self.intercept_, self.relevant_vectors_, \n self.gamma, self.degree, self.coef0, self.kernel,\n self.kernel_params)\n \n\n\nclass RVC(ClassificationARD):\n '''\n Relevance Vector Classifier\n \n \n Parameters\n ----------\n n_iter: int, optional (DEFAULT = 300)\n Maximum number of iterations before termination\n \n tol: float, optional (DEFAULT = 1e-3)\n If absolute change in precision parameter for weights is below threshold\n algorithm terminates.\n \n solver: str, optional (DEFAULT = 'lbfgs_b')\n Optimization method that is used for finding parameters of posterior\n distribution ['lbfgs_b','newton_cg']\n \n n_iter_solver: int, optional (DEFAULT = 20)\n Maximum number of iterations before termination of solver\n \n tol_solver: float, optional (DEFAULT = 1e-5)\n Convergence threshold for solver (it is used in estimating posterior\n distribution), \n\n fit_intercept : bool, optional ( DEFAULT = True )\n If True will use intercept in the model. If set\n to false, no intercept will be used in calculations\n \n penalise_intercept: bool, optional ( DEFAULT = False)\n If True uses prior distribution on bias term (penalises intercept)\n \n normalize : boolean, optional (DEFAULT = False)\n If True, the regressors X will be normalized before regression\n \n verbose : boolean, optional (DEFAULT = True)\n Verbose mode when fitting the model\n \n kernel: str, optional (DEFAULT = 'rbf')\n Type of kernel to be used (all kernels: ['rbf' | 'poly' | 'sigmoid']\n \n degree : int, (DEFAULT = 3)\n Degree for poly kernels. Ignored by other kernels.\n \n gamma : float, optional (DEFAULT = 1/n_features)\n Kernel coefficient for rbf and poly kernels, ignored by other kernels\n \n coef0 : float, optional (DEFAULT = 0.1)\n Independent term in poly and sigmoid kernels, ignored by other kernels\n \n kernel_params : mapping of string to any, optional\n Parameters (keyword arguments) and values for kernel passed as\n callable object, ignored by other kernels\n \n \n Attributes\n ----------\n coef_ : array, shape = (n_features)\n Coefficients of the regression model (mean of posterior distribution)\n \n lambda_ : float\n estimated precisions of weights\n \n active_ : array, dtype = np.bool, shape = (n_features)\n True for non-zero coefficients, False otherwise\n\n sigma_ : array, shape = (n_features, n_features)\n estimated covariance matrix of the weights, computed only\n for non-zero coefficients\n\n '''\n \n def __init__(self, n_iter = 300, tol = 1e-4, solver = 'lbfgs_b', \n n_iter_solver = 30, tol_solver = 1e-5, fit_intercept = True, \n verbose = False, kernel = 'rbf', degree = 2,\n gamma = None, coef0 = 1, kernel_params = None):\n # use constructor of Classification ARD\n super(RVC,self).__init__(n_iter = 300, tol = 1e-4, solver = 'lbfgs_b', \n n_iter_solver = 30, tol_solver = 1e-5, \n fit_intercept = True, normalize = False,\n verbose = False)\n self.kernel = kernel\n self.degree = degree\n self.gamma = gamma\n self.coef0 = coef0\n self.kernel_params = kernel_params\n self.full_kernel = False\n \n \n def fit(self,X,y):\n '''\n Fit Relevance Vector Classifier\n \n Parameters\n -----------\n X: array-like of size [n_samples, n_features]\n Training data, matrix of explanatory variables\n \n y: array-like of size [n_samples, n_features] \n Target values\n \n Returns\n -------\n self: object\n self\n '''\n X,y = check_X_y(X,y, accept_sparse = None, dtype = np.float64)\n # kernelise features\n K = get_kernel( X, X, self.gamma, self.degree, self.coef0, \n self.kernel, self.kernel_params)\n # use fit method of RegressionARD\n _ = super(RVC,self).fit(K,y)\n self.relevant_ = [np.where(active==True)[0] for active in self.active_]\n if X.ndim == 1:\n self.relevant_vectors_ = [ X[relevant_] for relevant_ in self.relevant_]\n else:\n self.relevant_vectors_ = [ X[relevant_,:] for relevant_ in self.relevant_ ]\n return self\n \n \n def decision_function(self,X):\n '''\n Decision function\n '''\n check_is_fitted(self, \"coef_\")\n X = check_array(X, accept_sparse = None, dtype = np.float64) \n f = lambda coef,x,rv,act,c: decision_function(self,coef[:,act==True].T,x,\n c ,rv, self.gamma, self.degree,\n self.coef0, self.kernel, self.kernel_params)\n decision = np.asarray([ f(coef,X,rv,act,c)[:,0] for coef,rv,act,c in zip(self.coef_,\n self.relevant_vectors_,self.active_,self.intercept_) ]).T\n if decision.shape[1] == 1:\n return decision[:,0]\n return decision\n \n\n def predict_proba(self,X):\n '''\n Predicts probabilities of targets for test set\n \n Theoretical Note\n ================\n Current version of method does not use MacKay's approximation\n to convolution of Gaussian and sigmoid. This results in less accurate \n estimation of class probabilities and therefore possible increase\n in misclassification error for multiclass problems (prediction accuracy\n for binary classification problems is not changed)\n \n Parameters\n ----------\n X: array-like of size [n_samples_test,n_features]\n Matrix of explanatory variables (test set)\n \n Returns\n -------\n probs: numpy array of size [n_samples_test]\n Estimated probabilities of target classes\n \n '''\n prob = expit(self.decision_function(X))\n if prob.ndim == 1:\n prob = np.vstack([1 - prob, prob]).T\n prob = prob / np.reshape(np.sum(prob, axis = 1), (prob.shape[0],1))\n return prob\n \n \n def predict(self,X):\n '''\n Predict function\n \n Parameters\n ----------\n X: array-like of size [n_samples_test,n_features]\n Matrix of explanatory variables (test set)\n \n Returns\n -------\n y_pred: numpy array of size [n_samples_test]\n Estimated values of targets\n '''\n probs = self.predict_proba(X)\n indices = np.argmax(probs, axis = 1)\n y_pred = self.classes_[indices]\n return y_pred\n","sub_path":"skbayes/rvm_ard_models/fast_rvm.py","file_name":"fast_rvm.py","file_ext":"py","file_size_in_byte":39228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"62426078","text":"from itertools import combinations, product\n\n__author__ = 'Géraud'\n\n\ndef get_equipment():\n weapons = {\n \"Dagger\": {\"cost\": 8, \"damage\": 4, \"armor\": 0},\n \"Shortsword\": {\"cost\": 10, \"damage\": 5, \"armor\": 0},\n \"Warhammer\": {\"cost\": 25, \"damage\": 6, \"armor\": 0},\n \"Longsword\": {\"cost\": 40, \"damage\": 7, \"armor\": 0},\n \"Greataxe\": {\"cost\": 74, \"damage\": 8, \"armor\": 0}\n }\n armors = {\n \"Leather\": {\"cost\": 13, \"damage\": 0, \"armor\": 1},\n \"Chainmail\": {\"cost\": 31, \"damage\": 0, \"armor\": 2},\n \"Splintmail\": {\"cost\": 53, \"damage\": 0, \"armor\": 3},\n \"Bandedmail\": {\"cost\": 75, \"damage\": 0, \"armor\": 4},\n \"Platemail\": {\"cost\": 102, \"damage\": 0, \"armor\": 5},\n \"None\": {\"cost\": 0, \"damage\": 0, \"armor\": 0}\n }\n rings = {\n \"Damage +1\": {\"cost\": 25, \"damage\": 1, \"armor\": 0},\n \"Damage +2\": {\"cost\": 50, \"damage\": 2, \"armor\": 0},\n \"Damage +3\": {\"cost\": 100, \"damage\": 3, \"armor\": 0},\n \"Defense +1\": {\"cost\": 20, \"damage\": 0, \"armor\": 1},\n \"Defense +2\": {\"cost\": 40, \"damage\": 0, \"armor\": 2},\n \"Defense +3\": {\"cost\": 80, \"damage\": 0, \"armor\": 3},\n \"None1\": {\"cost\": 0, \"damage\": 0, \"armor\": 0},\n \"None2\": {\"cost\": 0, \"damage\": 0, \"armor\": 0}\n }\n weapons_index = [k for k in weapons]\n armors_index = [k for k in armors]\n rings_index = [k for k in rings]\n\n rings_comb = combinations(rings_index, 2)\n stuff_comb = product(weapons_index, armors_index)\n total_comb = product(stuff_comb, rings_comb)\n for stuff in total_comb:\n stuff = [stuff[0][0]] + [stuff[0][1]] + [stuff[1][0]] + [stuff[1][1]]\n ret = {\n \"weapon\": weapons[stuff[0]],\n \"body_armor\": armors[stuff[1]],\n \"ring1\": rings[stuff[2]],\n \"ring2\": rings[stuff[3]]\n }\n yield ret\n\n\nclass Player:\n def __init__(self, weapon, body_armor, ring1, ring2):\n self.weapon = weapon\n self.body_armor = body_armor\n self.ring1 = ring1\n self.ring2 = ring2\n self.hp = 100\n self.damage = weapon[\"damage\"] + ring1[\"damage\"] + ring2[\"damage\"]\n self.armor = body_armor[\"armor\"] + ring1[\"armor\"] + ring2[\"armor\"]\n self.cost = weapon[\"cost\"] + body_armor[\"cost\"] + ring1[\"cost\"] + ring2[\"cost\"]\n\n def won_fight(self):\n boss = {\"hp\": 103,\n \"damage\": 9,\n \"armor\": 2\n }\n while True:\n player_damage = self.damage - boss[\"armor\"]\n player_damage = 1 if player_damage < 1 else player_damage\n boss_damage = boss[\"damage\"] - self.armor\n boss_damage = 1 if boss_damage < 1 else boss_damage\n boss[\"hp\"] -= player_damage\n if boss[\"hp\"] < 1:\n return True, self.cost\n self.hp -= boss_damage\n if self.hp < 1:\n return False, self.cost\n\n\nif __name__ == \"__main__\":\n won_min_cost = float(\"inf\")\n lose_max_cost = -1\n\n for stuff in get_equipment():\n you = Player(**stuff)\n won, cost = you.won_fight()\n if won and cost < won_min_cost:\n won_min_cost = cost\n elif not won and cost > lose_max_cost:\n lose_max_cost = cost\n\n print(\"Part 1: {}\".format(won_min_cost))\n print(\"Part 2: {}\".format(lose_max_cost))\n","sub_path":"AOC-2015/Day-21/day-21.py","file_name":"day-21.py","file_ext":"py","file_size_in_byte":3341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"161268251","text":"from dataclasses import dataclass\nfrom typing import List\n\nfrom input_data.products import ProductType, Product, get_product_type\nimport xlrd\n\n\n@dataclass(frozen=True)\nclass DeliveryLineInput:\n vendor_id: str\n delivery_number: int\n volume: int\n product_type: ProductType\n arrival_day: int\n price: float\n\n\n@dataclass(frozen=True)\nclass TransportationCost:\n product_type: ProductType\n cost: float\n\n\n@dataclass(frozen=True)\nclass TransportationCostInput:\n product_type: ProductType\n cost: float\n vendor_id: str\n\n\n@dataclass(frozen=True)\nclass Delivery:\n arrival_day: int\n supply: List[Product]\n delivery_number: int\n\n\n@dataclass(frozen=True)\nclass Vendor:\n id: str\n deliveries: List[Delivery]\n transportation_cost_per_box: List[TransportationCost]\n\n\ndef load_vendors(path: str, adjust_delivery_estimate: float):\n workbook = xlrd.open_workbook(path)\n delivery_sheet = workbook.sheet_by_index(0)\n cell_values_deliveries = delivery_sheet._cell_values\n del cell_values_deliveries[0]\n delivery_lines = [\n DeliveryLineInput(\n vendor_id=delivery_row[0],\n delivery_number=int(delivery_row[1]),\n volume=int(delivery_row[2]),\n product_type=get_product_type(product_type=delivery_row[3]),\n price=delivery_row[4],\n arrival_day=int(delivery_row[5]),\n )\n for delivery_row in cell_values_deliveries\n ]\n\n transportation_sheet = workbook.sheet_by_index(1)\n cell_values_transportation_cost = transportation_sheet._cell_values\n del cell_values_transportation_cost[0]\n transportation_costs = [\n TransportationCostInput(\n vendor_id=transportation_row[0],\n product_type=get_product_type(product_type=transportation_row[1]),\n cost=transportation_row[2]\n )\n for transportation_row in cell_values_transportation_cost\n ]\n vendor_sheet = workbook.sheet_by_index(2)\n cell_values_vendors = vendor_sheet._cell_values\n del cell_values_vendors[0]\n vendors = [\n _load_vendor(\n vendor_row=vendor_row,\n delivery_lines=delivery_lines,\n transportation_costs=transportation_costs,\n adjust_delivery_estimate=adjust_delivery_estimate,\n )\n for vendor_row in cell_values_vendors\n ]\n return vendors\n\n\ndef _load_vendor(\n vendor_row,\n delivery_lines: List[DeliveryLineInput],\n transportation_costs: List[TransportationCostInput],\n adjust_delivery_estimate: float\n):\n vendor_id = vendor_row[0]\n deliveries = _get_deliveries_belonging_to_vendor(\n vendor_id=vendor_id, delivery_lines=delivery_lines, adjust_delivery_estimate=adjust_delivery_estimate)\n transportation_costs_from_vendor = [\n TransportationCost(\n product_type=transportation_cost.product_type,\n cost=transportation_cost.cost,\n )\n for transportation_cost in transportation_costs\n if transportation_cost.vendor_id == vendor_id\n ]\n vendor = Vendor(\n id=vendor_id,\n deliveries=deliveries,\n transportation_cost_per_box=transportation_costs_from_vendor,\n )\n return vendor\n\n\ndef _get_deliveries_belonging_to_vendor(vendor_id: str, delivery_lines: List[DeliveryLineInput], adjust_delivery_estimate: float):\n delivery_lines_belonging_to_vendor = [\n delivery_line\n for delivery_line in delivery_lines\n if delivery_line.vendor_id == vendor_id\n ]\n unique_delivery_numbers = set([\n delivery_line.delivery_number\n for delivery_line in delivery_lines_belonging_to_vendor\n ])\n delivery_lines_per_delivery_number = [\n [\n delivery_line\n for delivery_line in delivery_lines_belonging_to_vendor\n if delivery_line.delivery_number == delivery_number\n ]\n for delivery_number in unique_delivery_numbers\n ]\n deliveries = [\n _create_delivery(\n delivery_lines_for_one_delivery_number=delivery_lines_for_delivery_number,\n adjust_delivery_estimate=adjust_delivery_estimate,\n )\n for delivery_lines_for_delivery_number in delivery_lines_per_delivery_number\n ]\n return deliveries\n\n\ndef _create_delivery(delivery_lines_for_one_delivery_number: List[DeliveryLineInput], adjust_delivery_estimate: float):\n supply = [\n Product(\n product_type=delivery_line.product_type,\n volume=int(delivery_line.volume * (1 + adjust_delivery_estimate / 100)),\n price=delivery_line.price,\n )\n for delivery_line in delivery_lines_for_one_delivery_number\n ]\n\n delivery = Delivery(\n arrival_day=delivery_lines_for_one_delivery_number[0].arrival_day,\n supply=supply,\n delivery_number=delivery_lines_for_one_delivery_number[0].delivery_number,\n )\n return delivery\n","sub_path":"input_data/load_vendors.py","file_name":"load_vendors.py","file_ext":"py","file_size_in_byte":4904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"366631639","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom array import array\nd1 = np.empty([3,4])\nd1[0,0] = float(12.1)\nd1[0,1] = float(12.2)\nd1[0,2] = float(12.3)\nd1[0,3] = float(12.4)\n#print(d1[0,0])\n#print(d1[0,1])\n#print(type(d1))\n#print([1,2,3,4,5][1:4])\n\n#print([\"%8d\" % float('122.4546')])\n\n# flag_output_file_path=open('./d1.dat',\"wb\")\n# float_array = array('i', [1,2,3])\n# float_array.tofile(flag_output_file_path)\n# float_array = array('f', [1,2,3])\n# float_array.tofile(flag_output_file_path)\n\n#float_array.tofile('./d1.dat')\n\n\n\n###########################\n# x = array('b')\n# x.frombytes('test'.encode())\n#\n# #array('b', [116, 101, 115, 116])\n# x.tobytes()\n# print(x.tobytes())\n# x.tobytes().decode()\n# print(x.tobytes().decode())\n\n##################################\n# maxlat=90\n# maxlon=180\n# minlat=-90\n# minlon=-180\n# #calculate grid number\n# nx=(maxlon-minlon)/float(0.05)\n# ny=(maxlat-minlat)/float(0.05)\n# print(nx)\n# print(ny)\n#\n# #save data\n# data=list(np.random.random([int(nx),int(ny)]))\n# print(data)\n###############################\nnp.float32([1.0,2,3,'3']).tofile('output.grd')\nprint(np.float32([1.0,2,3,'3']))","sub_path":"MMS2_MRC/module/algorithm/src/grib/grib1.py","file_name":"grib1.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"216713151","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 18 13:50:53 2018\n\n@author: Jane Wu\n\"\"\"\n\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nimport matplotlib.pyplot as plt\n\nN = 200;\nX = np.linspace(-1, 1, N)\nnp.random.shuffle(X)\nY = 3*X + 0.5 + np.random.normal(0, 0.4, (N,))\n\nX_train, Y_train = X[:60], Y[:60]\nX_test, Y_test = X[60:], Y[60:]\n\n#plt.scatter(X, Y)\n#plt.show()\n\nmodel = Sequential()\nmodel.add(Dense(output_dim=1, input_dim = 1))\nmodel.compile(loss='mse', optimizer='sgd')\n\n\nfor k in np.arange(1, 51): \n Hist = model.fit(X_train, Y_train, batch_size=N, epochs=k, verbose=0)\n#print(K.history)\n W, b = model.layers[0].get_weights()\n print('For epoch =', k, 'Weight=', W, ', bias=', b)\n\n Y_pred = model.predict(X_test)\n plt.scatter(X_test, Y_test)\n plt.plot(X_test, Y_pred)\n plt.show()","sub_path":"regression_prac.py","file_name":"regression_prac.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"121946618","text":"#!/usr/bin/env python3\n\n#\n# client.py - Connect to TCP socket\n#\n# 17May17 Added call to socket.shutdown()\n# 16May17 Updated to use more sophisticated recv behavior\n# 10May16 Everett Lipman\n#\nUSAGE=\"\"\"\nusage: client.py [ipnum] port\n\n Open TCP connection to ipnum:port and print the output.\n ipnum defaults to 127.0.0.1\n\"\"\"\nN_ARGUMENTS = (1,2)\n\nimport sys\nimport os\nimport socket\n\n###############################################################################\n\ndef usage(message = ''):\n sys.stdout = sys.stderr\n if message != '':\n print()\n print(message)\n print(USAGE)\n\n sys.exit(1)\n###############################################################################\n\ndef check_arguments():\n \"\"\"Check command line arguments for proper usage.\n \"\"\"\n global nargs, progname\n nargs = len(sys.argv) - 1\n progname = os.path.basename(sys.argv[0])\n flag = True\n if nargs != 0 and N_ARGUMENTS[-1] == '*':\n flag = False\n else:\n for i in N_ARGUMENTS:\n if nargs == i:\n flag = False\n if flag:\n usage()\n return(nargs)\n###############################################################################\n\ndef open_connection(ipn, prt):\n \"\"\"Open TCP connection to ipnum:port.\n \"\"\"\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n \n connect_error = s.connect_ex((ipn, prt))\n\n if connect_error:\n if connect_error == 111:\n usage('Connection refused. Check address and try again.')\n else:\n usage('Error %d connecting to %s:%d' % (connect_error,ipn,prt))\n\n return(s)\n###############################################################################\n\ndef receive_data(thesock, nbytes):\n \"\"\"Attempt to receive nbytes of data from open socket thesock.\n \"\"\"\n dstring = b''\n rcount = 0 # number of bytes received\n thesock.settimeout(5)\n while rcount < nbytes:\n try:\n somebytes = thesock.recv(min(nbytes - rcount, 2048))\n except socket.timeout:\n print('Connection timed out.', file = sys.stderr)\n break\n if somebytes == b'':\n print('Connection closed.', file = sys.stderr)\n break\n rcount = rcount + len(somebytes)\n dstring = dstring + somebytes\n \n print('\\n%d bytes received.\\n' % rcount)\n\n return(dstring)\n###############################################################################\n\nif __name__ == '__main__':\n nargs = check_arguments()\n\n if nargs == 1:\n ipnum = '127.0.0.1'\n port = int(sys.argv[1])\n else:\n ipnum = sys.argv[1]\n port = int(sys.argv[2])\n\n print()\n print('Connecting to %s, port %d...\\n' % (ipnum, port))\n\n thesocket = open_connection(ipnum, port)\n\n indata = receive_data(thesocket, 4096)\n thesocket.shutdown(socket.SHUT_RDWR)\n thesocket.close()\n\n print()\n print('Data:')\n print()\n print(indata)\n\n datastring = indata.decode()\n print()\n print()\n print('Decoded data:')\n print()\n print(datastring)\n\n print\n","sub_path":"python/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"209688175","text":"import pandas as pd\nimport numpy as np\nimport lightgbm as lgb\nimport typing as t\nfrom scipy import stats\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split, KFold, GridSearchCV, RandomizedSearchCV\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nfrom sklearn.metrics import mean_squared_error\n\nTRAIN_PATH = 'src/sample_data/Kaggle/predict_target_of_bank/train.csv'\nTEST_PATH = 'src/sample_data/Kaggle/predict_target_of_bank/test.csv'\nSAVE_PATH = 'src/sample_data/Kaggle/predict_target_of_bank/submission.csv'\n\nMONTH = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']\nJOB = ['blue-collar', 'management', 'technician', 'admin.', 'services', 'retired', 'self-employed', 'entrepreneur', 'housemaid', 'student', 'unemployed', 'unknown']\nPOUTCOME = ['success', 'failure', 'other', 'unknown']\nEDUCATION = ['secondary','tertiary','primary','unknown']\nCONTACT = ['cellular', 'telephone', 'unknown']\nMARRIED = ['married', 'single', 'divorced']\nHOUSING = ['yes', 'no']\nLOAN = ['yes', 'no']\nDEFAULT = ['yes', 'no']\nCOLUMNS = {\n 'marital': MARRIED,\n 'housing': HOUSING,\n 'job': JOB,\n 'month': MONTH,\n 'poutcome': POUTCOME,\n 'education': EDUCATION,\n 'contact': CONTACT,\n 'loan': LOAN,\n 'default': DEFAULT,\n}\n\n\ndef read_csv(path: str) -> pd.DataFrame:\n df = pd.read_csv(path)\n return df\n\n\ndef train_preprocess(df: pd.DataFrame) -> t.Tuple[pd.DataFrame, pd.DataFrame]:\n train_x = replace_to_value(df) \n train_x = convert_type(train_x)\n train_x = smoothing(train_x)\n train_y = train_x.loc[:,'y']\n train_x = train_x.drop(['y','id', 'default', 'loan'], axis=1)\n return train_x, train_y\n\n\ndef test_preprocess(df: pd.DataFrame) -> t.Tuple[pd.DataFrame, pd.Series]:\n test = replace_to_value(df)\n test = convert_type(test)\n ids = test['id']\n test = test.drop(['id', 'default', 'loan'], axis=1)\n return test, ids\n\n\ndef replace_to_value(df: pd.DataFrame) -> None:\n for key, value in COLUMNS.items():\n for idx, row in enumerate(value):\n df[key] = df[key].mask(df[key] == row, idx)\n return df\n \n\ndef convert_type(df: pd.DataFrame) -> pd.DataFrame:\n df = df.astype(\n {\n 'marital': int,\n 'housing': int,\n 'job': int,\n 'month': int,\n 'poutcome': int,\n 'education': int,\n 'contact': int,\n 'loan': int,\n 'default': int,\n }\n )\n return df\n\ndef remove_outlier(column: pd.Series) -> pd.Series:\n z = stats.zscore(column) < 5\n sm_column = column[z]\n return sm_column\n\n\ndef smoothing(df: pd.DataFrame) -> pd.DataFrame:\n print(df)\n df = df.drop(df[(df['balance']>60000)].index)\n df = df.drop(df[(df['duration']>3000)].index)\n df = df.drop(df[(df['previous']>50)].index)\n print(df)\n return df\n\n\ndef check_fig(df: pd.DataFrame) -> pd.DataFrame:\n for name, item in df.iteritems():\n plt.figure()\n item.plot()\n plt.savefig(f'src/sample_data/Kaggle/predict_target_of_bank/{name}.png')\n\n\ndef check_corr(df: pd.DataFrame) -> None:\n corr = df.corr()\n plt.figure(figsize=(10,10))\n sns.heatmap(corr, square=True, annot=True)\n plt.savefig(f'src/sample_data/Kaggle/predict_target_of_bank/corr_heatmap.png')\n\n\ndef standardize(df: pd.DataFrame) -> pd.DataFrame:\n scaler = StandardScaler()\n scaler.fit(df)\n scaler_df = pd.DataFrame(scaler.transform(df), columns=df.columns)\n return scaler_df\n\n\ndef minmaxscaler(df: pd.DataFrame) -> pd.DataFrame:\n mm = MinMaxScaler()\n mm.fit(df)\n mm_df = pd.DataFrame(mm.transform(df), columns=df.columns)\n return mm_df\n\n\ndef get_model(tr_dataset: t.Any, val_dataset: t.Any) -> t.Any:\n model = lgb.LGBMRegressor(\n boosting_type='gbdt', \n num_leaves=30, \n learning_rate=0.3, \n n_estimators=100,\n )\n model.fit(\n train_set=tr_dataset,\n eval_set=val_dataset,\n early_stopping_rounds=5,\n )\n params = {\n \"objective\": \"regression\",\n \"boosting_type\": \"gbdt\",\n 'metric' : {'l2'},\n 'num_leaves' : 20,\n 'min_data_in_leaf': 100,\n 'num_iterations' : 2000,\n 'learning_rate' : 0.5,\n 'feature_fraction' : 0.7,\n }\n model = lgb.train(\n params=params,\n train_set=tr_dataset,\n valid_sets=val_dataset,\n early_stopping_rounds=5,\n )\n return model\n\n\ndef prediction(model: t.Any, test_df: pd.DataFrame) -> pd.Series:\n y_pred = model.predict(test_df, num_iteration=model.best_iteration)\n return pd.Series(y_pred)\n \n\ndef main(train_path: str, test_path: str) -> None:\n train = read_csv(train_path)\n test = read_csv(test_path)\n\n train_x, train_y = train_preprocess(train)\n test, ids = test_preprocess(test)\n # check_fig(train_x)\n check_corr(train_x)\n\n kf = KFold(n_splits=5, shuffle=True, random_state=0)\n y_preds = []\n best_scores = []\n for tr_idx, val_idx in kf.split(train_x, train_y):\n tr_x = train_x.iloc[tr_idx]\n tr_y = train_y.iloc[tr_idx]\n val_x = train_x.iloc[val_idx]\n val_y = train_y.iloc[val_idx]\n\n lgbr = lgb.LGBMRegressor(\n boosting_type='gbdt',\n objective='regression',\n early_stopping_rounds=5,\n eval_metric='l2',\n )\n params = {\n 'num_leaves' : [10, 20, 50, 100],\n 'min_data_in_leaf': [10, 100, 1000],\n 'num_iterations' : [10, 100, 1000, 2000],\n 'learning_rate' : [0.2, 0.5, 0.7],\n 'feature_fraction' : [0.5, 0,7],\n }\n clf = GridSearchCV(\n estimator = lgbr, \n param_grid = params, \n )\n clf.fit(\n tr_x,\n tr_y,\n eval_set = [[val_x, val_y]]\n )\n best_score = clf.best_params_\n best_scores.append(best_score)\n \n y_pred = clf.predict(test)\n y_preds.append(pd.Series(y_pred))\n \n print(\"##############bast_score##############\")\n print(best_scores)\n print(\"############################\") \n\n preds_df = pd.concat(y_preds, axis=1)\n \n pred_df = preds_df.mean(axis=1)\n submission = pd.concat([ids, pred_df], axis=1)\n print(submission)\n submission.to_csv(SAVE_PATH, header=False, index=False) \n\n\n\nif __name__ == \"__main__\":\n main(TRAIN_PATH, TEST_PATH)","sub_path":"app/src/python_file/kaggle/predict_target_of_bank/predict_target_of_bank(sklearn_interface).py","file_name":"predict_target_of_bank(sklearn_interface).py","file_ext":"py","file_size_in_byte":6425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"637036917","text":"import numpy as np\nfrom nn.models.single_layer import SingleNeuron\n\n\nclass Adaline(SingleNeuron):\n def __init__(self, input_size, activation_function=(lambda a: 1 if a > 0 else -1), init_max_weight=0.5):\n self.input_size = input_size + 1\n self.weights = (np.random.rand(1, self.input_size) * 2 - 1) * init_max_weight\n self.activation_function = activation_function\n\n def train(self, xs, ys, l_rate, batch_size=4, epochs=20, max_err=0.3):\n xs = np.column_stack([xs, np.ones((xs.shape[0], 1))])\n epoch = 1\n err = float('inf')\n while epoch < epochs and err > max_err:\n for i in range(self.input_size):\n diff = ys - self.feed_forward(xs)\n for j in range(batch_size):\n err = np.mean(diff) ** 2\n self.weights[0][i] = self.weights[0][i] + 2 * l_rate * xs[j][i] * diff[0][j]\n epoch = epoch + 1\n return epoch, err\n\n def feed_forward(self, xs):\n return np.matmul(self.weights, xs.T)\n\n\ndef train_adaline(a, train, l_rate, epoch_stop, test=None):\n if test is None:\n test = train\n train_x, train_y = train\n test_x, test_y = test\n print(\"Pre training results: \")\n\n print_predictions(train_x, train_y, a)\n print_predictions(test_x, test_y, a)\n epoches, err = a.train(xs=train_x, ys=train_y, l_rate=l_rate, epochs=epoch_stop, batch_size=train_x.shape[0])\n\n print(\"Post training results: \")\n\n print_predictions(train_x, train_y, a)\n print_predictions(test_x, test_y, a)\n\n print(\"Training took {} epochs.\\nFinal training loss: {:.4}\".format(epoches, err))\n\n\ndef print_predictions(xs, ys, a):\n xs = np.column_stack([xs, np.ones((xs.shape[0], 1))])\n for i in range(xs.shape[0]):\n print(\"{} -> {} | True: {}\".format(xs[i], a.predict(xs[i]), ys[i]))\n\n# End of file\n","sub_path":"nn/models/adaline.py","file_name":"adaline.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"300450611","text":"from opengever.ogds.base.actor import Actor\nfrom opengever.testing import IntegrationTestCase\n\n\nclass TestActorLookup(IntegrationTestCase):\n\n def test_null_actor(self):\n actor = Actor.lookup('not-existing')\n self.assertEqual('not-existing', actor.get_label())\n self.assertIsNone(actor.get_profile_url())\n self.assertEqual('not-existing', actor.get_link())\n\n def test_inbox_actor_lookup(self):\n actor = Actor.lookup('inbox:fa')\n\n self.assertEqual(u'Inbox: Finanzamt', actor.get_label())\n self.assertIsNone(actor.get_profile_url())\n self.assertEqual('Inbox: Finanzamt', actor.get_link())\n self.assertEqual(u'fa_inbox_users', actor.permission_identifier)\n self.assertEqual(\n u'<span class=\"actor-label actor-inbox\">Inbox: Finanzamt</span>',\n actor.get_link(with_icon=True))\n\n def test_contact_actor_lookup(self):\n self.login(self.regular_user)\n actor = Actor.lookup('contact:{}'.format(self.franz_meier.id))\n\n self.assertEqual('Meier Franz (meier.f@example.com)',\n actor.get_label())\n self.assertEqual(self.franz_meier.absolute_url(),\n actor.get_profile_url())\n\n link = actor.get_link(with_icon=True)\n self.assertIn(actor.get_label(), link)\n self.assertIn(actor.get_profile_url(), link)\n self.assertIn('class=\"actor-label actor-contact\"', link)\n\n def test_team_actor_lookup(self):\n self.login(self.regular_user)\n actor = Actor.lookup('team:1')\n\n self.assertEqual(u'Projekt \\xdcberbaung Dorfmatte (Finanzamt)',\n actor.get_label())\n self.assertEqual('http://nohost/plone/kontakte/team-1/view',\n actor.get_profile_url())\n\n self.assertEqual(\n u'<a href=\"http://nohost/plone/kontakte/team-1/view\" '\n u'class=\"actor-label actor-team\">Projekt \\xdcberbaung Dorfmatte '\n u'(Finanzamt)</a>',\n actor.get_link(with_icon=True))\n\n self.assertEqual(\n u'<a href=\"http://nohost/plone/kontakte/team-1/view\">'\n u'Projekt \\xdcberbaung Dorfmatte (Finanzamt)</a>',\n actor.get_link())\n\n def test_user_actor_ogds_user(self):\n actor = Actor.lookup('jurgen.konig')\n\n self.assertEqual(\n u'K\\xf6nig J\\xfcrgen (jurgen.konig)', actor.get_label())\n self.assertEqual('jurgen.konig', actor.permission_identifier)\n self.assertTrue(\n actor.get_profile_url().endswith('@@user-details/jurgen.konig'))\n\n self.assertEqual(\n u'<a href=\"http://nohost/plone/@@user-details/jurgen.konig\">'\n u'K\\xf6nig J\\xfcrgen (jurgen.konig)</a>',\n actor.get_link())\n\n self.assertEqual(\n u'<a href=\"http://nohost/plone/@@user-details/jurgen.konig\" '\n u'class=\"actor-label actor-user\">K\\xf6nig J\\xfcrgen '\n u'(jurgen.konig)</a>',\n actor.get_link(with_icon=True))\n\n def test_get_link_returns_safe_html(self):\n self.login(self.regular_user)\n\n self.franz_meier.firstname = u\"Foo <b onmouseover=alert('Foo!')>click me!</b>\"\n self.franz_meier.reindexObject()\n actor = Actor.lookup('contact:meier-franz')\n\n self.assertEquals(\n u'<a href=\"http://nohost/plone/kontakte/meier-franz\">Meier Foo <b onmouseover=alert('Foo!')>click me!</b> (meier.f@example.com)</a>',\n actor.get_link())\n\n\nclass TestActorCorresponding(IntegrationTestCase):\n\n def test_user_corresponds_to_current_user(self):\n actor = Actor.lookup('jurgen.konig')\n\n self.assertTrue(\n actor.corresponds_to(self.get_ogds_user(self.secretariat_user)))\n self.assertFalse(\n actor.corresponds_to(self.get_ogds_user(self.regular_user)))\n\n def test_inbox_corresponds_to_all_inbox_assigned_users(self):\n actor = Actor.lookup('inbox:fa')\n\n self.assertTrue(\n actor.corresponds_to(self.get_ogds_user(self.secretariat_user)))\n self.assertFalse(\n actor.corresponds_to(self.get_ogds_user(self.regular_user)))\n\n def test_team_corresponds_to_all_team_group_members(self):\n actor = Actor.lookup('team:1')\n\n self.assertTrue(\n actor.corresponds_to(self.get_ogds_user(self.regular_user)))\n self.assertTrue(\n actor.corresponds_to(self.get_ogds_user(self.dossier_responsible)))\n self.assertFalse(\n actor.corresponds_to(self.get_ogds_user(self.secretariat_user)))\n\n\nclass TestActorRepresentatives(IntegrationTestCase):\n\n def test_user_is_the_only_representatives_of_a_user(self):\n actor = Actor.lookup('jurgen.konig')\n self.assertEquals([self.get_ogds_user(self.secretariat_user)],\n actor.representatives())\n\n actor = Actor.lookup(self.regular_user.getId())\n self.assertEquals([self.get_ogds_user(self.regular_user)],\n actor.representatives())\n\n def test_all_users_of_the_inbox_group_are_inbox_representatives(self):\n actor = Actor.lookup('inbox:fa')\n self.assertItemsEqual(\n [self.get_ogds_user(self.secretariat_user)],\n actor.representatives())\n\n def test_contact_has_no_representatives(self):\n actor = Actor.lookup('contact:meier-franz')\n self.assertItemsEqual([], actor.representatives())\n\n def test_all_group_members_are_team_representatives(self):\n actor = Actor.lookup('team:1')\n self.assertItemsEqual(\n [self.get_ogds_user(self.regular_user),\n self.get_ogds_user(self.dossier_responsible)],\n actor.representatives())\n\n\nclass TestActorPermissionIdentifier(IntegrationTestCase):\n\n def test_groupid_is_team_actors_permission_identifier(self):\n actor = Actor.lookup('team:1')\n\n self.assertEquals('projekt_a', actor.permission_identifier)\n","sub_path":"opengever/ogds/base/tests/test_actor_lookup.py","file_name":"test_actor_lookup.py","file_ext":"py","file_size_in_byte":5970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"489554421","text":"import os\nfrom PIL import Image\nimport numpy as np\nfrom pathlib import Path\n\nfrom chainer.dataset import dataset_mixin\n\nclass FacadeDataset(dataset_mixin.DatasetMixin):\n def __init__(self, imgDir='../../Image', contourDir='../../Image_Contour', data_num = 400):\n print(\"load dataset start\")\n print(\"Original Image from: {}\".format(imgDir))\n print(\"Contour Image from: {}\".format(contourDir))\n print(\"Data num: {}\".format(data_num))\n imgDir = Path(imgDir)\n contourDir = Path(contourDir)\n self.dataset = []\n imgs = [img for img in imgDir.iterdir()][:data_num]\n for img_path in imgs:\n img = Image.open(img_path)\n label = Image.open(contourDir/img_path.name)\n label = label.convert(mode='RGB')\n w_in = 512\n img = img.resize((w_in, w_in), Image.BILINEAR)\n label = label.resize((w_in, w_in), Image.NEAREST)\n\n img = np.asarray(img).astype('f').transpose(2,0,1)/128.0-1.0\n label = np.asarray(label).astype('f').transpose(2,0,1)/128.0-1.0\n\n self.dataset.append((img,label))\n print(\"load dataset done\")\n\n def __len__(self):\n return len(self.dataset)\n\n # return (label, img)\n def get_example(self, i, crop_width=256):\n return self.dataset[i][1], self.dataset[i][0]\n","sub_path":"facade_dataset.py","file_name":"facade_dataset.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"183417052","text":"# -*- coding: utf-8 -*-\nfrom flask import Flask, request, jsonify\nimport io\nimport os\nimport base64\nimport firebase_admin\nfrom firebase_admin import credentials, firestore, storage\nfrom google.cloud import vision\nfrom google.cloud.vision import types\nimport time\n\napp = Flask(__name__)\n\n@app.route('/NF/upload', methods = ['POST'])\ndef leituraImagem():\n\n db = configFirebase()\n bucket = configFirebaseStorage()\n\n msg = None\n req_data = request.get_json()\n\n if (validaEntrada(request) != True):\n return jsonify({'msg': \"Erro: Json inválido\"})\n \n NFbase64 = req_data['nroNotaFiscal']\n\n client = vision.ImageAnnotatorClient()\n \n content = None\n imagemNota = None\n try:\n content = base64.b64decode(NFbase64)\n imagemNota = open('nota.jpg', 'wb')\n imagemNota.write(content)\n except:\n print(\"Erro: Não foi possível ler a imagem em formato base64!\")\n return jsonify({\"msg\":\"Erro: Não foi possível ler a imagem em formato base64!\"})\n\n image = types.Image(content=content)\n response = client.text_detection(image=image)\n texts = response.text_annotations\n\n numeroNota = buscaNumeroNF(texts)\n valor = buscaValor(texts)\n codVerificacao = buscaCodVerificacao(texts)\n\n timestamp = (str(time.localtime(time.time()).tm_year) + \"-\"\n + str(time.localtime(time.time()).tm_mon).zfill(2) + \"-\"\n + str(time.localtime(time.time()).tm_mday).zfill(2) + \"-\"\n + str(time.localtime(time.time()).tm_hour).zfill(2) + \"-\"\n + str(time.localtime(time.time()).tm_min).zfill(2) + \"-\"\n + str(time.localtime(time.time()).tm_sec).zfill(2))\n nmeArquivo = \"notas/nota_\" + str(numeroNota) + \"_\" + timestamp + \".jpg\"\n\n blob = bucket.blob(nmeArquivo)\n blob.upload_from_string(content)\n \n doc_ref = db.collection(u'requisicoes').document()\n ret = doc_ref.set({\n u'nroNotaFiscal': numeroNota,\n u'codVerificacao': codVerificacao,\n u'valor': valor,\n u'arquivo': nmeArquivo\n })\n\n retorno = { \"nroNotaFiscal\": numeroNota,\n \"valor\": valor,\n \"codVerificacao\": codVerificacao}\n return jsonify(retorno)\n\n@app.route('/NF/busca/<nota>', methods = ['GET'])\ndef buscarNota(nota):\n\n configFirebase()\n db = configFirebase()\n\n # Use the application default credentials\n if (not len(firebase_admin._apps)):\n firebase_admin.initialize_app()\n\n db = firestore.client()\n\n # Create a query against the collection\n query = db.collection(u'requisicoes').where(u'nroNotaFiscal', u'==', nota).order_by(u'arquivo', direction=firestore.Query.DESCENDING).limit(1).stream()\n\n retorno = None\n for res in query:\n retorno = res.to_dict()\n\n return jsonify(retorno)\n\ndef configFirebase():\n # Use the application default credentials\n if (not len(firebase_admin._apps)):\n firebase_admin.initialize_app()\n\n db = firestore.client()\n return db\n\ndef configFirebaseStorage():\n # Use the application default credentials\n if (not len(firebase_admin._apps)):\n firebase_admin.initialize_app()\n\n bucket = storage.bucket(\"chalengenfsantodigital.appspot.com\")\n return bucket\n\ndef validaEntrada(request):\n if (request.is_json != True):\n return False\n\n req_data = request.get_json()\n\n try:\n NFbase64 = req_data['nroNotaFiscal']\n print(\"Leitura ok do Json\")\n except:\n return False\n \n return True\n\ndef buscaNumeroNF(texts):\n flag1 = False\n flag2 = False\n flag3 = False\n\n for text in texts:\n if (flag3 == True):\n numeroNota = text.description\n flag1 = False\n flag2 = False\n flag3 = False\n return numeroNota\n \n if (text.description == 'Nimero' or text.description == 'Número'):\n flag1 = True\n \n if (text.description == 'de' and flag1 == True):\n flag2 = True\n\n if (text.description == 'Nota' and flag2 == True):\n flag3 = True\n\n\ndef buscaCodVerificacao(texts):\n \n flag1 = False\n flag2 = False\n flag3 = False\n\n for text in texts:\n if (flag3 == True):\n codVerificacao = text.description\n flag1 = False\n flag2 = False\n flag3 = False\n return codVerificacao\n \n if (text.description == 'Código'):\n flag1 = True\n \n if (text.description == 'de' and flag1 == True):\n flag2 = True\n\n if (text.description == 'Verificação' and flag2 == True):\n flag3 = True\n\n\ndef buscaValor(texts):\n \n flag1 = False\n flag2 = False\n flag3 = False\n flag4 = False\n flag5 = False\n\n for text in texts:\n if (flag5 == True):\n valor = text.description\n flag1 = False\n flag2 = False\n flag3 = False\n flag4 = False\n flag5 = False\n return valor\n \n if (text.description == 'VALOR'):\n flag1 = True\n \n if (text.description == 'TOTAL' and flag1 == True):\n flag2 = True\n\n if (text.description == 'DA' and flag2 == True):\n flag3 = True\n\n if (text.description == 'NOTA' and flag3 == True):\n flag4 = True\n\n if (text.description == 'R$' and flag4 == True):\n flag5 = True\n\n\ndef exibirTextoCompleto(texts):\n for text in texts:\n print('\\n\"{}\"'.format(text.description))\n vertices = (['({},{})'.format(vertex.x, vertex.y)\n for vertex in text.bounding_poly.vertices])\n\n print('bounds: {}'.format(','.join(vertices)))\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8080, debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"2052706","text":"#!/usr/bin/python3.5\n\"\"\"\nrender.py\n# This script renders the merged experiments into\n# actions and videos by doing the following\n# 1) Unzipping various mcprs and building render directories\n# containing meta data.\n# 2) Running the action_rendering scripts\n# 3) Running the video_rendering scripts\n\"\"\"\nimport os\nimport shutil\nimport sys\nimport glob\nimport numpy as np\nimport tqdm\nimport zipfile\nimport subprocess\nimport json\nimport time\nimport pyautogui\nimport shutil\nimport psutil\nimport traceback\nimport re\nfrom shutil import copyfile\n\n# 3\n# UTILITIES\n#######################\nJ = os.path.join\nE = os.path.exists\nWORKING_DIR = \"output\"\nMERGED_DIR = J(WORKING_DIR, \"merged\")\nRENDER_DIR = J(WORKING_DIR, \"rendered_new\")\nMINECRAFT_DIR = J('/', 'home', 'hero', 'minecraft')\nRECORDING_PATH = J(MINECRAFT_DIR, 'replay_recordings')\nRENDERED_VIDEO_PATH = J(MINECRAFT_DIR, 'replay_videos')\nRENDERED_LOG_PATH = J(MINECRAFT_DIR, 'replay_logs')\nFINISHED_FILE = J(MINECRAFT_DIR, 'finished.txt')\nLOG_FILE = J(J(MINECRAFT_DIR, 'logs'), 'debug.log') # RAH\nEOF_EXCEP_DIR = J(WORKING_DIR, 'EOFExceptions')\nZEROLEN_DIR = J(WORKING_DIR, 'zeroLengthFiles')\nNULL_PTR_EXCEP_DIR = J(WORKING_DIR, 'nullPointerExceptions')\n\nMC_LAUNCHER = '/home/hero/minecraft/launch.sh'\n# MC_JAR = # This seems to be excluded from the current launcher\n# MC_LAUNCH_ARGS = '-Xmx4G -XX:+UnlockExperimentalVMOptions -XX:+UseG1GC -XX:G1NewSizePercent=20 -XX:G1ReservePercent=20 -XX:MaxGCPauseMillis=50 -XX:G1HeapRegionSize=32M'\nBLACKLIST_PATH = J(WORKING_DIR, \"blacklist.txt\")\n\nEND_OF_STREAM = 'end_of_stream.txt'\nACTION_FILE = \"actions.tmcpr\"\nBAD_MARKER_NAME, GOOD_MARKER_NAME = 'INVALID', 'VALID'\nSKIPPED_RENDER_FLAG = 'SKIPPED_RENDER'\n\nMETADATA_FILES = [\n 'metaData.json',\n 'markers.json',\n 'mods.json',\n 'stream_meta_data.json']\n\n\ndef touch(path):\n with open(path, 'w'):\n pass\n\n\ndef remove(path):\n if E(path):\n os.remove(path)\n\n\ndef get_recording_archive(recording_name):\n \"\"\"\n Gets the zipfile object of a mcpr recording.\n \"\"\"\n mcpr_path = J(MERGED_DIR, (recording_name + \".mcpr\"))\n assert E(mcpr_path)\n\n return zipfile.ZipFile(mcpr_path)\n\n##################\n# PIPELINE\n#################\n\n# 1. Construct render working dirs.\n\n\ndef construct_render_dirs(blacklist):\n \"\"\"\n Constructs the render directories omitting\n elements on a blacklist.\n \"\"\"\n if not E(RENDER_DIR):\n os.makedirs(RENDER_DIR)\n # We only care about unrendered directories.\n render_dirs = []\n\n for filename in tqdm.tqdm(os.listdir(MERGED_DIR)):\n if filename.endswith(\".mcpr\") and filename not in blacklist:\n recording_name = filename.split(\".mcpr\")[0]\n render_path = J(RENDER_DIR, recording_name)\n print(render_path)\n if not E(render_path):\n os.makedirs(render_path)\n\n render_dirs.append((recording_name, render_path))\n\n return render_dirs\n\n# 2. render metadata from the files.\n\n\ndef render_metadata(renders: list) -> list:\n \"\"\"\n Unpacks the metadata of a recording and checks its validity.\n \"\"\"\n good_renders = []\n bad_renders = []\n\n for recording_name, render_path in tqdm.tqdm(renders):\n if E(render_path):\n # Check if metadata has already been extracted.\n if (E(J(render_path, GOOD_MARKER_NAME)) or\n E(J(render_path, BAD_MARKER_NAME))):\n # If it has been computed see if it is valid\n # or not.\n if E(J(render_path, GOOD_MARKER_NAME)):\n good_renders.append((recording_name, render_path))\n else:\n bad_renders.append((recording_name, render_path))\n else:\n try:\n recording = get_recording_archive(recording_name)\n\n def extract(fname): return recording.extract(\n fname, render_path)\n\n # Test end of stream validity.\n #with open(extract(END_OF_STREAM), 'r') as eos:\n # assert len(eos.read()) > 0\n\n # If everything is good extfct the metadata.\n for mfile in METADATA_FILES:\n assert str(mfile) in [str(x)\n for x in recording.namelist()]\n extract(mfile)\n\n # check that stream_meta_data is good\n with open(J(render_path, 'metaData.json'), 'r') as f:\n# print(render_path)\n jbos = json.load(f)\n assert (jbos[\"duration\"] > 60000 or jbos[\"duration\"] == 0)\n\n # check that stream_meta_data is good\n with open(J(render_path, 'stream_meta_data.json'), 'r') as f:\n jbos = json.load(f)\n assert jbos[\"has_EOF\"]\n assert not jbos[\"miss_seq_num\"]\n\n touch(J(render_path, GOOD_MARKER_NAME))\n good_renders.append((recording_name, render_path))\n except (json.decoder.JSONDecodeError, AssertionError) as e:\n _, _, tb = sys.exc_info()\n traceback.print_tb(tb) # Fixed format\n # Mark that this is a bad file.\n touch(J(render_path, BAD_MARKER_NAME))\n remove(J(render_path, GOOD_MARKER_NAME))\n bad_renders.append((recording_name, render_path))\n\n return good_renders, bad_renders\n\n# 2.Renders the actions.\n\n\ndef render_actions(renders: list):\n \"\"\"\n For every render directory, we render the actions\n \"\"\"\n good_renders = []\n bad_renders = []\n\n for recording_name, render_path in tqdm.tqdm(renders):\n if E(J(render_path, 'network.npy')):\n if E(J(render_path, GOOD_MARKER_NAME)):\n good_renders.append((recording_name, render_path))\n else:\n bad_renders.append((recording_name, render_path))\n else:\n try:\n recording = get_recording_archive(recording_name)\n\n def extract(fname): return recording.extract(\n fname, render_path)\n\n # Extract actions\n assert str(ACTION_FILE) in [str(x)\n for x in recording.namelist()]\n # Extract it if it doesnt exist\n action_mcbr = extract(ACTION_FILE)\n # Check that it's not-empty.\n assert not os.stat(action_mcbr).st_size == 0\n\n # Run the actual parse action and make sure that its actually of length 0.\n p = subprocess.Popen([\"python3\", \"parse_action.py\", os.path.abspath(\n action_mcbr)], cwd='action_rendering')\n returncode = (p.wait())\n assert returncode == 0\n\n good_renders.append((recording_name, render_path))\n except AssertionError as e:\n _, _, tb = sys.exc_info()\n traceback.print_tb(tb) # Fixed format\n touch(J(render_path, BAD_MARKER_NAME))\n remove(J(render_path, GOOD_MARKER_NAME))\n bad_renders.append((recording_name, render_path))\n\n return good_renders, bad_renders\n\n# 3.Render the video encodings\n\n# RAH - Kill MC (or any process) given the PID\ndef killMC(pid):\n process = psutil.Process(int(pid))\n for proc in process.children(recursive=True):\n proc.kill()\n process.kill()\n\n# RAH Launch MC - return the process so we can kill later if needed\ndef launchMC():\n # Run the Mine Craft Launcher\n p = subprocess.Popen(\n MC_LAUNCHER)#, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n print(\"Launched \", MC_LAUNCHER)\n\n # x = 388\n # y = 626\n # print(\"Launching Minecraft: \", end='', flush=True)\n # pyautogui.moveTo(x, y)\n # delay = 5\n # for i in range(delay):\n # print(delay-i, ' ', end='', flush=True)\n # time.sleep(1)\n # print(\"0\")\n\n # # Click on the launcher button that starts Minecraft\n # pyautogui.click(x, y)\n # print(\"\\tWaiting for it to load:\", end='', flush=True)\n # pyautogui.click(x, y) # Click on the launcher button that starts Minecraft\n # delay = 5\n # for i in range(delay):\n # print((delay-i) * 5, '', end='', flush=True)\n # time.sleep(5)\n # print(\"0\")\n time.sleep(10)\n return p\n\n\ndef launchReplayViewer():\n x = 860 # 1782\n y = 700 # 1172\n #pyautogui.moveTo(x, y)\n print(\"\\tLaunching ReplayViewer: \", end='', flush=True)\n delay = 5\n for i in range(delay):\n print(delay-i, '', end='', flush=True)\n time.sleep(1)\n print(\"0\")\n #pyautogui.click(x, y) # Then click the button that launches replayMod\n\n\ndef render_videos(renders: list):\n \"\"\"\n For every render directory, we render the videos.\n This works by:\n 1) Copying the file to the minecraft directory\n 2) Waiting for user input:\n User render the video using replay mod and hit enter once the video is rendered\n 3) Copying the produced mp4 to the rendered directory\n\n \"\"\"\n # Restart minecraft after so many renders\n maxConsecutiveRenders = 8\n numSuccessfulRenders = 0\n\n # Remove any finished file flags to prevent against copying unfinished renders\n try:\n os.remove(FINISHED_FILE)\n except FileNotFoundError:\n pass\n\n # Clear recording directory to protect against crash messages\n for messyFile in glob.glob(J(RECORDING_PATH, '*')):\n try:\n os.remove(messyFile)\n except IsADirectoryError:\n shutil.rmtree(messyFile)\n\n p = launchMC() # RAH launchMC() now returns subprocess - use p.PID to get process ID\n for recording_name, render_path in tqdm.tqdm(renders):\n # Get mcpr file from merged\n print(\"Rendering:\", recording_name, '...')\n\n # Skip if the folder has an recording already\n # * means all if need specific format then *.csv\n list_of_files = glob.glob(J(render_path, '*.mp4'))\n if len(list_of_files):\n print(\"\\tSkipping: replay folder contains\", list_of_files[0])\n continue\n\n # Skip if the file has been skipped allready\n skip_path = J(render_path, SKIPPED_RENDER_FLAG)\n if E(skip_path):\n print(\"\\tSkipping: file was previously skipped\")\n continue\n\n mcpr_path = J(MERGED_DIR, (recording_name + \".mcpr\"))\n\n copyfile(mcpr_path, J(RECORDING_PATH, (recording_name + \".mcpr\")))\n copy_time = os.path.getmtime(\n J(RECORDING_PATH, (recording_name + \".mcpr\")))\n\n # Presses the ReplayViewer() button - this step can be automated in the code, but this is cleaner\n launchReplayViewer()\n logFile = open(LOG_FILE, 'r', os.O_NONBLOCK)\n lineCounter = 0 # RAH So we can print line number of the error\n\n # Wait for completion (it creates a finished.txt file)\n video_path = None\n notFound = True\n while notFound:\n if os.path.exists(FINISHED_FILE):\n os.remove(FINISHED_FILE)\n notFound = False\n numSuccessfulRenders += 1\n if(numSuccessfulRenders > maxConsecutiveRenders):\n killMC(p.pid)\n time.sleep(5)\n p = launchMC()\n else:\n # RAH Begin - this could be cleaner\n logLine = logFile.readline()\n if len(logLine) > 0:\n lineCounter += 1\n m = re.search(r\"java.io.EOFException:\", logLine)\n if m:\n print(\"\\tline {}: {}\".format(lineCounter, logLine))\n print(\"\\tfound java.io.EOFException\")\n killMC(p.pid)\n time.sleep(5) # Give the OS time to release this file\n try:\n os.rename(J(RECORDING_PATH, recording_name+'.mcpr'),\n J(EOF_EXCEP_DIR, recording_name+'.mcpr'))\n shutil.copy(LOG_FILE, J(\n EOF_EXCEP_DIR, recording_name+'.log'))\n except:\n pass\n try:\n shutil.rmtree(\n J(RECORDING_PATH, recording_name+'.mcpr.tmp'))\n except:\n pass\n\n p = launchMC()\n break # Exit the current file processing loop and process the next file\n\n m = re.search(\n r\"Adding time keyframe at \\d+ time -\\d+\", logLine)\n if m:\n print(\"\\tline {}: {}\".format(lineCounter, logLine))\n print(\"\\tfound 0 length file\")\n killMC(p.pid)\n time.sleep(15) # Give the OS time to release this file\n try:\n os.rename(J(RECORDING_PATH, recording_name+'.mcpr'),\n J(ZEROLEN_DIR, recording_name+'.mcpr'))\n shutil.copy(LOG_FILE, J(\n ZEROLEN_DIR, recording_name+'.log'))\n except:\n pass\n try:\n shutil.rmtree(J(RECORDING_PATH, recording_name+'.mcpr.tmp'))\n with open(skip_path, 'a'):\n try:\n os.utime(skip_path, None) # => Set skip time to now\n except OSError:\n pass # File deleted between open() and os.utime() calls\n except:\n pass\n p = launchMC()\n break # Exit the current file processing loop and process the next file\n\n m = re.search(r\"java.lang.NullPointerException\", logLine)\n if m:\n print(\"\\tline {}: {}\".format(lineCounter, logLine),)\n print(\"\\tNullPointerException\")\n killMC(p.pid)\n # Give the OS time to release this file nullPointerException needs more time than others\n time.sleep(20)\n print(J(RECORDING_PATH, recording_name+'.mcpr'),\n J(NULL_PTR_EXCEP_DIR, recording_name+'.mcpr'))\n try:\n os.rename(J(RECORDING_PATH, recording_name+'.mcpr'),\n J(NULL_PTR_EXCEP_DIR, recording_name+'.mcpr'))\n shutil.copy(LOG_FILE, J(\n NULL_PTR_EXCEP_DIR, recording_name+'.log'))\n except:\n pass\n try:\n shutil.rmtree(\n J(RECORDING_PATH, recording_name+'.mcpr.tmp'))\n with open(skip_path, 'a'):\n try:\n os.utime(skip_path, None) # => Set skip time to now\n except OSError:\n pass # File deleted between open() and os.utime() calls\n except:\n pass\n p = launchMC()\n break # Exit the current file processing loop and process the next file\n # RAH End\n\n # * means all if need specific format then *.cs\n list_of_files = glob.glob( J(RENDERED_VIDEO_PATH, '*.mp4'))\n # GET RECORDING\n if len(list_of_files) > 0:\n # Check that this render was created after we copied\n video_path = max(list_of_files, key=os.path.getmtime)\n if os.path.getmtime(video_path) < copy_time:\n print(\"\\tError! Rendered file is older than replay!\")\n # user_input = input(\"Are you sure you want to copy this out of date render? (y/n)\")\n # if \"y\" in user_input:\n # print(\"using out of date recording\")\n # else:\n print(\"\\tskipping out of date rendering\")\n video_path = None\n\n # GET UNIVERSAL ACTION FORMAT SHIT.\n list_of_logs = glob.glob( J(RENDERED_LOG_PATH, '*.json'))\n if len(list_of_logs) > 0:\n # Check that this render was created after we copied\n log_path = max(list_of_logs, key=os.path.getmtime)\n if os.path.getmtime(log_path) < copy_time:\n print(\"\\tError! Rendered log! is older than replay!\")\n # user_input = input(\"Are you sure you want to copy this out of date render? (y/n)\")\n # if \"y\" in user_input:\n # print(\"using out of date recording\")\n # else:\n print(\"\\tskipping out of date rendering\")\n log_path = None\n\n # GET new markers.json SHIT.\n list_of_logs = glob.glob( J(RENDERED_VIDEO_PATH, '*.json'))\n if len(list_of_logs) > 0:\n # Check that this render was created after we copied\n marker_path = max(list_of_logs, key=os.path.getmtime)\n if os.path.getmtime(marker_path) < copy_time:\n print(\"\\tError! Rendered log! is older than replay!\")\n # user_input = input(\"Are you sure you want to copy this out of date render? (y/n)\")\n # if \"y\" in user_input:\n # print(\"using out of date recording\")\n # else:\n print(\"\\tskipping out of date rendering\")\n marker_path = None\n\n\n if not video_path is None and not log_path is None and not marker_path is None:\n print(\"\\tCopying file\", video_path, '==>\\n\\t',\n render_path, 'created', os.path.getmtime(video_path))\n os.rename(video_path, J(render_path, 'recording.mp4'))\n print(\"\\tCopying file\", log_path, '==>\\n\\t',\n render_path, 'created', os.path.getmtime(log_path))\n os.rename(log_path, J(render_path, 'univ.json'))\n\n print(\"\\tRecording start and stop timestamp for video\")\n metadata = json.load(open(J(render_path, 'stream_meta_data.json')))\n videoFilename = video_path.split('/')[-1]\n\n metadata['start_timestamp'] = int(videoFilename.split('_')[1])\n metadata['stop_timestamp'] = int(\n videoFilename.split('_')[2].split('-')[0])\n with open(marker_path) as markerFile:\n metadata['markers'] = json.load(markerFile)\n json.dump(metadata, open(\n J(render_path, 'stream_meta_data.json'), 'w'))\n else:\n print(\"\\tNo Video file found\")\n print(\"\\tSkipping this file in the future\")\n with open(skip_path, 'a'):\n try:\n os.utime(skip_path, None) # => Set skip time to now\n except OSError:\n pass # File deleted between open() and os.utime() calls\n # Remove mcpr file from dir\n try:\n os.remove(J(RECORDING_PATH, (recording_name + \".mcpr\")))\n except:\n pass\n killMC(p.pid)\n\n\ndef main():\n \"\"\"\n The main render script.\n \"\"\"\n # 1. Load the blacklist.\n blacklist = set(np.loadtxt(BLACKLIST_PATH, dtype=np.str).tolist())\n\n print(\"Constructing render directories.\")\n renders = construct_render_dirs(blacklist)\n\n print(\"Validating metadata from files:\")\n valid_renders, invalid_renders = render_metadata(renders)\n print(len(valid_renders))\n # print(\"Rendering actions: \")\n # valid_renders, invalid_renders = render_actions(valid_renders)\n print(\"... found {} valid recordings and {} invalid recordings\"\n \" out of {} total files\".format(\n len(valid_renders), len(invalid_renders), len(os.listdir(MERGED_DIR)))\n )\n print(\"Rendering videos: \")\n render_videos(valid_renders)\n\n # from IPython import embed; embed()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":20511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"620221685","text":"import network\nimport machine\nimport os\nimport upip\nfrom time import sleep_ms\n\nlan = network.LAN(mdc = machine.Pin(23), mdio = machine.Pin(18), power=machine.Pin(12), phy_type = network.PHY_LAN8720, phy_addr=0, clock_mode=network.ETH_CLOCK_GPIO17_OUT)\nlan.active(True)\ntimer = 0\nwhile not lan.isconnected():\n timer += 1\n if timer > 300000: # Well, this is sketchy AF\n raise Exception (\"Network took too long\")\nsleep_ms(5000)\nupip.install(\"micropython-uasyncio\")\nupip.install(\"micropython-uasyncio.queues\")\nupip.install(\"micropython-utarfile\")\n\nif \"tmp\" not in os.listdir():\n os.mkdir(\"tmp\")\n\nif \"firmware\" not in os.listdir():\n os.mkdir(\"firmware\")\n\nimport utarfile\nfor fn in os.listdir():\n if fn.endswith(\".tar\"):\n t = utarfile.TarFile(fn)\n for i in t:\n print(i)\n if i.type == utarfile.DIRTYPE:\n os.mkdir(i.name)\n else:\n tf = t.extractfile(i)\n with open(i.name, \"wr\") as f:\n f.write(tf.read())\n","sub_path":"hardware/keypad_fw/bootstrap.py","file_name":"bootstrap.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"188493528","text":"\"\"\"\nWrite a Python program that find the value of a raised to the power b recursively.\n\nThe operation is a**b in Python, where a is the base and b is the exponent.\n\nIf the value of b is 0, the result is automatically 1 because every number raised to the power 0 is 1.\n\"\"\"\n\ndef calculate_power(a, b):\n if b == 0:\n return 1\n elif b == 1:\n return a\n else:\n return a * calculate_power(a, b-1)\n\nprint(calculate_power(2, 1))","sub_path":"Basic Python/recursion/power.py","file_name":"power.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"600555724","text":"from kh_common.config.credentials import message_queue\nfrom kh_common import getFullyQualifiedClassName\nfrom traceback import format_tb\nfrom kh_common import logging\nimport pika\nimport sys\n\n\nclass Receiver :\n\n\tdef __init__(self) :\n\t\tself._route = message_queue['routing_key']\n\t\tself._connection_info = message_queue['connection_info']\n\t\tself._channel_info = message_queue['channel_info']\n\t\tself._exchange_info = message_queue.get('exchange_info')\n\t\tself.logger = logging.getLogger(__name__)\n\n\n\tdef consumer(self) :\n\t\tyield from self._recv()\n\n\n\tdef receiveAll(self) :\n\t\treturn list(self._recv())\n\n\n\tdef receiveJson(self, forcelist=False) :\n\t\tif forcelist :\n\t\t\treturn list(map(json.loads, self._recv()))\n\t\telse :\n\t\t\treturn map(json.loads, self._recv())\n\n\n\tdef _recv(self) :\n\t\tconnection = None\n\t\ttry :\n\t\t\t# returns a list of all messages retrieved from the message queue\n\t\t\tconnection = pika.BlockingConnection(pika.ConnectionParameters(**self._connection_info))\n\t\t\tchannel = connection.channel()\n\n\t\t\tif self._exchange_info :\n\t\t\t\tchannel.exchange_declare(**self._exchange_info)\n\t\t\t\tname = channel.queue_declare(self._route).method.queue\n\t\t\t\tchannel.queue_bind(routing_key=self._route, queue=name, exchange=self._exchange_info['exchange'])\n\n\t\t\telse :\n\t\t\t\tchannel.queue_declare(self._route)\n\t\t\t\tname = self._route\n\n\t\t\tit = channel.consume(name, **self._channel_info)\n\n\t\t\tack = -1\n\t\t\tfor method_frame, _, body in it :\n\t\t\t\tif body :\n\t\t\t\t\tyield body\n\t\t\t\t\tack = max(ack, method_frame.delivery_tag)\n\t\t\t\telse :\n\t\t\t\t\tbreak\n\n\t\t\tif ack >= 0 :\n\t\t\t\tchannel.basic_ack(delivery_tag=ack, multiple=True)\n\n\t\t\tchannel.cancel()\n\t\tfinally :\n\t\t\t# don't channel.cancel here since, if it fails, we want the messages to remain in the queue\n\t\t\ttry :\n\t\t\t\tif connection :\n\t\t\t\t\tconnection.close()\n\n\t\t\texcept :\n\t\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\t\tself.logger.warning({\n\t\t\t\t\t'message': f'{GetFullyQualifiedClassName(exc_obj)}: {exc_obj}',\n\t\t\t\t\t'stacktrace': format_tb(exc_tb),\n\t\t\t\t})\n","sub_path":"kh_common/message_queue.py","file_name":"message_queue.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"179890971","text":"#!/usr/bin/python\nfrom Crypto.Cipher import AES\nfrom binascii import b2a_hex, a2b_hex\nfrom base64 import b64encode, b64decode\n\ndef aes_ecb_decrypt(ct,key,blocksize):\n assert len(ct) % blocksize == 0\n obj = AES.new(key=key,mode=AES.MODE_ECB)\n plaintext = obj.decrypt(ct)\n return plaintext\n\ndef main():\n block_size = 16\n key = b'YELLOW SUBMARINE'\n with open('07.txt') as f:\n ciphertext = b64decode(f.read())\n plaintext = aes_ecb_decrypt(ciphertext,key,block_size)\n print(plaintext)\n\nif __name__ == \"__main__\":\n main()","sub_path":"set1/challenge07.py","file_name":"challenge07.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"465157554","text":"import csv\nimport numpy as np\nimport os\nimport shutil\nimport time\n\n\nclass time_ticker(object):\n def __init__(self):\n self.init_time = time.time()\n\n def begin(self):\n self.init_time = time.time()\n\n def tick(self, token, save_path=None):\n interval_time = time.time() - self.init_time\n self.init_time = time.time()\n # print('{0}: {1}'.format(token, interval_time))\n if save_path is not None:\n write_file(save_path, '{0}: {1}\\n'.format(token, interval_time), False)\n return interval_time\n\n\ndef action_format_transfer(index):\n \"\"\"\n Transfer action from scalar to a list.\n :param index:\n :return:\n \"\"\"\n action_0 = index // 3\n action_1 = index % 3\n return [action_0, action_1]\n\n\n# 0 -- idle & idle --> [4, 2] --> 14\n# 1 -- left & dribble --> [2, 2] --> 12\n# 2 -- right & dribble --> [3, 2] --> 13\n# 3 -- up & dribble --> [0, 2] --> 10\n# 4 -- down & dribble --> [1, 2] --> 11\n# 5 -- idle & shot_low --> [4, 0] --> 4\n# 6 -- left & shot_low --> [2, 0] --> 2\n# 7 -- right & shot_low --> [3, 0] --> 3\n# 8 -- up & shot_low --> [0, 0] --> 0\n# 9 -- down & shot_low --> [1, 0] --> 1\n\ndef action_ind2lst(ind):\n if ind == 0:\n return [4, 2]\n elif ind == 1:\n return [2, 2]\n elif ind == 2:\n return [3, 2]\n elif ind == 3:\n return [0, 2]\n elif ind == 4:\n return [1, 2]\n elif ind == 5:\n return [4, 0]\n elif ind == 6:\n return [2, 0]\n elif ind == 7:\n return [3, 0]\n elif ind == 8:\n return [0, 0]\n elif ind == 9:\n return [1, 0]\n else:\n raise ValueError(\"Invalid action index!\")\n\n\ndef action_lst2ind(lst):\n if lst == [4, 2]:\n return 0\n elif lst == [2, 2]:\n return 1\n elif lst == [3, 2]:\n return 2\n elif lst == [0, 2]:\n return 3\n elif lst == [1, 2]:\n return 4\n elif lst == [4, 0]:\n return 5\n elif lst == [2, 0]:\n return 6\n elif lst == [3, 0]:\n return 7\n elif lst == [0, 0]:\n return 8\n elif lst == [1, 0]:\n return 9\n else:\n raise ValueError(\"Invalid action index!\")\n\n\ndef action_ind2lst_15acts(ind):\n assert 0 <= ind <= 14\n return [int(ind % 5), int(ind // 5)]\n\n\ndef action_lst2ind_15acts(lst):\n return int(lst[0] + lst[1] * 5)\n\n\n# def action_grf2cvfifa(ind):\n# \"\"\"\n# Transfer grf action (int) to cvFIFA action (list).\n# :param index:\n# :return:\n# \"\"\"\n# action_mapping = [14, 12, 13, 10, 11, 4, 2, 3, 0, 1]\n# index_mapping = int(action_mapping[ind])\n# action_0 = index_mapping % 5\n# action_1 = index_mapping // 5\n# result = [action_0, action_1]\n# print(\"Action mapping: {0} --> {1}\".format(ind, result))\n# return result\n#\n#\n# def action_cvfifa2grf(lst):\n# \"\"\"\n# Transfer cvFIFA action (list) to grf action (int).\n# :param index:\n# :return:\n# \"\"\"\n# ind = int(lst[0] + lst[1] * 5)\n# action_mapping = [8, 9, 6, 7, 5, -1, -1, -1, -1, -1, 3, 4, 1, 2, 0]\n# ind_mapping = int(action_mapping[ind])\n# assert ind_mapping > 0\n# return ind_mapping\n\n\ndef exist_or_create_folder(path_name):\n \"\"\"\n Check whether a path exists, if not, then create this path.\n :param path_name: i.e., './logs/log.txt' or './logs/'\n :return: flag == False: failed; flag == True: successful.\n \"\"\"\n flag = False\n pure_path = os.path.dirname(path_name)\n if not os.path.exists(pure_path):\n try:\n os.makedirs(pure_path)\n flag = True\n except OSError:\n pass\n return flag\n\n\ndef my_print(content, signal):\n print(signal*10, str(content), signal*10)\n\n\ndef write_file(path, content, overwrite=False):\n \"\"\"\n Write data to file.\n :param path:\n :param content:\n :param overwrite: open file by 'w' (True) or 'a' (False)\n :return:\n \"\"\"\n exist_or_create_folder(path)\n if overwrite is True:\n with open(path, 'w') as f:\n f.write(str(content))\n else:\n with open(path, 'a') as f:\n f.write(content)\n\n\ndef read_file(path):\n \"\"\"\n Read data from file.\n :param path:\n :return:\n \"\"\"\n # Check the file path.\n if os.path.exists(os.path.dirname(path)):\n with open(path, 'r') as fo:\n data = fo.read()\n else:\n data = 'NONE'\n return data\n\n\ndef write_csv_file(path, data, overwrite=False):\n \"\"\"\n Write data to csv file.\n :param path:\n :param data: list\n :param overwrite: open file by 'w' (True) or 'a' (False)\n :return:\n \"\"\"\n exist_or_create_folder(path)\n # Write data.\n if overwrite is True:\n with open(path, 'w', newline='') as csv_file:\n writer = csv.writer(csv_file)\n writer.writerow(data)\n else:\n with open(path, 'a', newline='') as csv_file:\n writer = csv.writer(csv_file)\n writer.writerow(data)\n\n\ndef read_csv_file_to_int(path):\n \"\"\"\n Read data from csv file.\n :param path:\n :return: One element is one row.\n \"\"\"\n list_rows = []\n with open(path, encoding='utf-8') as fo:\n csv_reader = csv.reader(fo)\n for row in csv_reader:\n list_rows.append(row)\n rows = len(list_rows)\n all_data = list_rows[0]\n for i in range(rows):\n all_data += list_rows[i]\n for j in range((len(all_data))):\n all_data[j] = int(float(all_data[j]))\n return all_data\n\n\ndef copy_rename_folder(oldpath, newpath, new_name):\n \"\"\"\n Copy a folder and rename it.\n :param oldpath: string\n :param newpath: string\n :param new_name: string\n :return:\n \"\"\"\n # Check the old path.\n if os.path.exists(os.path.dirname(oldpath)):\n try:\n shutil.copytree(oldpath, newpath)\n os.rename(newpath, new_name)\n except OSError: # Guard against race condition\n print('Warning: old path is not valid!')\n raise\n\n\ndef seg_reward(reward):\n \"\"\"\n make the reward more centralized.\n :param reward:\n :return:\n \"\"\"\n if -0.1 < reward <= 0.005:\n n_reward = -0.1\n elif 0.005 < reward < 0.01:\n n_reward = 0\n elif 0.01 <= reward < 0.1:\n n_reward = 0.1\n else:\n n_reward = round(reward, 3)\n return n_reward\n\n\n# ---------------New for weekly report--------------- #\ndef difference(state1, state2):\n return np.sum(np.abs(np.subtract(state1, state2)))\n# ---------------New for weekly report--------------- #\n\n\ndef main():\n # for i in range(15):\n # print('{0} : {1}'.format(i, action_format_transfer(i)))\n a = np.array([1, 1, 1, 1, 1, 1, 1, 1])\n b = np.array([-1, 2, 3, 1, 0, -2, -3, 1])\n print(difference(a, b))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"rl/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"520680208","text":"#Stephen Barton Jr\r\n#Python Classes, Cars\r\n#25 APR 2019\r\n\r\nclass Car:\r\n def __init__(self, year, make, speed):\r\n self.__year = year\r\n self.__make = make\r\n self.__speed = speed\r\n \r\n def set_year(self, year):\r\n self.__year = year\r\n \r\n def set_make(self, make):\r\n self.__make = make\r\n \r\n def set_speed(self, speed):\r\n self.__speed = speed\r\n \r\n def get_year(self):\r\n return self.__year\r\n \r\n def get_make(self):\r\n return self.__make\r\n \r\n def accelerate(self, speed):\r\n self.__speed += 5\r\n \r\n def brake(self, speed):\r\n if self.__speed > 0:\r\n self.__speed -= 5\r\n else:\r\n print(\"Error: The vehicle is not moving.\")\r\n \r\n def get_speed(self):\r\n return self.__speed\r\n \r\n def __str__(self):\r\n return \"Year: \" + self.__year + \\\r\n \"\\nMake: \" + self.__make\r\n \r\ndef main():\r\n year = input(\"Enter the Year of your vehicle: \")\r\n make = input(\"Enter the Make of your vehicle: \")\r\n speed = 0\r\n car = Car(year, make, speed)\r\n \r\n ACCELERATE = 1\r\n BRAKE = 2\r\n CURRENT = 3\r\n CAR_INFO = 4\r\n QUIT = 5\r\n \r\n choice = 0\r\n \r\n while choice != QUIT:\r\n choice = int(input(\"1 = accel, 2 = brake, 3 = current, 4 = car info, 5 = quit: \"))\r\n \r\n if choice == ACCELERATE:\r\n for count in range (1,6):\r\n car.accelerate(speed)\r\n print(\"Current speed: \" + str(car.get_speed()))\r\n elif choice == BRAKE:\r\n for count in range (1,6):\r\n car.brake(speed)\r\n print(\"Current speed: \" + str(car.get_speed()))\r\n elif choice == CURRENT:\r\n print(\"Current speed: \" + str(car.get_speed()))\r\n elif choice == CAR_INFO:\r\n print(car)\r\n if choice == QUIT:\r\n print(\"End of Program\")\r\nmain()","sub_path":"Python/class/cars.py","file_name":"cars.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"260258364","text":"import random\nimport gc\nimport requests\n\nyahooHeadlineURLList=[\n \"https://news.yahoo.co.jp/pickup/rss.xml\",\n \"https://news.yahoo.co.jp/pickup/domestic/rss.xml\",\n \"https://news.yahoo.co.jp/pickup/world/rss.xml\",\n \"https://news.yahoo.co.jp/pickup/entertainment/rss.xml\",\n \"https://news.yahoo.co.jp/pickup/computer/rss.xml\",\n \"https://news.yahoo.co.jp/pickup/local/rss.xml\",\n \"https://news.yahoo.co.jp/pickup/domestic/rss.xml\",\n \"https://news.yahoo.co.jp/pickup/sports/rss.xml\",\n \"https://news.yahoo.co.jp/pickup/science/rss.xml\"\n ]\n\ntabooWords=[\"殺\", \"軍\", \"死\"] #突っ込みによって不謹慎になりそうなのを外す\n\ndef getYahooHeadline(categoryIndex):\n if categoryIndex < len(yahooHeadlineURLList):\n categoryURL = yahooHeadlineURLList[categoryIndex]\n else:\n categoryURL = random.choice(yahooHeadlineURLList)\n \n #Yahooヘッドライン取得(XML)\n yahooHeadLineResponse = requests.get(categoryURL)\n yahooHeadLine = yahooHeadLineResponse.text\n \n titleTextList = []\n titleCount = 0\n startIndex = 0\n #<title>との間を取得。最初のtitleはニュースカテゴリ名だけど気にせず読む。\n while titleCount < 10: #念のためMAX10まで\n yahooHeadLine = yahooHeadLine[startIndex:-1]#前回検索対象となった部分以降のみ取得\n titleStartIndex = yahooHeadLine.find(\"\")\n titleEndIndex = yahooHeadLine.find(\"\")\n if titleStartIndex == -1:\n break\n titleStartIndex = titleStartIndex + 7 #の分をずらす\n titleText = yahooHeadLine[titleStartIndex:titleEndIndex]\n #不謹慎フィルター\n tabooFind = False\n for tabooword in tabooWords:\n if titleText.find(tabooword) != -1:\n tabooFind = True\n break\n if tabooFind == False:\n titleTextList.append(titleText)\n\n startIndex = titleEndIndex + 1 #以降、この後ろから探す\n titleCount = titleCount + 1\n\n gc.collect()\n return titleTextList\n\ndef getCategoryCount():\n return len(yahooHeadlineURLList)","sub_path":"nanikaHeadlineHost/YahooHeadline.py","file_name":"YahooHeadline.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"573659820","text":"import pickle\n\ndef bigram_classifier():\n\tdata = open('/home/utoniumharsha/HARSHA/NLP/NLP_Project/training_data.txt', 'r')\n\n\tpositive = {}\n\tnegative = {}\n\tbigram_vocabulary = {}\n\n\twith open('bigram_vocabulary.pickle', 'rb') as handle:\n\t\tbigram_vocabulary = pickle.load(handle)\n\n\twith open('positive_bigrams_count.pickle', 'rb') as handle:\n\t\tbigram_positive = pickle.load(handle)\n\n\twith open('negative_bigrams_count.pickle', 'rb') as handle:\n\t\tbigram_negative = pickle.load(handle)\n\n\tpositive_prob = {}\n\tnegative_prob = {}\n\n\tV = len(bigram_vocabulary)\n\tCount_Positive = 0\n\tCount_Negative = 0\n\n\tfor word1 in bigram_positive:\n\t\tfor word2 in bigram_positive[word1]:\n\t\t\tCount_Positive += int(bigram_positive[word1][word2])\n\n\tfor word1 in bigram_negative:\n\t\tfor word2 in bigram_negative[word1]:\n\t\t\tCount_Negative += int(bigram_negative[word1][word2])\n\n\tfor word1 in bigram_positive:\n\t\tpositive_prob[word1] = {}\n\t\tfor word2 in bigram_positive[word1]:\n\t\t\tpositive_prob[word1][word2] = (int (bigram_positive[word1][word2]) + 1.0 ) / (Count_Positive + V)\n\n\tfor word1 in bigram_negative:\n\t\tnegative_prob[word1] = {}\n\t\tfor word2 in bigram_negative[word1]:\n\t\t\tnegative_prob[word1][word2] = (int (bigram_negative[word1][word2]) + 1.0 ) / (Count_Negative + V)\n\n\n\twith open('bigram_nbayes_positive_prob.pickle', 'wb') as handle:\n\t\tpickle.dump(positive_prob, handle)\n\n\twith open('bigram_nbayes_negative_prob.pickle', 'wb') as handle:\n\t\tpickle.dump(negative_prob, handle)\n\t\n#bigram_classifier()","sub_path":"bigram_naive_bayes_classifier.py","file_name":"bigram_naive_bayes_classifier.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"216401049","text":"from tkinter import *\n\nroot = Tk()\nlabel = Label(root, text=\"What is the answer of 99-47\")\nlabel.config(font =(\"Italic\",22))\n\ndef click():\n label_2 = Label(root, text=\"Wrong\")\n label_2.config(font =(\"Calibri\",18))\n label_2.pack()\n\nbtn = Button(root, text=\"1000\", width=5,height=2,bg = \"Lime\",fg = \"black\",command=click)\nbtn.config(font =(\"Italic\",22))\n\ndef click_2():\n label_3 = Label(root, text=\"Wrong\")\n label_3.config(font =(\"Calibri\",18))\n label_3.pack()\n\nbtn_2 = Button(root, text=\"199\", width=5,height=2,bg = \"Lime\",fg = \"black\",command=click_2)\nbtn_2.config(font =(\"Italic\",22))\n\ndef click_3():\n label_4 = Label(root, text=\"Wrong\")\n label_4.config(font =(\"Calibri\",18))\n label_4.pack()\n \nbtn_3 = Button(root, text=\"50\", width=5,height=2,bg = \"Lime\",fg = \"black\",command=click_3)\nbtn_3.config(font =(\"Italic\",22))\n \ndef click_4():\n label_5 = Label(root, text=\"Correct\")\n label_5.config(font =(\"Calibri\",18))\n label_5.pack()\n \nbtn_4 = Button(root, text=\"52\", width=5,height=2,bg = \"Lime\",fg = \"black\",command=click_4)\nbtn_4.config(font =(\"Italic\",22))\n\ndef click_5():\n label_6 = Label(root, text=\"wrong\")\n label_6.config(font =(\"Calibri\",18))\n label_6.pack()\n \nbtn_5 = Button(root, text=\"2000\", width=5,height=2,bg = \"Lime\",fg = \"black\",command=click_5)\nbtn_5.config(font =(\"Italic\",22))\n\ndef click_6():\n label_7 = Label(root, text=\"Wrong\")\n label_7.config(font =(\"Calibri\",18))\n label_7.pack()\n \nbtn_6 = Button(root, text=\"33\", width=5,height=2,bg = \"lime\",fg = \"black\",command=click_6) \nbtn_6.config(font =(\"Italic\",22))\n\nlabel.pack()\nbtn.pack()\nbtn_2.pack()\nbtn_3.pack()\nbtn_4.pack()\nbtn_5.pack()\nbtn_6.pack()\n\nroot.mainloop()\n","sub_path":"prem quiz game.py","file_name":"prem quiz game.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"108540637","text":"# Problem Statement:\r\n# Given a collection of distinct integers, return all possible permutations.\r\n# Input: [1,2,3]\r\n# Output:[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]\r\nresult = []\r\n\r\nnums = [1,2,3]\r\ndef Permutations(nums,l ,r):\r\n\r\n\tif l == r-1:\r\n\t\tresult.append(nums[:])\r\n\telse:\r\n\t\tfor i in range(l,r):\r\n\t\t\tnums[l] , nums[i] = nums[i] , nums[l]\r\n\t\t\tPermutations(nums,l+1,r)\r\n\t\t\tnums[l] , nums[i] = nums[i] , nums[l]\r\n\r\n\r\n\r\ndef permutate(nums):\r\n\tn = len(nums)\r\n\tPermutations(nums,0,n)\r\n\tprint(result)\r\n\r\npermutate([1,2,3])\r\n","sub_path":"BackTracking/Permutations.py","file_name":"Permutations.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"381680569","text":"from __future__ import division, print_function, absolute_import\nimport pickle\nimport numpy as np \nimport os.path\nimport codecs\nimport tflearn\nfrom tflearn.layers.core import input_data, dropout, fully_connected\nfrom tflearn.layers.conv import conv_2d, max_pool_2d\nfrom tflearn.layers.normalization import local_response_normalization\nfrom tflearn.layers.estimator import regression\nfrom scipy.misc import imread\nfrom scipy.misc import imresize\nimport tensorflow as tf\nimport config\n\nfrom caffe_classes import class_names\n\nnet_data = np.load(open(\"bvlc_alexnet.npy\", \"rb\"), encoding=\"latin1\").item()\n\n# Building 'AlexNet'\ndef create_alexnet(num_classes):\n in_put= input_data(shape=[None, 227, 227, 3], dtype=tf.float32)\n conv1 = conv_2d(in_put, 96, 11, strides=4, activation='relu', padding='same')\n lrn = local_response_normalization(conv1, depth_radius=2, alpha=2e-05, beta=0.75, bias=1.0)\n pool1 = max_pool_2d(lrn, 3, strides=2, padding='valid')\n lrn_1, lrn_2 = tf.split(pool1, 2, 3)\n conv2_1 = conv_2d(lrn_1, 128, 5, activation='relu', padding=\"same\")\n conv2_2 = conv_2d(lrn_2, 128, 5, activation='relu', padding=\"same\")\n conv2 = tf.concat([conv2_1, conv2_2], 3)\n lru = local_response_normalization(conv2, depth_radius=2, alpha=2e-05, beta=0.75, bias=1.0)\n pool2= max_pool_2d(lru, 3, strides=2, padding='valid')\n conv3 = conv_2d(pool2, 384, 3, activation='relu', padding=\"same\")\n\n conv3_1, conv3_2 = tf.split(conv3, 2, 3)\n conv4_1 = conv_2d(conv3_1, 192, 3, activation='relu', padding=\"same\")\n conv4_2 = conv_2d(conv3_2, 192, 3, activation='relu', padding=\"same\")\n# conv4 = tf.concat([conv4_1, conv4_2], 3)\n \n conv5_1 = conv_2d(conv4_1, 128, 3, activation='relu', padding=\"same\")\n conv5_2 = conv_2d(conv4_2, 128, 3, activation='relu', padding=\"same\")\n conv5 = tf.concat([conv5_1, conv5_2], 3)\n \n pool3 = max_pool_2d(conv5, 3, strides=2, padding='valid')\n# lru = local_response_normalization(pool3)\n fc1 = fully_connected(pool3, 4096, activation='relu')\n# dp1 = dropout(fc1, 0.5)\n fc2 = fully_connected(fc1, 4096, activation='relu')\n# dp2 = dropout(fc2, 0.5)\n fc3 = fully_connected(fc2, num_classes, activation='softmax')\n# network = fc3\n network = regression(fc3, optimizer='momentum',\n loss='categorical_crossentropy',\n learning_rate=0.001)\n \n model = tflearn.DNN(network)\n \n model.set_weights(fc3.W, net_data[\"fc8\"][0])\n model.set_weights(fc3.b, net_data[\"fc8\"][1])\n model.set_weights(fc2.W, net_data[\"fc7\"][0])\n model.set_weights(fc2.b, net_data[\"fc7\"][1])\n model.set_weights(fc1.W, net_data[\"fc6\"][0])\n model.set_weights(fc1.b, net_data[\"fc6\"][1])\n \n model.set_weights(conv5_1.W, np.split(np.array(net_data[\"conv5\"][0]), 2, 3)[0])\n model.set_weights(conv5_1.b, np.split(np.array(net_data[\"conv5\"][1]), 2, 0)[0])\n model.set_weights(conv5_2.W, np.split(np.array(net_data[\"conv5\"][0]), 2, 3)[1])\n model.set_weights(conv5_2.b, np.split(np.array(net_data[\"conv5\"][1]), 2, 0)[1])\n \n model.set_weights(conv4_1.W, np.split(np.array(net_data[\"conv4\"][0]), 2, 3)[0])\n model.set_weights(conv4_1.b, np.split(np.array(net_data[\"conv4\"][1]), 2, 0)[0])\n model.set_weights(conv4_2.W, np.split(np.array(net_data[\"conv4\"][0]), 2, 3)[1])\n model.set_weights(conv4_2.b, np.split(np.array(net_data[\"conv4\"][1]), 2, 0)[1])\n \n model.set_weights(conv3.W, net_data[\"conv3\"][0])\n model.set_weights(conv3.b, net_data[\"conv3\"][1])\n \n \n model.set_weights(conv2_1.W, np.split(np.array(net_data[\"conv2\"][0]), 2, 3)[0])\n model.set_weights(conv2_1.b, np.split(np.array(net_data[\"conv2\"][1]), 2, 0)[0])\n model.set_weights(conv2_2.W, np.split(np.array(net_data[\"conv2\"][0]), 2, 3)[1])\n model.set_weights(conv2_2.b, np.split(np.array(net_data[\"conv2\"][1]), 2, 0)[1])\n \n model.set_weights(conv1.W, net_data[\"conv1\"][0])\n model.set_weights(conv1.b, net_data[\"conv1\"][1])\n model.save(config.SAVE_MODEL_PATH)\n \n return model\n\nif __name__ == '__main__':\n \n \n im1 = (imread(\"laska.png\")[:,:,:3]).astype(np.float32)\n im1 = im1 - np.mean(im1)\n im1[:, :, 0], im1[:, :, 2] = im1[:, :, 2], im1[:, :, 0]\n \n im2 = (imread(\"poodle.png\")[:,:,:3]).astype(np.float32)\n im2 = im2 - np.mean(im2)\n im2[:, :, 0], im2[:, :, 2] = im2[:, :, 2], im2[:, :, 0]\n \n im3 = (imread(\"dog.png\")[:,:,:3]).astype(np.float32)\n im3 = im3 - np.mean(im3)\n im3[:, :, 0], im3[:, :, 2] = im3[:, :, 2], im3[:, :, 0]\n \n im4 = (imread(\"dog2.png\")[:,:,:3]).astype(np.float32)\n im4 = im4 - np.mean(im4)\n im4[:, :, 0], im4[:, :, 2] = im4[:, :, 2], im4[:, :, 0]\n \n model = create_alexnet(1000)\n output = model.predict(np.asarray([im1, im2, im3, im4]))\n print(output.shape)\n for input_im_ind in range(output.shape[0]):\n inds = np.argsort(output)[input_im_ind,:]\n print(\"Image\", input_im_ind)\n for i in range(5):\n print(class_names[inds[-1-i]], output[input_im_ind, inds[-1-i]])","sub_path":"imagenet_alexnet_pretrain.py","file_name":"imagenet_alexnet_pretrain.py","file_ext":"py","file_size_in_byte":5036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"89289223","text":"\"\"\"\n 4. Найти сумму n элементов следующего ряда чисел: 1, -0.5, 0.25, -0.125,…\n Количество элементов (n) вводится с клавиатуры.\n\"\"\"\n\nlen_seq = abs(int(input(\"Введите длину последовательности: \")))\nsecond_element = 1\nsum_seq = 0\n\nfor i in range(len_seq):\n sum_seq += second_element\n second_element /= -2\n\nprint(f\"Сумма последовательности 1, -0.5, 0.25, -0.125,… до {len_seq} = {sum_seq}\")\n\n\n","sub_path":"les_2/les_2_task_4.py","file_name":"les_2_task_4.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"403555088","text":"# Copyright 2016 by MPI-SWS and Data-Ken Research.\n# Licensed under the Apache 2.0 License.\n\"\"\"Test mqtt broker\n\nIn addition to testing mqtt publish/subscribe functionality, this runs a\noutput_thing that has its own event loop.\n\nTo run the test, you will need the paho-mqtt client and the mosquitto broker.\nYou can get the client via:\n\n pip install paho-mqtt\n\nOn Debian-based linuxes, you can get the broker via:\n\n sudo apt-get install mosquitto\n\nWe assume that the broker is listening on localhost:1883.\n\n\"\"\"\n\nimport unittest\nimport sys\nimport thingflow.filters.output\nimport thingflow.filters.json\nimport thingflow.filters.select\nfrom thingflow.base import Scheduler, InputThing, SensorEvent, ScheduleError, ExcInDispatch\nfrom thingflow.adapters.mqtt import MQTTReader, MQTTWriter\nfrom utils import make_test_output_thing_from_vallist, ValidationInputThing\n\ntry:\n import paho.mqtt\n MQTT_CLIENT_AVAILABLE = True\nexcept ImportError:\n MQTT_CLIENT_AVAILABLE = False\n\nMQTT_PORT=1883\n \nimport asyncio\n\nsensor_data = [1, 2, 3, 4, 5]\n\nclass StopLoopAfter(InputThing):\n def __init__(self, stop_after, cancel_thunk):\n self.events_left = stop_after\n self.cancel_thunk = cancel_thunk\n\n def on_next(self, x):\n self.events_left -= 1\n if self.events_left == 0:\n print(\"Requesting stop of event loop\")\n self.cancel_thunk()\n\ndef mqtt_msg_to_unicode(m):\n v = (m.payload).decode(\"utf-8\")\n return v\n\n\ndef is_broker_running():\n import subprocess\n rc = subprocess.call(\"netstat -an | grep %d\" % MQTT_PORT, shell=True)\n if rc==0:\n print(\"MQTT broker running\")\n return True\n else:\n print(\"MQTT broker not running\")\n return False\n\n\n@unittest.skipUnless(MQTT_CLIENT_AVAILABLE,\n \"MQTT client not installed for python at %s\" % sys.executable)\n@unittest.skipUnless(is_broker_running(),\n \"MQTT broker not running on port %d\" % MQTT_PORT)\nclass TestCase(unittest.TestCase):\n def test_mqtt(self):\n loop = asyncio.get_event_loop()\n s = Scheduler(loop)\n sensor = make_test_output_thing_from_vallist(1, sensor_data)\n mqtt_writer = MQTTWriter('localhost', topics=[('bogus/bogus',0),])\n sensor.to_json().connect(mqtt_writer)\n s.schedule_periodic(sensor, 0.5)\n\n mqtt_reader = MQTTReader(\"localhost\", topics=[('bogus/bogus', 0),])\n vs = ValidationInputThing(sensor_data, self)\n mqtt_reader.take(5).select(mqtt_msg_to_unicode).from_json(constructor=SensorEvent) \\\n .output().connect(vs)\n c = s.schedule_on_private_event_loop(mqtt_reader)\n stop = StopLoopAfter(5, c)\n mqtt_reader.connect(stop)\n mqtt_reader.print_downstream()\n sensor.print_downstream()\n s.run_forever()\n loop.stop()\n self.assertTrue(vs.completed)\n print(\"that's it\")\n\n def test_daniels_bug(self):\n \"\"\"Test bug reported by Daniel (issue #1). If you call the mqtt writer without\n serializing the message, you should get a fatal error.\n \"\"\"\n import time\n import asyncio\n import thingflow.filters.output # This has output side-effect\n from thingflow.base import Scheduler, from_list\n from thingflow.adapters.mqtt import MQTTReader, MQTTWriter\n from collections import namedtuple\n\n StripEvent = namedtuple('StripEvent', ['strip_id', 'ts', 'val'])\n\n strip_events = (\n StripEvent('strip-1', 1500000000, 50),\n StripEvent('strip-1', 1500000000, 5),\n StripEvent('strip-1', 1500000000, 50))\n\n mqtt = MQTTWriter('localhost', topics=[('strip-data', 0),])\n\n strip = from_list(strip_events)\n strip.connect(mqtt)\n strip.output()\n\n sched = Scheduler(asyncio.get_event_loop())\n sched.schedule_periodic(strip, 1.0)\n try:\n sched.run_forever()\n except ScheduleError as e:\n # verify the cause of the error\n dispatch_error = e.__cause__\n self.assertTrue(isinstance(dispatch_error, ExcInDispatch),\n \"expecting cause to be a dispatch error, instead got %s\" % repr(dispatch_error))\n orig_error = dispatch_error.__cause__\n self.assertTrue(isinstance(orig_error, TypeError),\n \"expecting original exception to be a TypeError, intead got %s\" % repr(orig_error))\n print(\"Got expected exception: '%s'\" % e)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_mqtt.py","file_name":"test_mqtt.py","file_ext":"py","file_size_in_byte":4563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"260157185","text":"import time\n\nfrom watchmen.common.constants import pipeline_constants\nfrom watchmen.monitor.model.pipeline_monitor import InsertAndMergeRowAction\nfrom watchmen.pipeline.model.pipeline import UnitAction\nfrom watchmen.pipeline.single.stage.unit.mongo.index import run_mapping_rules, \\\n build_query_conditions, __build_mongo_query, index_conditions\nfrom watchmen.pipeline.single.stage.unit.mongo.read_topic_data import query_topic_data\nfrom watchmen.pipeline.single.stage.unit.mongo.write_topic_data import insert_topic_data, update_topic_data\nfrom watchmen.pipeline.single.stage.unit.utils import PIPELINE_UID\nfrom watchmen.topic.storage.topic_schema_storage import get_topic_by_id\nfrom watchmen.topic.topic import Topic\n\n\ndef init(action: UnitAction, pipeline_topic: Topic):\n def merge_or_insert_topic(instance, context):\n raw_data, old_value = instance[pipeline_constants.NEW], instance[pipeline_constants.OLD]\n unit_action_status = InsertAndMergeRowAction(type=action.type)\n start = time.time()\n pipeline_uid = context[PIPELINE_UID]\n unit_action_status.uid = pipeline_uid\n\n if action.topicId is None:\n raise ValueError(\"action.topicId is empty {0}\".format(action.name))\n\n target_topic = get_topic_by_id(action.topicId)\n\n mapping_results = run_mapping_rules(action.mapping, target_topic, raw_data, pipeline_topic, context)\n joint_type, where_condition = build_query_conditions(action.by, pipeline_topic, raw_data, target_topic, context)\n unit_action_status.whereConditions = where_condition\n unit_action_status.mapping = mapping_results\n trigger_pipeline_data_list = []\n\n # print(\"mapping_results\",mapping_results)\n for index, mapping_result in enumerate(mapping_results):\n mongo_query = __build_mongo_query(joint_type, index_conditions(where_condition, index))\n target_data = query_topic_data(mongo_query, target_topic.name)\n\n if target_data is None:\n trigger_pipeline_data_list.append(insert_topic_data(target_topic.name, mapping_result, pipeline_uid))\n unit_action_status.insertCount = unit_action_status.insertCount + 1\n else:\n trigger_pipeline_data_list.append(\n update_topic_data(target_topic.name, mapping_result, target_data, pipeline_uid, mongo_query))\n unit_action_status.updateCount = unit_action_status.updateCount + 1\n\n elapsed_time = time.time() - start\n unit_action_status.complete_time = elapsed_time\n\n #print(\"trigger_pipeline_data_list\", trigger_pipeline_data_list)\n return context, unit_action_status, trigger_pipeline_data_list\n\n return merge_or_insert_topic\n","sub_path":"watchmen/pipeline/single/stage/unit/action/insert_or_merge_row.py","file_name":"insert_or_merge_row.py","file_ext":"py","file_size_in_byte":2748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"143990611","text":"\n################################################################################\n# Low-Rank Frequency Matrix Based Stationary Gaussian Process\n# Author: Max W. Y. Lam (maxingaussian@gmail.com)\n################################################################################\n\nfrom __future__ import absolute_import\n\nimport sys, os\nimport string\nimport scipy as sp\nimport numpy.random as npr\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as anm\n\nfrom lrfmsgp.casadi import *\nfrom lrfmsgp.util import optimizer, normalizer\n\nclass lrfmSGP(object):\n \n \" Low-Rank Frequency Matrix Based Stationary Gaussian Process \"\n\n ID, seed, opt, msg = \"\", None, None, True\n rank, M, N, D = 1, 0, -1, -1\n X, y, Xs, ys, hyper, R, alpha, train_func = [None]*8\n TrCost, TrMSE, TrNMSE, TsMSE, TsNMSE, TsMNLP = [sp.inf]*6\n \n def __init__(self, M, L, rank, X_nml_meth=\"linear\", msg=True):\n self.M = M\n self.L = L\n self.rank = rank\n self.X_nml = normalizer(X_nml_meth)\n self.y_nml = normalizer(\"standardize\")\n self.msg = msg\n self.generate_ID()\n \n def message(self, *arg):\n if(self.msg):\n print(\" \".join(map(str, arg)))\n sys.stdout.flush()\n \n def generate_ID(self):\n self.ID = ''.join(\n chr(sp.random.choice([ord(c) for c in (\n string.ascii_uppercase+string.digits)])) for _ in range(10)) \n self.seed = sp.prod([ord(c) for c in self.ID])%4294967291\n npr.seed(self.seed)\n \n def _train_func(self, X, y, hyper):\n res = self.train_func(X=X, y=y, hyper=hyper)\n R, alpha, beta = map(sp.array, [res['R'], res['alpha'], res['beta']])\n Cost = sp.double(res['Cost'])\n dhyper = sp.array(res['dhyper']).ravel()\n return R, alpha, beta, Cost, dhyper\n \n def _pred_func(self, Xs, hyper, R, alpha):\n a = hyper[0]\n b = hyper[1]\n c = sp.reshape(hyper[2:2+self.D*self.rank],\n (self.D, self.rank), order='F')\n d = sp.reshape(hyper[2+self.D*self.rank:2+(self.D+self.M)*self.rank],\n (self.M, self.rank), order='F')\n l = sp.reshape(hyper[2+(self.D+self.M)*self.rank:2+(self.D+self.M)*\\\n self.rank+self.D*self.L], (self.D, self.L), order='F')\n p = sp.reshape(hyper[2+(self.D+self.M)*self.rank+self.D*self.L:2+(\n self.D+self.M)*self.rank+2*self.D*self.L], (self.D, self.L), order='F')\n sig_n, sig_f = sp.exp(a), sp.exp(b)\n sig2_n, sig2_f = sig_n**2, sig_f**2\n Omega = sp.dot(c, d.T)\n OmegaHat = sp.hstack([sp.dot(sp.diag(1./sp.exp(l[:, i])), Omega)+\\\n sp.hstack([p[:, i][:, None] for _ in range(self.M)]) for i in range(self.L)])\n XscdT = sp.dot(Xs, OmegaHat)\n sinXscdT = sp.sin(2*sp.pi*XscdT)\n cosXscdT = sp.cos(2*sp.pi*XscdT)\n Phis = sp.hstack((sinXscdT, cosXscdT))\n gamma = sp.linalg.solve_triangular(R, Phis.T)\n mu = sp.dot(Phis, alpha)\n std = sig_n*(1+sig2_f/self.M*sp.sum(gamma**2, 0).T)**0.5\n std = np.tile(std[:, None], (1, self.P))\n return mu, std\n \n def set_casadi_training_function(self, N, D, P, M, L, rank, msg=True):\n if(msg):\n self.message(\"=\"*50)\n self.message(\"Pre-set CasADi Formulas For lrfmSGP Training\")\n X = SX.sym('X', N, D)\n Y = SX.sym('Y', N, P)\n hyper = SX.sym('hyper', rank*(D+M)+2*D*L+2)\n a = hyper[0]\n b = hyper[1]\n c = reshape(hyper[2:2+D*rank], D, rank)\n d = reshape(hyper[2+D*rank:2+(D+M)*rank], M, rank)\n l = reshape(hyper[2+(D+M)*rank:2+(D+M)*rank+D*L], D, L)\n p = reshape(hyper[2+(D+M)*rank+D*L:2+(D+M)*rank+2*D*L], D, L)\n sig_n, sig_f = exp(a), exp(b)\n sig2_n, sig2_f = sig_n**2, sig_f**2\n if(msg):\n self.message(\"1) Calculate Phi\")\n Omega = mtimes(c, d.T)\n OmegaHat = horzcat(*[mtimes(diag(1./exp(l[:, i])), Omega)+\\\n horzcat(*[p[:, i] for _ in range(M)]) for i in range(L)])\n XcdT = mtimes(X, OmegaHat)\n sinXcdT = sin(2*sp.pi*XcdT)\n cosXcdT = cos(2*sp.pi*XcdT)\n Phi = horzcat(sinXcdT, cosXcdT)\n if(msg):\n self.message(\"2) Calculate A\")\n Gamma = mtimes(Phi.T, Phi)\n A = Gamma + sig2_n*M/sig2_f*SX.eye(Gamma.size1())\n if(msg):\n self.message(\"3) Calculate R=chol(A)\")\n R = chol(A)\n if(msg):\n self.message(\"4) Calculate zeta, alpha, beta\")\n zeta = solve(R.T, mtimes(Phi.T, Y))\n alpha = solve(R, zeta)\n beta = mtimes(Phi, alpha)\n if(msg):\n self.message(\"5) Calculate Cost\")\n mu_omega = sum2(Omega)/M\n sigma_omega = sum2((Omega-horzcat(*[mu_omega for _ in range(M)]))**2)/M\n NLML = N*P/2*log(sig2_n*2*sp.pi)+1./(2*sig2_n)*(\n sum2(sum1(Y*Y))-sum2(sum1(zeta*zeta)))+norm_1(log(diag(R)))-\\\n 0.5*sum1(sigma_omega+mu_omega**2-log(sigma_omega)-1)\n Penalty = norm_2(sum1(Omega)/D)\n Cost = NLML/N+Penalty/rank\n if(msg):\n self.message(\"6) Calculate dCost/dhyper\")\n dhyper = gradient(Cost, hyper)\n if(msg):\n self.message(\"7) Wrap Training Function\")\n train_input = [X, Y, hyper]\n train_input_name = ['X', 'y', 'hyper']\n train_output = [R, alpha, beta, Cost, dhyper]\n train_output_name = ['R', 'alpha', 'beta', 'Cost', 'dhyper']\n if(msg):\n self.message(\"=\"*50)\n return Function('train_func',\n train_input, train_output, train_input_name, train_output_name)\n \n def fit(self, X, y, Xs=None, ys=None,\n train_func=None, pred_func=None, opt=None, plot=None):\n self.X_nml.fit(X)\n self.y_nml.fit(y)\n self.X = self.X_nml.forward_transform(X)\n self.y = self.y_nml.forward_transform(y)\n self.N, self.D = self.X.shape\n _, self.P = self.y.shape\n if(train_func is not None):\n self.train_func = train_func\n else:\n self.train_func = self.set_casadi_training_function(\n self.N, self.D, self.P, self.M, self.L, self.rank, self.msg)\n if(Xs is not None and ys is not None):\n self.Xs = self.X_nml.forward_transform(Xs)\n self.ys = self.y_nml.forward_transform(ys)\n iter_list = []\n cost_list = []\n train_mse_list = []\n test_mse_list = []\n if(opt is None):\n opt = optimizer(\"smorms3\", 10000000, 8, 1e-4, [0.005])\n if(plot is not None):\n fig, axarr = plot\n if(self.rank != 2 and self.D != 1):\n fig.suptitle('Training Curve of lrfmSGP (Rank=%d, M=%d)'%(\n self.rank, self.M), fontsize=20)\n plt.xlabel('# iteration', fontsize=13)\n def animate(i):\n if(self.D == 1 and self.P == 1):\n axarr.cla()\n pts = 300\n errors = [0.25, 0.39, 0.52, 0.67, 0.84, 1.04, 1.28, 1.64, 2.2]\n xrng = 1\n Xplot = sp.linspace(-0.1, 1.1, pts)[:, None]\n mu, std = self._pred_func(Xplot, self.hyper, self.R, self.alpha)\n mu = mu.ravel()\n std = std.ravel()\n for er in errors:\n axarr.fill_between(Xplot[:, 0], mu-er*std, mu+er*std,\n alpha=((3-er)/5.5)**1.7, facecolor='blue',\n linewidth=0.0)\n axarr.plot(Xplot[:, 0], mu, 'black')\n axarr.errorbar(self.X[:, 0], self.y.ravel(), fmt='r.', markersize=10)\n yrng = self.y.max()-self.y.min()\n axarr.set_ylim([self.y.min() - 0.5*yrng, self.y.max() + 0.5*yrng])\n axarr.set_xlim([-0.1, 1.1])\n elif(self.rank == 2 and self.P > 1 and Xs is not None):\n axarr.cla()\n c = sp.reshape(self.hyper[2:2+self.D*self.rank],\n (self.D, self.rank), order='F')\n tX = self.Xs.dot(c)\n if(self.P == 1):\n for i in range(tX.shape[0]):\n axarr.plot(tX[i, 0], tX[i, 1], 'o',\n color=('r' if ys[i]==1 else 'b'))\n else:\n for i in range(tX.shape[0]):\n axarr.plot(tX[i, 0], tX[i, 1], 'o',\n color=plt.cm.Set1(int(sp.where(ys[i]==1)[0])/(self.P+3)))\n minx, maxx = min(tX[:, 0]), max(tX[:, 0])\n miny, maxy = min(tX[:, 1]), max(tX[:, 1])\n axarr.set_xlim([minx-(maxx-minx)*0.05,maxx+(maxx-minx)*0.05])\n axarr.set_ylim([miny-(maxy-miny)*0.05,maxy+(maxy-miny)*0.05])\n else:\n if(len(iter_list) > 100):\n iter_list.pop(0)\n cost_list.pop(0)\n train_mse_list.pop(0)\n test_mse_list.pop(0)\n axarr[0].cla()\n axarr[0].plot(iter_list, sp.log(cost_list),\n color='r', linewidth=2.0, label='Training Cost')\n axarr[1].cla()\n axarr[1].plot(iter_list, train_mse_list,\n color='b', linewidth=2.0, label='Training MSE')\n if(Xs is None or ys is None):\n return\n axarr[1].plot(iter_list, test_mse_list,\n color='g', linewidth=2.0, label='Testing MSE')\n handles, labels = axarr[0].get_legend_handles_labels()\n axarr[0].legend(handles, labels, loc='upper center',\n bbox_to_anchor=(0.5, 1.15), ncol=1, fancybox=True)\n handles, labels = axarr[1].get_legend_handles_labels()\n axarr[1].legend(handles, labels, loc='upper center',\n bbox_to_anchor=(0.5, 1.15), ncol=2, fancybox=True)\n def init_hyper():\n a, b = 0, -2*np.log(4.)\n best_hyper, min_cost = None, sp.inf\n cross_val_k = 4\n num_per_k = int(self.N/cross_val_k)\n CV = num_per_k*(cross_val_k-1)\n cross_val_train_func = self.set_casadi_training_function(\n CV, self.D, self.P, self.M, self.L, self.rank, False)\n for _ in range(100):\n c = sp.random.rand(self.D, self.rank)\n d = sp.random.randn(self.M, self.rank)\n l = sp.random.randn(self.D, self.L)\n p = sp.random.randn(self.D, self.L)\n cost = 0\n hyper = sp.concatenate([[a, b], c.ravel(), d.ravel(), l.ravel(), p.ravel()])\n for k in range(cross_val_k):\n train_ind = sp.random.choice(range(self.N), CV)\n res = cross_val_train_func(\n X=self.X[train_ind], y=self.y[train_ind], hyper=hyper)\n R, alpha, beta = map(np.array, [res['R'], res['alpha'], res['beta']])\n test_ind = list(set(range(self.N)).difference(train_ind))\n p_y, p_std = self._pred_func(self.X[test_ind], hyper, R, alpha)\n cost += sp.mean((p_y-self.y[test_ind])**2.)/sp.var(self.y[test_ind])/\\\n sp.mean((beta-self.y[train_ind])**2.)/sp.var(self.y[train_ind])\n self.message(\"Random parameters yield cost:\", cost)\n if(cost < min_cost):\n min_cost = cost\n best_hyper = hyper.copy()\n return best_hyper\n def train(iter, hyper):\n self.hyper = hyper.copy()\n R, alpha, beta, Cost, dhyper = self._train_func(self.X, self.y, hyper)\n self.R, self.alpha = R.copy(), alpha.copy()\n self.beta = self.y_nml.backward_transform(beta)\n self.TrMSE = np.mean((self.beta-y)**2.)\n self.TrCost = Cost\n self.message(\"=\"*15, \"lrfmSGP ITERATION\", iter, \"=\"*15)\n self.message(\"\\t\\tlrfmSGP\\t TrMSE\\t=\", self.TrMSE)\n self.message(\"\\t\\tlrfmSGP\\t TrCost\\t=\", self.TrCost)\n if(Xs is not None and ys is not None):\n test()\n if(iter == -1):\n return\n iter_list.append(iter)\n cost_list.append(self.TrCost)\n train_mse_list.append(self.TrMSE)\n if(plot is not None):\n if(self.D == 1 and self.P == 1):\n plt.pause(0.05)\n elif(self.rank == 2 and self.P > 1 and Xs is not None):\n plt.pause(0.1)\n else:\n plt.pause(0.01)\n return self.TrCost, self.TrMSE/np.var(y), dhyper\n def test():\n mu, std = self._pred_func(self.Xs, self.hyper, self.R, self.alpha)\n mu = self.y_nml.backward_transform(mu)\n std = std*self.y_nml.data[\"std\"]\n self.TsMSE = sp.mean((mu-ys)**2.)\n self.TsMNLP = 0.5*(sp.log(2*sp.pi)+sp.mean(\n sp.square((ys-mu)/std)+sp.log(std**2)))\n self.message(\"\\t\\tlrfmSGP\\t TsMSE\\t=\", self.TsMSE)\n self.message(\"\\t\\tlrfmSGP\\t TsMNLP\\t=\", self.TsMNLP)\n if(iter == -1):\n return\n test_mse_list.append(self.TsMSE)\n train(0, init_hyper())\n if(plot is not None):\n if(self.D == 1 and self.P == 1):\n ani = anm.FuncAnimation(fig, animate, interval=500)\n elif(self.rank == 2 and self.P > 1 and Xs is not None):\n ani = anm.FuncAnimation(fig, animate, interval=1000)\n else:\n ani = anm.FuncAnimation(fig, animate, interval=300)\n opt.run(train, self.hyper)\n\n def predict(self, Xs):\n _Xs = self.X_nml.forward_transform(Xs)\n mu, std = self._pred_func(_Xs, self.hyper, self.R, self.alpha)\n mu = self.y_nml.backward_transform(mu)\n std = std*self.y_nml.data[\"std\"]\n return mu, std\n\n def save(self, path):\n prior_settings = (self.ID, self.seed)\n fit_input = (self.X, self.y, self.M)\n set_func = (self.train_func, self.pred_func)\n params = self.hyper\n normalizers = (self.X_nml, self.y_nml)\n computed_matrices = (self.R, self.alpha)\n performances = (self.TrCost, self.TrMSE, self.TrNMSE,\n self.TsMSE, self.TsNMSE, self.TsMNLP)\n save_pack = [prior_settings, fit_input, set_func, \n params, normalizers, computed_matrices, performances]\n import pickle\n with open(path, \"wb\") as save_f:\n pickle.dump(save_pack, save_f, pickle.HIGHEST_PROTOCOL)\n\n def load(self, path):\n import pickle\n with open(path, \"rb\") as load_f:\n load_pack = pickle.load(load_f)\n self.ID, self.seed = load_pack[0]\n npr.seed(self.seed)\n self.X, self.y, self.M = load_pack[1]\n self.N, self.D = self.X.shape\n self.train_func, self.pred_func = load_pack[2]\n self.hyper = load_pack[3]\n self.X_nml, self.y_nml = load_pack[4]\n self.R, self.alpha = load_pack[5]\n self.TrCost, self.TrMSE, self.TrNMSE = load_pack[6][:3]\n self.TsMSE, self.TsNMSE, self.TsMNLP = load_pack[6][3:]\n\n\n\n\n\n\n","sub_path":"lrfmsgp/model/lrfmSGP.py","file_name":"lrfmSGP.py","file_ext":"py","file_size_in_byte":15191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"508440222","text":"from NodeModel import NodeModel\nimport numpy as np\nimport math\ndef LTM_MC(nodes, links, origins, destinations, ODmatrix, dt, totT, TF):\n eps = np.finfo(float).eps\n totLinks = len(links.get('fromNode'))\n totDest = len(destinations)\n timeSlices = np.arange(0.0, totT + 1, 1) * 0.5\n\n cvn_up = np.zeros((totLinks, totT + 1, totDest))\n cvn_down = np.zeros((totLinks, totT + 1, totDest))\n\n fromNodes = links.get('fromNode')\n toNodes = links.get('toNode')\n freeSpeeds = links.get('freeSpeed')\n capacities = links.get('capacity')\n kJams = links.get('KJam')\n lengths = links.get('length')\n wSpeeds = capacities / (kJams - capacities / freeSpeeds)\n\n originsAndDest = np.append(origins, destinations)\n normalNodes = np.setdiff1d(nodes.get('ID') - 1, originsAndDest)\n\n # the problem is initialized ID as 1.2.3... not good.. so need subtract 1\n\n def loadOriginNodes(t):\n for o_index in range(0, len(origins)):\n o = origins[o_index]\n outgoingLinks = np.where(fromNodes == o)[0]\n for l_index in range(0, len(outgoingLinks)):\n l = outgoingLinks[l_index]\n for d_index in range(0, totDest):\n SF_d = TF[o, t - 1, d_index] * np.sum(ODmatrix[o_index, d_index, t - 1]) * dt\n cvn_up[l, t, d_index] = cvn_up[l, t - 1, d_index] + SF_d\n\n def loadDestinationNodes(t):\n for d_index in range(0, len(destinations)):\n d = destinations[d_index]\n incomingLinks = np.where(toNodes == d)[0]\n for l_index in range(0, len(incomingLinks)):\n l = incomingLinks[l_index]\n for d_index in range(0, totDest):\n SF_d = findCVN(cvn_up[l, :, :], timeSlices[t] - lengths[l] / freeSpeeds[l], timeSlices,\n dt) - cvn_down[l, t - 1, :]\n cvn_down[l, t, :] = cvn_down[l, t - 1, :] + SF_d\n\n def findCVN(cvn, time, timeSlices, dt):\n if time <= timeSlices[0]:\n val = cvn[0, 0, :]\n elif time >= timeSlices[-1]:\n val = cvn[0, -1, :]\n else:\n t1 = math.ceil(time / dt)\n t2 = t1 + 1\n val = cvn[t1 - 1] + (time / dt - t1 + 1) * (cvn[t2 - 1] - cvn[t1 - 1])\n return val\n\n def calculateDestSendFlow(l, t):\n\n SFCAP = capacities[l] * dt\n time = timeSlices[t] - lengths[l] / freeSpeeds[l]\n val = findCVN(cvn_up[l, :, :], time, timeSlices, dt)\n SF = val - cvn_down[l, t - 1, :]\n if SF.all() > SFCAP:\n red = SFCAP / np.sum(SF)\n SF = np.dot(red, SF)\n return SF\n\n def calculateReceivingFlow_VQ(l):\n RF = capacities[l] * dt\n return RF\n\n def calculateReceivingFlow_HQ(l, t):\n RF = capacities[l] * dt\n val = np.sum(cvn_down[l, t - 1, :]) + kJams[l] * lengths[l]\n RF = min(RF, val - np.sum(cvn_up[l, t - 1, :]))\n return RF\n\n def calculateReceivingFlow_FQ(l, t):\n RF = capacities[l] * dt\n time = timeSlices[t] - lengths[l] / wSpeeds[l]\n val = findCVN(np.sum(cvn_down[l, :, :], axis=1), time, timeSlices, dt) + kJams[l] * lengths[l]\n RF = min(RF, val - np.sum(cvn_up[l, t - 1, :]))\n RF = max(RF, np.zeros(RF.shape))\n return RF\n\n def calculateTurningFractions(n, t):\n TF_n = np.zeros((nbIn, nbOut))\n if nbOut == 1:\n TF_n[0:nbIn, 0] = 1\n else:\n for d in range(0, totDest):\n TF_n = TF_n + np.matlib.repmat(np.expand_dims(SF_d[:, d], axis=1), 1, nbOut) * TF[n, t, d]\n\n TF_n = TF_n / np.matlib.repmat(np.expand_dims(np.finfo(float).eps + np.sum(TF_n, axis=1), axis=1), 1, nbOut)\n return TF_n\n\n for t in range(1, totT + 1):\n loadOriginNodes(t)\n\n for nIndex in range(0, len(normalNodes)):\n n = normalNodes[nIndex]\n incomingLinks = np.where(toNodes == n)[0]\n nbIn = len(incomingLinks)\n SF_d = np.zeros((nbIn, totDest))\n SF_tot = np.zeros((nbIn, 1))\n SF = np.zeros((nbIn, 1))\n\n for l_index in range(0, nbIn):\n l = incomingLinks[l_index]\n SF_d[l_index, :] = calculateDestSendFlow(l, t)\n SF_tot[l_index] = np.sum(SF_d[l_index, :])\n SF[l_index] = min(capacities[l] * dt, SF_tot[l_index])\n\n outgoingLinks = np.where(fromNodes == n)[0]\n nbOut = len(outgoingLinks)\n RF = np.zeros((nbOut, 1))\n for l_index in range(0, nbOut):\n l = outgoingLinks[l_index]\n RF[l_index] = calculateReceivingFlow_FQ(l, t)\n\n TF_n = calculateTurningFractions(n, t - 1)\n\n TransferFlow = NodeModel(nbIn, nbOut, SF, TF_n, RF, capacities[incomingLinks] * dt)\n\n red = np.sum(TransferFlow, axis=1) / (eps + SF_tot).transpose()\n for d in range(0, totDest):\n cvn_down[incomingLinks, t, d] = cvn_down[incomingLinks, t - 1, d] + red * SF_d[:, d]\n cvn_up[outgoingLinks, t, d] = cvn_up[outgoingLinks, t - 1, d] + np.dot((red * SF_d[:, d]),\n TF[n][t - 1][d]).squeeze()\n\n loadDestinationNodes(t)\n\n return cvn_up, cvn_down","sub_path":"M2P 2/LTM_MC.py","file_name":"LTM_MC.py","file_ext":"py","file_size_in_byte":5315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"625400413","text":"from django.shortcuts import render, redirect\nfrom product.forms import *\n\ndef add_product_types(request):\n if request.method == 'POST':\n form = AddProductTypeForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('dashboard')\n else:\n form = AddProductTypeForm()\n return render(request, 'product/add_product_type.html', {'form': form})\n\ndef add_product(request):\n if request.method == 'POST':\n form = AddProductForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('dashboard')\n else:\n form = AddProductForm()\n return render(request, 'product/add_product.html', {'form': form})\n","sub_path":"product/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"315680561","text":"class Dicionarios:\r\n\r\n def __init__(self):\r\n keys_pds = ['ID', 'IDOPER', 'NOME', 'OCR', 'ALINT', 'ALRIN', 'TAC', 'TCL', 'TIPO', 'STINI', 'STNOR', 'OBSRV',\r\n 'BDTR', 'CDINIC', 'EQP', 'HISTSLC', 'HISTSLC_SOE', 'SELSD', 'TPEQP', 'TPFIL', 'UAPL', 'ATLZINV',\r\n 'SOEIN', 'IDICCP', 'EE', 'SINCR_MAN', 'INVRT', 'NCOMISS', 'PCONDALR', 'AOR', 'CIA', 'LSCINF', 'PMU',\r\n 'SUBTIPO1', 'TELA', 'CMT', 'INC', 'MRID']\r\n keys_pdf = ['ID', 'NV2', 'ORDEM', 'PNT', 'TPPNT', 'DESC1', 'DESC2', 'KCONV', 'CMT', 'INC', 'MRID']\r\n keys_pdd = ['ID', 'PDS', 'TDD', 'CMT', 'INC', 'MRID']\r\n\r\n keys_pas = ['ID', 'IDOPER', 'NOME', 'TAC', 'LIA', 'LIE', 'LIU', 'LSA', 'LSE', 'LSU', 'ALINT', 'ALRIN', 'TCL',\r\n 'OCR', 'OBSRV', 'BDTR', 'BNDMO', 'CDINIC', 'DPE', 'EQP', 'EST', 'HISTPER', 'HTRIS', 'INVSN',\r\n 'SELSD',\r\n 'TEND', 'EE', 'PCONDALR', 'TERM', 'TIPO', 'TPEQP', 'TPFIL', 'TXVAR', 'UAPL', 'VLINIC', 'ATLZINV',\r\n 'PARM_CAG', 'IDICCP', 'LIUMI', 'LIAMI', 'LSAMI', 'LSUMI', 'LIULE', 'LIALE', 'LSALE', 'LSULE',\r\n 'LIUME',\r\n 'LIAME', 'LSAME', 'LSUME', 'LIUPE', 'LIAPE', 'LSAPE', 'LSUPE', 'LIUMA', 'LIAMA', 'LSAMA', 'LSUMA',\r\n 'HISTSLC', 'SINCR_MAN', 'EXCDEV', 'COMPDEV', 'STEP', 'NCOMISS', 'TMP_CURTA', 'TMP_LONGA', 'PRIO',\r\n 'AOR', 'CIA', 'HISTLIN', 'LSCINF', 'ORIGEM', 'PMU', 'PREVCAR', 'PTC', 'SUBTIPO1', 'TELA', 'CMT',\r\n 'INC', 'MRID']\r\n keys_paf = ['ID', 'NV2', 'ORDEM', 'PNT', 'TPPNT', 'KCONV1', 'KCONV2', 'DESC1', 'DESC2', 'KCONV4', 'KCONV5',\r\n 'KCONV3', 'MODULO', 'CMT', 'INC', 'MRID']\r\n keys_pad = ['ID', 'PAS', 'TDD', 'CMT', 'INC', 'MRID']\r\n\r\n keys_ocr = ['AOR', 'AUTOE', 'AUTOR', 'CONSIDERA_AOI', 'DUR', 'GRPOCR', 'ID', 'NREP', 'OCR_COPIA', 'SEVER',\r\n 'TELA',\r\n 'TEXTO', 'TIPOE', 'TPSOM', 'TPUSR', 'CMT', 'INC', 'MRID']\r\n keys_nv2 = ['ID', 'NV1', 'ORDEM', 'TN2', 'TPPNT', 'CONFIG', 'CMT', 'INC', 'MRID']\r\n keys_nv1 = ['ID', 'CNF', 'ORDEM', 'TN1', 'CONFIG', 'CMT', 'INC', 'MRID']\r\n\r\n keys_noh = ['ENDIP', 'ID', 'NOME', 'NTATV', 'TPNOH', 'CMT', 'INC', 'MRID']\r\n keys_mul = ['CNF', 'GSD', 'GUARD', 'ID', 'JANEL', 'LSIMP', 'NOME', 'ORDEM', 'TRQML', 'TRSTN', 'VPROT', 'CMT',\r\n 'INC', 'MRID']\r\n keys_map = ['ID', 'NARRT', 'ORDEM', 'CMT', 'INC', 'MRID']\r\n keys_lsc = ['COS', 'GSD', 'ID', 'MAP', 'NOME', 'NSRV1', 'NSRV2', 'SITE', 'TCV', 'TIPO', 'TTP', 'VERBD', 'CMT',\r\n 'INC', 'MRID']\r\n keys_ins = ['ACO', 'AOR', 'CIA', 'FREQ', 'ID', 'LATIT', 'LONGT', 'NOME', 'PTC', 'SME', 'TELA', 'TIPO', 'UFE',\r\n 'CMT', 'INC', 'MRID']\r\n keys_inp = ['NOH', 'ORDEM', 'PRO', 'CMT', 'INC', 'MRID']\r\n keys_gsd = ['ID', 'NO1', 'NO2', 'NOME', 'SITE', 'CMT', 'INC', 'MRID']\r\n keys_grupo = ['APLIC', 'COR_BG', 'COR_FG', 'ID', 'NOME', 'PNT', 'TIPO', 'TPPNT', 'CMT', 'INC', 'MRID']\r\n keys_grcmp = ['ACAO', 'CORTXT', 'GRUPO', 'ORDEM1', 'ORDEM2', 'PARAM', 'PNT', 'TPPNT', 'TPSIMB', 'TPTXT', 'TXT',\r\n 'CMT', 'INC', 'MRID']\r\n keys_enm = ['ENPRI', 'ENSEC', 'ID', 'JANLK', 'MUL', 'NOME', 'ORDEM', 'PARN1', 'PARN2', 'PART1', 'TECON', 'CMT',\r\n 'INC', 'MRID']\r\n keys_enu = ['CXU', 'ID', 'NOME', 'ORDEM', 'TDESC', 'TRANS', 'VLUTR', 'CMT', 'INC', 'MRID']\r\n keys_e2m = ['IDPTO', 'MAP', 'TIPO', 'CMT', 'INC', 'MRID']\r\n keys_cxu = ['AQANL', 'AQPOL', 'AQTOT', 'FAILP', 'FAILR', 'GSD', 'ID', 'INTGR', 'NFAIL', 'NOME', 'ORDEM',\r\n 'SFAIL',\r\n 'CMT', 'INC', 'MRID']\r\n keys_cnf = ['CONFIG', 'ID', 'LSC', 'CMT', 'INC', 'MRID']\r\n keys_cgs = ['ID', 'IDOPER', 'LMI1C', 'LMI2C', 'LMS1C', 'LMS2C', 'NOME', 'OBSRV', 'PAC', 'PINT', 'TAC', 'TIPO',\r\n 'TIPOE', 'TPCTL', 'TRRAC', 'TBLOQ', 'AOR', 'IDICCP', 'INVCT', 'NCOMISS', 'RSULT', 'CMT', 'INC',\r\n 'MRID']\r\n keys_cgf = ['CGS', 'CNF', 'DESC1', 'DESC2', 'ID', 'KCONV', 'NOME', 'NV2', 'OPCOES', 'ORDEM', 'CMT', 'INC',\r\n 'MRID']\r\n keys_utr = ['ID', 'CNF', 'CXU', 'ENUTR', 'NTENT', 'RESPT', 'ORDEM', 'NOME', 'CMT', 'INC', 'MRID']\r\n keys_tdd = ['ID', 'NOME', 'LSC', 'CMT', 'INC', 'MRID']\r\n keys_tctl = ['ALR_CLOSE', 'ALR_TRIP', 'COR', 'DLG_CLOSE', 'DLG_TRIP', 'ID', 'NSEQ', 'TIP', 'CMT', 'INC', 'MRID']\r\n keys_tac = ['ID', 'NOME', 'INS', 'TPAQS', 'LIA', 'LSA', 'LSC', 'CMT', 'INC', 'MRID']\r\n keys_sev = ['ID', 'NOME', 'CMT', 'INC', 'MRID']\r\n keys_rfc = ['ORDEM', 'PARC', 'PNT', 'TPPARC', 'TPPNT', 'CMT', 'INC', 'MRID']\r\n keys_rca = ['FMULT', 'ORDEM', 'PARC', 'PNT', 'TIPOP', 'TPPARC', 'TPPNT', 'CMT', 'INC', 'MRID']\r\n keys_pro = ['ID', 'NOME', 'SCRAT', 'SCRDE', 'SCRPARAM', 'SCRDS', 'SCRRE', 'TINIC', 'ATIVA', 'ATVAT', 'ESSEN',\r\n 'HORAA', 'MONIT', 'NUATV', 'PERIO', 'TIPPR', 'TIPPAR', 'WATCHDOG', 'PRE_REQUISITO', 'CMT', 'INC',\r\n 'MRID']\r\n keys_cor = ['BLINK', 'COR_BLINK', 'COR_PERCENT_B', 'COR_PERCENT_G', 'COR_PERCENT_R', 'COR_PRINT', 'ID',\r\n 'ORDEM', 'CMT', 'INC', 'MRID']\r\n keys_ctx = ['COS', 'ID', 'NOME', 'CMT', 'INC', 'MRID']\r\n keys_cxp = ['CLASSE', 'PRO', 'CMT', 'INC', 'MRID']\r\n keys_grpocr = ['DESCR', 'ID', 'CMT', 'INC', 'MRID']\r\n keys_psv = ['GRUPO', 'NOME', 'PRESERV', 'CMT', 'INC', 'MRID']\r\n keys_tcl = ['DESCR', 'FORMULA', 'ID', 'NCOLUNAS', 'NOME', 'NSEQ', 'TITULOS', 'CMT', 'INC', 'MRID']\r\n keys_tcv = ['DESCR', 'ID', 'NOME', 'NSEQ', 'CMT', 'INC', 'MRID']\r\n keys_tn1 = ['DESCR', 'ID', 'NSEQ', 'CMT', 'INC', 'MRID']\r\n keys_tn2 = ['DESCR', 'ID', 'NSEQ', 'CMT', 'INC', 'MRID']\r\n keys_ttp = ['DESCR', 'ID', 'NSEQ', 'CMT', 'INC', 'MRID']\r\n keys_rfi = ['ORDEM', 'PNT', 'TIPOP', 'CMT', 'INC', 'MRID']\r\n\r\n self.atributos = {'pds': keys_pds, 'pdf': keys_pdf, 'pdd': keys_pdd, 'pas': keys_pas, 'paf': keys_paf,\r\n 'pad': keys_pad, 'ocr': keys_ocr, 'nv2': keys_nv2, 'nv1': keys_nv1, 'noh': keys_noh,\r\n 'mul': keys_mul, 'map': keys_map, 'lsc': keys_lsc, 'ins': keys_ins, 'inp': keys_inp,\r\n 'gsd': keys_gsd, 'grupo': keys_grupo, 'grcmp': keys_grcmp, 'enm': keys_enm, 'enu': keys_enu,\r\n 'e2m': keys_e2m, 'cxu': keys_cxu, 'cnf': keys_cnf, 'cgs': keys_cgs, 'cgf': keys_cgf,\r\n 'utr': keys_utr, 'tdd': keys_tdd, 'tctl': keys_tctl, 'tac': keys_tac, 'sev': keys_sev,\r\n 'rfc': keys_rfc, 'rca': keys_rca, 'pro': keys_pro, 'cor': keys_cor, 'ctx': keys_ctx,\r\n 'cxp': keys_cxp, 'grpocr': keys_grpocr, 'psv': keys_psv, 'tcl': keys_tcl, 'tcv': keys_tcv,\r\n 'tn1': keys_tn1, 'tn2': keys_tn2, 'ttp': keys_ttp, 'rfi': keys_rfi\r\n }\r\n\r\n self.entidades_limpas = {'pds': [], 'pdf': [], 'pdd': [], 'pas': [], 'paf': [], 'pad': [], 'ocr': [], 'nv2': [],\r\n 'nv1': [], 'noh': [], 'mul': [], 'map': [], 'lsc': [], 'ins': [], 'inp': [], 'gsd': [],\r\n 'grupo': [], 'grcmp': [], 'enm': [], 'enu': [], 'e2m': [], 'cxu': [], 'cnf': [],\r\n 'cgs': [], 'cgf': [], 'utr': [], 'tdd': [], 'tctl': [], 'tac': [], 'sev': [],\r\n 'rfc': [], 'rca': [], 'pro': [], 'cor': [], 'ctx': [], 'cxp': [], 'grpocr': [],\r\n 'psv': [], 'tcl': [], 'tcv': [], 'tn1': [], 'tn2': [], 'ttp': [], 'rfi': []\r\n }\r\n\r\n self.classes = {'pds': PDS(), 'pdf': PDF(), 'pdd': PDD(), 'pas': PAS(), 'paf': PAF(), 'pad': PAD(),\r\n 'ocr': OCR(), 'nv2': NV2(), 'nv1': NV1(), 'noh': NOH(), 'mul': MUL(), 'map': MAP(),\r\n 'lsc': LSC(), 'ins': INS(), 'inp': INP(), 'gsd': GSD(), 'grupo': GRUPO(), 'grcmp': GRCMP(),\r\n 'enm': ENM(), 'enu': ENU(), 'e2m': E2M(), 'cxu': CXU(), 'cnf': CNF(), 'cgs': CGS(),\r\n 'cgf': CGF(), 'utr': UTR(), 'tdd': TDD(), 'tctl': TCTL(), 'tac': TAC(), 'sev': SEV(),\r\n 'rfc': RFC(), 'rca': RCA(), 'pro': PRO(), 'cor': COR(), 'ctx': CTX(), 'cxp': CXP(),\r\n 'grpocr': GRPOCR(), 'psv': PSV(), 'tcl': TCL(), 'tcv': TCV(), 'tn1': TN1(), 'tn2': TN2(),\r\n 'ttp': TTP(), 'rfi': RFI()\r\n }\r\n\r\n self.entidades = {'configuradas': ('pds', 'pdf', 'pdd', 'pas', 'paf', 'pad', 'ocr', 'nv2', 'nv1', 'noh', 'mul',\r\n 'map', 'lsc', 'ins', 'inp', 'gsd', 'grupo', 'grcmp', 'enm', 'enu', 'e2m',\r\n 'cxu', 'cnf', 'cgs', 'cgf', 'utr', 'tdd', 'tctl', 'tac', 'sev', 'rfc', 'rca',\r\n 'pro', 'cor', 'ctx', 'cxp', 'grpocr', 'psv', 'tcl', 'tcv', 'tn1', 'tn2',\r\n 'ttp', 'rfi'),\r\n 'cepel': ('pro', 'ctx', 'inp', 'noh', 'sev', 'noct', 'prct', 'map', 'e2m', 'grpocr', 'ocr',\r\n 'tela', 'cfsis', 'tcv', 'ttp', 'gsd', 'cxu', 'enu', 'utr', 'mul', 'enm', 'cnm',\r\n 'psv', 'lsc', 'ins', 'tac', 'cgs', 'tctl', 'pas', 'pis', 'pts', 'pds', 'rca', 'tcl',\r\n 'site', 'cos', 'subsis', 'ptc', 'tempo', 'tgl', 'frd', 'dts', 'node_opc',\r\n 'refnh_opc', 'var_opc', 'tdd', 'pad', 'ptd', 'pdd', 'tnd', 'grp', 'cnf', 'nv1',\r\n 'nv2', 'tn1', 'tn2', 'cgf', 'paf', 'pdf', 'pif', 'ptf', 'rfi', 'rfc', 'aor', 'acao',\r\n 'gract', 'gr2act', 'papel', 'autoz', 'cor', 'grcmp', 'grupo', 'regra', 'qld', 'cag',\r\n 'bnd', 'cea', 'eca', 'flg', 'fxg', 'mrpg', 'tcg', 'uge', 'afp', 'are', 'bah', 'dpe',\r\n 'deqp', 'est', 'gca', 'gusi', 'lar', 'lct', 'pfc', 'regh', 'rio', 'slar', 'sme',\r\n 'subcia', 'teq', 'ude', 'usi', 'ufe', 'sis', 'reg', 'aco', 'cia', 'eano', 'estm',\r\n 'gbt', 'resv', 'tprede', 'bcp', 'cfu', 'cli', 'cnc', 'cpb', 'cre', 'cse', 'csi',\r\n 'guge', 'gugt', 'rea', 'sba', 'tat', 'car', 'ltr', 'ram', 'tr2', 'tr3', 'ugt',\r\n 'cnv', 'ele', 'elo', 'ldc', 'modp', 'modpv', 'frd_pas', 'ufe_pas', 'pmu', 'fasor',\r\n 'prfas', 'pdc', 'vsi')}\r\n\r\n\r\nclass PDS:\r\n def __init__(self, _id=None, _nome=None, _ocr=None, _tac=None, _cmt=None, _tcl=None, _stini='A', _stnor=None,\r\n _obsrv=None, _bdtr=None, _cdinic=None, _eqp=None, _histslc=None, _histslc_soe=None, _selsd=None,\r\n _tpeqp=None, _tpfil=None, _uapl=None, _atlzinv=None, _soein=None, _idiccp=None, _ee=None,\r\n _sincr_man=None, _invrt='NAO', _ncomiss=None, _pcondalr=None, _aor=None, _cia=None, _lscinf=None,\r\n _pmu=None, _subtipo1=None, _tela=None, _alint='SIM', _alrin='NAO', _idoper=None, ):\r\n\r\n self.ID = _id\r\n self.IDOPER = _idoper\r\n self.NOME = _nome\r\n self.OCR = _ocr\r\n self.ALINT = _alint\r\n self.ALRIN = _alrin\r\n self.TAC = _tac\r\n self.TCL = _tcl\r\n self.STINI = _stini\r\n self.STNOR = _stnor\r\n self.OBSRV = _obsrv\r\n self.BDTR = _bdtr\r\n self.CDINIC = _cdinic\r\n self.EQP = _eqp\r\n self.HISTSLC = _histslc\r\n self.HISTSLC_SOE = _histslc_soe\r\n self.SELSD = _selsd\r\n self.TPEQP = _tpeqp\r\n self.TPFIL = _tpfil\r\n self.UAPL = _uapl\r\n self.ATLZINV = _atlzinv\r\n self.SOEIN = _soein\r\n self.IDICCP = _idiccp\r\n self.EE = _ee\r\n self.SINCR_MAN = _sincr_man\r\n self.INVRT = _invrt\r\n self.NCOMISS = _ncomiss\r\n self.PCONDALR = _pcondalr\r\n self.AOR = _aor\r\n self.CIA = _cia\r\n self.LSCINF = _lscinf\r\n self.PMU = _pmu\r\n self.SUBTIPO1 = _subtipo1\r\n self.TELA = _tela\r\n self.CMT = _cmt\r\n self.entidade = 'PDS'\r\n\r\n @property\r\n def id(self):\r\n return self.ID\r\n\r\n @id.setter\r\n def id(self, _id):\r\n if len(_id) < 33:\r\n self.ID = _id\r\n else:\r\n raise ValueError('Tamanho Excedido, ID > 32')\r\n\r\n @property\r\n def nome(self):\r\n return self.NOME\r\n\r\n @nome.setter\r\n def nome(self, _nome):\r\n if len(_nome) < 63:\r\n self.NOME = _nome\r\n else:\r\n raise ValueError('Tamanho Excedido, Nome > 62')\r\n\r\n @property\r\n def obsrv(self):\r\n return self.OBSRV\r\n\r\n @obsrv.setter\r\n def obsrv(self, _obsrv):\r\n if len(_obsrv) < 43:\r\n self.OBSRV = _obsrv\r\n else:\r\n self.OBSRV = 'Tamanho Excedido, OBSRV > 42'\r\n\r\n def __str__(self):\r\n return f'Objeto tipo PDS, ID = {self.ID}'\r\n\r\n\r\nclass PDD:\r\n def __init__(self, _id=None, _pds=None, _tdd=None, _cmt=None):\r\n self.ID = _id\r\n self.PDS = _pds\r\n self.TDD = _tdd\r\n self.CMT = _cmt\r\n self.entidade = 'PDD'\r\n\r\n def __str__(self):\r\n return f'Objeto tipo PDD, ID = {self.ID}'\r\n\r\n\r\nclass PDF:\r\n def __init__(self, _id=None, _nv2=None, _ordem=None, _pnt=None, _tppnt=None, _desc1=None, _desc2=None, _kconv=None,\r\n _cmt=None):\r\n self.ID = _id\r\n self.NV2 = _nv2\r\n self.ORDEM = _ordem\r\n self.PNT = _pnt\r\n self.TPPNT = _tppnt\r\n self.DESC1 = _desc1\r\n self.DESC2 = _desc2\r\n self.KCONV = _kconv\r\n self.CMT = _cmt\r\n self.entidade = 'PDF'\r\n\r\n def __str__(self):\r\n return f'Objeto tipo PDF, ID = {self.ID}'\r\n\r\n\r\nclass NV2:\r\n def __init__(self, _id=None, _nv1=None, _ordem=None, _tn2=None, _tppnt=None, _config=None, _cmt=None):\r\n self.ID = _id\r\n self.NV1 = _nv1\r\n self.ORDEM = _ordem\r\n self.TN2 = _tn2\r\n self.TPPNT = _tppnt\r\n self.CONFIG = _config\r\n self.CMT = _cmt\r\n self.entidade = 'NV2'\r\n\r\n\r\nclass NV1:\r\n def __init__(self, _id=None, _cnf=None, _ordem=None, _tn1=None, _config=None, _cmt=None):\r\n self.ID = _id\r\n self.CNF = _cnf\r\n self.ORDEM = _ordem\r\n self.TN1 = _tn1\r\n self.CONFIG = _config\r\n self.CMT = _cmt\r\n self.entidade = 'NV1'\r\n\r\n\r\nclass CNF:\r\n def __init__(self, _config=None, _id=None, _lsc=None, _cmt=None):\r\n self.CONFIG = _config\r\n self.ID = _id\r\n self.LSC = _lsc\r\n self.CMT = _cmt\r\n self.entidade = 'CNF'\r\n\r\n def __str__(self):\r\n return f'Objeto tipo CNF, ID = {self.ID}'\r\n\r\n\r\nclass LSC:\r\n def __init__(self, _cos=None, _gsd=None, _id=None, _map=None, _nome=None, _nsrv1=None, _nsrv2=None, _site=None,\r\n _tcv=None, _tipo=None, _tpp=None, _verbd=None, _cmt=None):\r\n # 'COS', 'GSD', 'ID', 'MAP', 'NOME', 'NSRV1', 'NSRV2', 'SITE', 'TCV', 'TIPO', 'TTP', 'VERBD', 'CMT']\r\n self.COS = _cos\r\n self.GSD = _gsd\r\n self.ID = _id\r\n self.MAP = _map\r\n self.NOME = _nome\r\n self.NSRV1 = _nsrv1\r\n self.NSRV2 = _nsrv2\r\n self.SITE = _site\r\n self.TCV = _tcv\r\n self.TIPO = _tipo\r\n self.TPP = _tpp\r\n self.VERBD = _verbd\r\n self.CMT = _cmt\r\n self.entidade = 'LSC'\r\n\r\n\r\nclass MUL:\r\n def __init__(self, _cnf=None, _gsd=None, _guard=None, _id=None, _janel=None, _lsimp=None, _nome=None, _ordem=None,\r\n _trqml=None, _vprot=None, _cmt=None):\r\n # 'CNF', 'GSD', 'GUARD', 'ID', 'JANEL', 'LSIMP', 'NOME', 'ORDEM', 'TRQML', 'TRSTN', 'VPROT', 'CMT',\r\n self.CNF = _cnf\r\n self.GSD = _gsd\r\n self.GUARD = _guard\r\n self.ID = _id\r\n self.JANEL = _janel\r\n self.LSIMP = _lsimp\r\n self.NOME = _nome\r\n self.ORDEM = _ordem\r\n self.TRQML = _trqml\r\n self.VPROT = _vprot\r\n self.CMT = _cmt\r\n self.entidade = 'MUL'\r\n\r\n\r\nclass ENM:\r\n def __init__(self, _enpri=None, _ensec=None, _id=None, _janlk=None, _mul=None, _nome=None, _ordem=None, _parn1=None,\r\n _parn2=None, _part1=None, _tecon=None, _cmt=None):\r\n # 'ENPRI', 'ENSEC', 'ID', 'JANLK', 'MUL', 'NOME', 'ORDEM', 'PARN1', 'PARN2', 'PART1', 'TECON', 'CMT',\r\n self.ENPRI = _enpri\r\n self.ENSEC = _ensec\r\n self.ID = _id\r\n self.JANLK = _janlk\r\n self.MUL = _mul\r\n self.NOME = _nome\r\n self.ORDEM = _ordem\r\n self.PARN1 = _parn1\r\n self.PARN2 = _parn2\r\n self.PART1 = _part1\r\n self.TECON = _tecon\r\n self.CMT = _cmt\r\n self.entidade = 'ENM'\r\n\r\n\r\nclass TAC:\r\n def __init__(self, _id=None, _nome=None, _ins=None, _tpaqs=None, _lia=None, _lsa=None, _lsc=None, _cmt=None):\r\n # 'ID', 'NOME', 'INS', 'TPAQS', 'LIA', 'LSA', 'LSC', 'CMT', 'INC', 'MRID']\r\n self.ID = _id\r\n self.NOME = _nome\r\n self.INS = _ins\r\n self.TPAQS = _tpaqs\r\n self.LIA = _lia\r\n self.LSA = _lsa\r\n self.LSC = _lsc\r\n self.CMT = _cmt\r\n self.entidade = 'TAC'\r\n\r\n\r\nclass TDD:\r\n def __init__(self, _id=None, _nome=None, _lsc=None, _cmt=None):\r\n # ['ID', 'NOME', 'LSC', 'CMT', 'INC', 'MRID']\r\n self.ID = _id\r\n self.NOME = _nome\r\n self.LSC = _lsc\r\n self.CMT = _cmt\r\n self.entidade = 'TDD'\r\n\r\n\r\nclass RCA:\r\n def __init__(self, _fmult=None, _ordem=None, _parc=None, _pnt=None, _tipop=None, _tpparc=None, _tppnt=None,\r\n _cmt=None):\r\n # FMULT', 'ORDEM', 'PARC', 'PNT', 'TIPOP', 'TPPARC', 'TPPNT', 'CMT', 'INC', 'MRID'\r\n\r\n self.FMULT = _fmult\r\n self.ORDEM = _ordem\r\n self.PARC = _parc\r\n self.PNT = _pnt\r\n self.TIPOP = _tipop\r\n self.TPPARC = _tpparc\r\n self.TPPNT = _tppnt\r\n self.CMT = _cmt\r\n self.entidade = 'RCA'\r\n\r\n\r\nclass RFC:\r\n def __init__(self, _ordem=None, _parc=None, _pnt=None, _tpparc=None, _tppnt=None, _cmt=None):\r\n # 'ORDEM', 'PARC', 'PNT', 'TPPARC', 'TPPNT', 'CMT', 'INC', 'MRID']\r\n self.ORDEM = _ordem\r\n self.PARC = _parc\r\n self.PNT = _pnt\r\n self.TPPARC = _tpparc\r\n self.TPPNT = _tppnt\r\n self.CMT = _cmt\r\n self.entidade = 'RFC'\r\n\r\n\r\nclass PAS:\r\n def __init__(self, ID=None, IDOPER=None, NOME=None, TAC=None, LIA=None, LIE=None, LIU=None, LSA=None,\r\n LSE=None, LSU=None, ALINT=None, ALRIN=None, TCL=None, OCR=None, OBSRV=None, BDTR=None,\r\n BNDMO=None, CDINIC=None, DPE=None, EQP=None, EST=None, HISTPER=None, HTRIS=None, INVSN=None,\r\n SELSD=None, TEND=None, EE=None, PCONDALR=None, TERM=None, TIPO=None, TPEQP=None, TPFIL=None,\r\n TXVAR=None, UAPL=None, VLINIC=None, ATLZINV=None, PARM_CAG=None, IDICCP=None, LIUMI=None,\r\n LIAMI=None, LSAMI=None, LSUMI=None, LIULE=None, LIALE=None, LSALE=None, LSULE=None, LIUME=None,\r\n LIAME=None, LSAME=None, LSUME=None, LIUPE=None, LIAPE=None, LSAPE=None, LSUPE=None, LIUMA=None,\r\n LIAMA=None, LSAMA=None, LSUMA=None, HISTSLC=None, SINCR_MAN=None, EXCDEV=None, COMPDEV=None,\r\n STEP=None, NCOMISS=None, TMP_CURTA=None, TMP_LONGA=None, PRIO=None, AOR=None, CIA=None,\r\n HISTLIN=None, LSCINF=None, ORIGEM=None, PMU=None, PREVCAR=None, PTC=None, SUBTIPO1=None,\r\n TELA=None, CMT=None):\r\n self.ID = ID\r\n self.IDOPER = IDOPER\r\n self.NOME = NOME\r\n self.TAC = TAC\r\n self.LIA = LIA\r\n self.LIE = LIE\r\n self.LIU = LIU\r\n self.LSA = LSA\r\n self.LSE = LSE\r\n self.LSU = LSU\r\n self.ALINT = ALINT\r\n self.ALRIN = ALRIN\r\n self.TCL = TCL\r\n self.OCR = OCR\r\n self.OBSRV = OBSRV\r\n self.BDTR = BDTR\r\n self.BNDMO = BNDMO\r\n self.CDINIC = CDINIC\r\n self.DPE = DPE\r\n self.EQP = EQP\r\n self.EST = EST\r\n self.HISTPER = HISTPER\r\n self.HTRIS = HTRIS\r\n self.INVSN = INVSN\r\n self.SELSD = SELSD\r\n self.TEND = TEND\r\n self.EE = EE\r\n self.PCONDALR = PCONDALR\r\n self.TERM = TERM\r\n self.TIPO = TIPO\r\n self.TPEQP = TPEQP\r\n self.TPFIL = TPFIL\r\n self.TXVAR = TXVAR\r\n self.UAPL = UAPL\r\n self.VLINIC = VLINIC\r\n self.ATLZINV = ATLZINV\r\n self.PARM_CAG = PARM_CAG\r\n self.IDICCP = IDICCP\r\n self.LIUMI = LIUMI\r\n self.LIAMI = LIAMI\r\n self.LSAMI = LSAMI\r\n self.LSUMI = LSUMI\r\n self.LIULE = LIULE\r\n self.LIALE = LIALE\r\n self.LSALE = LSALE\r\n self.LSULE = LSULE\r\n self.LIUME = LIUME\r\n self.LIAME = LIAME\r\n self.LSAME = LSAME\r\n self.LSUME = LSUME\r\n self.LIUPE = LIUPE\r\n self.LIAPE = LIAPE\r\n self.LSAPE = LSAPE\r\n self.LSUPE = LSUPE\r\n self.LIUMA = LIUMA\r\n self.LIAMA = LIAMA\r\n self.LSAMA = LSAMA\r\n self.LSUMA = LSUMA\r\n self.HISTSLC = HISTSLC\r\n self.SINCR_MAN = SINCR_MAN\r\n self.EXCDEV = EXCDEV\r\n self.COMPDEV = COMPDEV\r\n self.STEP = STEP\r\n self.NCOMISS = NCOMISS\r\n self.TMP_CURTA = TMP_CURTA\r\n self.TMP_LONGA = TMP_LONGA\r\n self.PRIO = PRIO\r\n self.AOR = AOR\r\n self.CIA = CIA\r\n self.HISTLIN = HISTLIN\r\n self.LSCINF = LSCINF\r\n self.ORIGEM = ORIGEM\r\n self.PMU = PMU\r\n self.PREVCAR = PREVCAR\r\n self.PTC = PTC\r\n self.SUBTIPO1 = SUBTIPO1\r\n self.TELA = TELA\r\n self.CMT = CMT\r\n self.entidade = 'PAS'\r\n\r\n\r\nclass PAF:\r\n def __init__(self, id=None, nv2=None, ordem=None, pnt=None, tppnt=None, kconv1=None, kconv2=None, desc1=None,\r\n desc2=None, kconv4=None, kconv5=None, kconv3=None, modulo=None, cmt=None):\r\n self.ID = id\r\n self.NV2 = nv2\r\n self.ORDEM = ordem\r\n self.PNT = pnt\r\n self.TPPNT = tppnt\r\n self.KCONV1 = kconv1\r\n self.KCONV2 = kconv2\r\n self.DESC1 = desc1\r\n self.DESC2 = desc2\r\n self.KCONV4 = kconv4\r\n self.KCONV5 = kconv5\r\n self.KCONV3 = kconv3\r\n self.MODULO = modulo\r\n self.CMT = cmt\r\n self.entidade = 'PAF'\r\n\r\n\r\nclass PAD:\r\n def __init__(self):\r\n self.ID = None\r\n self.PAS = None\r\n self.TDD = None\r\n self.CMT = None\r\n self.entidade = 'PAD'\r\n\r\n\r\nclass OCR:\r\n def __init__(self, _aor=None, _autoe=None, _autor=None, _considera_aoi=None, _dur=None, _grpocr=None, _id=None,\r\n _nrep=None, _ocr_copia=None, _sever=None, _tela=None, _texto=None, _tipoe=None, _tsom=None,\r\n _tpusr=None, _cmt=None):\r\n self.AOR = _aor\r\n self.AUTOE = _autoe\r\n self.AUTOR = _autor\r\n self.CONSIDERA_AOI = _considera_aoi\r\n self.DUR = _dur\r\n self.GRPOCR = _grpocr\r\n self.ID = _id\r\n self.NREP = _nrep\r\n self.OCR_COPIA = _ocr_copia\r\n self.SEVER = _sever\r\n self.TELA = _tela\r\n self.TEXTO = _texto\r\n self.TIPOE = _tipoe\r\n self.TPSOM = _tsom\r\n self.TPUSR = _tpusr\r\n self.CMT = _cmt\r\n self.entidade = \"OCR\"\r\n\r\n\r\nclass NOH:\r\n def __init__(self):\r\n self.ENDIP = None\r\n self.ID = None\r\n self.NOME = None\r\n self.NTATV = None\r\n self.TPNOH = None\r\n self.CMT = None\r\n self.entidade = 'NOH'\r\n\r\n\r\nclass MAP:\r\n def __init__(self):\r\n self.ID = None\r\n self.NARRT = None\r\n self.ORDEM = None\r\n self.CMT = None\r\n self.entidade = 'MAP'\r\n\r\n pass\r\n\r\n\r\nclass INS:\r\n def __init__(self):\r\n self.ID = None\r\n self.LATIT = None\r\n self.LONGT = None\r\n self.NOME = None\r\n self.PTC = None\r\n self.SME = None\r\n self.TELA = None\r\n self.TIPO = None\r\n self.UFE = None\r\n self.CMT = None\r\n self.entidade = 'INS'\r\n\r\n\r\nclass INP:\r\n def __init__(self):\r\n self.NOH = None\r\n self.ORDEM = None\r\n self.PRO = None\r\n self.CMT = None\r\n self.entidade = 'INP'\r\n\r\n\r\nclass GSD:\r\n def __init__(self):\r\n self.ID = None\r\n self.NO1 = None\r\n self.NO2 = None\r\n self.NOME = None\r\n self.SITE = None\r\n self.CMT = None\r\n self.entidade = 'GSD'\r\n\r\n\r\nclass GRUPO:\r\n def __init__(self):\r\n self.APLIC = None\r\n self.COR_BG = None\r\n self.COR_FG = None\r\n self.ID = None\r\n self.NOME = None\r\n self.PNT = None\r\n self.TIPO = None\r\n self.TPPNT = None\r\n self.CMT = None\r\n self.entidade = 'GRUPO'\r\n\r\n\r\nclass GRCMP:\r\n def __init__(self):\r\n self.ACAO = None\r\n self.CORTXT = None\r\n self.GRUPO = None\r\n self.ORDEM1 = None\r\n self.ORDEM2 = None\r\n self.PARAM = None\r\n self.PNT = None\r\n self.TPPNT = None\r\n self.TPSIMB = None\r\n self.TPTXT = None\r\n self.TXT = None\r\n self.CMT = None\r\n self.entidade = 'GRCMP'\r\n\r\n\r\nclass ENU:\r\n def __init__(self):\r\n self.CXU = None\r\n self.ID = None\r\n self.NOME = None\r\n self.ORDEM = None\r\n self.TDESC = None\r\n self.TRANS = None\r\n self.VLUTR = None\r\n self.CMT = None\r\n self.entidade = 'ENU'\r\n\r\n\r\nclass E2M:\r\n def __init__(self):\r\n self.IDPTO = None\r\n self.MAP = None\r\n self.TIPO = None\r\n self.CMT = None\r\n self.entidade = 'E2M'\r\n\r\n\r\nclass CXU:\r\n def __init__(self):\r\n self.AQANL = None\r\n self.AQPOL = None\r\n self.AQTOT = None\r\n self.FAILP = None\r\n self.FAILR = None\r\n self.GSD = None\r\n self.ID = None\r\n self.INTGR = None\r\n self.NFAIL = None\r\n self.NOME = None\r\n self.ORDEM = None\r\n self.SFAIL = None\r\n self.CMT = None\r\n self.entidade = 'CXU'\r\n\r\n\r\nclass CGS:\r\n def __init__(self):\r\n self.ID = None\r\n self.IDOPER = None\r\n self.LMI1C = None\r\n self.LMI2C = None\r\n self.LMS1C = None\r\n self.LMS2C = None\r\n self.NOME = None\r\n self.OBSRV = None\r\n self.PAC = None\r\n self.PINT = None\r\n self.TAC = None\r\n self.TIPO = None\r\n self.TIPOE = None\r\n self.TPCTL = None\r\n self.TRRAC = None\r\n self.TBLOQ = None\r\n self.AOR = None\r\n self.IDICCP = None\r\n self.INVCT = None\r\n self.NCOMISS = None\r\n self.RSULT = None\r\n self.CMT = None\r\n self.entidade = 'CGS'\r\n\r\n\r\nclass CGF:\r\n def __init__(self):\r\n self.CGS = None\r\n self.CNF = None\r\n self.DESC1 = None\r\n self.DESC2 = None\r\n self.ID = None\r\n self.KCONV = None\r\n self.NOME = None\r\n self.NV2 = None\r\n self.OPCOES = None\r\n self.ORDEM = None\r\n self.CMT = None\r\n self.entidade = 'CGF'\r\n\r\n\r\nclass UTR:\r\n def __init__(self):\r\n self.ID = None\r\n self.CNF = None\r\n self.CXU = None\r\n self.ENUTR = None\r\n self.NTENT = None\r\n self.RESPT = None\r\n self.ORDEM = None\r\n self.NOME = None\r\n self.CMT = None\r\n self.entidade = 'UTR'\r\n\r\n\r\nclass TCTL:\r\n def __init__(self):\r\n self.ALR_CLOSE = None\r\n self.ALR_TRIP = None\r\n self.COR = None\r\n self.DLG_CLOSE = None\r\n self.DLG_TRIP = None\r\n self.ID = None\r\n self.NSEQ = None\r\n self.TIP = None\r\n self.CMT = None\r\n self.entidade = 'TCTL'\r\n\r\n\r\nclass SEV:\r\n def __init__(self):\r\n self.ID = None\r\n self.NOME = None\r\n self.CMT = None\r\n self.entidade = 'SEV'\r\n\r\n\r\nclass PRO:\r\n def __init__(self):\r\n self.ID = None\r\n self.NOME = None\r\n self.SCRAT = None\r\n self.SCRDE = None\r\n self.SCRPARAM = None\r\n self.SCRDS = None\r\n self.SCRRE = None\r\n self.TINIC = None\r\n self.ATIVA = None\r\n self.ATVAT = None\r\n self.ESSEN = None\r\n self.HORAA = None\r\n self.MONIT = None\r\n self.NUATV = None\r\n self.PERIO = None\r\n self.TIPPR = None\r\n self.TIPPAR = None\r\n self.WATCHDOG = None\r\n self.PRE_REQUISITO = None\r\n self.CMT = None\r\n self.entidade = 'PRO'\r\n\r\n\r\nclass COR:\r\n def __init__(self):\r\n self.BLINK = None\r\n self.COR_BLINK = None\r\n self.COR_PERCENT_B = None\r\n self.COR_PERCENT_G = None\r\n self.COR_PERCENT_R = None\r\n self.COR_PRINT = None\r\n self.ID = None\r\n self.ORDEM = None\r\n self.CMT = None\r\n self.entidade = 'COR'\r\n\r\n\r\nclass CTX:\r\n def __init__(self):\r\n self.COS = None\r\n self.ID = None\r\n self.NOME = None\r\n self.CMT = None\r\n self.entidade = 'CTX'\r\n\r\n\r\nclass CXP:\r\n def __init__(self):\r\n self.CLASSE = None\r\n self.PRO = None\r\n self.CMT = None\r\n self.entidade = 'CXP'\r\n\r\n\r\nclass GRPOCR:\r\n def __init__(self):\r\n self.DESCR = None\r\n self.ID = None\r\n self.CMT = None\r\n self.entidade = 'GRPOCR'\r\n\r\n\r\nclass PSV:\r\n def __init__(self):\r\n self.GRUPO = None\r\n self.NOME = None\r\n self.PRESERV = None\r\n self.CMT = None\r\n self.entidade = 'PSV'\r\n\r\n\r\nclass TCL:\r\n def __init__(self):\r\n self.DESCR = None\r\n self.FORMULA = None\r\n self.ID = None\r\n self.NCOLUNAS = None\r\n self.NOME = None\r\n self.NSEQ = None\r\n self.TITULOS = None\r\n self.CMT = None\r\n self.entidade = 'TCL'\r\n\r\n\r\nclass TCV:\r\n def __init__(self):\r\n self.DESCR = None\r\n self.ID = None\r\n self.NOME = None\r\n self.NSEQ = None\r\n self.CMT = None\r\n self.entidade = 'TCV'\r\n\r\n\r\nclass TN1:\r\n def __init__(self):\r\n self.DESCR = None\r\n self.ID = None\r\n self.NSEQ = None\r\n self.CMT = None\r\n self.entidade = 'TN1'\r\n\r\n\r\nclass TN2:\r\n def __init__(self):\r\n self.DESCR = None\r\n self.ID = None\r\n self.NSEQ = None\r\n self.CMT = None\r\n self.entidade = 'TN2'\r\n\r\n\r\nclass TTP:\r\n def __init__(self):\r\n self.DESCR = None\r\n self.ID = None\r\n self.NSEQ = None\r\n self.CMT = None\r\n self.entidade = 'TTP'\r\n\r\n\r\nclass RFI:\r\n def __init__(self):\r\n self.ORDEM = None\r\n self.PNT = None\r\n self.TIPOP = None\r\n self.CMT = None\r\n self.entidade = 'RFI'\r\n","sub_path":"Obj_Entidades.py","file_name":"Obj_Entidades.py","file_ext":"py","file_size_in_byte":30838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"318145934","text":"from message import Message\nclass ADDRESSBOOKMessage:\n '''\n Init appid,appkey,sign_type(Optional)\n '''\n def __init__(self,configs):\n self.configs = configs\n self.appid = configs['appid']\n self.appkey = configs['appkey']\n self.sign_type = ''\n if configs['sign_type'] != '':\n self.sign_type = configs['sign_type']\n self.address = ''\n self.target = ''\n \n '''\n set name and address\n '''\n def set_address(self, address, name=''):\n self.address = name+'<'+address+'>'\n\n '''\n set target\n '''\n def set_address_book(self, target):\n self.target = target\n\n '''\n build request array\n '''\n def build_request(self):\n request = {}\n '''\n set subscribe address\n '''\n request['address'] = self.address\n\n '''\n set target addressbook\n '''\n if self.target != '':\n request['target'] = self.target\n return request\n '''\n @subscribe\n '''\n def subscribe(self):\n message_configs = {}\n '''\n set appid and appkey\n '''\n message_configs['appid'] = self.appid\n message_configs['appkey'] = self.appkey\n\n '''\n set sign_type,if is set\n '''\n if self.sign_type != '':\n message_configs['sign_type'] = self.sign_type\n\n '''\n init mail class\n '''\n addressbook = Message(message_configs)\n\n '''\n build request and send email and return the result\n '''\n return addressbook.subscribe(self.build_request())\n\n '''\n @unsubscribe\n '''\n def unsubscribe(self):\n message_configs = {}\n '''\n set appid and appkey\n '''\n message_configs['appid'] = self.appid\n message_configs['appkey'] = self.appkey\n\n '''\n set sign_type,if is set\n '''\n if self.sign_type != '':\n message_configs['sign_type'] = self.sign_type\n\n '''\n init mail class\n '''\n addressbook = Message(message_configs)\n\n '''\n build request and send email and return the result\n '''\n return addressbook.unsubscribe(self.build_request())\n\n","sub_path":"submail/address_book_message.py","file_name":"address_book_message.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"161924428","text":"\nfrom base import *\n\nDEBUG = os.environ['DEBUG']\n\n# Enable security for website\n# Force HTTPS\nSECURE_SSL_REDIRECT = True # [1]\n\n# Update database configuration with $DATABASE_URL.\ndb_from_env = dj_database_url.config(conn_max_age=500)\nDATABASES['default'].update(db_from_env)\n\n","sub_path":"vaizlabs/settings/staging.py","file_name":"staging.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"142688011","text":"# encoding: utf-8\n\"\"\"\n@author: zeming li\n@contact: zengarden2009@gmail.com\n\"\"\"\n\nimport os\nfrom torch import nn\nfrom momentum_teacher.exps.arxiv.momentum2_teacher_exp import Exp as BaseExp\nfrom momentum_teacher.layers.optimizer import LARS_SGD\n\n\nclass Exp(BaseExp):\n def __init__(self):\n super(Exp, self).__init__()\n self.max_epoch = 100\n self.exp_name = os.path.split(os.path.realpath(__file__))[1].split(\".\")[0]\n\n # ----------------------- setting for 4096 batch-size -------------------------- #\n self.param_momentum = 0.99\n self.basic_lr_per_img = 0.45 / 256.0\n self.weight_decay = 1e-6\n\n def get_optimizer(self, batch_size):\n if \"optimizer\" not in self.__dict__:\n if self.warmup_epochs > 0:\n lr = self.warmup_lr\n else:\n lr = self.basic_lr_per_img * batch_size\n\n params_lars = []\n params_exclude = []\n for m in self.model.modules():\n if isinstance(m, nn.BatchNorm1d) or isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.SyncBatchNorm):\n params_exclude.append(m.weight)\n params_exclude.append(m.bias)\n elif isinstance(m, nn.Linear):\n params_lars.append(m.weight)\n params_exclude.append(m.bias)\n elif isinstance(m, nn.Conv2d):\n params_lars.extend(list(m.parameters()))\n\n assert len(params_lars) + len(params_exclude) == len(list(self.model.parameters()))\n\n self.optimizer = LARS_SGD(\n [{\"params\": params_lars, \"lars_exclude\": False}, {\"params\": params_exclude, \"lars_exclude\": True}],\n lr=lr,\n weight_decay=self.weight_decay,\n momentum=self.momentum,\n )\n return self.optimizer\n","sub_path":"momentum_teacher/exps/arxiv/exp_128_2080ti/momentum2_teacher_100e_4096batch_16mm_exp.py","file_name":"momentum2_teacher_100e_4096batch_16mm_exp.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"279750432","text":"import unittest\nfrom MatrixScrapper import cMatrixScrapper as MS\n\nclass MSTest(unittest.TestCase):\n def setUp(self):\n try:\n self._oMS = MS('AllPropScrapper', 'DEV')\n except:\n print(MS.__file__)\n raise\n\n def testSFH_Result_Details_Page(self):\n file = '..\\\\testData\\\\sfh.html'\n with open(file, 'r') as s:\n sHtml = s.read()\n self._oMS.ScrapSearchResultPropertyDetail(sHtml)\n\n return\n\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"MatrixScrapper/cMatrixScrapper_Test.py","file_name":"cMatrixScrapper_Test.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"179333118","text":"from collections import deque\n\n\ndef is_correct_parentheses(w):\n stack = []\n\n for char in w:\n if char == '(':\n stack.append(True)\n else:\n if stack:\n stack.pop()\n\n return len(stack) == 0\n\n\ndef reverse_parentheses(w):\n reverse = \"\"\n\n for char in w:\n if char == '(':\n reverse += ')'\n else:\n reverse += '('\n\n return reverse\n\n\ndef solution(p):\n if p == \"\":\n return \"\"\n\n queue = deque(p)\n u, v = \"\", \"\"\n left, right = 0, 0\n\n for char in p:\n if char == '(':\n left += 1\n else:\n right += 1\n\n u += queue.popleft()\n\n if left == right:\n v = ''.join(queue)\n break\n\n if is_correct_parentheses(u):\n return u + solution(v)\n else:\n return \"(\" + solution(v) + \")\" + reverse_parentheses(u[1: -1])\n\n\nprint(solution(\"(()())()\"))\n\n","sub_path":"programmers/2021_kakao_blind_recruitment/is_correct_parentheses.py","file_name":"is_correct_parentheses.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"53920172","text":"import http.client\nimport responseBuilder\nimport unittest\nfrom unittest.mock import MagicMock\n\n\nclass ResponseBuilder_ProcessResponseTests(unittest.TestCase):\n def test_SetsResponseStatusCodeAndResponseDataAndLocationheader(self):\n mock_response = MagicMock()\n mock_response.status = 200\n mock_response.headers = { \"Location\": \"the location\" }\n sut = responseBuilder.ResponseBuilder()\n sut._read_response = MagicMock(return_value=\"response data\")\n expected = \"response data\", 200, \"the location\"\n\n actual = sut.process_response(mock_response, True)\n\n self.assertEqual(expected, actual)\n\n def test_SetsResponseToNoneAndStatusCodeToTimeoutIfNoResponse(self):\n sut = responseBuilder.ResponseBuilder()\n\n data, status_code, _ = sut.process_response(None, True)\n\n self.assertEqual(None, data)\n self.assertEqual(http.client.GATEWAY_TIMEOUT, status_code)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"LinkChecker/tests/test_responseBuilder.py","file_name":"test_responseBuilder.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"630653466","text":"import scrapy\nfrom scrapy.http import FormRequest\n\n\nclass SpidyQuotesLoginSpider(scrapy.Spider):\n name = 'spidy-quotes-loginspider-v2'\n start_urls = ('https://spidyquotes.herokuapp.com/login',)\n download_delay = 2.0\n\n def parse(self, response):\n yield FormRequest.from_response(\n response,\n formdata={\n 'username': 'any',\n 'passwd': 'doesntmatter'\n },\n callback=self.after_login,\n )\n\n def after_login(self, response):\n self.log(response.css('h3 > a ::text').extract_first())\n for quote in response.css('div.quote'):\n yield {\n 'author': quote.css('small a ::text').extract_first(),\n 'author_url': quote.css('small a ::attr(href)').extract_first(),\n 'text': quote.css('span::text').extract_first(),\n 'tags': quote.css('.tags a::text').extract()\n }\n\n","sub_path":"examples/spidy-loginspider-v2.py","file_name":"spidy-loginspider-v2.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"357477151","text":"import json\nimport csv\nfrom heapq import heappush, heappop\nfrom cmp import cmp\n\ndebug_mode = False\n\n\ndef load(file_dir):\n course_file = \"round-final-02.csv\"\n accept_file = \"student-final-02.csv\"\n\n with open(f'{file_dir}/{course_file}', 'r', encoding='utf-8-sig') as course_file:\n course_list = csv.DictReader(course_file)\n course_map = {}\n join_amount = {}\n for i in course_list:\n course_map[i['_id']] = i\n course_map[i['_id']]['amount'] = 0\n course_map[i['_id']]['heap'] = []\n course_map[i['_id']]['min'] = False\n\n course_map[i['_id']]['receive_student_number'] = int(\n course_map[i['_id']]['receive_student_number'])\n\n if i[\"join_id\"]:\n join_id = i['university_id']+i[\"join_id\"]\n if not join_amount.get(join_id):\n join_amount[join_id] = []\n join_amount[join_id].append(i['_id'])\n\n with open(f'{file_dir}/{accept_file}') as student_file:\n reader = csv.DictReader(student_file)\n header = []\n accept_raw = []\n std_map = {}\n enroll_map = {}\n for num, line in enumerate(reader):\n if num == 0:\n header = [i for i in line]\n raw = [line[i] for i in line]\n accept_raw.append(raw)\n\n if not enroll_map.get(line['citizen_id']):\n enroll_map[line['citizen_id']] = {}\n enroll_map[line['citizen_id']][line['round_id']] = int(\n line['priority'])\n\n if not std_map.get(line['citizen_id']):\n std_map[line['citizen_id']] = []\n\n try:\n # if int(line['ranking']) == 0:\n # line['ranking'] = -99999\n # else:\n line['ranking'] = -float(line['ranking'])\n except:\n print(line)\n exit()\n std_map[line['citizen_id']].append(line)\n\n return course_map, join_amount, enroll_map, std_map, accept_raw, header\n\n\ndef add_std(course, score, std_id, mark):\n heappush(course['heap'], (score, std_id))\n course[\"amount\"] += 1\n mark[std_id][0] = True\n if debug_mode and course['_id'] == debug_course:\n print('+=', score, std_id)\n # print('++', course[\"amount\"],\n # course['receive_student_number'], course['heap'])\n\ndef unmark(mark, std_id):\n mark[std_id][0] = False\n mark[std_id][1] += 1\n\ndef comp_new(std, course, mark):\n # when someone kicked return 1 and return 0 otherwise\n # kick by mark[id] = (is_ok, order)\n # is_ok false mean need to compare order\n # order++ to next order\n\n if std['ranking'] == 0:\n mark[std['citizen_id']][1] += 1\n return 1\n\n kicks = []\n if not course['min'] or std['ranking'] > course['min']:\n add_std(course, std['ranking'], std['citizen_id'], mark)\n kicks = cmp(\n course['heap'], course['receive_student_number'], \\\n course['receive_add_limit']\n )\n\n # course['amount'] = len(course['heap'])\n course['amount'] += -len(kicks)\n for i in kicks:\n unmark(mark, i[1])\n course['min'] = i[0]\n else:\n unmark(mark, std['citizen_id'])\n return 1\n\n if debug_mode and course['_id'] == debug_course:\n print('-=', kicks, course['min'])\n\n return 1 if kicks else 0\n\ndef add(std_id, std_list, mark):\n if len(std_list) <= mark[std_id][1]:\n return False\n std = std_list[mark[std_id][1]]\n course = course_map[std['round_id']]\n if course[\"join_id\"]:\n join_id = course['university_id']+course[\"join_id\"]\n course = course_map[join_amount[join_id][0]]\n # kick = comp(std, course, mark)\n kick = comp_new(std, course, mark)\n return kick\n\n\ndef solve(course_map, std_map, mark):\n change = True\n t = 0\n while change:\n change = False\n x = 0\n for std_id, std_list in std_map.items():\n if not mark[std_id][0]:\n x += 1\n change |= add(std_id, std_list, mark)\n t += 1\n # print('#', t, x)\n\n\ndef get_real_order(std_id, course_id):\n x = enroll_map[std_id][course_id]\n y = 0\n for i in enroll_map[std_id].values():\n if i < x:\n y += 1\n return y+1\n\n\nif __name__ == \"__main__\":\n\n file_dir = './data/real/ver4'\n\n course_map, join_amount, enroll_map, std_map, accept_raw, header = load(\n file_dir)\n\n mark = {}\n for key, val in std_map.items():\n val.sort(key=lambda x: enroll_map[x['citizen_id']][x['round_id']])\n mark[key] = [False, 0]\n\n debug_id = '1248100003773'\n debug_course = '5e1afdd9552088a0512f60ce'\n # debug_mode = True\n\n solve(course_map, std_map, mark)\n\n if debug_mode:\n print(mark[debug_id])\n print(std_map[debug_id])\n print(enroll_map[debug_id])\n print(course_map[debug_course])\n # print(join_amount[course_map[debug_course]\n # ['university_id']+course_map[debug_course]['join_id']])\n\n print(','.join(header))\n output_file = \"chay-r4-test.csv\"\n # id_order = 7\n id_order = 1\n course_order = 5\n # pp = 0\n for i in accept_raw:\n if debug_mode:\n if i[id_order] == debug_id:\n print(i)\n print(mark[i[id_order]])\n print(enroll_map[i[id_order]][i[course_order]])\n else:\n if mark[i[id_order]][0]:\n p = get_real_order(i[id_order], i[course_order])\n if mark[i[id_order]][1]+1 == p:\n i[-1] = 2\n # pp += 1 # for count\n elif mark[i[id_order]][1]+1 > p:\n i[-1] = 8\n else:\n i[-1] = 9\n else:\n i[-1] = 8\n # print(','.join([str(j) for j in i]))\n\n if not debug_mode:\n with open(output_file, 'w') as csvfile:\n csvwriter = csv.writer(csvfile)\n csvwriter.writerow(header)\n for i in accept_raw:\n csvwriter.writerow(i)\n # print(pp)\n","sub_path":"main_test.py","file_name":"main_test.py","file_ext":"py","file_size_in_byte":6137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"501862518","text":"def rank3(x, y, z, ascending = True):\n tup = () #Contains the tuple that will eventually be returned\n\n if ascending: #If the numbers in the tuple must be in ascending order\n if x <= y and x <= z: #This whole if-elif-else checks which number (x, y, or z) is to be put in the tuple first for being the smallest\n tup += (x,)\n\n elif y <= x and y <= z:\n tup += (y,)\n\n else: #Marks end of the if-elif-else statement that determines which number is put first\n tup += (z,)\n\n if (x >= y and x <= z) or (x <= y and x >= z): #This whole if-elif-else checks which number (x, y, or z) is to be put in the tuple next for being in the middle\n tup += (x,)\n\n elif (y >= x and y <= z) or (y <= x and y >= z):\n tup += (y,)\n\n else: #Marks end of the if-elif-else statement that determines which number is put second\n tup += (z,)\n\n if x > y and x > z: #This whole if-elif-else checks which number (x, y, or z) is to be put in the tuple last for being in the biggest\n tup += (x,)\n\n elif y > x and y > z:\n tup += (y,)\n\n else: #Marks end of the if-elif-else statement that determines which number is put last\n tup += (z,)\n\n else: #If the numbers in the tuple must be in descending order\n if x > y and x > z: #This whole if-elif-else checks which number (x, y, or z) is to be put in the tuple first for being the biggest\n tup += (x,)\n\n elif y > x and y > z:\n tup += (y,)\n\n else: #Marks end of the if-elif-else statement that determines which number is put first\n tup += (z,)\n\n if (x >= y and x <= z) or (x <= y and x >= z): #This whole if-elif-else checks which number (x, y, or z) is to be put in the tuple next for being in the middle\n tup += (x,)\n\n elif (y >= x and y <= z) or (y <= x and y >= z):\n tup += (y,)\n\n else: #Marks end of the if-elif-else statement that determines which number is put second\n tup += (z,)\n\n if x <= y and x <= z: #This whole if-elif-else checks which number (x, y, or z) is to be put in the tuple last for being the smallest\n tup += (x,)\n\n elif y <= x and y <= z:\n tup += (y,)\n\n else: #Marks end of the if-elif-else statement that determines which number is put last\n tup += (z,)\n\n return tup #The final tuple is returned\n\ndef\tremove(val,\txs,\tlimit = None):\n count = 0 #Keeps track of how many times the value \"val\" is deleted from the list xs\n containsVal = False #Determines whether the list \"xs\" still contains the value \"val\"\n\n if limit != None: #Determines if the \"limit\" of the number of times \"val\" can be deleted from list \"xs\" is an actual number\n if limit < 0: #If it is, if it is a negative number, then no changes must be done to it\n return None\n\n while (count != limit or limit == None): #Keeps iterating through the list \"xs\" as long as the \"limit\" has not been reached or if there is no numerical limit\n for ind in range(len(xs)): #deletes the value that needs to be just once and adds on to the \"count\" of the number of times \"val\" has been deleted from \"xs\"\n if xs[ind] == val:\n del xs[ind]\n containsVal = True\n count += 1\n break\n\n if not containsVal: #If the list no longer contains the value needed to be deleted, the function is exited\n return None\n\n containsVal = False #Resets the \"containsVal\" variable so that it can check if \"val\" is still in the list \"xs\" in the next iteration\n\n return None #Exits the method just in case it is not already exited from the while loop\n\ndef filter_chars(msg, keeps = ''):\n newMsg = '' #Contains the string that will eventually be returned\n \n if keeps == '': #If there is no set of characters, \"keeps\", provided, then only letters will be added to the final string \"newMsg\"\n for str in msg:\n if str.isalpha():\n newMsg += str\n\n else: #Otherwise, only characters that both \"keeps\" and \"msg\" contain will be added to final string \"newMsg\"\n for str in msg:\n for s in keeps:\n if str == s:\n newMsg += s\n break\n\n return newMsg #The final string is returned\n\ndef relocate_evens(data, new_home = []):\n containsEvens = True #Checks whether \"data\" still has even numbers\n newEvens = [] #If there is no second paramater \"new_home\", this list of even numbers from \"data\" will be returned\n alreadyContained = False #Checks if the list \"new_home\" already has an even number\n noNewHome = False #Is true if there is no second parameter \"new_home\"\n count = 0 #Keeps a count of even numbers found in \"data\"\n\n if new_home == []: #If there is no second parameter \"new_home\" or if it is empty, then \"noNewHome\" is true indicating that there is no \"new_home\"\n noNewHome = True\n\n while containsEvens: #Keeps on looping if there are still even numbers in \"data\"\n for ind in range(len(data)): #Checking through out the list \"data\"\n if data[ind] % 2 == 0: #If an even number is found in \"data\", then \"containsEvens\" indicating the list includes evens and the \"count\" is incremented\n containsEvens = True\n count += 1\n newEvens.append(data[ind]) #Keeps a list of the even numbers found in case there is no \"new_home\"\n\n for i in range(len(new_home)): #Checks if \"new_home\" already has the even number found in \"data\"\n if new_home[i] == data[ind]:\n alreadyContained = True\n\n if not alreadyContained and not noNewHome: #If it doesn't already contain the even and if the list exits, \"new_home\" is appended with the even\n new_home.append(data[ind])\n\n del data[ind] #Deletes the even from the orginial list \"data\"\n break #Goes back to the top loop because a new list \"data\" is formed after the deletion\n\n if count == 0: #If there are no evens found and counted, then \"containsEvens\" is false and the whole loop must end\n containsEvens = False\n\n count = 0 #\"count\" resets\n\n if not noNewHome: #If there is a second parameter \"new_home\" already, then that list is returned with the evens appended to it in the previous loop\n return new_home\n\n else: #If there is no second parameter \"new_home\" then just the list of even_numbers found in \"data\" is returned (\"newEvens\")\n return newEvens\n","sub_path":"GMU CS 112 by Zayn Hasan/GMU CS/zhasan4_226_L7.py","file_name":"zhasan4_226_L7.py","file_ext":"py","file_size_in_byte":6658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"115717594","text":"class Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n if not strs:\n return \"\"\n else:\n minn = min(strs)\n maxn = max(strs)\n for i,element in enumerate(minn):\n if(element != maxn[i]):\n return minn[:i]\n return minn\n","sub_path":"src/Python/STL/0014.Longest Common Prefix 最长公共前缀.py","file_name":"0014.Longest Common Prefix 最长公共前缀.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"20869851","text":"import socket\r\nimport sys\r\nfrom Database.database import *\r\n\r\nserverAddressPort = (\"168.122.206.223\", 20001)\r\n\r\nbufferSize = 1024\r\n\r\n# Create a UDP socket at client side\r\nUDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)\r\n\r\nstatus = input('Do you want to be discovered? ')\r\n\r\nprint('please input messages that you what to send: ')\r\n\r\n# Send to server using created UDP socket\r\nif status == 'yes':\r\n\tmessages = msg_sending(cursor)\r\n\tfor message in messages:\r\n\t\tbytesToSend = message.encode()\r\n\t\tUDPClientSocket.sendto(bytesToSend, serverAddressPort)\r\n\r\n\twhile True:\r\n\r\n\t\tline = input()\r\n\r\n\t\tbytesToSend = line.encode()\r\n\r\n\t\tUDPClientSocket.sendto(bytesToSend, serverAddressPort)\r\n\r\n\t\tmsgFromServer = UDPClientSocket.recvfrom(bufferSize)\r\n\r\n\t\tmsg = \"Message from Server {}\".format(msgFromServer[0])\r\n\t\tprint(msg)\r\n\r\n\t\t\r\n\r\nelse:\r\n\tname = input('Who do you want to talk to? ')\r\n\tfor line in sys.stdin:\r\n\t\ttry:\r\n\t\t\tmsg_to_send(cursor, name, line)\r\n\t\texcept:\r\n\t\t\tprint('The person you want to chat is not in address book, please add it')\r\n\t\t\tip = input('please enter his/her ip address: ')\r\n\t\t\tcreate_user(cursor, name, ip)\r\n","sub_path":"Chat/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"505469080","text":"import tensorflow as tf\nfrom networks.configurations.cnn import CNNConfig\nfrom networks.architectures.base import NeuralNetwork\nfrom core.env import stemmer\nimport utils\n\n\nclass VanillaCNN(NeuralNetwork):\n\n def __init__(self, config, embedding_shape):\n assert(isinstance(config, CNNConfig))\n self.cfg = config\n\n tf.reset_default_graph()\n\n batch_size = self.cfg.bag_size * self.cfg.bags_per_minibatch\n embedding_size_p = embedding_shape[1] + 2 + (self.cfg.pos_emb_size if self.cfg.use_pos else 0)\n\n # Hidden state variables\n W = tf.Variable(tf.random_normal([self.cfg.filters_count, self.cfg.output_classes]), dtype=tf.float32)\n bias = tf.Variable(tf.random_normal([self.cfg.output_classes]), dtype=tf.float32)\n conv_filter = tf.Variable(tf.random_normal([self.cfg.window_size * embedding_size_p, 1, self.cfg.filters_count]), dtype=tf.float32)\n\n # Input placeholders\n self.x = tf.placeholder(dtype=tf.int32, shape=[batch_size, self.cfg.words_per_news])\n self.dist_from_subj = tf.placeholder(dtype=tf.float32, shape=[batch_size, self.cfg.words_per_news])\n self.dist_from_obj = tf.placeholder(dtype=tf.float32, shape=[batch_size, self.cfg.words_per_news])\n self.y = tf.placeholder(dtype=tf.int32, shape=[batch_size])\n self.E = tf.placeholder(dtype=tf.float32, shape=embedding_shape)\n bernoulli = tf.distributions.Bernoulli(self.cfg.dropout, dtype=tf.float32)\n # Part of Speech parameters\n self.pos = tf.placeholder(tf.int32, shape=[batch_size, self.cfg.words_per_news])\n self.pos_emb = tf.get_variable(dtype=tf.float32, shape=[len(stemmer.pos_names), self.cfg.pos_emb_size], trainable=True, name=\"pos_emb\")\n\n # Apply embeding for input x indices\n emb_words = tf.nn.embedding_lookup(self.E, self.x)\n\n # Part of speech embedding\n if self.cfg.use_pos:\n emb_pos = tf.nn.embedding_lookup(self.pos_emb, self.pos)\n emb_words = tf.concat([emb_words, emb_pos], axis=-1)\n\n emb_words = utils.merge_with_embedding(emb_words, [self.dist_from_subj, self.dist_from_obj])\n\n # Add padding embedding rows (reason -- have the same amount of rows after conv1d).\n left_padding = (self.cfg.window_size - 1) / 2\n right_padding = (self.cfg.window_size - 1) - left_padding\n emb_words = tf.pad(emb_words, [[0, 0], [left_padding, right_padding], [0, 0]])\n\n # Concatenate rows of matrix\n bwc_line = tf.reshape(emb_words, [batch_size, (self.cfg.words_per_news + (self.cfg.window_size - 1)) * embedding_size_p, 1])\n bwc_conv = tf.nn.conv1d(bwc_line, conv_filter, embedding_size_p, \"VALID\", data_format=\"NHWC\", name=\"conv\")\n bwgc_conv = tf.reshape(bwc_conv, [batch_size, 1, self.cfg.words_per_news, self.cfg.filters_count])\n\n # Maxpool\n bwgc_mpool = tf.nn.max_pool(\n bwgc_conv,\n [1, 1, self.cfg.words_per_news, 1],\n [1, 1, self.cfg.words_per_news, 1],\n padding='VALID',\n data_format=\"NHWC\")\n\n bc_mpool = tf.squeeze(bwgc_mpool, axis=[1, 2])\n bc_pmpool = tf.reshape(bc_mpool, [batch_size, self.cfg.filters_count])\n g = tf.tanh(bc_pmpool)\n\n self.labels = tf.argmax(self.get_logits(g, W, bias), axis=1)\n\n if self.cfg.use_bernoulli_mask:\n # Apply Bernoulli mask for 'g'\n r = bernoulli.sample(sample_shape=[1, 3*self.cfg.filters_count])\n r_batch = tf.matmul(tf.constant(1, shape=[batch_size, 1], dtype=tf.float32), r)\n g = tf.multiply(g, r_batch)\n\n logits_unscaled_dropout = tf.nn.dropout(\n self.get_logits(g, W, bias),\n self.cfg.dropout)\n\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits=logits_unscaled_dropout,\n labels=self.y)\n cross_entropy_per_bag = tf.reshape(cross_entropy, [self.cfg.bags_per_minibatch, self.cfg.bag_size])\n\n self.cost = tf.reduce_max(cross_entropy_per_bag, axis=1)\n\n def get_feed_dict(self, X, labels, dist_from_subj, dist_from_obj, embedding, pos=None):\n feed_dict = {\n self.x: X,\n self.y: labels,\n self.dist_from_subj: dist_from_subj,\n self.dist_from_obj: dist_from_obj,\n self.E: embedding\n }\n\n if self.cfg.use_pos:\n feed_dict[self.pos] = pos\n\n return feed_dict\n\n @staticmethod\n def get_logits(g, W, bias):\n return tf.matmul(g, W) + bias\n\n @property\n def Cost(self):\n return self.cost\n\n @property\n def Labels(self):\n return self.labels\n\n @property\n def ParametersDictionary(self):\n return self.cfg.get_paramters()\n","sub_path":"networks/architectures/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":4771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"238998111","text":"import nltk\nfrom nltk import collections\nfrom nltk.corpus import brown\n\n\nCOMPILED_BROWN = 'brown.pickle'\n\nBROWN_CATEGORIES = ('adventure', 'fiction', 'government', 'humor', 'news')\ntext = \"\"\nwords = \"\"\n\n\nclass BrownCorpus(object):\n\n def __init__(self):\n self.words = nltk.corpus.brown.tagged_words()\n\n self.text = \" \".join(brown.words()).lower()\n\n\ndef nouns_more_common_in_plural_form(bc):\n sentence = \"\"\n set_singal = set()\n set_plural = set()\n # puts singular and plural nouns into different sets\n for word in bc.words:\n if word[1] == \"NN\":\n set_singal.add(word[0])\n sentence += \" \" + word[0]\n elif word[1] == \"NNS\" and word[0].isalpha():\n set_plural.add(word[0][:-1])\n sentence += \" \" + word[0]\n sentence = sentence.lower()\n final_set = set()\n\n # puts all the nouns that are plural and singular into fd\n fd = nltk.FreqDist(nltk.word_tokenize(sentence))\n # adds to final set if the singular form is greater within the plural version\n for m in set_singal:\n if fd.__contains__(m + \"s\") and fd.get(m + \"s\") > fd.get(m) and set_plural.__contains__(m):\n final_set.add(m)\n\n # removes from singal set\n for m in set_singal:\n if set_plural.__contains__(m):\n set_plural.remove(m)\n # adds to final set the remainder\n for m in set_plural:\n final_set.add(m)\n\n return final_set\n\n\ndef which_word_has_greatest_number_of_distinct_tags(bc):\n word_tag = nltk.defaultdict(set)\n for w, t in bc.words:\n if w.isalpha():\n word_tag[w.lower()].add(t)\n m = max(len(word_tag[w]) for w in word_tag)\n return [(w, t) for w, t in word_tag.items() if len(t) == m]\n\n\ndef tags_in_order_of_decreasing_frequency(bc):\n counts = collections.Counter((subl[1] for subl in bc.words))\n return counts.most_common(20)\n\n\ndef tags_that_nouns_are_most_commonly_found_after(bc):\n word_tag_pairs = nltk.bigrams(bc.words)\n # finds the tags that are NN , NNS , NNP or NNPS which represents nouns\n proceding_nouns = [a[1] for (a, b) in word_tag_pairs if\n b[1] == \"NN\" or b[1] == \"NNS\" or b[1] == \"NNP\" or b[1] == \"NNPS\"]\n # puts into fd\n fd = nltk.FreqDist(proceding_nouns)\n # finds the most common\n return [(tag, v) for (tag, v) in fd.most_common()]\n\n\ndef proportion_ambiguous_word_types(bc):\n brown_tagged_words = bc.words\n cfd = nltk.ConditionalFreqDist(brown_tagged_words)\n conditions = cfd.conditions()\n mono_tags = [condition for condition in conditions if len(cfd[condition]) == 1]\n proportion_mono_tags = len(mono_tags) / len(conditions)\n\n return 1 - proportion_mono_tags\n\n\ndef proportion_ambiguous_word_tokens(bc):\n dict_tagged = {}\n for tuple in bc.words:\n word = tuple[0].lower()\n if word not in dict_tagged.keys():\n dict_tagged[word] = set()\n dict_tagged[word].add(tuple[1])\n\n fd = nltk.FreqDist([tag[0] for tag in bc.words])\n count = 0\n for word in dict_tagged.keys():\n if len(dict_tagged[word]) == 1:\n count += fd.get(word, 0)\n total = len(bc.words)\n return 1 - (count / total)\n","sub_path":"assigmentFour/TextAnalysis/brown.py","file_name":"brown.py","file_ext":"py","file_size_in_byte":3175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"181157121","text":"from jarvis.core.graphs import StructureDataset, Graph\nfrom jarvis.db.figshare import data\n\n\ndef test_graph():\n from jarvis.core.atoms import Atoms\n from jarvis.db.figshare import get_jid_data\n\n atoms = Atoms.from_dict(get_jid_data(\"JVASP-664\")[\"atoms\"])\n feature_sets = (\"atomic_number\", \"basic\", \"cfid\", \"cgcnn\")\n for i in feature_sets:\n g = Graph.atom_dgl_multigraph(atoms=atoms, atom_features=i)\n print(i, g)\n g = Graph.from_atoms(atoms=atoms, features=\"atomic_number\")\n g = Graph.from_atoms(atoms=atoms, features=\"atomic_fraction\")\n g = Graph.from_atoms(\n atoms=atoms,\n features=\"basic\",\n get_prim=True,\n zero_diag=True,\n node_atomwise_angle_dist=True,\n node_atomwise_rdf=True,\n )\n g = Graph.from_atoms(\n atoms=atoms,\n features=\"cfid\",\n get_prim=True,\n zero_diag=True,\n node_atomwise_angle_dist=True,\n node_atomwise_rdf=True,\n )\n g = Graph.from_atoms(\n atoms=atoms,\n features=\"atomic_number\",\n get_prim=True,\n zero_diag=True,\n node_atomwise_angle_dist=True,\n node_atomwise_rdf=True,\n )\n g = Graph.from_atoms(atoms=atoms, features=\"basic\")\n g = Graph.from_atoms(\n atoms=atoms, features=[\"Z\", \"atom_mass\", \"max_oxid_s\"]\n )\n g = Graph.from_atoms(atoms=atoms, features=\"cfid\", max_cut=10000)\n print(g)\n d = g.to_dict()\n g = Graph.from_dict(d)\n num_nodes = g.num_nodes\n num_edges = g.num_edges\n print(num_nodes, num_edges)\n assert num_nodes == 48\n assert num_edges == 2256\n assert (g.adjacency_matrix.shape) == (48, 48)\n\n\ndef test_dataset():\n d = data(\"dft_2d\")\n x = []\n y = []\n z = []\n for i in d[0:100]:\n if i[\"formation_energy_peratom\"] != \"na\":\n x.append(i[\"atoms\"])\n y.append(i[\"formation_energy_peratom\"])\n z.append(i[\"jid\"])\n s = StructureDataset(x, y, ids=z)\n\n\n# test_graph()\n","sub_path":"jarvis/tests/testfiles/core/test_graph.py","file_name":"test_graph.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"171726054","text":"import hashlib\r\nimport pyperclip\r\n\r\n\r\n# With terminal:\r\n\r\n'''\r\n\r\nword = str(input(\"Enter a word to hash: \")).encode()\r\n\r\nprint(f\"hashed value of {word.decode()}: \\n{hashlib.blake2b(word).hexdigest()}\")\r\n\r\ncopy = input(\"Do you want to copy hash to clipboard? (Y/n) \")\r\n\r\nif(copy == \"Y\" or copy == \"y\" or copy == \"yes\"):\r\n pyperclip.copy(hashlib.blake2b(word).hexdigest())\r\n print(\"Hash copied !\")\r\nelse:\r\n pass \r\n'''\r\n\r\n# with GUI :\r\n\r\nfrom PyQt5 import QtWidgets, uic \r\nfrom PyQt5.QtWidgets import QMessageBox, QDesktopWidget\r\nimport sys\r\n\r\n\r\nclass Ui(QtWidgets.QMainWindow):\r\n def __init__(self):\r\n super(Ui, self).__init__()\r\n uic.loadUi('hasher_design.ui', self)\r\n \r\n # self.findChild(QtWidgets.QPushButton, 'HelloBtn').clicked.connect(self.hello)\r\n self.hashButton.clicked.connect(self.startHash)\r\n \r\n self.show()\r\n\r\n def startHash(self):\r\n self.word = str(self.lineEdit.text()).encode()\r\n self.label_2.setText(hashlib.blake2b(self.word).hexdigest())\r\n self.setGeometry(360,250,660, 300)\r\n self.copyButton.setEnabled(True)\r\n self.copyButton.clicked.connect(self.copyHash)\r\n \r\n\r\n def copyHash(self):\r\n pyperclip.copy(hashlib.blake2b(self.word).hexdigest())\r\n print(\"Copied!\") \r\napp = QtWidgets.QApplication(sys.argv)\r\nwindow = Ui()\r\napp.exec_()\r\n","sub_path":"hasher.py","file_name":"hasher.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"529492739","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport h5py\nimport tensorflow as tf\n\nclass Model(object):\n def __init__(self, **kwargs):\n self.X_placeholder = kwargs.pop('X_placeholder')\n self.Y_placeholder = kwargs.pop('Y_placeholder')\n self.trainflag_placeholder = kwargs.pop('trainflag_placeholder')\n self.X_processed = kwargs.pop('X_processed')\n self.nnet = kwargs.pop('nnet')\n self.train_ops = kwargs.pop('train_ops')\n self.predict_op = kwargs.pop('predict_op')\n self.sess = kwargs.pop('sess')\n self.saver = kwargs.pop('saver')\n\n\ndef dense_layer_ops(X, num_X, num_Y, config):\n W = tf.Variable(tf.truncated_normal([num_X, num_Y],\n mean=0.0,\n stddev=config.var_init_stddev),\n name='W')\n B = tf.Variable(tf.constant(value=config.bias_init,\n dtype=tf.float32,\n shape=[num_Y]),\n name='B')\n Y = tf.add(tf.matmul(X, W), B, name='Y')\n\n return W,B,Y\n\ndef get_reg_term(config, vars_to_reg):\n reg_term = tf.constant(value=0.0, dtype=tf.float32)\n if (config.l2reg>0.0 or config.l1reg>0.0) and len(vars_to_reg)>0:\n for x_var in vars_to_reg:\n if config.l2reg>0.0:\n x_squared = x_var * x_var\n l2norm = tf.reduce_sum(x_squared)\n reg_term += config.l2reg * l2norm\n if config.l1reg>0.0:\n x_abs = tf.abs(x_var)\n l1norm = tf.reduce_sum(x_abs)\n reg_term += config.l1reg * l1norm\n return reg_term\n\ndef cross_entropy_loss_ops(logits, labels, config, vars_to_reg):\n cross_entropy_loss_all = tf.nn.softmax_cross_entropy_with_logits(logits, labels)\n loss = tf.reduce_mean(cross_entropy_loss_all)\n reg_term = get_reg_term(config, vars_to_reg)\n opt_loss = loss + reg_term\n return loss, opt_loss\n\nclass LinearClassifier(object):\n def __init__(self, num_features, num_outputs, config,\n features_dtype=tf.float32, labels_dtype=tf.float32):\n self.num_features = num_features\n self.num_outputs = num_outputs\n self.config = config\n self.vars_to_init = []\n \n with tf.name_scope(name='logits'):\n self.X_pl = tf.placeholder(dtype=features_dtype, shape=(None, num_features), name='X')\n self.Y_pl = tf.placeholder(dtype=labels_dtype, shape=(None, num_outputs), name='Y')\n self.W, self.B, self.logits = dense_layer_ops(X=self.X_pl,\n num_X=num_features,\n num_Y=num_outputs,\n config=config)\n \n with tf.name_scope(name='loss'):\n self.loss, self.opt_loss = cross_entropy_loss_ops(logits=self.logits,\n labels=self.Y_pl,\n config=config,\n vars_to_reg=[self.W])\n self.vars_to_init.extend([self.W, self.B])\n \n def get_training_feed_dict(self,X,Y):\n feed_dict = {self.X_pl:X, self.Y_pl:Y}\n return feed_dict\n\n def get_validation_feed_dict(self,X,Y):\n feed_dict = {self.X_pl:X, self.Y_pl:Y}\n return feed_dict\n\n def train_ops(self):\n return []\n\n def predict_op(self):\n return self.logits\n \n def get_W_B(self, sess):\n return sess.run([self.W, self.B])\n\n def get_logits(self, sess):\n return sess.run([self.logits])[0]\n\n def save(self, h5group, sess):\n h5group['W'], h5group['B'] =self.get_W_B(sess)\n \n def restore(self, h5group, sess):\n W = h5group['W'][:]\n B = h5group['B'][:]\n sess.run(self.W.assign(W))\n sess.run(self.B.assign(B))\n\n def restore_from_file(self, fname, sess):\n h5 = h5py.File(fname)\n h5group = h5['model']\n self.restore(h5group, sess)\n \n","sub_path":"psmlearn/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"10725430","text":"'''\nbinary search\n367. Valid Perfect Square\n\nGiven a positive integer num, write a function which returns True if num is a perfect square else False.\n'''\nclass Solution(object):\n def isPerfectSquare(self, num):\n if num <= 0:\n return False\n if num == 1:\n return True\n right, left = num // 2 + 1, 1\n while right > left + 1:\n mid = (right + left) // 2\n if mid * mid == num:\n return True\n elif mid * mid < num:\n print(\"search for the larger half :\", mid)\n left = mid\n else: # 往小的那半找\n print(\"search for the smaller half :\", mid)\n right = mid\n return False\nif __name__ == '__main__':\n res = Solution().isPerfectSquare(100)\n print(res)\n","sub_path":"367_validSquare.py","file_name":"367_validSquare.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"461607441","text":"import torch\nimport torch.nn as nn\nimport torchvision\nimport numpy as np\n\nimport torch.nn.functional as F\nprint(\"PyTorch Version: \",torch.__version__)\nprint(\"Torchvision Version: \",torchvision.__version__)\n\n__all__ = ['ResNet50', 'ResNet101','ResNet152']\n\ndef Conv1(in_planes, places, stride=2):\n return nn.Sequential(\n nn.Conv2d(in_channels=in_planes,out_channels=places,kernel_size=7,stride=stride,padding=3, bias=False),\n nn.BatchNorm2d(places),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n )\n\nclass Bottleneck(nn.Module):\n def __init__(self,in_places,places, stride=1,downsampling=False, expansion = 4):\n super(Bottleneck,self).__init__()\n self.expansion = expansion\n self.downsampling = downsampling\n\n self.bottleneck = nn.Sequential(\n nn.Conv2d(in_channels=in_places,out_channels=places,kernel_size=1,stride=1, bias=False),\n nn.BatchNorm2d(places),\n nn.ReLU(inplace=True),\n nn.Conv2d(in_channels=places, out_channels=places, kernel_size=3, stride=stride, padding=1, bias=False),\n nn.BatchNorm2d(places),\n nn.ReLU(inplace=True),\n nn.Conv2d(in_channels=places, out_channels=places*self.expansion, kernel_size=1, stride=1, bias=False),\n nn.BatchNorm2d(places*self.expansion),\n )\n\n if self.downsampling:\n self.downsample = nn.Sequential(\n nn.Conv2d(in_channels=in_places, out_channels=places*self.expansion, kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(places*self.expansion)\n )\n self.relu = nn.ReLU(inplace=True)\n def forward(self, x):\n residual = x\n out = self.bottleneck(x)\n\n if self.downsampling:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n return out\n\nclass ResNet(nn.Module):\n def __init__(self,blocks, num_classes=512, expansion = 4):\n super(ResNet,self).__init__()\n self.expansion = expansion\n\n self.conv1 = Conv1(in_planes = 3, places= 64)\n\n self.layer1 = self.make_layer(in_places = 64, places= 64, block=blocks[0], stride=1)\n self.layer2 = self.make_layer(in_places = 256,places=128, block=blocks[1], stride=2)\n self.layer3 = self.make_layer(in_places=512,places=256, block=blocks[2], stride=2)\n self.layer4 = self.make_layer(in_places=1024,places=512, block=blocks[3], stride=2)\n\n self.avgpool = nn.AvgPool2d(7, stride=1)\n self.fc = nn.Linear(2048,num_classes)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n def make_layer(self, in_places, places, block, stride):\n layers = []\n layers.append(Bottleneck(in_places, places,stride, downsampling =True))\n for i in range(1, block):\n layers.append(Bottleneck(places*self.expansion, places))\n\n return nn.Sequential(*layers)\n\n\n def forward(self, x):\n x = self.conv1(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n return x\n\nclass pose_Net(nn.Module):\n def __init__(self):\n super(pose_Net,self).__init__()\n self.input = torch.nn.Linear(4, 256)\n self.hidden1 = torch.nn.Linear(256,512)\n self.hidden2 = torch.nn.Linear(512,512)\n self.hidden3 = torch.nn.Linear(512, 512)\n self.out = torch.nn.Linear(512,512)\n def forward(self,x):\n x = torch.relu(self.input(x.cuda()))\n x = torch.relu(self.hidden1(x))\n x = torch.relu(self.hidden2(x))\n x = torch.relu(self.hidden3(x))\n return x\ndef ResNet50():\n return ResNet([3, 4, 6, 3])\n\ndef ResNet101():\n return ResNet([3, 4, 23, 3])\n\ndef ResNet152():\n return ResNet([3, 8, 36, 3])\nclass ActionDetect_Net(nn.Module):\n def __init__(self):\n super(ActionDetect_Net,self).__init__()\n self.resnet = ResNet50()\n self.posenet = pose_Net()\n\n self.hidden1 = torch.nn.Linear(1024, 512)\n self.hidden2 = torch.nn.Linear(512, 512)\n self.hidden3 = torch.nn.Linear(512, 512)\n self.out = torch.nn.Linear(512, 3)\n\n def forward(self,pose,pic):\n x_pose = self.posenet(pose)\n x_resnet = self.resnet(pic)\n #print(x_pose.shape,x_resnet.shape)\n x = torch.cat((x_pose,x_resnet),1)\n x = torch.relu(self.hidden1(x))\n #x.retain_grad()\n #print(x.grad)\n x = torch.relu(self.hidden2(x))\n x = torch.relu(self.hidden3(x))\n x = self.out(x)\n x = F.softmax(x,dim=1)\n return x\nif __name__=='__main__':\n #model = torchvision.models.resnet50()\n model = ActionDetect_Net()\n pic = torch.randn(1, 3, 224, 224)\n pose = torch.randn(1,4)\n pose = pose.float()\n out = model(pose,pic)\n\n","sub_path":"action_net.py","file_name":"action_net.py","file_ext":"py","file_size_in_byte":5399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"556814486","text":"import check\r\nimport math\r\n\r\ndef parking_costs( short_term , time):\r\n\r\n '''\r\n\r\n parking_costs returns either a daily rate of time * shortTermParkingRate if shortTermBool is False to a max of $28 , or time * \r\n dailyParkingRate if it's true to a max of $120\r\n\r\n parking_costs: Int -> Int\r\n\r\n assumption: is that short_term cannot be false if time is 0, because this implies the time parked is less than 1 day, and therefore short_term should be true\r\n\r\n assumption: time must be greater than 0 if short_term is True\r\n\r\n '''\r\n\r\n # performs integer division to break time into 20 minute intervals plus 1 for the first interval\r\n\r\n shortTermParkingRate = (((time // 20) + 1) * 4)\r\n\r\n # the daily parking Rate of 28$ per hour\r\n\r\n dailyParkingRate = 28\r\n\r\n if short_term:\r\n\r\n if (shortTermParkingRate) > 28:\r\n\r\n return 28\r\n\r\n else:\r\n\r\n return shortTermParkingRate\r\n\r\n else:\r\n\r\n if (time * dailyParkingRate) > 120:\r\n\r\n return 120\r\n\r\n else:\r\n\r\n return time * dailyParkingRate\r\n \r\n\r\n\r\n\r\ncheck.expect( \"check_parking_costs\" , parking_costs(True, 47) , 12)\r\n\r\ncheck.expect( \"check_parking_costs\" , parking_costs(True, 500) , 28)\r\n\r\ncheck.expect( \"check_parking_costs\" , parking_costs(False, 6) , 120)\r\n\r\ncheck.expect( \"check_parking_costs\" , parking_costs(False, 3) , 84)\r\n","sub_path":"a02q1.py","file_name":"a02q1.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"156471805","text":"# import the necessary packages\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.models import load_model\nfrom imutils.video import VideoStream\nimport face_recognition\nimport numpy as np\nimport argparse\nimport imutils\nimport pickle\nimport time\nimport cv2\nimport os\n\ndef detect_and_predict_mask(frame, faceNet, maskNet):\n\t# grab the dimensions of the frame and then construct a blob\n\t# from it\n\t(h, w) = frame.shape[:2]\n\tblob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300),\n\t\t(104.0, 177.0, 123.0))\n\t# pass the blob through the network and obtain the face detections\n\tfaceNet.setInput(blob)\n\tdetections = faceNet.forward()\n\t# initialize our list of faces, their corresponding locations,\n\t# and the list of predictions from our face mask network\n\tfaces = []\n\tlocs = []\n\tpreds = []\n\n # loop over the detections\n\tfor i in range(0, detections.shape[2]):\n\t\t# extract the confidence (i.e., probability) associated with\n\t\t# the detection\n\t\tconfidence = detections[0, 0, i, 2]\n\t\t# filter out weak detections by ensuring the confidence is\n\t\t# greater than the minimum confidence\n\t\tif confidence > args[\"confidence\"]:\n\t\t\t# compute the (x, y)-coordinates of the bounding box for\n\t\t\t# the object\n\t\t\tbox = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n\t\t\t(startX, startY, endX, endY) = box.astype(\"int\")\n\t\t\t# ensure the bounding boxes fall within the dimensions of\n\t\t\t# the frame\n\t\t\t(startX, startY) = (max(0, startX), max(0, startY))\n\t\t\t(endX, endY) = (min(w - 1, endX), min(h - 1, endY))\n\n # extract the face ROI, convert it from BGR to RGB channel\n\t\t\t# ordering, resize it to 224x224, and preprocess it\n\t\t\tface = frame[startY:endY, startX:endX]\n\t\t\tface = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)\n\t\t\tface = cv2.resize(face, (224, 224))\n\t\t\tface = img_to_array(face)\n\t\t\tface = preprocess_input(face)\n\t\t\t# add the face and bounding boxes to their respective\n\t\t\t# lists\n\t\t\tfaces.append(face)\n\t\t\tlocs.append((startX, startY, endX, endY))\n\n # only make a predictions if at least one face was detected\n\tif len(faces) > 0:\n\t\t# for faster inference we'll make batch predictions on *all*\n\t\t# faces at the same time rather than one-by-one predictions\n\t\t# in the above `for` loop\n\t\tfaces = np.array(faces, dtype=\"float32\")\n\t\tpreds = maskNet.predict(faces, batch_size=32)\n\t# return a 2-tuple of the face locations and their corresponding\n\t# locations\n\treturn (locs, preds)\n\n# construct the argument parser and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-f\", \"--face\", type=str,\n\tdefault=\"face_detection_models\",\n\thelp=\"path to face detector model directory\")\nap.add_argument(\"-m\", \"--model\", type=str,\n\tdefault=\"mask_detector.model\",\n\thelp=\"path to trained face mask detector model\")\nap.add_argument(\"-c\", \"--confidence\", type=float, default=0.3,\n\thelp=\"minimum probability to filter weak detections\")\nap.add_argument(\"-e\", \"--encodings\", default=\"encodings.pickle\",\n\thelp=\"path to serialized db of facial encodings\")\nap.add_argument(\"-d\", \"--detection-method\", type=str, default=\"hog\",\n\thelp=\"face detection model to use: either `hog` or `cnn`\")\nargs = vars(ap.parse_args())\n\n# load our serialized face detector model from disk\nprint(\"[INFO] loading face detector model...\")\nprototxtPath = os.path.sep.join([args[\"face\"], \"deploy.prototxt\"])\nweightsPath = os.path.sep.join([args[\"face\"],\n\t\"res10_300x300_ssd_iter_140000.caffemodel\"])\nfaceNet = cv2.dnn.readNet(prototxtPath, weightsPath)\n\n# load the face mask detector model from disk\nprint(\"[INFO] loading face mask detector model...\")\nmaskNet = load_model(args[\"model\"])\n\n# load the known faces and embeddings\nprint(\"[INFO] loading encodings...\")\ndata = pickle.loads(open(args[\"encodings\"], \"rb\").read())\n\n# initialize the video stream and allow the camera sensor to warm up\nprint(\"[INFO] starting video stream...\")\nvs = VideoStream(src=0).start()\ntime.sleep(2.0)\n\n# loop over the frames from the video stream\nwhile True:\n\t# grab the frame from the threaded video stream and resize it\n\t# to have a maximum width of 400 pixels\n\tframe = vs.read()\n\tframe = imutils.resize(frame, width=500)\n\n\t# detect faces in the frame and determine if they are wearing a\n\t# face mask or not\n\t(locs, preds) = detect_and_predict_mask(frame, faceNet, maskNet)\n\n\tcv2.imwrite(\"frame.jpg\", frame)\n\t# load the input image and convert it from BGR to RGB\n\timage = cv2.imread(\"D:/Major_Project_8th_sem/frame.jpg\")\n\trgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n # detect the (x, y)-coordinates of the bounding boxes corresponding\n # to each face in the input image, then compute the facial embeddings\n # for each face\n\tprint(\"[INFO] recognizing faces...\")\n\tboxes = face_recognition.face_locations(rgb, model=args[\"detection_method\"])\n\tencodings = face_recognition.face_encodings(rgb, boxes)\n # initialize the list of names for each face detected\n\tnames = []\n\n # loop over the facial embeddings\n\tfor encoding in encodings:\n # attempt to match each face in the input image to our known\n # encodings\n\t\tmatches = face_recognition.compare_faces(data[\"encodings\"], encoding)\n\t\tname = \"Unknown\"\n\n # check to see if we have found a match\n\t\tif True in matches:\n # find the indexes of all matched faces then initialize a\n # dictionary to count the total number of times each face\n # was matched\n\t\t\tmatchedIdxs = [i for (i, b) in enumerate(matches) if b]\n\t\t\tcounts = {}\n # loop over the matched indexes and maintain a count for\n # each recognized face face\n\t\t\tfor i in matchedIdxs:\n\t\t\t\tname = data[\"names\"][i]\n\t\t\t\tcounts[name] = counts.get(name, 0) + 1\n # determine the recognized face with the largest number of\n # votes (note: in the event of an unlikely tie Python will\n # select first entry in the dictionary)\n\t\t\tname = max(counts, key=counts.get)\n \n # update the list of names\n\t\tnames.append(name)\n \n # loop over the recognized faces\n\tfor ((top, right, bottom, left), name) in zip(boxes, names):\n # draw the predicted face name on the image\n\t\tcv2.rectangle(image, (left, top), (right, bottom), (0, 255, 0), 2)\n\t\ty = top - 15 if top - 15 > 15 else top + 15\n\t\tcv2.putText(image, name, (left, y), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2)\n\n\t\n\t\n # loop over the detected face locations and their corresponding\n\t# locations\n\tfor (box, pred) in zip(locs, preds):\n\t\t# unpack the bounding box and predictions\n\t\t(startX, startY, endX, endY) = box\n\t\t(mask, withoutMask) = pred\n\t\t# determine the class label and color we'll use to draw\n\t\t# the bounding box and text\n\t\tlabel = \"Mask\" if mask > withoutMask else \"No Mask\"\n\t\tlabel2 = \"Mask\" if mask > withoutMask else \"No Mask\"\n\t\tcolor = (0, 255, 0) if label == \"Mask\" else (0, 0, 255)\n\t\t# include the probability in the label\n\t\tlabel = \"{}: {:.2f}%\".format(label, max(mask, withoutMask) * 100)\n\t\t# display the label and bounding box rectangle on the output\n\t\t# frame\n\t\tcv2.putText(frame, label, (startX, startY - 10),\n\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)\n\t\tcv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)\n\n # show the output frame\n\tcv2.imshow(\"Frame\", frame)\n\tkey = cv2.waitKey(1) & 0xFF\n\t\n\tif(label2==\"No Mask\"):\n # show the output image\n\t\tcv2.imshow(\"Image\", image)\n\t\tkey2 = cv2.waitKey(1) & 0xFF\n\t\tif key2 == ord(\"e\"):\n\t\t#cv2.imwrite(\"pic.jpg\",image)\n\t\t\tbreak\n\n\t# if the `q` key was pressed, break from the loop\n\tif key == ord(\"q\"):\t\n\t\tbreak\n\n# do a bit of cleanup\ncv2.destroyAllWindows()\nvs.stop()","sub_path":"check_project.py","file_name":"check_project.py","file_ext":"py","file_size_in_byte":7577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"236531979","text":"import numpy as np\nimport gym\nimport time\nimport matplotlib.pyplot as plt\n\nclass QLearning:\n def __init__(self, *,\n game,\n # learning_rate = alpha\n learning_rate,\n # discount_rate = gamma\n discount_rate=1.0,\n # random_action_prob = epsilon\n random_action_prob=0.5,\n random_action_decay_rate=0.99):\n # dyna_iterations=0):\n self.env = gym.make(game)\n self._observation_shape = self.env.observation_space.shape\n self._num_states = 36\n self._num_actions = self.env.action_space.n\n self._action = np.arange(self._num_actions)\n self._learning_rate = learning_rate\n self._discount_rate = discount_rate\n self._random_action_prob = random_action_prob\n self._random_action_decay_rate = random_action_decay_rate\n # self._dyna_iterations = dyna_iterations\n self.regret = 0\n self._experiences = []\n self._Q = np.zeros((self._num_states, self._num_actions))\n self._Q += np.random.normal(0, 0.3, self._Q.shape)\n \n\n # use pid control as a sample to figure out the state space, action meaning\n # and also help qlearning swiftly\n def _sample(self, observation, observation_prime):\n if (observation==0).all() and (observation_prime==0).all():\n action = np.random.choice(self._action)\n else:\n action = self._pid(observation, observation_prime)\n return action\n\n def _pid(self, observation, observation_prime):\n board, _, ball = self._get_position(observation)\n board_prime, _, ball_prime= self._get_position(observation_prime)\n if ball_prime[1]==0:\n ball_prime[0] = 80\n distance_prime = board_prime-ball_prime\n pid = distance_prime[0]\n #print(ball, distance_prime)\n if pid<0:\n action = 5\n else:\n action = 4\n return action\n\n # Q learning and epsilon greedy for exploration\n def _learner(self, state, action, reward, state_prime, reward_prime):\n self._Q[state,action] = self._Q[state,action]*(1-self._learning_rate) + self._learning_rate*(reward + self._discount_rate*np.max(self._Q[state_prime]))\n prob = np.random.rand(1)\n if prob > self._random_action_prob:\n action = np.argmax(self._Q[state_prime])\n else:\n action = np.random.choice(self._num_actions)\n return action\n\n # interface for learning\n # input: \n # iterations & step\n # input_file: default None, load the data to self._Q if not None\n # output_file: save the learned Q\n def learn(self, iterations, output_file=None, input_file=None):\n if input_file!=None:\n self._Q = np.load(input_file)\n All_score = np.zeros((iterations,))\n state = None\n for i in range(iterations):\n self.env.reset()\n observation = np.zeros(self._observation_shape)\n observation_prime = np.zeros_like(observation)\n state_prime = None\n done = False\n reward_prime = 0\n while True:\n self.env.render()\n if done:\n print(\"Episode finished after {} timesteps\".format(i+1))\n print('The reward after this episode is ', All_score[i])\n self._random_action_prob *= self._random_action_decay_rate\n self._learning_rate *= 0.9\n break\n if (observation==0).all() and (observation_prime==0).all():\n action = np.random.choice(self._action)\n # at the very beginning use pid samples to help learning\n elif i==0:\n action = self._sample(observation, observation_prime)\n _, __, ball = self._get_position(observation)\n # if state_prime!=state:\n _ = self._learner(state, action, reward, state_prime, reward_prime)\n else:\n # if state_prime!=state:\n action = self._learner(state, action, reward, state_prime, reward_prime)\n observation = observation_prime\n reward = reward_prime\n state = state_prime\n observation_prime, score, done, info = self.env.step(action)\n state_prime = self._get_move_state(observation_prime)\n a, b = np.unravel_index(state_prime, (3,12))\n\n # define the reward, default -0.1, -5 for lost, and 2 for nearly collide the ball\n reward_prime = -0.1\n if b == 0:\n reward_prime = -5\n if b == 1 and a == 0:\n reward_prime=2\n\n All_score[i]+=score\n if output_file!=None:\n np.save(output_file, self._Q)\n self.env.close()\n\n # to get the position of board, board_op and the ball from the RGB image\n def _get_position(self, observation):\n Green = np.array([92,186,92])\n Yellow = np.array([213,130,74])\n White = np.array([236,236,236])\n board_position = np.argwhere(observation[34:194]==Green)\n board = np.zeros((2,))\n board[0] = np.mean(board_position,axis=0)[0]\n board[1] = np.mean(board_position,axis=0)[1]\n ball = np.zeros((2,))\n ball_position = np.argwhere(observation[34:194]==White)\n ball[0] = np.mean(ball_position,axis=0)[0]\n ball[1] = np.mean(ball_position,axis=0)[1]\n board_op_position = np.argwhere(observation[34:194]==Yellow)\n board_op = np.zeros((2,))\n board_op[0] = np.mean(board_op_position,axis=0)[0]\n board_op[1] = np.mean(board_op_position,axis=0)[1]\n\n # Because sometimes there's no ball or board in the image, it might get arrays like (nan,nan)\n # To avoid that, convert the nan to zero\n board = np.nan_to_num(board)\n board_op = np.nan_to_num(board_op)\n ball = np.nan_to_num(ball)\n \n return board, board_op, ball\n \n # state space:\n # a: means the vertical distance between the board and ball, discrete values vary from 0 to 2;\n # 0 for ball in range of board's width, 1 for below the board and 2 for above the board\n # b: means the horizontal distane between the board and ball, discrete values vary from 0 to 11\n def _get_move_state(self, observation):\n board, _, ball = self._get_position(observation)\n if ball[1]<60:\n b = 11\n board[0] = 80\n elif board[1]-ball[1]<0:\n b = 0\n else:\n b = int((board[1]-ball[1])/10)+1\n if abs(board[0]-ball[0])<=6:\n a = 0\n else:\n a=(board[0]>ball[0])+1\n #print(board, board_op, ball, ball_direction)\n return np.ravel_multi_index((a,b),(3,12))\n \n\n # test the learned Q value\n def test(self, input_file):\n scores = 0\n self._Q = np.load(input_file)\n state = None\n print(self._Q)\n self.env.reset()\n observation = np.zeros(self._observation_shape)\n observation_prime = np.zeros_like(observation)\n state_prime = None\n done = False\n while True:\n self.env.render()\n time.sleep(0.01)\n if done:\n print('The reward after this episode is ', scores)\n self._random_action_prob *= self._random_action_decay_rate\n self._learning_rate *= 0.9\n break\n if (observation==0).all() and (observation_prime==0).all():\n action = np.random.choice(self._action)\n # at the very beginning use sample to help learning\n else:\n if state_prime!=state:\n action = np.argmax(self._Q[state_prime])\n observation = observation_prime\n state = state_prime\n observation_prime, score, done, info = self.env.step(action)\n state_prime = self._get_move_state(observation_prime)\n scores += score\n self.env.close()\n\nif __name__=='__main__':\n QL = QLearning(game='Pong-v0', learning_rate=0.8, discount_rate=0.9,random_action_prob=0.5, random_action_decay_rate=0.9)\n #QL.learn(50, 'Q_v7.npy')\n QL.test('Q_v7.npy')","sub_path":"homework3/homework3/ql_learn_gym.py","file_name":"ql_learn_gym.py","file_ext":"py","file_size_in_byte":8373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"396729777","text":"#!/usr/bin/python\n\nimport argparse\nimport re\nimport os\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--events\", type=int)\nparser.add_argument(\"--tracefile\")\nargs = parser.parse_args()\n\nnb_events = args.events\ntrace_filename = args.tracefile\n\ntrace = open(trace_filename, \"r\")\n\nregex = \"<event[\\w\\W\\s]*?</event>\\n\"\n\npattern = re.compile(regex)\nmatches = pattern.findall(trace.read())\n\nfor i in range(0,nb_events):\n\tnew_name = os.path.splitext(trace_filename)[0]+\"_\"+str(i+1)+\".xml\"\n\tnew_trace = open(new_name, \"w\")\n\tline_count = 0\n\tfor line in matches:\n\t\tif (line_count != i):\t\t\n\t\t\tnew_trace.write(line)\n\t\tline_count+=1\n\tnew_trace.close()\n\ntrace.close()\n\n\n\n\n\n","sub_path":"scripts/generate_eval_usecases.py","file_name":"generate_eval_usecases.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"572301649","text":"\n\nimport sys\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import MinMaxScaler \nfrom sklearn.preprocessing import StandardScaler\nfrom statsmodels.graphics.gofplots import qqplot\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nimport pickle\ndf= pd.read_excel(r\"C:/Users/deshp/Desktop/pro/Incidents_service.xlsx\")\n# replacing junk values\ndf[\"problem_id\"].replace({\"?\": \"NA\"}, inplace=True)\ndf['problem_id'].value_counts() # NA: 139417\ndf[\"change request\"].replace({\"?\": \"NA\"}, inplace=True)\ndf['change request'].value_counts() # NA: 140721\n\n# understanding categorical and numerical values\ncategorical = [var for var in df.columns if df[var].dtype=='O']\nprint('There are {} categorical variables\\n'.format(len(categorical)))\nprint('The categorical variables are :\\n\\n', categorical)\ndf[categorical].isnull().sum() # shows no null values\n\nfor var in categorical: # view frequency of each categorical variable type, junk values are there\n print(df[var].value_counts()) # notify(139417), problem_id(140721) have almost 98% missing values\n \nfor var in categorical: \n print(df[var].value_counts()/np.float(len(df))) \n\n\nfor var in categorical: # check different unique lebels for each\n print(var, 'contains ', len(df[var].unique()), ' labels')\n \nnumerical = [var for var in df.columns if df[var].dtype!='O']\nprint('There are {} numerical variables\\n'.format(len(numerical)))\nprint('The numerical variables are :', numerical)\ndf[numerical].isnull().sum()\n\nfor var in numerical: # view frequency of each numerical variable type, junk values are there\n print(df[var].value_counts())\n \nfor var in numerical: \n print(df[var].value_counts()/np.float(len(df))) # all proportions add upto 100%\n\n\nfor var in numerical: # check different unique lebels for each\n print(var, ' contains ', len(df[var].unique()), ' labels')\n\n# encoding all categorical variables\n# \"ID_status\" have -100, which needs to be converted into string value\ndf[\"ID_status\"].replace({-100: \"minus hundred\"}, inplace=True)\ndf.ID_status.value_counts()\n\n# creating new dataframe by dropping attributes with junk values\ndf= df.drop(['problem_id', 'change request', 'count_opening'],axis=1)\ndf.shape #(141712, 22)\n\n# removing duplicate values\nduplicate= df[df.duplicated()] \ndf1= df.drop_duplicates() # there are no duplicate values\ndf1.shape\n\n# label encoding categorical variables\n\nstring_new= ['ID','ID_status','ID_caller','active','type_contact','impact','notify', 'opened_time', 'created_at', 'updated_at', 'Doc_knowledge', 'confirmation_check','opened_by', 'Created_by', 'updated_by', 'location', 'category_ID', 'user_symptom', 'Support_group', 'support_incharge']\nnumber= preprocessing.LabelEncoder()\nfor i in string_new:\n df[i] = number.fit_transform(df[i])\n\n\n# impute outliers\nQ1 = df.quantile(0.25)\nQ3 =df.quantile(0.75)\nIQR = Q3 - Q1\nlow= Q1 - 1.5*IQR\nhigh = Q3 + 1.5*IQR\nprint(IQR) # gives IQR for all attributes\n\ndf[\"count_updated\"].median() # 3\ndf[\"count_updated\"].mode()\ndf[\"count_updated\"].mean() # 5\ndf[\"count_reassign\"].median()# 1\ndf[\"count_reassign\"].mode()\ndf[\"count_reassign\"].mean() # 1.1\n\n# impute all attributes with outliers togther by creating anew dataframe and loop\n\ndf3= df.loc[:,[\"count_updated\",\"count_reassign\"]]\ndf3.describe\n\nfor col_name in df3.select_dtypes(include=np.number).columns:\n print(col_name)\n q1 = df3[col_name].quantile(0.25)\n q3 = df3[col_name].quantile(0.75)\n iqr = q3 - q1\n low = q1-1.5*iqr\n high = q3+1.5*iqr \n print(\"Change the outliers with median \",df3[col_name].median())\n df3.loc[(df3[col_name] < low) | (df3[col_name] > high)] = df3[col_name].median()\n\n\ndf4= df.drop([\"count_updated\",\"count_reassign\"], axis= 1)\ndf4.shape\ndf_new= pd.concat([df4, df3],axis= 1)\n\nx= df_new.drop([\"impact\"],axis= 1)\ny= df_new[\"impact\"] # series\ny= pd.DataFrame(y)\ny[\"impact\"].value_counts() # 1(medium): 134335, 2(low): 3886, 0(high): 3491\n# define the min max scaler\nscaler= MinMaxScaler()\nd_scale= scaler.fit_transform(x) # an array is getting created \nd_scale.shape #(141712, 21)\n#convert array to dataframe\nd_scale= pd.DataFrame(d_scale, columns= x.columns)\n\n# y = impact (target), x= d_scale (predictors)\n\nfrom imblearn.under_sampling import NearMiss\n\n# define the undersampling method\nundersample = NearMiss(version=1, n_neighbors=3)\n# transform the dataset\nx_re, y_re = undersample.fit_resample(d_scale, y)\nx_re = x_re.drop(['notify'], axis= 1)\ny_re[\"impact\"].value_counts().plot(kind=\"pie\")\n\n\n# use x_re and y_re for test train split\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x_re, y_re, test_size=.2, random_state=42)\nx_col = x_train.columns\n\n# XGBoost feature selection====================================================================\nfrom xgboost import XGBClassifier\nxgb = XGBClassifier()\nxgb.fit(x_train, y_train.values.ravel())\nimportance = xgb.feature_importances_\nfor i,v in enumerate(importance):\n\tprint('Feature: %0d, Score: %.5f' % (i,v))\n# plot feature importance, same as RF\nplt.bar([x for x in range(len(importance))], importance)\nplt.show()\nfrom xgboost import plot_importance\nplot_importance(xgb)\n\n#=========================================================================================================\n#MODEL BUILDING\n#============================================================================================================\n\npredictor = x_train.loc[:,['category_ID','ID_status', 'opened_time','updated_at',\n 'Support_group', 'support_incharge', 'location' , 'count_updated',\n 'ID_caller']]\n\n\npred_test= x_test.loc[:,['category_ID','ID_status' , 'opened_time','updated_at',\n 'Support_group', 'support_incharge', 'location' , 'count_updated',\n 'ID_caller']]\n# Building model with XGBoost---------------------------------\n\nxgb1 = XGBClassifier(n_estimators=2000,learning_rate=0.3)\n\nxgb1.fit(predictor,y_train.values.ravel())\ntrain_pred_xgb = xgb1.predict(predictor)\nprint(confusion_matrix(y_train, train_pred_xgb))\nprint(classification_report(y_train, train_pred_xgb)) # 100%\ny_train= pd.DataFrame(y_train)\n\ntest_pred_xgb = xgb1.predict(pred_test)\n\nprint(confusion_matrix(y_test, test_pred_xgb ))\nprint(classification_report(y_test, test_pred_xgb )) # 95%\n\nprint(\"Printing xgb1:\",xgb1)\nprint(type(xgb1))\nwith open(\"C:/Users/deshp/Desktop/pro/XGBoost_classification_model2.pkl\", \"wb\") as weightsfolder:\n pickle.dump(xgb1, weightsfolder)\n\nmodel = pickle.load(open('C:/Users/deshp/Desktop/pro/XGBoost_classification_model2.pkl', 'rb'))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"P31-Classification-Project-Incident Prediction/XGBoost_classification_model (2).py","file_name":"XGBoost_classification_model (2).py","file_ext":"py","file_size_in_byte":6663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"528218138","text":"#!/usr/bin/env python3.7\n\n# from https://github.com/ControlEverythingCommunity/ADXL345/blob/master/Python/ADXL345.py\n\n# Distributed with a free-will license.\n# Use it any way you want, profit or free, provided it fits in the licenses of its associated works.\n# ADXL345\n# This code is designed to work with the ADXL345_I2CS I2C Mini Module available from ControlEverything.com.\n# https://www.controleverything.com/content/Accelorometer?sku=ADXL345_I2CS#tabs-0-product_tabset-2\n\nimport signal\nimport sys\nimport time\nimport struct\n\nimport smbus\n\nassert len(sys.argv) == 2, \"missing output file\"\nofile = sys.argv[1]\n\n# handle ctr-c\ndef signal_handler(sig, frame):\n print('done')\n sys.exit(0)\nsignal.signal(signal.SIGINT, signal_handler)\n\n\nsr = 3200\nADXL345_ADDRESS = 0x53\nADXL345_REG_DEVID = 0x00 # Device ID\nADXL345_REG_DATAX0 = 0x32 # X-axis data 0 (6 bytes for X/Y/Z)\nADXL345_REG_POWER_CTL = 0x2D # Power-saving features control\nADXL345_REG_DATA_FORMAT = 0x31\nADXL345_REG_BW_RATE = 0x2C\nADXL345_DATARATE_0_10_HZ = 0x00\nADXL345_DATARATE_0_20_HZ = 0x01\nADXL345_DATARATE_0_39_HZ = 0x02\nADXL345_DATARATE_0_78_HZ = 0x03\nADXL345_DATARATE_1_56_HZ = 0x04\nADXL345_DATARATE_3_13_HZ = 0x05\nADXL345_DATARATE_6_25HZ = 0x06\nADXL345_DATARATE_12_5_HZ = 0x07\nADXL345_DATARATE_25_HZ = 0x08\nADXL345_DATARATE_50_HZ = 0x09\nADXL345_DATARATE_100_HZ = 0x0A # (default)\nADXL345_DATARATE_200_HZ = 0x0B\nADXL345_DATARATE_400_HZ = 0x0C\nADXL345_DATARATE_800_HZ = 0x0D\nADXL345_DATARATE_1600_HZ = 0x0E\nADXL345_DATARATE_3200_HZ = 0x0F\nADXL345_RANGE_2_G = 0x00 # +/- 2g (default)\nADXL345_RANGE_4_G = 0x01 # +/- 4g\nADXL345_RANGE_8_G = 0x02 # +/- 8g\nADXL345_RANGE_16_G = 0x03 # +/- 16g\n\n\n# Get I2C bus\nbus = smbus.SMBus(1)\n\n# condiguring the adxl345\nbus.write_byte_data(ADXL345_ADDRESS, 0x2C, 0x0A) # sampling rate\nbus.write_byte_data(ADXL345_ADDRESS, 0x2D, 0x08) # power control\nbus.write_byte_data(ADXL345_ADDRESS, 0x31, 0x08) # data format\ntime.sleep(1)\n\nwith open(ofile, \"w\") as f:\n while 1:\n\n initial_time = time.perf_counter()\n data = bus.read_i2c_block_data(ADXL345_ADDRESS, ADXL345_REG_DATAX0, 6)\n X = ((data[1] & 0x03) * 256 + (data[0] & 0xFF))\n Y = ((data[3] & 0x03) * 256 + (data[2] & 0xFF))\n Z = ((data[5] & 0x03) * 256 + (data[4] & 0xFF))\n\n if X > 511 :\n \tX -= 1024\n\n if Y > 511 :\n \tY -= 1024\n\n if Z > 511 :\n \tZ -= 1024\n\n f.write(\"{} {} {} {}\\n\".format(initial_time, X, Y, Z))\n ending_time = time.perf_counter()\n sleep_time = 1.0/sr - (ending_time - initial_time) if 1.0/sr > (ending_time - initial_time) else 0.0\n time.sleep(sleep_time)\n\n","sub_path":"get_sensor_adxl345.py","file_name":"get_sensor_adxl345.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"9456815","text":"# -*- coding: utf-8 -*-\r\nimport os\r\nimport sys\r\nroot = os.path.join(os.path.dirname(__file__), '..')\r\nsys.path.append(root)\r\n\r\nimport os\r\nimport math\r\nimport json\r\nimport shutil \r\nimport warnings\r\nfrom graph.duality_graph import DualityGraph\r\nfrom pathfinder.astar import a_star_search\r\nfrom pathfinder.util import reconstruct_path\r\n\r\nclass TwoStageGraph(DualityGraph):\r\n def __init__(self, width, height, step, celldir=None):\r\n super(TwoStageGraph, self).__init__(width, height)\r\n self.width_s1 = width\r\n self.height_s1 = height\r\n self.step = step\r\n self.celldir = celldir\r\n self.init_graph()\r\n \r\n def init_graph(self):\r\n self.walls_s1 = set()\r\n self.walls_s2 = set()\r\n self.width_s2 = int(math.ceil(self.width_s1/float(self.step)))\r\n self.height_s2 = int(math.ceil(self.height_s1/float(self.step)))\r\n # init file system\r\n if not self.celldir:\r\n try:\r\n shutil.rmtree('.cell')\r\n except:\r\n warnings.warn('No existing .cell folder!')\r\n self.celldir = '.cell'\r\n os.makedirs(self.celldir)\r\n \r\n for x in range(self.width_s2):\r\n for y in range(self.height_s2):\r\n with open(os.path.join(self.celldir, '.x{}y{}'.format(x, y)), 'wb') as writeFile:\r\n json.dump(list(), writeFile)\r\n \r\n def add_wall(self, pos):\r\n if self.in_bounds(pos):\r\n sec = self.get_s2_section(pos)\r\n filename = '.x{}y{}'.format(sec[0], sec[1])\r\n with open(os.path.join(self.celldir, filename), 'rb') as readFile:\r\n set_ = set(json.load(readFile))\r\n set_.add(pos)\r\n with open(os.path.join(self.celldir, filename), 'wb') as writeFile:\r\n json.dump(list(set_), writeFile)\r\n self.walls_s2.add(sec)\r\n \r\n def add_walls(self, pos_set):\r\n sec_dict = {}\r\n for pos in pos_set:\r\n sec = self.get_s2_section(pos)\r\n sec_set = sec_dict.get(sec, set())\r\n sec_set.add(pos)\r\n sec_dict[sec] = sec_set\r\n \r\n for sec in sec_dict.keys():\r\n filename = '.x{}y{}'.format(sec[0], sec[1])\r\n with open(os.path.join(self.celldir, filename), 'rb') as readFile:\r\n list_ = json.load(readFile)\r\n set_ = set([tuple(l) for l in list_])\r\n set_ |= sec_dict[sec]\r\n with open(os.path.join(self.celldir, filename), 'wb') as writeFile:\r\n json.dump(list(set_), writeFile)\r\n self.walls_s2.add(sec)\r\n \r\n def get_s2_section(self, pos):\r\n x = int(math.floor(pos[0]/float(self.step)))\r\n y = int(math.floor(pos[1]/float(self.step)))\r\n return (x, y)\r\n \r\n def load_section(self, sec):\r\n filename = '.x{}y{}'.format(sec[0], sec[1])\r\n with open(os.path.join(self.celldir, filename), 'rb') as readFile:\r\n list_ = json.load(readFile)\r\n self.walls_s1 |= set([tuple(l) for l in list_])\r\n \r\n def in_sections(self, sec):\r\n (x, y) = sec\r\n return 0 <= x < self.width_s2 and 0 <= y < self.height_s2\r\n \r\n def preload(self, start, end):\r\n self.walls.clear()\r\n start_sec = self.get_s2_section(start)\r\n end_sec = self.get_s2_section(end)\r\n self.walls |= self.walls_s2 - set([start_sec, end_sec])\r\n self.set_search(start_sec, end_sec)\r\n came_from, cost_so_far = a_star_search(self, start_sec, end_sec)\r\n path_sec = reconstruct_path(came_from, start_sec, end_sec)\r\n \r\n blocks = []\r\n for sec in path_sec:\r\n if self.in_sections(sec):\r\n blocks += self.get_candidates(sec)\r\n blocks = set(blocks) & self.walls_s2\r\n \r\n visited = {}\r\n expand = set()\r\n for block in blocks:\r\n expand |= self.bfs_blocks(block, visited)\r\n self.walls.clear()\r\n \r\n for sec in expand:\r\n self.load_section(sec)\r\n self.walls = self.walls_s1\r\n \r\nif __name__ == '__main__':\r\n from shape.OctagonLine import solid_octagon_line\r\n import matplotlib.pyplot as plt\r\n \r\n graph = TwoStageGraph(10000, 10000, 100)\r\n \r\n print('*')\r\n blocks = solid_octagon_line((550, 500), (550, 5500), 20)\r\n print(len(blocks))\r\n# for pos in solid_octagon_line((550, 500), (550, 5500), 20):\r\n# graph.add_wall(pos)\r\n graph.add_walls(solid_octagon_line((550, 500), (550, 5500), 20)) \r\n print('**')\r\n start, end = (500, 500), (600, 5100)\r\n \r\n graph.preload(start, end)\r\n graph.set_search(start, end)\r\n print(len(graph.walls))\r\n \r\n came_from, cost_so_far = a_star_search(graph, start, end)\r\n path = reconstruct_path(came_from, start, end)\r\n \r\n plt.figure()\r\n plt.scatter([pos[0] for pos in blocks], [pos[1] for pos in blocks], color='black')\r\n plt.scatter([pos[0] for pos in graph.walls], [pos[1] for pos in graph.walls], color='orange')\r\n for i in range(1, len(path)):\r\n plt.plot([path[i-1][0], path[i][0]],\r\n [path[i-1][1], path[i][1]], color='red')","sub_path":"graph/hierarchical_graph.py","file_name":"hierarchical_graph.py","file_ext":"py","file_size_in_byte":5264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"173666673","text":"import logging\nlogging.basicConfig(format='[%(levelname)s|%(asctime)s] %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n level=logging.DEBUG)\n# Database config\nDATABASE_DIR = 'database'\nDATABASE_NAME_LOAD = 'newest_database.pkl'\nDATABASE_NAME_SAVE = 'newest_database.pkl'\nSAVE_DATABASE = False\nRAW_IMAGES_DIR = 'images'\n#http://192.168.137.214:8080/video\nDB_HOST = 'localhost'\nDB_USER = 'root'\nDB_PASSWD = 'root'\nDB_NAME = 'faceid'\n\n# Model Config\nMODEL_DIR = 'model'\nIMAGES_DIR = 'images'\nDETECT_DEVICE = 'auto'\nENCODE_EMBEDD_DEVICE = 'auto'\nIDENTIFICATION_THRESH_HOLD = 0.20\n# IDENTIFICATION_THRESH_HOLD = 0.64\nBIGGEST_FACE = False\nADMIN_REVIEWER = False\nDETECT_SCALE = 2\nFLIP = True\nENRICH_DATA = False\nNUM_TRIED = 5\nDELAY_TRIED = 0.3\n# Screen config \nINPUT_SCALE = 2\nSHOW_LOCAL_SCREEN = True\nSIZE_OF_INPUT_IMAGE = 160\nPOS_COLOR = (0, 255, 0)\nNEG_COLOR = (0, 0, 255)\nMID_COLOR = (255, 255, 255)\nTHUMB_BOUNDER_COLOR = (255, 255, 255)\nLINE_THICKNESS = 1\nFONT_SIZE = 0.7\nDIS_THUMB_X = 10\nDIS_THUMB_Y = 30\nDIS_BETWEEN_THUMBS = 5\nFPS_POS = (10, 20)\nSCREEN_SIZE = {\n 'width' : 1280,\n 'height' : 720\n}\nTRAINING_AREA = (320-128, 0, 320+128, 480)\nPADDING = 5\nSHOW_LOG_PREDICTION = True\nSHOW_LOG_TRACKING = False\nDEBUG_MOD = False\n\n# Some necessary funtion\ndef set_screen_size(w, h):\n global SCREEN_SIZE, TRAINING_AREA\n w = int(w)\n h = int(h)\n SCREEN_SIZE['width'] = w\n SCREEN_SIZE['height'] = h\n TRAINING_AREA = (int(w/2-w/2) + PADDING, PADDING, int(w/2+w/2)-2*PADDING, h-2*PADDING)\n\ndef get_time():\n import datetime\n now = datetime.datetime.now()\n return now.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n# Service config\nREDIS_HOST = '127.0.0.1'\nREDIS_PORT = 6379\nMAX_CLIENT = 5\nMAX_WORKER = 5\nSERVICE_TOKEN = 'AAA'\nSERVICE_REGISTER_CLIENT = SERVICE_TOKEN + '-REG-CLIENT'\nSERVICE_REGISTER_WORKER = SERVICE_TOKEN + '-REG-WORKER'\nWORKER_OFFLINE = -1\nWORKER_ONLINE = 0\nWORKER_RUNNING = 1\n\nMAX_TIME_CLIENT_REGISTER = 10\nMAX_TIME_WORKER_REGISTER = 10\n\n# Service identify config\nBATCH = 1\nIDENTIFY_QUEUE = SERVICE_TOKEN + '-IDENTIFY'\nENCODE_MOD = \"1\"\nIDEN_MOD = \"0\"\nFLAG_REFETCH_DB = \"-REFETCH_DB\"\n\n#Service client config\nTRANSFER_LEARNING_MSG = \"Transfer Learning\"\nNEW_LEARNING_MSG = \"New Learning\"\nSTREAM = True\ndef set_service_token(token):\n global SERVICE_TOKEN, SERVICE_REGISTER_CLIENT , SERVICE_REGISTER_WORKER, IDENTIFY_QUEUE\n SERVICE_TOKEN = token\n SERVICE_REGISTER_CLIENT = SERVICE_TOKEN + '-CLIENT'\n SERVICE_REGISTER_WORKER = SERVICE_TOKEN + '-WORKER'\n IDENTIFY_QUEUE = SERVICE_TOKEN + '-IDENTIFY'\n\n\n","sub_path":"vision_config.py","file_name":"vision_config.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"584054444","text":"# -*- coding: utf-8 -*-\n\"\"\"\nBuild clothing hierarchical caategories into a tree\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom collections import defaultdict\nfrom treelib import Node, Tree\nimport pandas as pd\nimport numpy as np\n\n# class Node():\n# \"\"\"Node class\"\"\"\n# def __init__(self, val, children=[], parent=None):\n# self.value = val\n# self.children = children\n# self.parent = parent\n#\n# def get_value(self):\n# return self.value\n#\n# def set_value(self, value):\n# self.value = value\n#\n# def get_children(self):\n# return self.children\n#\n# def set_children(self, children):\n# self.children = children\n#\n# def add_child(self, child):\n# self.children.append(child)\n#\n# def get_parent(self):\n# return self.parent\n#\n# def __repr__(self):\n# return \"Tree.Node({},{})\".format(self.value, \",\".join(self.children))\n\nclass ClothingTreeFromFile():\n \"\"\"\n construct a tree with node-leaf list\n label_file: label file containing hierarchical labels with leaf category integer index and followed by its higher nodes\n\n a list of list with path from node to leaf, eg:\n [ [0, node1-1, node2-1, leaf1],\n [1, node1-1, node2-1, leaf2],\n ...]\n\n\n \"\"\"\n def __init__(self, label_file):\n self.label_file = label_file\n\n def mapping_name_to_id(self):\n self.node_leaf_list = np.asarray(pd.read_csv(self.label_file, sep=\":\", header=None))\n levels = self.node_leaf_list.shape[1] - 1\n name_to_id_dict = defaultdict(dict)\n for level in range(1, levels+1):\n class_level = \"class\"+str(level)\n name_to_id_dict[class_level] = defaultdict(dict)\n counter = 0\n for cate in self.node_leaf_list[:, level]:\n if not cate in name_to_id_dict[class_level]:\n name_to_id_dict[class_level][cate] = counter\n counter += 1\n print(\"Read in label file done! Labels name to id are:, \", name_to_id_dict)\n return name_to_id_dict\n\n\n def generate_tree(self):\n \"\"\"\n return a treelib tree class with node name in each level\n node1-1\n / \\\n node2-1 node2-2\n / \\ / \\\n leaf1 leaf2 leaf3 leaf4\n \"\"\"\n name_to_id_dict = self.mapping_name_to_id()\n tree = Tree()\n tree.create_node(\"ROOT\", \"ROOT\")\n for node_leaf in self.node_leaf_list[:, 1:]:\n node_leaf = np.insert(node_leaf, 0, 'ROOT')\n for i in range(1, len(node_leaf)):\n if not tree.contains(node_leaf[i]):\n tree.create_node(tag=node_leaf[i], identifier=node_leaf[i], parent=node_leaf[i-1], data=name_to_id_dict['class'+str(i)][node_leaf[i]])\n print(\"Construct tree done! Tree structure is:\")\n print(tree.show())\n return tree\n\n\n def get_leaf_path(self, tree, leafname):\n \"\"\"\n get path to given leaf name\n \"\"\"\n paths_to_leaves = tree.paths_to_leaves()\n leaf_path = np.squeeze([x for x in paths_to_leaves if x[-1] == leafname])\n # exclude ROOT node\n return leaf_path[1:]\n\n\nclass TreeTools():\n \"\"\"\n Hierarchical class tree operation tools class\n Reference: https://talbaumel.github.io/softmax/\n \"\"\"\n def __init__(self):\n # get number of nodes in tree, not include the root node\n self._count_nodes_dict = {}\n\n def _get_subtrees(self, tree):\n # get all subtrees of given tree\n yield tree\n for subtree in tree:\n if type(subtree) == list:\n for x_tree in self._get_subtrees(subtree):\n yield x_tree\n\n def _get_leaves_and_paths(self, tree):\n # get all leaves value and its corresponding path\n for i, subtree in enumerate(tree):\n if type(subtree) == list:\n for path, value in self._get_leaves_and_paths(subtree):\n yield [i]+path, value\n else:\n yield [i], subtree\n\n def _get_nodes_count(self, tree):\n # storing node count of each subtree, use id(tree_object) as its key\n if id(tree) in self._count_nodes_dict:\n return self._count_nodes_dict[id(tree)]\n else:\n count = 0\n for node in tree:\n if type(node) == list:\n count += 1 + self._get_nodes_count(node)\n # print(\"current count of node {} is {}\".format(node, count))\n self._count_nodes_dict[id(tree)] = count\n return count\n\n def _get_nodes(self, tree, path):\n # get nodes in a path\n next_node = 0 # root node\n nodes = []\n for decision in path:\n nodes.append(next_node)\n next_node += 1 + self._get_nodes_count(tree[:decision])\n tree = tree[decision]\n return nodes\n\n\nif __name__ == \"__main__\":\n clothing_tree = ClothingTreeFromFile(label_file=\"/home/arkenstone/tensorflow/workspace/models/slim/models/deepfashion_l2/data/second_class_labels.txt\")\n tree = clothing_tree.generate_tree()\n print(tree.get_node('Tee'))\n print([node for node in tree.leaves()])\n print(clothing_tree.get_leaf_path(tree, \"Cardigan\"))\n print(tree.all_nodes())\n\n","sub_path":"slim/parse_hierarchy_tree.py","file_name":"parse_hierarchy_tree.py","file_ext":"py","file_size_in_byte":5410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"20894387","text":"# -*- coding: utf-8 -*-\nfrom xml.dom import minidom\nimport base64\nfrom odoo.exceptions import AccessError, UserError, RedirectWarning, ValidationError, Warning\nimport re\nfrom odoo import models, fields, api\nimport datetime\n\nclass AccountInvoice(models.Model):\n _inherit = \"account.invoice\"\n\n def binary_to_xml(self):\n self.ensure_one()\n if not self.x_xml_file:\n raise ValidationError('No hay ningún archivo XML adjunto!')\n\n else:\n try:\n # If the XML is ok can be parsed into a document object model\n '''The file is stored in odoo encoded in base64 bytes column, in order to get the information in \n the original way, It must have to be decoded in the same base.'''\n\n xml = minidom.parseString(base64.b64decode(self.x_xml_file))\n\n except:\n # If the XML has ilegal characters, it has to be decoded in base 64\n decoded = base64.b64decode(self.x_xml_file)\n\n # Conversion to string so it han be handled by sub() function\n string = str(decoded, \"utf-8\")\n\n # Definition of ilegal characters in XML files\n ilegal_characters = re.compile(u'[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1F\\uD800-\\uDFFF\\uFFFE\\uFFFF]')\n\n # Replacement of ilegal characters in the string\n fixed_xml = ilegal_characters.sub('', string)\n\n # Now the fixed string can be parsed into a document object model without error\n xml = minidom.parseString(fixed_xml)\n\n return xml\n\n def map_xml_to_odoo_fields(self):\n\n xml = self.binary_to_xml()\n\n # Obtengo el nodo del receptor\n receptor_items = xml.getElementsByTagName(\"cfdi:Receptor\")\n\n # Obtengo nombre y RFC del receptor\n NombreReceptor = receptor_items[0].attributes['Nombre'].value\n\n RfcReceptor = receptor_items[0].attributes['Rfc'].value\n\n # Valido que la factura sea para la compañía actual\n if RfcReceptor == self.env.user.company_id.vat:\n\n # Obtengo el nodo del emisor\n emisor_items = xml.getElementsByTagName(\"cfdi:Emisor\")\n\n # Obtengo los datos necesarios\n try:\n NombreEmisor = emisor_items[0].attributes['Nombre'].value\n\n except:\n NombreEmisor = \"FACTURA TIMBRADA SIN NOMBRE DE PROVEEDOR\"\n\n RfcEmisor = emisor_items[0].attributes['Rfc'].value\n RegimenEmisor = emisor_items[0].attributes['RegimenFiscal'].value\n\n # Obtengo el nodo del comprobante\n invoice_items = xml.getElementsByTagName(\"cfdi:Comprobante\")\n\n # Obtengo los datos principales de la factura\n try:\n Serie = invoice_items[0].attributes['Serie'].value\n\n except:\n Serie = \"\"\n\n try:\n Folio = invoice_items[0].attributes['Folio'].value\n\n except:\n Folio = xml.getElementsByTagName(\"tfd:TimbreFiscalDigital\")[0].attributes['UUID'].value\n Folio = Folio[-5:]\n\n reference = Serie + \" \" + Folio\n\n x_invoice_date_sat = invoice_items[0].attributes['Fecha'].value\n\n \"\"\"\n x_invoice_date_sat_year = datetime.datetime.strptime(x_invoice_date_sat, '%Y-%m-%dT%H:%M:%S')\n\n current_year = datetime.datetime.now().year\n\n if x_invoice_date_sat_year.year < current_year:\n\n raise ValidationError('La factura no corresponde al presente año fiscal ' + str(current_year)\n + \"\\nLa factura fue timbrada en : \" + str(x_invoice_date_sat_year)\n + \" y no se encuentra provisionada, favor de solicitar refacturación.\")\n \"\"\"\n\n amount_untaxed = invoice_items[0].attributes['SubTotal'].value\n\n try:\n discount = invoice_items[0].attributes['Descuento'].value\n\n except:\n discount = 0\n\n try:\n taxes = xml.getElementsByTagName(\"cfdi:Impuestos\")[len(xml.getElementsByTagName(\"cfdi:Impuestos\"))-1].attributes['TotalImpuestosTrasladados'].value\n except:\n taxes = 0\n\n amount_total = invoice_items[0].attributes['Total'].value\n\n # Obtengo los nodos con la información de las líneas de factura\n invoice_line_ids = xml.getElementsByTagName(\"cfdi:Concepto\")\n\n # Busco al proveedor\n partner = self.env['res.partner'].search([[\"vat\", \"=\", RfcEmisor]], limit=1)\n\n # Si no existe lo creo en odoo\n if not partner:\n partner = self.create_partner(RegimenEmisor=RegimenEmisor, NombreEmisor=NombreEmisor, RfcEmisor=RfcEmisor)\n\n xml_mapped = MappedXml(reference=reference,\n x_invoice_date_sat=x_invoice_date_sat,\n amount_untaxed=amount_untaxed,\n discount=discount,\n taxes=taxes,\n amount_total=amount_total,\n invoice_line_ids=invoice_line_ids,\n partner=partner)\n\n return xml_mapped\n\n # Si la factura no es de la compañia actual envío una alerta\n else:\n\n raise ValidationError('La factura no corresponde a ' + self.env.user.company_id.name\n + \"\\nLa factura está hecha a: \" + NombreReceptor\n + \" RFC: \" + RfcReceptor)\n\n def import_xml_data(self):\n self.ensure_one()\n\n xml = self.map_xml_to_odoo_fields()\n\n if self.state == 'draft':\n\n # Asigno los datos al documento\n self.write({'partner_id': xml.partner.id,\n 'reference': xml.reference,\n 'x_invoice_date_sat': xml.x_invoice_date_sat})\n\n if self.search([('type', '=', self.type), ('reference', '=', self.reference),\n ('company_id', '=', self.company_id.id),\n ('commercial_partner_id', '=', self.commercial_partner_id.id),\n ('id', '!=', self.id)]):\n\n raise ValidationError(\"Se ha detectado una referencia de \" + xml.partner.name +\n \" duplicada: \" + self.reference +\n \" timbrada el \" + xml.x_invoice_date_sat +\n \" en el SAT por un monto de \" +\n \"${:,.2f}\".format(xml.amount_total))\n\n xml_line_items = xml.invoice_line_ids\n\n # Si tiene lineas de factura\n if self.invoice_line_ids:\n # Cuento las lineas de factura de odoo y del XML\n odoo_lines = 0\n\n for lines in self.invoice_line_ids:\n odoo_lines = odoo_lines + 1\n\n xml_lines = len(xml_line_items)\n # Si son iguales solamente edito las de odoo\n if odoo_lines == xml_lines:\n\n for idx, line in enumerate(self.invoice_line_ids):\n\n self.overwrite_invoice_line(line, xml_line_items, idx)\n\n elif odoo_lines > xml_lines:\n\n for idx, line in enumerate(self.invoice_line_ids):\n\n try:\n\n self.overwrite_invoice_line(line, xml_line_items, idx)\n\n except:\n\n line.unlink()\n\n elif xml_lines > odoo_lines:\n\n for idx, line in enumerate(self.invoice_line_ids):\n\n self.overwrite_invoice_line(line, xml_line_items, idx)\n\n for idx, line in enumerate(xml_line_items):\n\n if idx < odoo_lines:\n\n continue\n\n else:\n\n self.create_invoice_line(line)\n\n # Sino tiene lineas de factura\n else:\n\n # Para cada concepto del XML creo una linea de factura en odoo\n for line in xml_line_items:\n\n self.create_invoice_line(line)\n\n self.compute_taxes()\n\n elif self.state == 'approved_by_manager' or self.state == 'open' or self.state == 'paid':\n if self.match_xml(xml):\n self.write({'partner_id': xml.partner.id,\n 'reference': xml.reference,\n 'x_invoice_date_sat': xml.x_invoice_date_sat})\n\n def overwrite_invoice_line(self, odoo_line, xml_line, i):\n\n odoo_line.write({\n 'name': xml_line[i].attributes['Descripcion'].value,\n 'quantity': xml_line[i].attributes['Cantidad'].value,\n 'uom_id': self.get_uom(xml_line[i]),\n 'invoice_line_tax_ids': self.get_tax_id(odoo_line, xml_line[i]),\n 'price_unit': self.get_discounted_unit_price(xml_line[i])\n })\n\n def create_invoice_line(self, xml_line):\n\n # Creación de la línea de factura\n new_line = self.env['account.invoice.line'].create({\n 'invoice_id': self.id,\n 'product_id': 921,\n 'name': xml_line.attributes['Descripcion'].value,\n 'account_id': 1977,\n 'quantity': xml_line.attributes['Cantidad'].value,\n 'uom_id': self.get_uom(xml_line),\n 'price_unit': self.get_discounted_unit_price(xml_line),\n 'type': \"in_invoice\"\n })\n\n new_line.invoice_line_tax_ids = self.get_tax_id(new_line, xml_line)\n\n def match_xml(self, xml):\n\n Error = []\n\n if self.partner_id.id != xml.partner.id:\n\n Error.append(\"\\nNo coincide el Proveedor de la Factura Odoo con el del CFDi!\" +\n \"\\n**********Proveedor en la Factura: \" + self.partner_id.name +\n \"\\n**********Proveedor en el CFDi: \" + xml.partner.name)\n\n if self.search([('type', '=', self.type), ('reference', '=', self.reference),\n ('company_id', '=', self.company_id.id),\n ('commercial_partner_id', '=', self.commercial_partner_id.id),\n ('id', '!=', self.id)]):\n\n Error.append(\"\\nSe ha detectado una referencia de \" + xml.partner.name +\n \" duplicada: \" + self.reference +\n \" timbrada el \" + xml.x_invoice_date_sat +\n \" en el SAT por un monto de \" +\n \"${:,.2f}\".format(xml.amount_total))\n\n if self.x_invoice_date_sat != xml.x_invoice_date_sat:\n\n Error.append(\"\\nNo coincide la fecha de timbrado de la Factura Odoo con el del CFDi!\" +\n \"\\n**********Fecha de facturación del SAT en la Factura Odoo: \" + self.x_invoice_date_sat +\n \"\\n**********Fecha de timbrado en el CFDi: \" + xml.x_invoice_date_sat)\n\n difference = self.amount_total - xml.amount_total\n\n if not (-.10 <= difference <= .10):\n\n Error.append(\"\\nNo coincide el monto de factura!\" +\n \"\\n**********Monto total en la Factura Odoo: \" + \"${:,.2f}\".format(self.amount_total) +\n \"\\n**********Monto total en el CFDi: \" + \"${:,.2f}\".format(xml.amount_total) +\n \"\\n**********Variación: \" + \"${:,.2f}\".format(difference))\n\n if Error:\n\n raise ValidationError(Error)\n\n def create_partner(self, RegimenEmisor, NombreEmisor, RfcEmisor):\n if RegimenEmisor == 612:\n company_type = \"person\"\n fiscal_position = 10\n else:\n company_type = \"company\"\n fiscal_position = 1\n\n partner = self.env['res.partner'].create({\n 'company_type': company_type,\n 'name': NombreEmisor,\n 'vat': RfcEmisor,\n 'country_id': 156,\n 'lang': \"es_MX\",\n 'supplier': 1,\n 'customer': 0,\n 'property_account_position_id': fiscal_position,\n 'l10n_mx_type_of_operation': \"85\",\n 'type': 'contact'\n })\n\n return partner\n\n def get_product_id(self):\n pass\n\n def get_account_id(self):\n return self.account_id\n\n def get_tax_id(self, odoo_line, xml_line):\n\n try:\n\n rate = float(xml_line.getElementsByTagName(\"cfdi:Traslado\")[0].attributes['TasaOCuota'].value)\n\n if rate == 0:\n tax_id = self.env['account.tax'].search([[\"type_tax_use\", \"=\", \"purchase\"],\n [\"company_id\", \"=\", self.company_id.id],\n [\"amount\", \"=\", rate],\n [\"name\", \"like\", \"0%\"]], limit=1)\n\n if tax_id:\n\n return [(6, 0, [tax_id.id])]\n\n else:\n\n return odoo_line.product_id.supplier_taxes_id\n else:\n\n return odoo_line.product_id.supplier_taxes_id\n\n except:\n\n product_id = self.env['product.product'].search([[\"purchase_ok\", \"=\", True],\n [\"company_id\", \"=\", self.company_id.id],\n [\"supplier_taxes_id.name\", \"like\", \"EXENTO\"]], limit=1)\n\n if product_id:\n\n odoo_line.product_id = product_id\n\n return odoo_line.product_id.supplier_taxes_id\n\n else:\n\n return odoo_line.product_id.supplier_taxes_id\n\n def get_uom(self, xml_line):\n\n try:\n\n odoo_code = self.env['product.uom'].search([[\"l10n_mx_edi_code_sat_id.code\", \"=\", xml_line.attributes['ClaveUnidad'].value]], limit=1)\n\n return odoo_code.id\n\n except:\n\n odoo_code = self.env['product.uom'].search([[\"l10n_mx_edi_code_sat_id.code\", \"=\", \"E48\"]], limit=1)\n\n return odoo_code.id\n\n def get_discounted_unit_price(self, xml_line):\n\n price_unit = float(xml_line.attributes['ValorUnitario'].value)\n\n try:\n\n unitary_discount = float(xml_line.attributes['Descuento'].value) / float(\n xml_line.attributes['Cantidad'].value)\n\n price_unit = price_unit - unitary_discount\n\n except:\n\n price_unit = price_unit\n\n return price_unit\n\n\nclass MappedXml:\n\n def __init__(self, reference, x_invoice_date_sat, amount_untaxed, discount, taxes, amount_total, invoice_line_ids, partner):\n self.reference = reference\n self.x_invoice_date_sat = str(datetime.datetime.strptime(x_invoice_date_sat, '%Y-%m-%dT%H:%M:%S').date())\n self.amount_untaxed = float(amount_untaxed)\n self.discount = float(discount)\n self.taxes = float(taxes)\n self.amount_total = float(amount_total)\n self.invoice_line_ids = invoice_line_ids\n self.partner = partner\n","sub_path":"xmltoinvoice/models/account_invoice.py","file_name":"account_invoice.py","file_ext":"py","file_size_in_byte":15160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"210949387","text":"'''\nInspired from https://brian2.readthedocs.io/en/stable/examples/CUBA.html\nLIF_CUBA_AC_simplified_STDP\n- CUBA LIF with alternative current (AC for short)\n- Since the weights are fixed, this example shows no plasticity, i.e. no learning\nrule is applied\n- El is close to Vth so that neurons are likely to fire even with a small stimulation.\n- This network is a self-connectivity one.\n- No excitatory or inhibitory neurons are created.\n'''\nfrom brian2 import *\nimport time\n\nprint ('Simulation running....')\nstart_time =time.time()\ntaum = 20*ms\ntaue = 5*ms\ntaui = 10*ms\nVth = -50*mV # Threshold voltage\nVRest = -60*mV # Resting voltage\nEl = -49*mV\nnum =10\n#w = (60*0.27/10)*mV # excitatory synaptic weight (positive value)\nw= (-20*4.5/10) *mV\neqs = '''\ndv/dt = (I-(v-El))/taum : volt (unless refractory)\ndI/dt = -I/taue : volt\n'''\n\nP = NeuronGroup(num,\n eqs,\n threshold='v>Vth',\n reset='v = VRest',\n refractory=5*ms,\n method='exact')\n#P.v = 'VRest + rand() * (Vth - VRest)'\nP.v = VRest\nP.I = 0*mV\n\n# excitatory synaptic weight (positive value)\n# Neurons of the group is connected with each other only\nwe = (60*0.27/10)*mV\nCe = Synapses(P,\n P,\n on_pre='I += w',\n method='linear')\nCe.connect('i!=j', p=.5)\n\ns_mon = SpikeMonitor(P)\nG_sta = StateMonitor(P,['v','I'],record = True)\n\n\nrun(1 * second)\n\nfigure(1)\nsubplot(211) ## Membrane potential\nfor idx in range(num):\n\tplot(G_sta.t/ms, G_sta.v[idx])\nxlabel('Time (ms)')\nylabel('Membrabe potential')\nsubplot(212) ## Raster plot of Poisson spike trains\nplot(s_mon.t/ms, s_mon.i, '.',c='C3')\nxlabel('Time (ms)')\nylabel('Neuron index')\n\nfigure(2) ## Input current\nfor idx in range(num):\n\tplot(G_sta.t/ms, G_sta.I[idx])\n\nprint ('Done')\nprint ('Number of neurons in the network are: ', num)\nprint ('Network construction time: ', time.time() - start_time,' seconds')\nshow()\n","sub_path":"LIF/CUBA/AC_self_connectivity_ok.py","file_name":"AC_self_connectivity_ok.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"387510919","text":"# coding: utf8\n\nimport torch\nimport pandas as pd\nimport numpy as np\nfrom os import path\nfrom torch.utils.data import Dataset\nfrom scipy.ndimage.filters import gaussian_filter\n\n\n#################################\n# Datasets loaders\n#################################\nFILENAME_TYPE = {'full': '_T1w_space-MNI152NLin2009cSym_res-1x1x1_T1w',\n 'cropped': '_T1w_space-MNI152NLin2009cSym_desc-Crop_res-1x1x1_T1w'}\n\n\nclass MRIDataset(Dataset):\n \"\"\"Dataset of MRI organized in a CAPS folder.\"\"\"\n\n def __init__(self, img_dir, data_file,\n preprocessing='t1-linear', transform=None):\n \"\"\"\n Args:\n img_dir (string): Directory of all the images.\n data_file (string): File name of the train/test split file.\n preprocessing (string): Defines the path to the data in CAPS\n transform (callable, optional): Optional transform to be applied on a sample.\n\n \"\"\"\n self.img_dir = img_dir\n self.transform = transform\n self.diagnosis_code = {\n 'CN': 0,\n 'AD': 1,\n 'sMCI': 0,\n 'pMCI': 1,\n 'MCI': 1,\n 'unlabeled': -1}\n self.data_path = preprocessing\n\n # Check the format of the tsv file here\n if isinstance(data_file, str):\n self.df = pd.read_csv(data_file, sep='\\t')\n elif isinstance(data_file, pd.DataFrame):\n self.df = data_file\n else:\n raise Exception('The argument datafile is not of correct type.')\n\n if ('diagnosis' not in list(self.df.columns.values)) or ('session_id' not in list(self.df.columns.values)) or \\\n ('participant_id' not in list(self.df.columns.values)):\n raise Exception(\"the data file is not in the correct format.\"\n \"Columns should include ['participant_id', 'session_id', 'diagnosis']\")\n\n self.size = self[0]['image'].numpy().size\n\n def __len__(self):\n return len(self.df)\n\n def __getitem__(self, idx):\n img_name = self.df.loc[idx, 'participant_id']\n img_label = self.df.loc[idx, 'diagnosis']\n sess_name = self.df.loc[idx, 'session_id']\n # Not in BIDS but in CAPS\n if self.data_path == \"t1-linear\":\n image_path = path.join(self.img_dir, 'subjects', img_name, sess_name,\n 'deeplearning_prepare_data', 'image_based', 't1_linear',\n img_name + '_' + sess_name\n + FILENAME_TYPE['cropped'] + '.pt')\n elif self.data_path == \"t1-volume\":\n image_path = path.join(self.img_dir, 'subjects', img_name, sess_name,\n 't1', 'spm', 'segmentation', 'normalized_space',\n img_name + '_' + sess_name + '_space-Ixi549Space_T1w.pt')\n else:\n raise NotImplementedError(\n \"The data path %s is not implemented\" %\n self.data_path)\n\n image = torch.load(image_path)\n label = self.diagnosis_code[img_label]\n\n if self.transform:\n image = self.transform(image)\n sample = {'image': image, 'label': label, 'participant_id': img_name, 'session_id': sess_name,\n 'image_path': image_path}\n\n return sample\n\n def session_restriction(self, session):\n \"\"\"\n Allows to generate a new MRIDataset using some specific sessions only (mostly used for evaluation of test)\n\n :param session: (str) the session wanted. Must be 'all' or 'ses-MXX'\n :return: (DataFrame) the dataset with the wanted sessions\n \"\"\"\n from copy import copy\n\n data_output = copy(self)\n if session == \"all\":\n return data_output\n else:\n df_session = self.df[self.df.session_id == session]\n df_session.reset_index(drop=True, inplace=True)\n data_output.df = df_session\n if len(data_output) == 0:\n raise Exception(\n \"The session %s doesn't exist for any of the subjects in the test data\" %\n session)\n return data_output\n\n\nclass MRIDataset_patch(Dataset):\n\n def __init__(self, caps_directory, data_file, patch_size, stride_size, transformations=None, prepare_dl=False,\n patch_index=None):\n \"\"\"\n Args:\n caps_directory (string): Directory of all the images.\n data_file (string): File name of the train/test split file.\n transformations (callable, optional): Optional transformations to be applied on a sample.\n\n \"\"\"\n self.caps_directory = caps_directory\n self.transformations = transformations\n self.diagnosis_code = {\n 'CN': 0,\n 'AD': 1,\n 'sMCI': 0,\n 'pMCI': 1,\n 'MCI': 1}\n self.patch_size = patch_size\n self.stride_size = stride_size\n self.prepare_dl = prepare_dl\n self.patch_index = patch_index\n\n # Check the format of the tsv file here\n if isinstance(data_file, str):\n self.df = pd.read_csv(data_file, sep='\\t')\n elif isinstance(data_file, pd.DataFrame):\n self.df = data_file\n else:\n raise Exception('The argument datafile is not of correct type.')\n\n if ('diagnosis' not in list(self.df.columns.values)) or ('session_id' not in list(self.df.columns.values)) or \\\n ('participant_id' not in list(self.df.columns.values)):\n raise Exception(\"the data file is not in the correct format.\"\n \"Columns should include ['participant_id', 'session_id', 'diagnosis']\")\n\n self.patchs_per_patient = self.num_patches_per_session()\n\n def __len__(self):\n return len(self.df) * self.patchs_per_patient\n\n def __getitem__(self, idx):\n sub_idx = idx // self.patchs_per_patient\n img_name = self.df.loc[sub_idx, 'participant_id']\n sess_name = self.df.loc[sub_idx, 'session_id']\n img_label = self.df.loc[sub_idx, 'diagnosis']\n label = self.diagnosis_code[img_label]\n if self.patch_index is None:\n patch_idx = idx % self.patchs_per_patient\n else:\n patch_idx = self.patch_index\n\n if self.prepare_dl:\n patch_path = path.join(self.caps_directory, 'subjects', img_name, sess_name,\n 'deeplearning_prepare_data', 'patch_based', 't1_linear',\n img_name + '_' + sess_name\n + FILENAME_TYPE['cropped']\n + '_patchsize-' + str(self.patch_size)\n + '_stride-' + str(self.stride_size)\n + '_patch-' + str(patch_idx) + '.pt')\n\n patch = torch.load(patch_path)\n else:\n image_path = path.join(self.caps_directory, 'subjects', img_name, sess_name,\n 'deeplearning_prepare_data', 'image_based', 't1_linear',\n img_name + '_' + sess_name\n + FILENAME_TYPE['cropped'] + '.pt')\n image = torch.load(image_path)\n patch = extract_patch_from_mri(\n image, patch_idx, self.patch_size, self.stride_size)\n\n # check if the patch has NaN value\n if torch.isnan(patch).any():\n print(\"Double check, this patch has NaN value: %s\" %\n str(img_name + '_' + sess_name + str(patch_idx)))\n patch[torch.isnan(patch)] = 0\n\n if self.transformations:\n patch = self.transformations(patch)\n\n sample = {'image_id': img_name + '_' + sess_name + '_patch' + str(patch_idx),\n 'image': patch, 'label': label,\n 'participant_id': img_name, 'session_id': sess_name,\n 'patch_id': patch_idx}\n\n return sample\n\n def num_patches_per_session(self):\n if self.patch_index is not None:\n return 1\n\n img_name = self.df.loc[0, 'participant_id']\n sess_name = self.df.loc[0, 'session_id']\n\n image_path = path.join(self.caps_directory, 'subjects', img_name, sess_name,\n 'deeplearning_prepare_data', 'image_based', 't1_linear',\n img_name + '_' + sess_name\n + FILENAME_TYPE['cropped'] + '.pt')\n image = torch.load(image_path)\n\n patches_tensor = image.unfold(1, self.patch_size, self.stride_size\n ).unfold(2, self.patch_size, self.stride_size\n ).unfold(3, self.patch_size, self.stride_size).contiguous()\n patches_tensor = patches_tensor.view(-1,\n self.patch_size,\n self.patch_size,\n self.patch_size)\n num_patches = patches_tensor.shape[0]\n return num_patches\n\n\nclass MRIDataset_patch_hippocampus(Dataset):\n\n def __init__(self, caps_directory, data_file,\n transformations=None, prepare_dl=False):\n \"\"\"\n Args:\n caps_directory (string): Directory of all the images.\n data_file (string): File name of the train/test split file.\n transformations (callable, optional): Optional transformations to be applied on a sample.\n prepare_dl (bool): If True the outputs of extract preprocessing are used, else the whole\n MRI is loaded.\n\n \"\"\"\n self.caps_directory = caps_directory\n self.transformations = transformations\n self.diagnosis_code = {\n 'CN': 0,\n 'AD': 1,\n 'sMCI': 0,\n 'pMCI': 1,\n 'MCI': 1}\n self.prepare_dl = prepare_dl\n\n # Check the format of the tsv file here\n if isinstance(data_file, str):\n self.df = pd.read_csv(data_file, sep='\\t')\n elif isinstance(data_file, pd.DataFrame):\n self.df = data_file\n else:\n raise Exception('The argument datafile is not of correct type.')\n\n if ('diagnosis' not in list(self.df.columns.values)) or ('session_id' not in list(self.df.columns.values)) or \\\n ('participant_id' not in list(self.df.columns.values)):\n raise Exception(\"the data file is not in the correct format.\"\n \"Columns should include ['participant_id', 'session_id', 'diagnosis']\")\n\n self.patchs_per_patient = 2\n\n def __len__(self):\n return len(self.df) * self.patchs_per_patient\n\n def __getitem__(self, idx):\n sub_idx = idx // self.patchs_per_patient\n img_name = self.df.loc[sub_idx, 'participant_id']\n sess_name = self.df.loc[sub_idx, 'session_id']\n img_label = self.df.loc[sub_idx, 'diagnosis']\n label = self.diagnosis_code[img_label]\n\n # 1 is left hippocampus, 0 is right\n left_is_odd = idx % self.patchs_per_patient\n if self.prepare_dl:\n raise NotImplementedError(\n 'The extraction of ROIs prior to training is not implemented.')\n\n else:\n image_path = path.join(self.caps_directory, 'subjects', img_name, sess_name,\n 'deeplearning_prepare_data', 'image_based', 't1_linear',\n img_name + '_' + sess_name\n + FILENAME_TYPE['cropped'] + '.pt')\n image = torch.load(image_path)\n patch = extract_roi_from_mri(image, left_is_odd)\n\n # check if the patch has NaN value\n if torch.isnan(patch).any():\n print(\"Double check, this patch has NaN value: %s\" %\n str(img_name + '_' + sess_name + str(left_is_odd)))\n patch[torch.isnan(patch)] = 0\n\n if self.transformations:\n patch = self.transformations(patch)\n\n sample = {'image_id': img_name + '_' + sess_name + '_patch' + str(left_is_odd),\n 'image': patch, 'label': label,\n 'participant_id': img_name, 'session_id': sess_name,\n 'patch_id': left_is_odd}\n\n return sample\n\n\nclass MRIDataset_slice(Dataset):\n \"\"\"\n This class reads the CAPS of image processing pipeline of DL\n\n To note, this class processes the MRI to be RGB for transfer learning.\n\n Return: a Pytorch Dataset objective\n \"\"\"\n\n def __init__(self, caps_directory, data_file,\n transformations=None, mri_plane=0, prepare_dl=False):\n \"\"\"\n Args:\n caps_directory (string): the output folder of image processing pipeline.\n transformations (callable, optional): if the data sample should be done some transformations or not, such as resize the image.\n\n To note, for each view:\n Axial_view = \"[:, :, slice_i]\"\n Coronal_veiw = \"[:, slice_i, :]\"\n Saggital_view= \"[slice_i, :, :]\"\n\n \"\"\"\n self.caps_directory = caps_directory\n self.transformations = transformations\n self.diagnosis_code = {\n 'CN': 0,\n 'AD': 1,\n 'sMCI': 0,\n 'pMCI': 1,\n 'MCI': 1}\n self.mri_plane = mri_plane\n self.prepare_dl = prepare_dl\n\n # Check the format of the tsv file here\n if isinstance(data_file, str):\n self.df = pd.read_csv(data_file, sep='\\t')\n elif isinstance(data_file, pd.DataFrame):\n self.df = data_file\n else:\n raise Exception('The argument datafile is not of correct type.')\n\n # This dimension is for the output of image processing pipeline of Raw:\n # 169 * 208 * 179\n if mri_plane == 0:\n self.slices_per_patient = 169 - 40\n self.slice_direction = 'sag'\n elif mri_plane == 1:\n self.slices_per_patient = 208 - 40\n self.slice_direction = 'cor'\n elif mri_plane == 2:\n self.slices_per_patient = 179 - 40\n self.slice_direction = 'axi'\n\n def __len__(self):\n return len(self.df) * self.slices_per_patient\n\n def __getitem__(self, idx):\n sub_idx = idx // self.slices_per_patient\n img_name = self.df.loc[sub_idx, 'participant_id']\n sess_name = self.df.loc[sub_idx, 'session_id']\n img_label = self.df.loc[sub_idx, 'diagnosis']\n label = self.diagnosis_code[img_label]\n slice_idx = idx % self.slices_per_patient\n\n if self.prepare_dl:\n # read the slices directly\n slice_path = path.join(self.caps_directory, 'subjects', img_name, sess_name,\n 'deeplearning_prepare_data', 'slice_based', 't1_linear',\n img_name + '_' + sess_name\n + FILENAME_TYPE['cropped']\n + self.slice_direction + '_rgbslice-' + str(slice_idx + 20) + '.pt')\n extracted_slice = torch.load(slice_path)\n else:\n image_path = path.join(self.caps_directory, 'subjects', img_name, sess_name,\n 'deeplearning_prepare_data', 'image_based', 't1_linear',\n img_name + '_' + sess_name\n + FILENAME_TYPE['cropped'] + '.pt')\n image = torch.load(image_path)\n extracted_slice = extract_slice_from_mri(\n image, slice_idx + 20, self.mri_plane)\n\n # check if the slice has NaN value\n if torch.isnan(extracted_slice).any():\n print(\"Slice %s has NaN values.\" %\n str(img_name + '_' + sess_name + '_' + str(slice_idx + 20)))\n extracted_slice[torch.isnan(extracted_slice)] = 0\n\n if self.transformations:\n extracted_slice = self.transformations(extracted_slice)\n\n sample = {'image_id': img_name + '_' + sess_name + '_slice' + str(slice_idx + 20),\n 'image': extracted_slice, 'label': label,\n 'participant_id': img_name, 'session_id': sess_name,\n 'slice_id': slice_idx + 20}\n\n return sample\n\n\nclass MRIDataset_slice_mixed(Dataset):\n \"\"\"\n This class reads the CAPS of image processing pipeline of DL. However, this is used for the bad data split strategy\n\n To note, this class processes the MRI to be RGB for transfer learning.\n\n Return: a Pytorch Dataset objective\n \"\"\"\n\n def __init__(self, caps_directory, data_file,\n transformations=None, mri_plane=0, prepare_dl=False):\n \"\"\"\n Args:\n caps_directory (string): the output folder of image processing pipeline.\n transformations (callable, optional): if the data sample should be done some transformations or not, such as resize the image.\n\n To note, for each view:\n Axial_view = \"[:, :, slice_i]\"\n Coronal_veiw = \"[:, slice_i, :]\"\n Saggital_view= \"[slice_i, :, :]\"\n\n \"\"\"\n self.caps_directory = caps_directory\n self.transformations = transformations\n self.diagnosis_code = {\n 'CN': 0,\n 'AD': 1,\n 'sMCI': 0,\n 'pMCI': 1,\n 'MCI': 1}\n self.mri_plane = mri_plane\n self.prepare_dl = prepare_dl\n\n # Check the format of the tsv file here\n if isinstance(data_file, str):\n self.df = pd.read_csv(data_file, sep='\\t')\n elif isinstance(data_file, pd.DataFrame):\n self.df = data_file\n else:\n raise Exception('The argument datafile is not of correct type.')\n\n if mri_plane == 0:\n self.slice_direction = 'sag'\n elif mri_plane == 1:\n self.slice_direction = 'cor'\n elif mri_plane == 2:\n self.slice_direction = 'axi'\n\n def __len__(self):\n return len(self.df)\n\n def __getitem__(self, idx):\n img_name = self.df.loc[idx, 'participant_id']\n sess_name = self.df.loc[idx, 'session_id']\n slice_name = self.df.loc[idx, 'slice_id']\n img_label = self.df.loc[idx, 'diagnosis']\n label = self.diagnosis_code[img_label]\n\n if self.prepare_dl:\n slice_path = path.join(self.caps_directory, 'subjects', img_name, sess_name,\n 'deeplearning_prepare_data', 'slice_based', 't1_linear',\n img_name + '_' + sess_name\n + FILENAME_TYPE['cropped']\n + self.slice_direction + '_rgbslice-' + str(slice_name) + '.pt')\n extracted_slice = torch.load(slice_path)\n\n else:\n image_path = path.join(self.caps_directory, 'subjects', img_name, sess_name,\n 'deeplearning_prepare_data', 'image_based', 't1_linear',\n img_name + '_' + sess_name\n + FILENAME_TYPE['cropped'] + '.pt')\n image = torch.load(image_path)\n extracted_slice = extract_slice_from_mri(\n image, slice_name, self.mri_plane)\n\n # check if the slice has NaN value\n if torch.isnan(extracted_slice).any():\n print(\"Slice %s has NaN values.\" %\n str(img_name + '_' + sess_name + '_' + str(slice_name)))\n extracted_slice[torch.isnan(extracted_slice)] = 0\n\n if self.transformations:\n extracted_slice = self.transformations(extracted_slice)\n\n sample = {'image_id': img_name + '_' + sess_name + '_slice' + str(slice_name),\n 'image': extracted_slice, 'label': label,\n 'participant_id': img_name, 'session_id': sess_name,\n 'slice_id': slice_name}\n\n return sample\n\n\ndef extract_slice_from_mri(image, index_slice, view):\n \"\"\"\n This is a function to grab one slice in each view and create a rgb image for transferring learning: duplicate the slices into R, G, B channel\n :param image: (tensor)\n :param index_slice: (int) index of the wanted slice\n :param view:\n :return:\n To note, for each view:\n Axial_view = \"[:, :, slice_i]\"\n Coronal_view = \"[:, slice_i, :]\"\n Sagittal_view= \"[slice_i, :, :]\"\n \"\"\"\n\n # reshape the tensor, delete the first dimension for slice-level\n image_tensor = image.squeeze(0)\n\n # sagittal\n if view == 0:\n slice_select = image_tensor[index_slice, :, :].clone()\n\n # coronal\n elif view == 1:\n slice_select = image_tensor[:, index_slice, :].clone()\n\n # axial\n elif view == 2:\n slice_select = image_tensor[:, :, index_slice].clone()\n\n else:\n raise ValueError(\n \"This view does not exist, please choose view in [0, 1, 2]\")\n\n extracted_slice = torch.stack((slice_select, slice_select, slice_select))\n\n return extracted_slice\n\n\ndef extract_patch_from_mri(image_tensor, index_patch, patch_size, stride_size):\n\n # use classifiers tensor.upfold to crop the patch.\n patches_tensor = image_tensor.unfold(1, patch_size, stride_size\n ).unfold(2, patch_size, stride_size\n ).unfold(3, patch_size, stride_size).contiguous()\n patches_tensor = patches_tensor.view(-1,\n patch_size,\n patch_size,\n patch_size)\n extracted_patch = patches_tensor[index_patch, ...].unsqueeze_(0).clone()\n\n return extracted_patch\n\n\ndef extract_roi_from_mri(image_tensor, left_is_odd):\n \"\"\"\n\n :param image_tensor: (Tensor) the tensor of the image.\n :param left_is_odd: (int) if 1 the left hippocampus is extracted, else the right one.\n :return: Tensor of the extracted hippocampus\n \"\"\"\n\n if left_is_odd == 1:\n crop_center = (61, 96, 68) # the center of the left hippocampus\n else:\n crop_center = (109, 96, 68) # the center of the right hippocampus\n crop_size = (50, 50, 50) # the output cropped hippocampus size\n\n extracted_roi = image_tensor[\n :,\n crop_center[0] - crop_size[0] // 2: crop_center[0] + crop_size[0] // 2:,\n crop_center[1] - crop_size[1] // 2: crop_center[1] + crop_size[1] // 2:,\n crop_center[2] - crop_size[2] // 2: crop_center[2] + crop_size[2] // 2:\n ].clone()\n\n return extracted_roi\n\n\nclass GaussianSmoothing(object):\n\n def __init__(self, sigma):\n self.sigma = sigma\n\n def __call__(self, sample):\n image = sample['image']\n np.nan_to_num(image, copy=False)\n smoothed_image = gaussian_filter(image, sigma=self.sigma)\n sample['image'] = smoothed_image\n\n return sample\n\n\nclass ToTensor(object):\n \"\"\"Convert image type to Tensor and diagnosis to diagnosis code\"\"\"\n\n def __call__(self, image):\n np.nan_to_num(image, copy=False)\n image = image.astype(float)\n\n return torch.from_numpy(image[np.newaxis, :]).float()\n\n\nclass MinMaxNormalization(object):\n \"\"\"Normalizes a tensor between 0 and 1\"\"\"\n\n def __call__(self, image):\n return (image - image.min()) / (image.max() - image.min())\n\n\ndef load_data(train_val_path, diagnoses_list,\n split, n_splits=None, baseline=True):\n\n train_df = pd.DataFrame()\n valid_df = pd.DataFrame()\n\n if n_splits is None:\n train_path = path.join(train_val_path, 'train')\n valid_path = path.join(train_val_path, 'validation')\n\n else:\n train_path = path.join(train_val_path, 'train_splits-' + str(n_splits),\n 'split-' + str(split))\n valid_path = path.join(train_val_path, 'validation_splits-' + str(n_splits),\n 'split-' + str(split))\n\n print(\"Train\", train_path)\n print(\"Valid\", valid_path)\n\n for diagnosis in diagnoses_list:\n\n if baseline:\n train_diagnosis_path = path.join(\n train_path, diagnosis + '_baseline.tsv')\n else:\n train_diagnosis_path = path.join(train_path, diagnosis + '.tsv')\n\n valid_diagnosis_path = path.join(\n valid_path, diagnosis + '_baseline.tsv')\n\n train_diagnosis_df = pd.read_csv(train_diagnosis_path, sep='\\t')\n valid_diagnosis_df = pd.read_csv(valid_diagnosis_path, sep='\\t')\n\n train_df = pd.concat([train_df, train_diagnosis_df])\n valid_df = pd.concat([valid_df, valid_diagnosis_df])\n\n train_df.reset_index(inplace=True, drop=True)\n valid_df.reset_index(inplace=True, drop=True)\n\n return train_df, valid_df\n\n\ndef load_data_test(test_path, diagnoses_list):\n\n test_df = pd.DataFrame()\n\n for diagnosis in diagnoses_list:\n\n test_diagnosis_path = path.join(test_path, diagnosis + '_baseline.tsv')\n test_diagnosis_df = pd.read_csv(test_diagnosis_path, sep='\\t')\n test_df = pd.concat([test_df, test_diagnosis_df])\n\n test_df.reset_index(inplace=True, drop=True)\n\n return test_df\n","sub_path":"clinicadl/clinicadl/tools/deep_learning/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":25159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"149238348","text":"#MTL用\nclass RankNet(nn.Module): #MTL\n def __init__(self, n_input, n_out):\n super(RankNet, self).__init__()\n self.n_input = n_input\n mid_io = 128\n self.fc1 = nn.Linear(n_input, mid_io)\n self.fc2 = nn.Linear(mid_io,mid_io)\n #self.fc3 = nn.Linear(128, 2)\n \n self.fc3_1 = nn.Linear(mid_io, 1)\n self.fc3_2 = nn.Linear(mid_io, 1)\n self.fc3_3 = nn.Linear(mid_io, 1)\n\n nn.init.xavier_normal_(self.fc1.weight)\n nn.init.xavier_normal_(self.fc2.weight)\n nn.init.xavier_normal_(self.fc3_1.weight)\n nn.init.xavier_normal_(self.fc3_2.weight)\n nn.init.xavier_normal_(self.fc3_3.weight)\n\n def forward(self, x, n_task):\n x = F.relu(self.fc1(x)) # ReLU: max(x, 0)\n x = F.relu(self.fc2(x)) # ReLU: max(x, 0)\n #x = self.fc3(x)\n if(n_task == 0 ): x = self.fc3_1(x)\n if(n_task == 1 ): x = self.fc3_2(x)\n if(n_task == 2 ): x = self.fc3_3(x)\n \n # if(n_task == 'cart' ): x = self.fc3_1(x)\n # if(n_task == 'click' ): x = self.fc3_2(x)\n # if(n_task == 'conversion'): x = self.fc3_3(x)\n\n return x\n\n def compare(self, x, n_task):\n # m = torch.nn.Softplus()\n # print(\"compare\", x.shape, n_task)\n x1 = x[:,:self.n_input,0]\n x2 = x[:,self.n_input:,0]\n # print(\"compare2\", x1.shape, x2.shape,n_task)\n o = self.forward(x1, n_task) - self.forward(x2, n_task)\n return o\n # return torch.ones(o.shape) / (torch.ones(o.shape) + torch.exp(-o) )\n","sub_path":"MTL_model_sample.py","file_name":"MTL_model_sample.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"222652434","text":"import os\n\ntry:\n import tkinter as tk\nexcept:\n import Tkinter as tk\n\ntry:\n from modules.Observer import Observer\nexcept:\n from Observer import Observer\n\n\nclass Screen(Observer):\n\n def __init__(self, parent):\n self.parent = parent\n self.current_note = tk.StringVar()\n self.pure_note = tk.IntVar()\n self.harmonic = tk.IntVar()\n self.chord = tk.IntVar()\n self.piano_keys = dict()\n self.notes_available = os.listdir('Sounds/')\n \n self.notes = ['C', 'C#', 'D', 'D#',\n 'E', 'F', 'F#', 'G',\n 'G#', 'A', 'A#', 'B']\n\n self.notes = ['C', 'D', 'E', 'F',\n 'G', 'A', 'B', 'C#',\n 'D#', 'F#', 'G#', 'A#']\n self.current_note.set('C')\n \n self.create_frames()\n self.create_labels()\n self.create_optmenus()\n self.create_spinboxes()\n self.create_buttons()\n self.create_checkboxes()\n self.create_listboxes()\n self.create_scrollbars()\n self.create_scales()\n self.create_canvas()\n self.show_all()\n\n def create_frames(self):\n self.gen_note_frame = tk.Frame(\n self.parent,\n highlightbackground='#273746',\n highlightcolor='#273746',\n highlightthickness=1.5,\n relief='raised',\n bd=0\n )\n\n self.gen_mode_frame = tk.Frame(\n self.gen_note_frame,\n highlightbackground='#273746',\n highlightcolor='#273746',\n highlightthickness=1.5,\n relief='raised',\n bd=0\n )\n\n self.notes_available_frame = tk.Frame(\n self.parent,\n highlightbackground='#273746',\n highlightcolor='#273746',\n highlightthickness=1.5,\n relief='raised',\n bd=0\n )\n\n self.keyboard_frame = tk.Frame(\n self.parent,\n highlightbackground='#273746',\n highlightcolor='#273746',\n highlightthickness=1.5,\n relief='raised',\n bd=0\n )\n\n self.oct_to_play_frame = tk.Label(\n self.parent,\n highlightbackground='#273746',\n highlightcolor='#273746',\n highlightthickness=1.5,\n relief='raised',\n bd=0\n )\n\n def create_labels(self):\n self.gen_note_title = tk.Label(\n self.gen_note_frame,\n text='Note Generator',\n font='Arial 14 bold italic',\n fg='white',\n bg='#2E4053',\n justify='center',\n height=2\n )\n\n self.note_label = tk.Label(\n self.gen_note_frame,\n text='Note to generate :',\n font='Arial 11 bold',\n fg='black',\n highlightbackground='#273746',\n highlightcolor='#273746',\n highlightthickness=1,\n relief='raised',\n bd=1\n )\n\n self.oct_label = tk.Label(\n self.gen_note_frame,\n text='Octave :',\n font='Arial 11 bold',\n fg='black',\n highlightbackground='#273746',\n highlightcolor='#273746',\n highlightthickness=1,\n relief='raised',\n bd=1\n )\n\n self.duration_label = tk.Label(\n self.gen_note_frame,\n text='Duration :',\n font='Arial 11 bold',\n fg='black',\n highlightbackground='#273746',\n highlightcolor='#273746',\n highlightthickness=1,\n relief='raised',\n bd=1\n )\n\n self.notes_available_title = tk.Label(\n self.notes_available_frame,\n text='Notes Available',\n font='Arial 14 bold italic',\n fg='white',\n bg='#2E4053',\n justify='center'\n )\n\n self.oct_label_2 = tk.Label(\n self.oct_to_play_frame,\n text='Octave :',\n font='Arial 14 bold',\n fg='black',\n bd=1\n )\n \n def create_optmenus(self):\n self.note_menu = tk.OptionMenu(\n self.gen_note_frame,\n self.current_note,\n *self.notes\n )\n\n self.note_menu.config(\n font='Arial 12 bold',\n highlightbackground='#273746',\n highlightcolor='#273746',\n highlightthickness=1,\n relief='raised',\n bd=1\n )\n\n def create_spinboxes(self):\n self.oct_spin = tk.Spinbox(\n self.gen_note_frame,\n font='Arial 12 bold',\n justify='center',\n from_=1,\n to=4,\n highlightbackground='#273746',\n highlightcolor='#273746',\n highlightthickness=1,\n relief='raised',\n bd=1\n )\n\n self.oct_spin_2 = tk.Spinbox(\n self.oct_to_play_frame,\n font='Arial 12 bold',\n justify='center',\n from_=1,\n to=6,\n highlightbackground='#273746',\n highlightcolor='#273746',\n highlightthickness=1,\n relief='raised',\n bd=1\n )\n \n def create_buttons(self):\n self.save_button = tk.Button(\n self.gen_note_frame,\n text='Save',\n font='Arial 15',\n justify='center',\n highlightbackground='#273746',\n highlightcolor='#273746',\n highlightthickness=1,\n relief='raised'\n )\n\n self.play_note_button = tk.Button(\n self.notes_available_frame,\n text='Play',\n font='Arial 15',\n justify='center',\n highlightbackground='#273746',\n highlightcolor='#273746',\n highlightthickness=1,\n relief='raised'\n )\n\n self.del_note_button = tk.Button(\n self.notes_available_frame,\n text='Delete',\n font='Arial 15',\n justify='center',\n highlightbackground='#273746',\n highlightcolor='#273746',\n highlightthickness=1,\n relief='raised'\n )\n\n self.create_piano_keys()\n\n def create_checkboxes(self):\n self.pure_note_cb = tk.Checkbutton(\n self.gen_mode_frame,\n text='Pure Note',\n font='Arial 12',\n variable=self.pure_note,\n onvalue=1,\n highlightbackground='#273746',\n highlightcolor='#273746',\n highlightthickness=1,\n relief='flat'\n )\n\n self.harmonic_cb = tk.Checkbutton(\n self.gen_mode_frame,\n text='Harmonic',\n font='Arial 12',\n variable=self.harmonic,\n onvalue=1,\n highlightbackground='#273746',\n highlightcolor='#273746',\n highlightthickness=1,\n relief='flat'\n )\n\n self.chord_cb = tk.Checkbutton(\n self.gen_mode_frame,\n text='Chord ',\n font='Arial 12',\n variable=self.chord,\n onvalue=1,\n highlightbackground='#273746',\n highlightcolor='#273746',\n highlightthickness=1,\n relief='flat',\n )\n\n def create_listboxes(self):\n self.notes_available_listbox = tk.Listbox(\n self.notes_available_frame,\n font='Arial 12 bold',\n highlightbackground='#273746',\n highlightthickness=1,\n highlightcolor='#273746',\n relief='sunken',\n bd=1\n )\n\n self.notes_available.sort()\n notes_available_name = [self.notes_available[k].split('.')[0] for k in range(len(self.notes_available))]\n self.notes_available_listbox.insert(0, *notes_available_name)\n\n def create_scrollbars(self):\n self.notes_scroll = tk.Scrollbar(\n self.notes_available_listbox,\n orient='vertical',\n command=self.notes_available_listbox.yview,\n width=15\n )\n\n def create_scales(self):\n self.duration_scale = tk.Scale(\n self.gen_note_frame,\n orient='horizontal',\n from_=1,\n to=5\n )\n\n def create_piano_keys(self):\n dx_white = 0\n delta_x = 0.05\n\n for n in self.notes:\n if n.startswith('#', 1, len(n)):\n self.piano_keys[n] = tk.Button(self.keyboard_frame, name=n.lower(), bg='black')\n self.piano_keys[n].place(relx=delta_x, relwidth=0.06, relheight=0.6)\n\n if n.startswith('D#', 0, len(n)):\n delta_x += 0.16\n else:\n delta_x += 0.08\n else:\n self.piano_keys[n] = tk.Button(self.keyboard_frame, name=n.lower(), bg='white')\n self.piano_keys[n].place(relx=0.08*(dx_white), relwidth=0.08, relheight=1)\n dx_white += 1\n\n def create_canvas(self):\n self.plot_canvas = tk.Canvas(\n self.keyboard_frame,\n bg='white',\n highlightbackground='#273746',\n highlightcolor='#273746',\n highlightthickness=2,\n relief='raised',\n bd=1\n )\n\n width = int(self.plot_canvas.cget('width'))\n height = int(self.plot_canvas.cget('height'))\n\n self.plot_canvas.create_line(0, height/2, width, height/2)\n self.plot_canvas.create_line(10, height-5, 10, 5, arrow=\"last\")\n step = width/10\n\n for t in range(11):\n x = t*(step+0.6)\n self.plot_canvas.create_line(x, height/2-10, x, height/2+10, width=1)\n\n def show_all(self):\n self.gen_note_frame.place(x=35, y=35, width=300, height=300, anchor='nw')\n self.gen_note_title.place(relx=0, rely=0, relwidth=1, relheight=0.1)\n self.note_label.place(relx=0.02, rely=0.15, relheight=0.1, anchor='nw')\n self.oct_label.place(relx=0.02, rely=0.3, relheight=0.1, anchor='nw')\n self.duration_label.place(relx=0.02, rely=0.45, relheight=0.1, anchor='nw')\n self.note_menu.place(relx=0.99, rely=0.15, relwidth=0.2, relheight=0.1, anchor='ne')\n self.oct_spin.place(relx=0.99, rely=0.3, relwidth=0.2, relheight=0.1, anchor='ne')\n self.duration_scale.place(relx=0.99, rely=0.41, anchor='ne')\n self.gen_mode_frame.place(relx=0.02, rely=0.65, relwidth=0.4, relheight=0.32)\n self.pure_note_cb.place(relx=0, rely=0, relwidth=1, relheight=0.33)\n self.harmonic_cb.place(relx=0, rely=0.33, relwidth=1, relheight=0.33)\n self.chord_cb.place(relx=0, rely=0.66, relwidth=1, relheight=0.34)\n self.save_button.place(relx=0.98, rely=0.98, relwidth=0.2, relheight=0.1, anchor='se')\n\n self.notes_available_frame.place(x=715, y=35, width=300, height=300, anchor='ne')\n self.notes_available_title.place(relx=0, rely=0, relwidth=1, relheight=0.1)\n self.notes_available_listbox.place(relx=0, rely=0.1, relwidth=1, relheight=0.75)\n self.notes_scroll.pack(side='right', fill='y')\n self.play_note_button.place(relx=0.1, rely=0.98, relwidth=0.35, relheight=0.1, anchor='sw')\n self.del_note_button.place(relx=0.9, rely=0.98, relwidth=0.35, relheight=0.1, anchor='se')\n\n self.keyboard_frame.place(x=375, y=640, width=710, height=250, anchor='s')\n self.oct_to_play_frame.place(x=20, y=392, width=220, height=35, anchor='sw')\n self.oct_label_2.place(relx=0.03, rely=0.45, anchor='w')\n self.oct_spin_2.place(relx=0.97, rely=0.5, relwidth=0.3, anchor='e')\n self.plot_canvas.place(relx=0.98, rely=0.02, relwidth=0.4, relheight=0.96, anchor='ne')\n \n def update(self):\n lines = self.notes_available_listbox.size()\n self.notes_available_listbox.delete(0, lines)\n\n self.notes_available = os.listdir('Sounds/')\n self.notes_available.sort()\n notes_available_name = [self.notes_available[k].split('.')[0] for k in range(len(self.notes_available))]\n\n notes_available_name.sort()\n self.notes_available_listbox.insert(0, *notes_available_name)\n\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n\n root.resizable(True, True)\n root.title('Generate Notes')\n root.geometry('750x650')\n\n view = Screen(root)\n \n root.mainloop()","sub_path":"modules/Screen.py","file_name":"Screen.py","file_ext":"py","file_size_in_byte":13015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"247898431","text":"from .meta import Base\nfrom sqlalchemy import (\n Column,\n Integer,\n Text,\n Boolean,\n Interval,\n DateTime,\n ForeignKey,\n Table,\n Float\n )\nimport datetime\nimport sqlalchemy.orm as orm\nfrom slugify import slugify\nfrom .category import Category\n\n\nclass Transaction(Base):\n __tablename__ = 'transactions'\n id = Column(Integer, primary_key=True)\n time = Column(DateTime, default=datetime.datetime.utcnow)\n value = Column(Float, default=0, nullable=False)\n periodical = Column(Boolean, default=False, nullable=False)\n period = Column(Interval, nullable=True)\n categories = orm.relationship(Category, secondary='transaction_category')\n comment = Column(Text, nullable=True)\n account_id = Column(Integer, ForeignKey('accounts.id'))\n virtual = Column(Boolean, default=False, nullable=False)\n\n def __init__(self):\n pass\n\n @property\n def time_date(self):\n return self.time.strftime('%d.%m.%y')\n \n \n\ntransaction_category_table = Table('transaction_category', Base.metadata,\n Column('transaction_id', Integer, ForeignKey(Transaction.id)),\n Column('category_id', Integer, ForeignKey(Category.id)),\n)","sub_path":"jade/models/transaction.py","file_name":"transaction.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"151256355","text":"from lxml import etree\n\nfrom mediator_framework.mediator_core import compare_device_configuration\n\nif __name__ == '__main__':\n with open('../test/expected_dc.xml', 'r') as f:\n parse = etree.XMLParser(remove_blank_text=True)\n root = etree.parse(f, parse) # get expected device configuration which translated by script\n neid = 'router 0'\n res = compare_device_configuration(neid, root)\n print(etree.tostring(res, pretty_print=True).decode('utf-8'))","sub_path":"test/_test_compare.py","file_name":"_test_compare.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"404979752","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# KEYENCE のクランプオン式流量センサ FD-Q10C と IO-LINK で通信を行なって\n# 流量を取得するスクリプトです.\n\nimport time\nimport struct\n\nimport ltc2874 as driver\n\ndef sense():\n try:\n spi = driver.com_open()\n ser = driver.com_start(spi)\n\n flow = driver.isdu_read(spi, ser, 0x94, driver.DATA_TYPE_UINT16) * 0.01\n driver.com_stop(spi, ser)\n\n # エーハイムの16/22用パイプの場合,内径14mm なので,内径12.7mの呼び径3/8の\n # 値に対して補正をかける.\n flow *= (14*14) / (12.7*12.7)\n\n return { 'flow': round(flow, 2) }\n except RuntimeError as e:\n driver.com_stop(spi, ser, True)\n raise\n\n\nif __name__ == '__main__':\n import pprint\n\n pprint.pprint(sense())\n","sub_path":"water_flow.py","file_name":"water_flow.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"141316703","text":"#!/usr/bin/python\n# coding=utf-8\n\n\"\"\"\nbrief: Oreans - Macro Entry Identifier (Biased); Tested on 2.3.0.0 - 3.0.8.0\nauthor: quosego\ncontact: https://github.com/quosego\nversion: 2020/AUG/25\nlicense: Apache License 2.0 (Apache-2.0)\n\"\"\"\n\ntry:\n import sys\n import idc\n import idautils\n import idaapi\nexcept ImportError as e:\n raise Exception(\"ERROR.ImportError: \" + e.message)\nexcept Exception as e:\n raise Exception(\"ERROR.UnhandledException: \" + e.message)\n\n\n# --------------------------------------------------------------------------------------------------\n# GLOBAL\n\n\nSCRIPT_VERSION = \"2020/AUG/20\"\nSCRIPT_NAME = \"Oreans - Macro Entry Identifier (Biased)\"\nSCRIPT_DESCRIPTION = \"This is a 'biased' Macro Entry Identifier script that works on [ALL] products protected by Oreans.\"\nSCRIPT_AUTHOR = \"quosego (https://github.com/quosego)\"\n\n\n# --------------------------------------------------------------------------------------------------\n# GLOBAL SETTINGS\n\n\nTEXT_SEGMENT = idaapi.get_segm_by_name('.text')\n# [!] often is the first segment \"___\"\nOREANS_SEGMENT = idaapi.get_segm_by_name('.extract')\n# [!] often can be identified after the fake \".idata\" segment \"________\"\nENTRY_MNEM = \"jmp\"\n# [!] to identify ENCRYPT macros * change to call\nENTRY_ID_BYTECODE = \"E9\"\n# [!] to identify ENCRYPT macros * change to E8\nLANDING_STRIP = \"89 ?? 89 ?? 89 ?? 89 ?? 89 ?? 89 ?? 89 ?? 89 ??\"\nOUTPUT_JSON = \"oreans_macro_entries.json\"\nBUFFER_NOP = True\n# [!] to identify ENCRYPT macros * change to False otherwise you will not be able to restore code!\nBUFFER_HIDE = False\n# [!] to identify ENCRYPT macros * change to False\nBUFFER_NAME = \"oreans buffer\"\nBUFFER_START_NAME = \"oreans_buffer_start\"\nBUFFER_END_NAME = \"oreans_buffer_end\"\n\n\n# --------------------------------------------------------------------------------------------------\n# UI Helpers\n\n\ndef script_start():\n return not idc.warning(SCRIPT_NAME + \"\\n\\n\" + SCRIPT_DESCRIPTION + \"\\n\\n- \" + SCRIPT_AUTHOR)\n\n\ndef script_information(text):\n return not idc.warning(SCRIPT_NAME + \"\\n\\n\" + text + \"\\n\\n- \" + SCRIPT_AUTHOR)\n\n\ndef script_settings():\n settings = \"Search:\\n\" + \\\n \"- Entry Mnemonic: \" + ENTRY_MNEM + \"\\n\" + \\\n \"- Entry Mnemonic Bytecode: \" + ENTRY_ID_BYTECODE + \"\\n\" + \\\n \"- Landing Strip Signature: \" + LANDING_STRIP + \"\\n\" + \\\n \"Manipulation:\\n\" + \\\n \"- NOP Buffer: \" + str(BUFFER_NOP) + \"\\n\" + \\\n \"- Hide Buffer: \" + str(BUFFER_HIDE) + \"\\n\" + \\\n \"- - Oreans Buffer Name: \" + str(BUFFER_NAME) + \"\\n\" + \\\n \"- - Oreans Start Buffer Name: \" + str(BUFFER_START_NAME) + \"\\n\" + \\\n \"- - Oreans End Buffer Name: \" + str(BUFFER_END_NAME) + \"\\n\" + \\\n \"Output:\\n\" + \\\n \"- JSON File: \" + current_idb_path() + OUTPUT_JSON + \"\\n\"\n return not idc.warning(SCRIPT_NAME + \" - Settings\\n\\n\" + settings + \"\\n\\n- \" + SCRIPT_AUTHOR)\n\n\n# --------------------------------------------------------------------------------------------------\n# Script Helpers\n\n\ndef current_idb_path():\n return '\\\\'.join(dirs for dirs in idc.GetIdbPath().split(\"\\\\\")[:-1]) + \"\\\\\"\n\n\ndef format_address(address):\n new_address = str(address)\n if str(address[-1:]) == 'L':\n new_address = str(address[:-1])\n return new_address\n\n\ndef get_jump_destination(address):\n return idc.GetOperandValue(address, 0)\n\n\ndef get_mnemonic(address):\n return idc.GetMnem(address)\n\n\ndef nop(start_address, end_address):\n for junk_code in range(start_address, end_address):\n idc.PatchByte(junk_code, 0x90)\n\n\ndef hide(start_address, end_address, name, start_name, end_name):\n idc.HideArea(start_address, end_address, name, start_name, end_name, 0)\n\n\ndef log_oreans_macro_information(start_address, entry_address, end_address):\n print(\"[FOUND] start: \" + format_address(hex(start_address)) + \\\n \", entry: \" + format_address(hex(entry_address)) + \\\n \", end: \" + format_address(hex(end_address)))\n\n\ndef valid_oreans_macro_entry(address):\n if idc.isCode(idc.GetFlags(address)) and get_mnemonic(address) == ENTRY_MNEM:\n jump_location_address = get_jump_destination(address)\n if (jump_location_address >= OREANS_SEGMENT.startEA) and (jump_location_address <= OREANS_SEGMENT.endEA):\n return True\n return False\n\n\n# --------------------------------------------------------------------------------------------------\n# Script\n\n\nclass OreansMacroEntryIdentifierBiased(object):\n def __init__(self):\n self.start_address = TEXT_SEGMENT.startEA\n self.end_address = TEXT_SEGMENT.endEA\n self.macros = []\n\n def __find_entry_jump(self, last_address):\n possible_entry_address = idc.FindBinary(last_address, idc.SEARCH_DOWN, ENTRY_ID_BYTECODE + \" ?? ??\")\n if possible_entry_address == idc.BADADDR or possible_entry_address == 0:\n return -1\n elif valid_oreans_macro_entry(possible_entry_address):\n return possible_entry_address\n else:\n # TODO: NOTICE!\n # smaller possible jump, unknown, or data found with a jump signature...\n # for now... assume anything not yet interp'd by ida's decompiler is misinfo\n # if an issue occurs and are still unable to find the proper entry, uncomment below and try to use\n \"\"\"\n idc.MakeUnknown(possible_entry_address, 5, idc.DOUNK_SIMPLE)\n idc.MakeCode(possible_entry_address)\n if valid_oreans_macro_entry(possible_entry_address):\n return possible_entry_address\n else:\n idc.MakeUnknown(possible_entry_address, 5, idc.DOUNK_EXPAND)\n \"\"\"\n return 0\n\n def __find_entry(self, iterate_address):\n possible_entry_address = self.__find_entry_jump(iterate_address)\n if possible_entry_address == 0 or possible_entry_address == 1:\n return 0\n elif possible_entry_address == -1:\n print(\"ERROR.FindingEntry: Issue finding entry from \" + format_address(hex(iterate_address)) + \\\n \" to \" + format_address(hex(self.end_address)) + \".\")\n return -1\n else:\n following_landing_address = idc.FindBinary(possible_entry_address, idc.SEARCH_DOWN, LANDING_STRIP)\n if following_landing_address == idc.BADADDR or following_landing_address == 0:\n # print(\"ERROR.FindingEntry: Issue finding landing for \" + format_address(hex(possible_entry_address)) + \".\")\n # assume end has not yet been reached, will continue to find the correct macro entry\n return 0\n else:\n # unwrap landing strip as it is usually formatted as data\n idc.MakeUnknown(following_landing_address, 2, idc.DOUNK_SIMPLE)\n idc.MakeCode(following_landing_address)\n # apply logging\n possible_jump_location_address = get_jump_destination(possible_entry_address)\n log_oreans_macro_information(possible_entry_address, possible_jump_location_address, following_landing_address)\n self.macros.append([possible_entry_address, possible_jump_location_address, following_landing_address])\n if BUFFER_NOP:\n nop(possible_entry_address + 5, following_landing_address)\n if BUFFER_HIDE:\n hide(possible_entry_address + 5, following_landing_address, BUFFER_NAME, BUFFER_START_NAME, BUFFER_END_NAME)\n # change main iterator address with that pass the landing so it will step over macro range\n next_macro_search_range_address = following_landing_address + 5\n return next_macro_search_range_address\n\n def __seek(self):\n # Method 1 (biased approach)\n current_address = self.start_address\n while current_address < self.end_address:\n next_iter = self.__find_entry(current_address)\n if next_iter == 1 or next_iter == 0:\n next_address = idc.FindBinary(current_address + 1, idc.SEARCH_DOWN, ENTRY_ID_BYTECODE + \" ?? ??\")\n current_address = next_address\n elif next_iter > 1:\n current_address = next_iter\n else:\n print(\"ERROR.SeekingIteration: Issue obtaining a valid macro block to search from at \" + \\\n format_address(hex(current_address)))\n break\n\n print(\"============================================================\")\n\n def run(self):\n print(SCRIPT_NAME + \" - \" + SCRIPT_AUTHOR)\n print(\"============================================================\")\n self.__seek()\n if len(self.macros) > 0:\n script_information(\"found \" + str(len(self.macros)) + \" macro entries!\")\n print(\"[OUTPUT] macro entries will try to be written to '\" + current_idb_path() + OUTPUT_JSON + \"'\")\n try:\n f = open(OUTPUT_JSON, \"w+\")\n entry_data = '{\\n\\t\"count\": ' + str(len(self.macros))\n entry_data += ',\\n\\t\"data\": [\\n'\n for entry in self.macros:\n entry_data += '\\n\\t\\t{\\n\\t\\t\\t\"start\":\"' + format_address(hex(entry[0])) + \\\n '\",\\n\\t\\t\\t\"entry\":\"' + format_address(hex(entry[1])) + \\\n '\",\\n\\t\\t\\t\"end\":\"' + format_address(hex(entry[2])) + \\\n '\"\\n\\t\\t},'\n entry_data = entry_data[:-1]\n entry_data += '\\n\\t]\\n}\\n'\n f.write(entry_data)\n f.close()\n except Exception as e:\n raise Exception(\"ERROR.OutputIssue: \" + e.message)\n else:\n print(\"OH NO! The script has failed!\\n\\nWas unable to find any macro signatures!\\n\\n\" +\n \"Please send me any information regarding the targeted Oreans Protector! \\n\" + \\\n \"Example:\\n\" + \\\n \"Version (3.0.8.0), \" + \\\n \"Protector Name (Themida), \" + \\\n \"Protection Features (Anti - Debugger Detection, Advanced API - Wrapping), \" + \\\n \"Target Type (DLL).\")\n\n\n# --------------------------------------------------------------------------------------------------\n# Script Launch\n\n\nif __name__ == '__main__':\n if script_start():\n script_settings()\n omeib = OreansMacroEntryIdentifierBiased()\n omeib.run()\n","sub_path":"Scripts/ida/oreans_macro_entry_identifier_biased.py","file_name":"oreans_macro_entry_identifier_biased.py","file_ext":"py","file_size_in_byte":10555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"264717769","text":"from PIL import Image, ImageDraw, ImageFont\n\ndef add_num(img):\n draw = ImageDraw.Draw(img)\n myfont = ImageFont.truetype('/Library/Fonts/Waseem.ttc', size = 90)\n fillcolor = \"#ff0000\"\n width, height = img.size\n txt = [100, 250, 400]\n for i in range(len(txt)):\n print (width - txt[i], 10, txt[i])\n draw.text((width - txt[i], 10), str(txt[i]), font = myfont, fill = fillcolor)\n img.save('2.jpg', 'jpeg')\n\nimage = Image.open('1.png')\nadd_num(image)\n","sub_path":"0000/test001.py","file_name":"test001.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"459127515","text":"\"\"\" release on pypi and npm\n\"\"\"\nimport os\nfrom subprocess import check_call\n\nFOR_REAL = bool(os.environ.get(\"FOR_REAL\", \"0\"))\n\n\ndef upload():\n \"\"\" upload releases\n \"\"\"\n if not FOR_REAL:\n print(\"Not uploading FOR_REAL: set the environment variable for a real release\")\n\n pypi_registry = (\n \"https://test.pypi.org/legacy/\" if FOR_REAL else \"https://test.pypi.org/legacy/\"\n )\n check_call([\"twine\", \"upload\", \"--repository-url\", pypi_registry, \"dist/*\"])\n\n if FOR_REAL:\n check_call([\"jlpm\", \"upload\"])\n\n\nif __name__ == \"__main__\":\n upload()\n","sub_path":"scripts/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"408873983","text":"# Skeleton Based Activity Recognition using Attention \r\n#\r\n# Version Num: 0.0.6\r\n#\r\n# Isaac Hogan\r\n# 14iach@queensu.ca\r\n\r\n# Data conversion tool: https://github.com/shahroudy/NTURGB-D\r\n\r\nprint(\"\\nloading libraries...\")\r\n\r\nimport numpy as np\r\n#import matplotlib.pyplot as plt\r\nimport os\r\nimport sys\r\nimport glob\r\nimport random\r\nimport math\r\nimport time\r\n\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\r\nimport tensorflow as tf\r\ntf.compat.v1.enable_eager_execution()\r\nprint(\"TensorFlow Version:\", tf.__version__)\r\n\r\nprint()\r\n\r\n# ---------- Functions ----------\r\n\r\ndef check_sample(sample):\r\n\t\"\"\"\r\n\tcheck if a sample always has one subject\r\n\t\"\"\"\r\n\tif not all(i == 1 for i in sample['nbodys']):\r\n\t\treturn False\r\n\treturn True\r\n\t\r\ndef scale_clips(set):\r\n\t\"\"\"\r\n\tlinearly scales all clips in the set so that the largest joint coordinate is 1 and the smallest is 0\r\n\t\"\"\"\r\n\tfor i in range(len(set)):\r\n\t\tmax = np.amax(np.amax(np.amax(set[i]['skel_body0'], axis=2), axis= 1), axis= 0)\r\n\t\tmin = np.amin(np.amin(np.amin(set[i]['skel_body0'], axis=2), axis= 1), axis= 0)\r\n\t\tset[i]['skel_body0'] = np.subtract(set[i]['skel_body0'], min)\r\n\t\tset[i]['skel_body0'] = np.divide(set[i]['skel_body0'], (max - min))\r\n\t\t\r\ndef add_class(set):\r\n\t\"\"\"\r\n\tadd class number as `class_num` to the NTU RGB+D dictionary\r\n\t\"\"\"\r\n\tfor i in range(len(set)):\r\n\t\tc_num = int(set[i]['file_name'][-3:])\r\n\t\tset[i]['class_num'] = c_num\r\n\t\t\r\ndef load_ntu(data_file, train_size=0.8, test_size=0.2, evaluation_mode=\"default\", first_classes=False, single_pose=False):\r\n\t\"\"\"\r\n\tCreates a training set and a testing set from the numpy-converted NTU RGB+D Skeleton dataset\r\n\r\n\tNTU RGB+D data is a dictionary with the following keys:\r\n\t `file_name`: file's name\r\n\t `nbodys`: it's a list with same length of the sequence. it represents the number of the actors in each frame.\r\n\t `njoints`: the number of the joint node in the skeleton, it's a constant here\r\n\t `skel_bodyx`: the skeleton coordinate with the shape of `(nframe, njoint, 3)`, the x denotes the id of the acting person in each frame. (starting at 0)\r\n\t `rgb_bodyx`: the projection of the skeleton coordinate in RGBs.\r\n\t `depth_bodyx`: the projection of the skeleton coordinate in Depths\r\n\r\n\tadded entries:\r\n\t `class_num`: the class number, extracted from the name\r\n\r\n\t\"\"\"\r\n\tprint(\"loading data...\")\r\n\t\r\n\ttrain_set = []\r\n\ttest_set = []\r\n\r\n\t#Load full file list\r\n\tfiles = [f for f in glob.glob(data_file + '*')]\r\n\tnum_classes = 120 \r\n\t\t\t\r\n\tif first_classes:\r\n\t\t#load the first 5 classes\r\n\t\tfiles = []\r\n\t\tnum_classes = 5\r\n\t\tfor i in range(num_classes):\r\n\t\t\tfiles = files + [f for f in glob.glob(data_file + '*A00' + str(i + 1) + '*')]\r\n\t\r\n\tif evaluation_mode == \"default\":\r\n\r\n\t\trandom.shuffle(files)\r\n\r\n\t\ttrain_samples = math.floor(len(files)*train_size)\r\n\t\ttest_samples = math.floor(len(files)*test_size)\r\n\r\n\t\tprev_sampels = 0\r\n\r\n\t\t#creates the training set\r\n\t\tfor i in range(train_samples):\r\n\t\t\tsample = np.load(files[i+prev_sampels],allow_pickle=True).item()\r\n\t\t\tif single_pose:\r\n\t\t\t\tif check_sample(sample):\r\n\t\t\t\t\ttrain_set.append(sample)\r\n\t\t\telse:\r\n\t\t\t\ttrain_set.append(sample)\r\n\t\tprev_sampels += train_samples\r\n\r\n\t\t#creates the test set\r\n\t\tfor i in range(test_samples):\r\n\t\t\tsample = np.load(files[i+prev_sampels],allow_pickle=True).item()\r\n\t\t\tif single_pose:\r\n\t\t\t\tif check_sample(sample):\r\n\t\t\t\t\ttest_set.append(sample)\r\n\t\t\telse:\r\n\t\t\t\ttest_set.append(sample)\r\n\t\tprev_sampels += test_samples\r\n\r\n\t#elif evaluation_mode == \"cv\":\r\n\t\t\r\n\r\n\telse:\r\n\t\tprint(evaluation_mode, \"is invalid evaluation mode\")\r\n\t\tprint(\"options: default, cv, cs\")\r\n\r\n\tadd_class(train_set)\r\n\tadd_class(test_set)\r\n\r\n\tif SCALE_CLIPS:\r\n\t\tprint(\"scaling clips...\")\r\n\t\tscale_clips(train_set)\r\n\t\tscale_clips(test_set)\r\n\r\n\treturn train_set, test_set\r\n\t\t\t\r\ndef get_vals_labels(set):\r\n\t\"\"\"\r\n\ttakes a set from the NTU RGB+D dictionary and returns training and testing sets and labels\r\n\t\"\"\"\r\n\tx = []\r\n\ty = []\r\n\t\r\n\tfor clip in set:\r\n\t\tx.append(clip['skel_body0'])\r\n\t\ty.append(clip['class_num'])\r\n\t\t\r\n\treturn x, y\r\n\t\r\ndef normalize_clip_length(set, new_len):\r\n\t\"\"\"\r\n\tpad or cut each clip in the set to a new length\r\n\t\"\"\"\r\n\tprint(\"normalizing clip length...\")\r\n\r\n\tfor clip in range(len(set)):\r\n\t\tif set[clip].shape[0] > new_len:\r\n\t\t\tset[clip] = set[clip][0:new_len]\r\n\t\tset[clip] = np.pad(set[clip], \\\r\n\t\t\tpad_width=((0,(new_len - set[clip].shape[0])), (0,0), (0,0)), \\\r\n\t\t\tmode='constant', constant_values=0)\r\n\t\t\r\n\r\ndef matplotlib_clip_vid(clip):\r\n\t\"\"\"\r\n\tshow activity clip\r\n\t\"\"\"\r\n\timport matplotlib.pyplot as plt\r\n\tfrom matplotlib.animation import FuncAnimation\r\n\t\r\n\tfig = plt.figure()\r\n\t\r\n\tclip_t = clip.transpose((0,2,1))\r\n\t\r\n\tdef update(frame_number):\r\n\t\tax = fig.add_subplot(projection='3d')\r\n\t\tax.set_xlabel('X')\r\n\t\tax.set_ylabel('Y')\r\n\t\tax.set_zlabel('Z')\r\n\t\tscatter = ax.scatter(clip_t[frame_number][0], clip_t[frame_number][1], clip_t[frame_number][2])\r\n\t\tax.set_xlim(0,1)\r\n\t\tax.set_ylim(0,1)\r\n\t\tax.set_zlim(0,1)\r\n\t\treturn scatter\r\n\t\t\r\n\tani = FuncAnimation(fig, update, interval=10)\r\n\tplt.show()\r\n\r\n# ---------- Classes ----------\r\n\r\nclass ModifySkeletons(tf.keras.layers.Layer):\r\n\t\"\"\"\r\n\tRotates and scales skeletons by random values\r\n\t\"\"\"\r\n\tdef __init__(self):\r\n\t\tsuper(ModifySkeletons, self).__init__()\r\n\t\t\r\n\tdef call(self, input, max_val=1., min_val=0., training=None):\r\n\t\r\n\t\tif training:\r\n\t\t\ttheta = random.uniform(0., 360.)\r\n\t\t\trad = theta*math.pi/180.\r\n\t\t\tscale = random.uniform(.5, 2)\r\n\t\t\r\n\t\t\ttranslate_val = (min_val - max_val) / 2.\r\n\t\t\ttranslate_forward = tf.constant([[1,0,0,translate_val],\r\n\t\t\t\t\t\t\t\t\t\t[0,1,0,translate_val],\r\n\t\t\t\t\t\t\t\t\t\t[0,0,1,translate_val],\r\n\t\t\t\t\t\t\t\t\t\t[0,0,0,1]])\t\r\n\t\t\ttranslate_back = tf.constant([[1,0,0,-translate_val],\r\n\t\t\t\t\t\t\t\t\t\t[0,1,0,-translate_val],\r\n\t\t\t\t\t\t\t\t\t\t[0,0,1,-translate_val],\r\n\t\t\t\t\t\t\t\t\t\t[0,0,0,1]])\t\r\n\t\t\trotate = tf.constant([[math.cos(rad),-math.sin(rad),0,0],\r\n\t\t\t\t\t\t\t\t[math.sin(rad),math.cos(rad),0,0],\r\n\t\t\t\t\t\t\t\t[0,0,1,0],\r\n\t\t\t\t\t\t\t\t[0,0,0,1]])\t\r\n\t\t\tscale = tf.constant([[scale,0,0,0],\r\n\t\t\t\t\t\t\t\t[0,scale,0,0],\r\n\t\t\t\t\t\t\t\t[0,0,scale,0],\r\n\t\t\t\t\t\t\t\t[0,0,0,1]])\r\n\t\t\t\t\t\t\t\t\r\n\t\t\tcomposed = tf.linalg.matmul(tf.linalg.matmul(tf.linalg.matmul( \\\r\n\t\t\t\t\t\tscale, translate_back), rotate), translate_forward)\r\n\t\t\t\r\n\t\t\tinput_4d = tf.concat([input, tf.ones([input.shape[0],input.shape[1],input.shape[2],1], dtype=tf.dtypes.float32)], axis=-1)\r\n\t\t\ttranslated_4d = tf.reshape(tf.linalg.matmul(composed,tf.expand_dims(input_4d, axis=-1)), [input_4d.shape[0],input_4d.shape[1],input_4d.shape[2],input_4d.shape[3]])\r\n\t\t\ttranslated = tf.slice(translated_4d, [0,0,0,0], [translated_4d.shape[0],translated_4d.shape[1],translated_4d.shape[2],translated_4d.shape[3]-1])\r\n\t\t\t\r\n\t\t\t#tf.print(\"translate_forward:\\n\", composed)\r\n\t\t\t#tf.print(\"rotate:\\n\", composed)\r\n\t\t\t#tf.print(\"translate_back:\\n\", composed)\r\n\t\t\t#tf.print(\"composed:\\n\", composed)\r\n\t\t\t#tf.print(\"input:\", input.shape, \"\\n\", input)\r\n\t\t\t#tf.print(\"translated:\", translated.shape, \"\\n\", translated)\r\n\t\t\t\r\n\t\t\treturn translated\r\n\t\t\r\n\t\telse:\r\n\t\t\treturn input\r\n\r\nclass FlattenDims(tf.keras.layers.Layer):\r\n\t\"\"\"\r\n\tAdds a learnable bias to each input.\r\n\t\"\"\"\r\n\tdef __init__(self):\r\n\t\tsuper(FlattenDims, self).__init__()\r\n\r\n\tdef call(self, input):\r\n\t\treturn tf.reshape(input, (-1,input.shape[1],input.shape[2]*input.shape[3]))\r\n\r\nclass LearnedComplexPosEncoding(tf.keras.layers.Layer):\r\n\t\"\"\"\r\n\tAdds a learnable bias to each input.\r\n\t\"\"\"\r\n\tdef __init__(self, ignore_zeros=False):\r\n\t\tsuper(LearnedComplexPosEncoding, self).__init__()\r\n\t\tself.ignore_zeros = ignore_zeros\r\n\r\n\tdef build(self, input_shape):\r\n\t\tself.encodings = self.add_weight(\"encodings\", shape=[1,input_shape[-2],input_shape[-1]])\r\n\r\n\tdef call(self, input):\r\n\t\tif self.ignore_zeros:\r\n\t\t\tmax_vals = tf.reduce_max(input, axis=-1, keepdims=True)\r\n\t\t\tencodings = (self.encodings * max_vals) / (max_vals + 0.00001)\r\n\t\telse:\r\n\t\t\tencodings = self.encodings\r\n\t\toutput = input + encodings\r\n\t\treturn output\r\n\t\t\r\nclass FeatureSumLayer(tf.keras.layers.Layer):\r\n\t\"\"\"\r\n\tSelects one attention block to pass forward\r\n\t\"\"\"\r\n\tdef __init__(self):\r\n\t\tsuper(FeatureSumLayer, self).__init__()\r\n\r\n\tdef call(self, input):\r\n\t\toutput = tf.math.reduce_sum(input, axis=-2)\r\n\t\treturn output\r\n\t\r\nclass MyDenseLayer(tf.keras.layers.Layer):\r\n\t\"\"\"\r\n\tA dense layer with a skip connection\r\n\t\"\"\"\r\n\tdef __init__(self, num_outputs, activation=None, skip_connection=False, dropout=0.):\r\n\t\tsuper(MyDenseLayer, self).__init__()\r\n\t\tself.num_outputs = num_outputs\r\n\t\tself.activation = activation\r\n\t\tself.skip_connection = skip_connection\r\n\t\tself.dropout = dropout\r\n\r\n\tdef build(self, input_shape):\r\n\t\tself.p_weights = self.add_weight(\"p_weights\", shape=[self.num_outputs,input_shape[-1]]) \r\n\t\tself.p_biases = self.add_weight(\"p_biases\", shape=[1,self.num_outputs]) \r\n \r\n\tdef call(self, input):\r\n\t\tif self.activation != None:\r\n\t\t\toutput = self.activation(tf.matmul(input,tf.transpose(self.p_weights)) + self.p_biases)\r\n\t\telse:\r\n\t\t\toutput = tf.matmul(input,tf.transpose(self.p_weights)) + self.p_biases\r\n\t\toutput = tf.nn.dropout(output, self.dropout)\r\n\t\tif self.skip_connection:\r\n\t\t\treturn output + input\r\n\t\telse:\r\n\t\t\treturn output\r\n\t\t\r\nclass MyMultiAttentionLayer(tf.keras.layers.Layer):\r\n\t\"\"\"\r\n\tMulti-head scaled dot-product attention layer\r\n\t\"\"\"\t\r\n\tdef __init__(self, num_outputs, param_number, multi_heads, activation=None, skip_connection=False, dropout=0.):\r\n\t\tsuper(MyMultiAttentionLayer, self).__init__()\r\n\t\tself.num_outputs = num_outputs\r\n\t\tself.param_number = param_number\r\n\t\tself.activation = activation\r\n\t\tself.multi_heads = multi_heads\r\n\t\tself.skip_connection = skip_connection\r\n\t\tself.dropout = dropout\r\n\r\n\tdef build(self, input_shape):\r\n\t\tself.q_weights = self.add_weight(\"q_weights\", shape=[self.multi_heads,self.param_number,input_shape[-1]]) \r\n\t\tself.q_biases = self.add_weight(\"q_biases\", shape=[self.multi_heads,1,self.param_number]) \r\n\r\n\t\tself.k_weights = self.add_weight(\"k_weights\", shape=[self.multi_heads,self.param_number,input_shape[-1]]) \r\n\t\tself.k_biases = self.add_weight(\"k_biases\", shape=[self.multi_heads,1,self.param_number]) \r\n\r\n\t\tself.v_weights = self.add_weight(\"v_weights\", shape=[self.multi_heads,self.param_number,input_shape[-1]]) \r\n\t\tself.v_biases = self.add_weight(\"v_biases\", shape=[self.multi_heads,1,self.param_number]) \r\n\r\n\t\tself.l_weights = self.add_weight(\"l_weights\", shape=[self.num_outputs,self.param_number*self.multi_heads])#shape=[self.num_outputs,input_shape[-2],self.param_number*self.multi_heads]) \r\n\t\tself.l_biases = self.add_weight(\"l_biases\", shape=[1,self.num_outputs]) \r\n\r\n\tdef call(self, input):\r\n\r\n\t\texp_input = tf.tile(tf.expand_dims(input, -3), [1,self.multi_heads,1,1])\r\n\r\n\t\tquery = tf.matmul(exp_input,tf.transpose(self.q_weights, perm=[0,2,1])) + self.q_biases\r\n\t\tkey = tf.matmul(exp_input,tf.transpose(self.k_weights, perm=[0,2,1])) + self.k_biases\r\n\t\tvalue = tf.matmul(exp_input,tf.transpose(self.v_weights, perm=[0,2,1])) + self.v_biases\r\n\r\n\t\tscores = tf.nn.softmax(tf.matmul(query,tf.transpose(key, perm=[0,1,3,2]))/tf.math.sqrt(float(self.param_number)), axis=2)\r\n\t\tsum = tf.transpose(tf.matmul(scores, value), perm=[0,2,1,3])\r\n\r\n\t\tconcat = tf.reshape(sum,[-1,sum.shape[-3],self.param_number*self.multi_heads])\r\n\r\n\t\toutput = tf.matmul(concat,tf.transpose(self.l_weights)) + self.l_biases\r\n\r\n\t\toutput = tf.nn.dropout(output, self.dropout)\r\n\r\n\t\tif self.skip_connection:\r\n\t\t\tskip_output = output + input\r\n\t\telse: \r\n\t\t\tskip_output = output\r\n\r\n\t\tif self.activation != None:\r\n\t\t\treturn self.activation(skip_output)\r\n\t\telse:\r\n\t\t\treturn skip_output\r\n\r\nclass AttentionNetwork():\r\n\t\"\"\"\r\n\tAttention model for skeleton based activity recognition.\r\n\t\"\"\"\t\r\n\tdef __init__(self, batch_shape, block_size, mlp_hidden, num_outputs, \\\r\n\t\t\tparam_number, multi_heads, activation=tf.nn.relu, skip_connections=True):\r\n\t\t\r\n\t\tself.model = tf.keras.models.Sequential()\r\n\t\tself.model.add(ModifySkeletons())\r\n\t\tself.model.add(FlattenDims())\r\n\t\tself.model.add(MyDenseLayer(block_size))\r\n\t\tself.model.add(LearnedComplexPosEncoding(ignore_zeros=True))\r\n\t\tfor layer in range(LAYERS):\r\n\t\t\tself.model.add(MyMultiAttentionLayer(block_size, param_number, multi_heads, \\\r\n\t\t\t\t\tactivation=activation, skip_connection=skip_connections, dropout=DROPOUT))\r\n\t\t\tself.model.add(tf.keras.layers.LayerNormalization(axis=-1))\r\n\t\t\tself.model.add(MyDenseLayer(block_size, activation=activation, skip_connection=skip_connections, dropout=DROPOUT))\r\n\t\t\tself.model.add(tf.keras.layers.LayerNormalization(axis=-1))\r\n\t\tself.model.add(FeatureSumLayer())\r\n\t\tself.model.add(MyDenseLayer(mlp_hidden))\r\n\t\tself.model.add(MyDenseLayer(CLASSES))\r\n\t\tself.model.add(tf.keras.layers.Activation('softmax'))\r\n\t\t\r\n\t\tself.model.compile(\r\n\t\toptimizer=OPTIMIZER,\r\n\t\tloss='sparse_categorical_crossentropy',\r\n\t\tmetrics=['sparse_categorical_accuracy'])\r\n\r\n\t\tself.model.build(batch_shape)\r\n\t\tself.model.summary()\r\n\t\t\r\n\tdef load_model(self, checkpoint_dir):\r\n\t\tprint(\"loading model...\")\r\n\t\tlatest = tf.train.latest_checkpoint(checkpoint_dir)\r\n\t\tself.model.load_weights(latest)\r\n\t\t\r\n\tdef train(self, epoch_num, epoch_steps, callback=None):\r\n\t\r\n\t\tself.model.fit(\r\n\t\tx_train.astype(np.float32), y_train.astype(np.float32),\r\n\t\tepochs=epoch_num,\r\n\t\tcallbacks=[callback],\r\n\t\tsteps_per_epoch=epoch_steps,\r\n\t\tvalidation_data=(x_test.astype(np.float32), y_test.astype(np.float32)),\r\n\t\tvalidation_freq=1\r\n\t\t)\r\n\r\n# ---------- Constants ----------\r\nDATA_FILE = '../nturgb_d_npy/'\r\nSEED = 1\r\nTRIAN_SIZE = 0.8\r\nTEST_SIZE = 0.2\r\nPAD_CLIP_LENGTH = 128\r\n\r\nEPCOHS = 1000\r\nBATCH_SIZE = 4\r\nLEARNING_RATE = 1e-4\r\nDROPOUT = 0.\r\n\r\nMLP_UNITS = 256\r\n\r\nBLOCK_SIZE = 128 \t# > sample size\r\nLAYERS = 8\t\t\t\r\nHEADS = 6\t\t\r\nPARAMETERS = 32 \t# > block size / heads\r\n\r\nOPTIMIZER = tf.keras.optimizers.Adam(learning_rate=LEARNING_RATE)\r\nINITIALIZER = tf.keras.initializers.GlorotUniform(SEED)\r\nACTIVATION_F = tf.nn.relu\r\n\r\ncheckpoint_path = \"checkpoints_1/cp-{epoch:04d}.ckpt\"\r\ncheckpoint_dir = os.path.dirname(checkpoint_path)\r\n\r\n\r\n# ---------- Flags ----------\r\n\r\nLOAD_MODEL = False\r\nSCALE_CLIPS = True\r\nSINGLE_POSE = False\r\nFIRST_CLASSES = True\r\n\r\n\r\n# ---------- Setup ----------\r\n\r\nrandom.seed(SEED)\r\ntrain_set, test_set = load_ntu(DATA_FILE, train_size=TRIAN_SIZE, test_size=TEST_SIZE, first_classes=FIRST_CLASSES, single_pose=SINGLE_POSE)\r\n\r\nx_train, y_train = get_vals_labels(train_set)\r\nx_test, y_test = get_vals_labels(test_set)\r\n\r\nclip_lengths = [x.shape[0] for x in x_train]\r\nprint(\"Mean Clip Length:\", round(np.mean(clip_lengths),2), \"\\tShortest Clip Length:\", min(clip_lengths), \"\\tLongest Clip Length:\", max(clip_lengths))\r\n\r\n#set all clips to the same number of frames\r\nnormalize_clip_length(x_train, PAD_CLIP_LENGTH)\r\nnormalize_clip_length(x_test, PAD_CLIP_LENGTH)\r\n\r\n#convert to numpy arrays\r\nx_train = np.array(x_train)\r\nx_test = np.array(x_test)\r\ny_train = np.array(y_train) - 1\r\ny_test = np.array(y_test) - 1\r\n\r\n#swap y and z coordinates so z is vertical\r\nswitch_yz_array = [[1,0,0],\r\n\t\t\t\t\t[0,0,1],\r\n\t\t\t\t\t[0,1,0]]\r\n\t\t\t\t\t\r\n\r\nprint(x_train.shape)\r\nx_train = np.reshape(np.matmul(switch_yz_array, np.expand_dims(x_train, axis=-1)), x_train.shape)\r\nprint(x_train.shape)\r\n\r\n#x_train = np.reshape(x_train, (-1,x_train.shape[1],x_train.shape[2]*x_train.shape[3]))\r\n#x_test = np.reshape(x_test, (-1,x_test.shape[1],x_test.shape[2]*x_test.shape[3]))\r\n\r\nprint(x_train.shape, x_test.shape, y_train.shape, y_test.shape)\r\n\r\nEPOCH_STEPS = \tmath.floor(x_train.shape[0]/BATCH_SIZE)\r\nCLASSES = int(np.max(y_train)-np.min(y_train))+1\r\nBATCH_SHAPE = tuple([BATCH_SIZE,x_train.shape[1],x_train.shape[2],x_train.shape[3]])#(int(x_train.shape[0]/EPOCH_STEPS),x_train.shape[1],x_train.shape[2])\r\n\r\n\r\n\"\"\"# ---------- Aug Tests ----------\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\n#batch = np.array([[1,1,1],\r\n#\t\t\t\t\t[1,0,0],\r\n#\t\t\t\t\t[0,1,0],\r\n#\t\t\t\t\t[0,0,1]], dtype=float)\r\n\r\nbatch = x_train[0:5]\r\n\r\nprint(\"Batch Shape:\", batch.shape)\r\n\r\nmatplotlib_clip_vid(batch[0])\r\n\r\nprint(batch[0].shape)\r\n\r\nmod_skel = ModifySkeletons()\r\nbatch_mod = np.array(mod_skel(batch, training=True))\r\n\r\nmatplotlib_clip_vid(batch_mod[0])\r\n\r\nprint(batch_mod[0].shape)\r\n\r\nbatch_plt = np.transpose(batch_mod[0][0])\t\r\n\t\r\nfig = plt.figure()\r\nax = fig.add_subplot(projection='3d')\r\nax.set_xlabel('X')\r\nax.set_ylabel('Y')\r\nax.set_zlabel('Z')\r\nax.scatter(batch_plt[0], batch_plt[1], batch_plt[2])\t\t\r\nax.set_xlim(0,1)\r\nax.set_ylim(0,1)\r\nax.set_zlim(0,1)\t\t\r\nplt.show()\r\n\r\n\r\n_ = 1/0\r\n\"\"\"\r\n\r\n# ---------- Training ----------\r\n\r\ncp_callback = tf.keras.callbacks.ModelCheckpoint(\r\n filepath=checkpoint_path, \r\n verbose=1, \r\n save_weights_only=True,\r\n save_freq='epoch')\r\n\r\nnetwork = AttentionNetwork(BATCH_SHAPE, BLOCK_SIZE, MLP_UNITS, BLOCK_SIZE, \\\r\n\t\t\tPARAMETERS, HEADS, activation=ACTIVATION_F, skip_connections=True)\r\n\t\r\nif LOAD_MODEL:\r\n\tnetwork.load_model(checkpoint_dir)\r\nelse:\r\n\tnetwork.model.save_weights(checkpoint_path.format(epoch=0))\r\n\t\t\t\r\nnetwork.train(EPCOHS, EPOCH_STEPS, callback=cp_callback)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t","sub_path":"asbar.py","file_name":"asbar.py","file_ext":"py","file_size_in_byte":16724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"380604581","text":"\nimport math\nimport json\nfrom datetime import (datetime, timedelta)\nimport random\nimport numpy as np\nimport pandas as pd\nimport time\nfrom RestrictedPython.Guards import (guarded_unpack_sequence, )\nfrom RestrictedPython.Eval import (default_guarded_getiter, )\nimport inspect\nfrom pixiu.api.utils import (load_json, dump_json)\n\nfrom ..api.v1 import (TimeFrame, OrderCommand, Order, APIStub as API_V1)\n\nimport logging\nlog = logging.getLogger(__name__)\n\n\nclass API_V1_Base(API_V1):\n \"\"\"\"\"\"\n def __init__(self, data_source, default_symbol):\n self.data_source = data_source\n self.default_symbol = default_symbol\n\n def dict_to_order(self, order_dict):\n return Order(order_dict)\n\n # def datetime_(self, *args, **kwargs):\n # return datetime(*args, **kwargs)\n\n #\n def default_guarded_getitem(self, ob, index):\n # No restrictions.\n return ob[index]\n\n def default_guarded_getattr(self, object, name, default=None):\n # No restrictions.\n return getattr(object, name, default)\n\n def default_unpack_sequence(self, *args, **kwargs):\n # No restrictions.\n #see: https://github.com/zopefoundation/RestrictedPython/blob/master/tests/transformer/test_assign.py\n return guarded_unpack_sequence(*args, **kwargs)\n # return getattr(object, name, default)\n\n def default_getiter(self, *args, **kwargs):\n # No restrictions.\n # return args.__iter__()\n return default_guarded_getiter(*args, **kwargs)\n\n def lock_object(self):\n return LockObject\n #\n def set_fun(self, env_dict):\n #BuildIn\n #see: https://github.com/zopefoundation/RestrictedPython/blob/9d3d403a97d7f030b6ed0f82900b2efac151dec3/tests/transformer/test_classdef.py\n env_dict[\"__metaclass__\"] = type #support class\n env_dict[\"__name__\"] = \"ea_script\" #support class\n env_dict[\"_write_\"] = lambda x: x\n #support print\n env_dict[\"_print_\"] = self._print_\n env_dict[\"_getitem_\"] = self.default_guarded_getitem\n env_dict[\"_getiter_\"] = self.default_getiter\n env_dict[\"_unpack_sequence_\"] = self.default_unpack_sequence\n #System Functions\n env_dict[\"json\"] = json\n env_dict[\"load_json\"] = load_json\n env_dict[\"dump_json\"] = dump_json\n env_dict[\"round\"] = round\n env_dict[\"dict\"] = dict\n env_dict[\"list\"] = list\n env_dict['math'] = math\n env_dict['nan'] = np.nan\n env_dict['isnan'] = np.isnan\n env_dict['isnull'] = pd.isnull\n env_dict[\"datetime\"] = datetime\n env_dict[\"timedelta\"] = timedelta\n env_dict[\"random\"] = random\n env_dict[\"time\"] = time\n env_dict[\"pandas\"] = pd\n env_dict[\"numpy\"] = np\n #\n env_dict[\"LockObject\"] = self.lock_object\n\n #\n members = inspect.getmembers(API_V1)\n for m in members:\n fun_n = m[0]\n if not fun_n.startswith('_'):\n env_dict[fun_n] = getattr(self, fun_n)\n elif fun_n == \"__global_defines__\":\n global_defines = getattr(self, fun_n)\n for k in global_defines:\n env_dict[k] = global_defines[k]\n\n","sub_path":"pixiu/base/api_base.py","file_name":"api_base.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"635637749","text":"from io import BytesIO\n\nimport scrapy\nfrom openpyxl import load_workbook\n\nfrom opennem.pipelines.aemo.general_information import (\n GeneralInformationGrouperPipeline,\n GeneralInformationStoragePipeline,\n)\n\n\nclass AEMOGeneralInformationCurrentSpider(scrapy.Spider):\n \"\"\"\n Extracts station and unit data from the AEMO general information spreadsheet\n\n\n \"\"\"\n\n # name = \"au.aemo.current.general_information\"\n\n start_urls = [\n # \"https://aemo.com.au/-/media/files/electricity/nem/planning_and_forecasting/generation_information/nem-generation-information-april-2020.xlsx?la=en\",\n # \"https://data.opennem.org.au/v3/data/NEM+Generation+Information+April+2020.xlsx\",\n \"https://data.opennem.org.au/v3/data/NEM+Generation+Information+July+2020.xlsx\"\n ]\n\n keys = [\n \"Region\",\n \"Status\",\n \"station_name\",\n \"Owner\",\n \"TechType\",\n \"FuelType\",\n \"duid\",\n \"Units\",\n \"unit_capacity_lower\",\n \"unit_capacity\",\n \"UpperCapacity\",\n \"NameCapacity\",\n \"StorageCapacity\",\n \"UnitStatus\",\n \"DispatchType\",\n \"UseDate\",\n \"ClosureDateExpected\",\n \"ClosureDate\",\n \"SurveyID\",\n \"SurveyVersion\",\n \"SurveyEffective\",\n ]\n\n pipelines_extra = set(\n [GeneralInformationGrouperPipeline, GeneralInformationStoragePipeline]\n )\n\n def parse(self, response):\n wb = load_workbook(BytesIO(response.body), data_only=True)\n\n ws = wb.get_sheet_by_name(\"ExistingGeneration&NewDevs\")\n\n records = []\n\n for row in ws.iter_rows(min_row=3, values_only=True):\n\n # pick out the columns we want\n # lots of hidden columns in the sheet\n row_collapsed = row[0:10] + (row[11],) + row[12:19] + row[21:]\n\n return_dict = dict(zip(self.keys, list(row_collapsed)))\n\n if return_dict is None:\n raise Exception(\"Failed on row: {}\".format(row))\n\n records.append(return_dict)\n\n yield {\"records\": records}\n","sub_path":"opennem/spiders/aemo/general_information.py","file_name":"general_information.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"635511551","text":"from dataclasses import dataclass, field\nfrom tests.fixtures.common.models.hl7_v3.ne2008.multicacheschemas.mcci_mt000200_uv01 import (\n McciMt000200Uv01Message,\n)\n\n__NAMESPACE__ = \"urn:hl7-org:v3\"\n\n\n@dataclass\nclass McciIn000002Uv01(McciMt000200Uv01Message):\n \"\"\"\n :ivar itsversion:\n \"\"\"\n class Meta:\n name = \"MCCI_IN000002UV01\"\n namespace = \"urn:hl7-org:v3\"\n\n itsversion: str = field(\n init=False,\n default=\"XML_1.0\",\n metadata=dict(\n name=\"ITSVersion\",\n type=\"Attribute\",\n required=True\n )\n )\n","sub_path":"tests/fixtures/common/models/hl7_v3/ne2008/multicacheschemas/mcci_in000002_uv01.py","file_name":"mcci_in000002_uv01.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"165489318","text":"import sys\nimport re\nimport xml.etree.ElementTree as etree\n\n\nnetscreen = open(sys.argv[1], 'r').read().splitlines()\npaloalto = open(sys.argv[2], 'r').read()\nDG = sys.argv[3]\nTP = sys.argv[4]\n\nnet_policy = []\nnet_service = []\nnet_servicegroup = []\nnet_address = []\nnet_addressgroup = []\nnet_static = []\n\nfor line in netscreen:\n if re.search('(?<=set policy id ).*?(?=\\s)', line):\n match = re.search('(?<=set policy id ).*?(?=\\s)', line)\n element = match.group(0)\n net_policy.append(element)\n net_policy_no_dupes = set(net_policy)\n\nfor line in netscreen:\n if re.search('set address', line):\n if re.search('(?<=\" \").*?(?=\")', line):\n match = re.search('(?<=\" \").*?(?=\")', line)\n element = match.group(0)\n element = (element.replace(\"/\", \"-\"))\n net_address.append(element)\n net_address_no_dupes = set(net_address)\n\nfor line in netscreen:\n if re.search('set group address', line):\n if re.search('(?<=\" \").*?(?=\")', line):\n match = re.search('(?<=\" \").*?(?=\")', line)\n element = match.group(0)\n net_addressgroup.append(element)\n net_addressgroup_no_dupes = set(net_addressgroup)\n\nfor line in netscreen:\n if re.search('(?<=set service \").*?(?=\" protocol)', line):\n match = re.search('(?<=set service \").*?(?=\" protocol)', line)\n element = match.group(0)\n net_service.append(element)\n net_service_no_dupes = set(net_service)\n\nfor line in netscreen:\n if re.search('(?<=set group service \").*?(?=\")', line):\n match = re.search('(?<=set group service \").*?(?=\")', line)\n element = match.group(0)\n net_servicegroup.append(element)\n net_servicegroup_no_dupes = set(net_servicegroup)\n\nfor line in netscreen:\n if re.search('(?<=set route ).*?(?=\\s)', line):\n match = re.search('(?<=set route ).*?(?=\\s)', line)\n element = match.group(0)\n net_static.append(element)\n net_static_no_dupes = set(net_static)\n\nprint('\\n##############################')\nprint('## NETSCRREN CONFIG COUNTS ##')\nprint('##############################\\n')\n\nprint('Netscreen Security Policy Count is: ' + str(len(net_policy_no_dupes)))\nprint('Netscreen Address Count is: ' + str(len(net_address_no_dupes)))\nprint('Netscreen Address-group Count is: ' + str(len(net_addressgroup_no_dupes)))\nprint('Netscreen Service Count is: ' + str(len(net_service_no_dupes)))\nprint('Netscreen Service-group Count is: ' + str(len(net_servicegroup_no_dupes)))\nprint('Netscreen Static Route Count is: ' + str(len(net_static_no_dupes)))\n\npalo_policy = []\npalo_service = []\npalo_servicegroup = []\npalo_address = []\npalo_addressgroup = []\npalo_static = []\n\nprint('\\n##############################')\nprint('## PALOALTO CONFIG COUNTS ##')\nprint('##############################\\n')\n\nroot = etree.fromstring(paloalto)\n\nfor child in root.findall(\".//entry[@name='\" + DG + \"']/pre-rulebase/security/rules/\"):\n name = child.get('name')\n if re.search('Cl-', name):\n palo_policy.append(name)\n else:\n name_search = re.search('[0-9].*', name)\n name_number = name_search.group(0)\n palo_policy.append(name_number)\n\nprint('Palo Alto Policy Count is: ' + str(len(palo_policy)))\n\nfor child in root.findall(\".//entry[@name='\" + DG + \"']/address/\"):\n name = child.get('name')\n palo_address.append(name)\n\nprint('Palo Alto Address Count is: ' + str(len(palo_address)))\n\nfor child in root.findall(\".//entry[@name='\" + DG + \"']/address-group/\"):\n name = child.get('name')\n palo_addressgroup.append(name)\n\nprint('Palo Alto Address-Group Count is: ' + str(len(palo_addressgroup)))\n\nfor child in root.findall(\".//entry[@name='\" + DG + \"']/service/\"):\n name = child.get('name')\n palo_service.append(name)\n\nprint('Palo Alto Service Count is: ' + str(len(palo_service)))\n\nfor child in root.findall(\".//entry[@name='\" + DG + \"']/service-group/\"):\n name = child.get('name')\n palo_servicegroup.append(name)\n\nprint('Palo Alto Service-Group Count is: ' + str(len(palo_servicegroup)))\n\nfor child in root.findall(\".//entry[@name='\" + TP + \"']/config/devices/entry[@name='localhost.localdomain']/network/virtual-router/entry[@name='\" + DG + \"-vr']/routing-table/ip/static-route/\"):\n destination = child.find('destination').text\n palo_static.append(destination)\n\nprint('Palo Alto Static Route Count is: ' + str(len(palo_static)))\n\nprint('\\n##############################')\nprint('## NETSCREEN UNIQUE OBJECTS ##')\nprint('##############################\\n')\n\nprint('## POLICY ##\\n')\n\nnet_policy_unique = (set(net_policy_no_dupes).difference(palo_policy))\nif len(net_policy_unique) == 0:\n print('No unique objects found\\n')\nelse:\n for item in net_policy_unique:\n print(item)\n print('\\n')\n\nprint('## ADDRESS ##\\n')\n\nnet_address_unique = (set(net_address_no_dupes).difference(palo_address))\nif len(net_address_unique) == 0:\n print('No unique objects found\\n')\nelse:\n for item in net_address_unique:\n print(item)\n print('\\n')\n\nprint('## ADDRESS-GROUP ##\\n')\n\nnet_addressgroup_unique = (set(net_addressgroup_no_dupes).difference(palo_addressgroup))\nif len(net_addressgroup_unique) == 0:\n print('No unique objects found\\n')\nelse:\n for item in net_addressgroup_unique:\n print(item)\n print('\\n')\n\nprint('## SERVICES ##\\n')\n\nnet_service_unique = (set(net_service_no_dupes).difference(palo_service))\nif len(net_service_unique) == 0:\n print('No unique objects found\\n')\nelse:\n for item in net_service_unique:\n print(item)\n print('\\n')\n\nprint('## SERVICES-GROUPS ##\\n')\n\nnet_servicegroup_unique = (set(net_servicegroup_no_dupes).difference(palo_servicegroup))\nif len(net_servicegroup_unique) == 0:\n print('No unique objects found\\n')\nelse:\n for item in net_servicegroup_unique:\n print(item)\n print('\\n')\n\nprint('## STATIC ROUTES ##\\n')\n\nnet_static_unique = (set(net_static_no_dupes).difference(palo_static))\nif len(net_static_unique) == 0:\n print('No unique objects found\\n')\nelse:\n for item in net_static_unique:\n print(item)\n\nprint('\\n##############################')\nprint('## PALOALTO UNIQUE OBJECTS ##')\nprint('##############################\\n')\n\nprint('## POLICY ##\\n')\n\npalo_policy_unique = (set(palo_policy).difference(net_policy_no_dupes))\nif len(palo_policy_unique) == 0:\n print('No unique objects found\\n')\nelse:\n for item in palo_policy_unique:\n print(item)\n print('\\n')\n\nprint('## ADDRESS ##\\n')\n\npalo_address_unique = (set(palo_address).difference(net_address_no_dupes))\nif len(palo_address_unique) == 0:\n print('No unique objects found\\n')\nelse:\n for item in palo_address_unique:\n print(item)\n print('\\n')\n\nprint('## ADDRESS-GROUP ##\\n')\n\npalo_addressgroup_unique = (set(palo_addressgroup).difference(net_addressgroup_no_dupes))\nif len(palo_addressgroup_unique) == 0:\n print('No unique objects found\\n')\nelse:\n for item in palo_addressgroup_unique:\n print(item)\n print('\\n')\n\nprint('## SERVICES ##\\n')\n\npalo_service_unique = (set(palo_service).difference(net_service_no_dupes))\nif len(palo_service_unique) == 0:\n print('No unique objects found\\n')\nelse:\n for item in palo_service_unique:\n print(item)\n print('\\n')\n\nprint('## SERVICES-GROUP ##\\n')\n\npalo_servicegroup_unique = (set(palo_servicegroup).difference(net_servicegroup_no_dupes))\nif len(palo_servicegroup_unique) == 0:\n print('No unique objects found\\n')\nelse:\n for item in palo_servicegroup_unique:\n print(item)\n print('\\n')\n\nprint('## STATIC ROUTES ##\\n')\n\npalo_static_unique = (set(palo_static).difference(net_static_no_dupes))\nif len(palo_static_unique) == 0:\n print('No unique objects found\\n')\nelse:\n for item in palo_servicegroup_unique:\n print(item)\n print('\\n')","sub_path":"Netscreen_compare.py","file_name":"Netscreen_compare.py","file_ext":"py","file_size_in_byte":7854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"464235723","text":"import numpy as np \nimport matplotlib.pyplot as plt \nimport pywt\nfrom scipy.optimize import minimize_scalar\n\nfrom __future__ import print \ndef SUREThresh(coefs):\n\t'''\n\tSingle level SURE adaptive thresholding of wavelet coefficients from:\n\t'Adapting to Unknown Smoothness via Wavelet Shrinkage', D. Donoho, I. Johnstone,\n\tDec 1995\n\n\tPerforms softmax thresholding of wavelet coefficients ('coefs') at this level. \n\tThreshold is selected by minimization of SURE objective for threshold ('t') values in range:\n\t0 < t < sqrt(2*log(d)) where 'd' is the number of coefficients at this level.\n\t\n\tFor more details see paper.\n\n\tArgs:\n coefs (float list): Single level wavelet coefficients.\n\n Returns:\n float list: Softmax thresholded wavelet coefficients.\n\n\t'''\n\td = coefs.shape[0]\n\tt_max = np.sqrt(2*np.log(d))\n\tt_min = 0\n\tdef SURE(t):\n\t\treturn d-2*np.sum(np.abs(coefs) <= t) + np.sum(np.minimum(coefs,t)**2)\n\n\ttrsh = minimize_scalar(SURE,bounds=[t_min,t_max]).x\n\tdef soft_threshold(y):\n\n\t\ta = np.absolute(y) - trsh\n\t\tsgn = np.sign(y)\n\t\tif a <= 0:\n\t\t\treturn 0\n\t\telse:\n\t\t\treturn sgn*a\n\t\n\tthresholded = np.vectorize(soft_threshold)(coefs)\n\t\n\treturn thresholded\n\ndef SUREShrink(data):\n\t'''\n\tMultilevel SURE adaptive thresholding of wavelet coefficients from:\n\t'Adapting to Unknown Smoothness via Wavelet Shrinkage', D. Donoho, I. Johnstone,\n\tDec 1995\n\n\tPerforms adaptive SURE denoising of input signal ('data') by adaptive softmax thresholding\n\teach level of wavelet coefficients representing the original signal. Works under the assumption\n\tof Gaussian additive noise in the case when energy signal is concentrated in relatively\n\tfew wavelet transform components allowing softmax thresholding to remove unwanted noise contributions.\n\n\tArgs:\n data (float list): .\n\n Returns:\n float list: SUREShrink Denoised signal.\n\n\t'''\n\tmode = \"periodic\"\n\twl = \"sym8\"\n\tn = data.shape[0]\n\tJ = np.ceil(np.log2(n))\n\t\n\tdwt = pywt.wavedec(data,wavelet=wl,mode=mode) \n\n\tfor i in range(len(dwt)):\n\t\tdwt[i] = SUREThresh(dwt[i])\n\n\treturn pywt.waverec(dwt,wavelet=wl,mode=mode)\n\ndef SkellamThresh(wavelet_coefs,scaling_coefs):\n\tyi = wavelet_coefs\n\tti = scaling_coefs\n\t# print len(yi), len(ti)\n\td = yi.shape[0]\n\tt_max = np.sqrt(2*np.log(d))\n\tt_min = 0\n\n\tdef SkellamObjective(t):\n\t\t\tt1 = np.sum(np.sign(np.abs(yi)-t)*ti)\n\t\t\tt2 = np.sum(np.minimum(yi**2,np.ones(yi.shape)*t**2))\n\t\t\tt3 = -t*np.sum(np.abs(yi)==t)\n\t\t\t# print t1,t2,t3\n\t\t\treturn np.sum([t1,t2,t3])\n\n\n\tdef SS(t):\n\t\tt1 = np.sum(np.sign(np.abs(yi)-t)*ti)\n\t\tt2 = np.sum(np.minimum(yi**2,np.ones(yi.shape)*t**2))\n\t\tt3 = -t*np.sum(np.abs(yi)==t)\n\t\t# print t1,t2,t3\n\t\treturn np.sum([t1,t2,t3])\n\n\ttrsh = minimize_scalar(SkellamObjective,bounds=[t_min,t_max]).x\n\t# print \"threshold\", trsh\n\tdef soft_threshold(y):\n\n\t\ta = np.absolute(y) - trsh\n\t\tsgn = np.sign(y)\n\t\tif a <= 0:\n\t\t\treturn 0\n\t\telse:\n\t\t\treturn sgn*a\n\n\t# sigma_x = np.std(yi)\n\t# def adjusted_threshold(y,t):\n\t# \tif np.abs(y) >= (np.sqrt(2)*t)/sigma_x:\n\t# \t\treturn -np.sign(y)*(np.sqrt(2)*t)/sigma_x\n\t# \telse:\n\t# \t\treturn -y\n\n\t# thresholded = np.zeros(yi.shape)\n\t# for i in range(yi.shape[0]):\n\t# \tthresholded[i] = adjusted_threshold(y=yi[i],t=ti[i])\n\t# soft threshold:\n\tthresholded = np.vectorize(soft_threshold)(yi)\n\treturn thresholded\n\n\ndef multiscale_function_apply(func,wavelet_name,max_level=None):\n\n\tdef multiscale_apply(ys,):\n\t\t# print len(ys)\n\t\twl = pywt.Wavelet(wavelet_name)\n\t\t\n\t\tif max_level is None:\n\t\t\tlevel = pywt.dwt_max_level(len(ys),wl)\n\t\telse:\n\t\t\tlevel = max_level\n\n\t\tcoeffs_list = []\n\t\ta = ys\n\t\tfor i in range(level):\n\t\t\ta, d = pywt.dwt(a, wavelet=wl)\n\t\t\tf = func(approx =a, detail=d)\n\t\t\tcoeffs_list.append(f)\n\t\tcoeffs_list.append(a)\n\t\tcoeffs_list.reverse()\n\t\treturn coeffs_list\n\n\treturn multiscale_apply \n\ndef SkellamShrink(data,max_level=-1):\n\t'''\n\tBased on: Skellam Shrinkage: Wavelet-Based Intensity Estimation for Inhomogeneous Poisson data\n\tRelated papers: Fast Haar-Wavelet denoising of multidimensional fluorescence microscopy data\n\t'''\n\n\tmode = \"periodic\"\n\twl = \"haar\"\n\tn = data.shape[0]\n\tJ = np.ceil(np.log2(n))\n\t\n\tdef identify(approx,detail):\n\t\treturn detail\n\n\tdef skellam(approx,detail):\n\t\treturn SkellamThresh(wavelet_coefs=detail,scaling_coefs=approx)\n\n\tif max_level == -1 :\n\t\tf = multiscale_function_apply(func=skellam,wavelet_name=wl)\n\telse:\n\t\tf = multiscale_function_apply(func=skellam,wavelet_name=wl,max_level=max_level)\n\tdwt = f(data)\n\treturn pywt.waverec(dwt,wavelet=wl,mode=mode)\n\n\ndef cycle_spinning(data, filter,stepsize=1,shifts=500,*args,**kwargs):\n\toutp = None\n\tshifts = len(data)\n\tprint(\"Datalength\",len(data))\n\tfor shift in range(-shifts/2,shifts/2):\n\t\tr = np.roll(data,shift*stepsize)\n\t\tdenoised = list(filter(r))\n\t\tdenoised = np.roll(denoised,-shift*stepsize)\n\t\tif outp is None:\n\t\t\toutp = denoised\n\t\telse:\n\t\t\toutp = outp + denoised\n\treturn outp/shifts\n\n\ndef level_zeroed_transform(data,threshold_level):\n\n\tmode = \"periodic\"\n\twl = \"sym8\"\n\n\tdwt = pywt.wavedec(data,wavelet=wl,mode=mode) \n\n\n\tfor i in range(threshold_level,len(dwt)):\n\t\tdwt[i] = np.zeros(len(dwt[i]))\n\n\treturn pywt.waverec(dwt,wavelet=wl,mode=mode)","sub_path":"toolkit/wavelets/dimension1.py","file_name":"dimension1.py","file_ext":"py","file_size_in_byte":5071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"525870423","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path(\"summarizer\", views.result, name = \"summarizer\" ),\n path(\"contact\", views.contact, name = \"contact\" ),\n path(\"intro\", views.intro, name = \"intro\" ),\n\n]","sub_path":"NLPSeq/textSummarizer/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"122239269","text":"import sys, time\nfrom datetime import date\nsys.path.extend(['..', '.'])\nfrom collections import *\nfrom fetch import *\nfrom util import *\nimport drawgraph\n#lo, hi, lt, pw = lazy_ints(multisplit(line, '-: ')) #chars only!\n#or lo, hi, lt, pw = lazy_ints(multisplit(line, ['-',': ','))\nimport re\n#use regex re.split(' |,|: ', line)\n\ndef db(*a): \n if DB: print(*a)\n\ndef check1(pw):\n for i in range(len(pw) -2):\n a, b, c = pw[i], pw[i+1], pw[i+2]\n if a == b -1 == c -2:\n return True\n return False\n\n\ndef check2(pw):\n \n cont = (ord('i') - ord('a')) in pw or (ord('o') - ord('a')) in pw or (ord('l') - ord('a')) in pw\n return not cont\n\ndef pair(pw, ch):\n for i in range(len(pw) -1):\n if ch == pw[i] == pw[i+1]:\n return True\n return False\n\ndef check3(pw):\n cnt = 0\n for ch in range(0, ord('z') - ord('a')+ 1):\n if pair(pw, ch):\n cnt += 1\n return cnt >= 2\n\ndef check(pw):\n #db(check1(pw))\n\n #db(check2(pw))\n #db(check3(pw))\n return check1(pw) and check2(pw) and check3(pw) \n\ndef asc(ch):\n return ord(ch) - ord('a')\n\ndef toch(pw):\n offs = ord('a')\n out = [chr(d + offs) for d in pw]\n return ''.join(out)\n\ndef inc(pw):\n rev = pw[::-1]\n MOD = 26\n carry = 1\n for i in range(len(rev)):\n rev[i] += carry\n carry = rev[i]//MOD\n rev[i] %= MOD\n return rev[::-1]\n\ndef p1(v):\n lines = v.strip()\n testing = {'hijklmmn', 'abbceffg', 'abbcegjk', 'ghijklmn'}\n tw = ['ghijklmn', 'ghijklmn', 'ghjaabcc']\n cnt = 0\n\n \n #for t in tw[0:1]:\n ok = False\n pw = [asc(lt) for lt in lines]\n while not check(pw):\n pw = inc(pw)\n #db('Checking {}'.format(pw))\n db('{}'.format(toch(pw)))\n #db('OK {}'.format(toch(pw)))\n \n \n return toch(pw)\n\ndef p2(v):\n return p1(v)\n\n\ndef manual():\n v = open(\"real.txt\", 'r').read().strip('\\n')\n print('part_1: {}\\npart2: {}'.format(p1(v), p2(v)))\n \ncmds, stats, io, so, DB = get_args(sys.argv) \nif not io: run_samples(p1, p2, cmds)\nif not so: run(2015,11, p1, p2, cmds)\nif stats: print_stats()\n#manual()\n","sub_path":"aoc15/D11/d11_part1.py","file_name":"d11_part1.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"586788927","text":"import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport plotinpy as pnp\nfrom matplotlib.patches import Patch\nimport numpy as np\nimport numpy.ma as ma\n\nsns.set()\nsns.set_style(\"ticks\")\nsns.palplot(sns.color_palette(\"Paired\"))\ndata = pd.read_csv(\"barplotstuff.csv\") \ndata = data.sort_values(by=[\"Human\"]).set_index(\"Domain\")\n#fig = plt.figure(figsize=(10,15))\n\n\nf,(ax) = plt.subplots(1,1,sharey=True,figsize=(3,18))\n# f.subplots_adjust(left=0.2)\n#ax = fig.add_subplot(1,1,1)\nax.set_xlim(1000,13000)\n#ax2.set_xlim(2000,13000)\n\n\n#ax.axvline(100,c='black')\nax.axhline(11.5,c='black')\n# ax2.axhline(11.5,c='black')\n\n\nax.set_facecolor('white')\n#ax2.set_facecolor('white')\n\nindices = np.arange(len(data))\n\nmask1 = ma.where(data.Human >= data.BPROST)\nmask2 = ma.where(data.Human <= data.BPROST)\nmaskNames1 = data.index[mask1].tolist()\nmaskNames2 = data.index[mask2].tolist()\n#print(data.index[mask1].tolist())\n#print(data.loc[maskNames,\"Human\"].tolist())\nax.barh(data.index,data.col, height=1, color='turquoise', alpha=1)\nax.barh(maskNames1,data.loc[maskNames1,\"Human\"].tolist(), height=0.90, color='turquoise', alpha=1, linewidth=0)\nax.barh(data.index,data.BPROST, height=0.90, color='gray', alpha=1, linewidth=0)\nax.barh(maskNames2,data.loc[maskNames2,\"Human\"].tolist(), height=0.90, color='turquoise', alpha=1, linewidth=0)\nax.legend(\n [\n Patch(facecolor=\"turquoise\"),\n Patch(facecolor=\"gray\")\n ], [\"DQN\", \"B-PROST\"],loc=4\n)\n#p3 = plt.bar(data.BPROST[mask2], color='r', alpha=1, edgecolor='none',linewidth=0,width=0.5, log=False)\n\n#data.col.plot(kind='barh',width=1, ax=ax,alpha=0.4)\n#data.query(\"Human < BPROST\").Human.plot(kind='barh',width=1, color=\"turquoise\", ax=ax,alpha=0.4)\n#data.query(\"Human < BPROST\").BPROST.plot(kind='barh',width=1, color=\"gray\", ax=ax,alpha=0.6)\n#data.query(\"Human < BPROST\").BPROST.plot(kind='barh',width=1, x=[\"B-PROST\"], color=\"gray\", ax=ax,alpha=0.6)\n#data.query(\"Human > BPROST\").Human.plot(kind='barh', x=[\"VAE-IW\"],width=1, color=\"turquoise\", ax=ax,alpha=0.4)\n#data.col.plot(kind='barh',width=1, ax=ax,alpha=0.4)\n\n#plt.yticks(rotation=30)\n# plt.xticks([0,100,200,400,600,800,1000])\nplt.xticks([2500,7500,12500])\n\n#kwargs.update(transform=ax2.transAxes) # switch to the bottom axes\n#data.Human.plot(kind='barh',width=1, ax=ax2,alpha=0.5)\n#data.BPROST.plot(kind='barh',width=1, ax=ax2,alpha=0.5)\n\n#ax.set_xscale(\"log\")\n#ax2.set_xscale(\"log\")\n\n# ax.spines['bottom'].set_visible(True)\n# ax2.spines['left'].set_visible(False)\n# ax.yaxis.tick_left()\n# ax.tick_params(bottom=True) # don't put tick labels at the top\n# ax2.yaxis.tick_bottom()\n\n# Make the spacing between the two axes a bit smaller\n#plt.subplots_adjust(wspace=0.15)\nsns.despine()\n\nax.text(2500, 12-0.2, \"Above human level\", color='black')\nax.text(2500, 11-0.2, \"Below human level\", color='black')\n\n# for i, v in enumerate(data.Human):\n# ax.text(10, i-0.25, str(round(v)) + \"%\", color='black')\n\n# d = .015 # how big to make the diagonal lines in axes coordinates\n# # arguments to pass plot, just so we don't keep repeating them\n# kwargs = dict(transform=ax.transAxes, color='k', clip_on=False)\n# ax.plot((1-d,1+d),(-d,+d), **kwargs) # top-left diagonal\n# ax.plot((1-d,1+d),(1-d,1+d), **kwargs) # bottom-left diagonal\n\n# kwargs.update(transform=ax2.transAxes) # switch to the bottom axes\n# ax2.plot((-d,d),(-d,+d), **kwargs) # top-right diagonal\n# ax2.plot((-d,d),(1-d,1+d), **kwargs) # bottom-right diagonal\n\n\nf.savefig(\"second_new_1.svg\",format=\"svg\")","sub_path":"util/plots_second.py","file_name":"plots_second.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"154547336","text":"#!/bin/python3\n\n\"\"\"\nOriginal findloop.py written by Tracy Baker\n\nV2 rewritten with loop detection concepts from Jonathan Heard,\nwhich only processes numbers if they aren't in the master number\nlist. Once a number is repeated, the loop number list can be\nconstructed.\n\"\"\"\n\n# Section to import all modules used in this program\n\n# Eventually, this will write to a file. So, sys is needed\n# also, \"copy\" stdout to orginal_stdout. This will allow\n# redirection of stdout to a file using print()\n\nimport sys\n\n# os needs to be imported to delete the log file, if it exists.\n# Otherwise, it just continues to grow with each execution of the script\nimport os\n\n# If time is being measured the time module will be needed.\n\nimport time\n\n# End of import section\n\noriginal_stdout = sys.stdout\n\n# Set the log file name\nLogFile = \"findloops.py.log\"\n\nif os.path.exists(LogFile):\n os.remove(LogFile)\n\nos.system('clear')\n\nprint(\"\\nThe log file being used is:\", LogFile)\n\n# MaxSize = sys.maxsize # Used to set the largest number to test.\nMaxSize = int(input(\"Enter the largest number to be tested: \"))\n\nprint(\"\\nThe numbers 2 though\", MaxSize, \"will be tested.\")\nprint(\"(It'll take roughly 5 million years, at 100 iterations per number,\")\nprint(\"to check them all ... which is still about 40 times faster than Bash.)\")\n\n# Ask for the Multiplier, the y in yx+1\nMultiplier = int(input(\"\\nEnter a multiplier. For example 3, 5, 7, etc..: \"))\n\n# Ask how many iterations to go through when testing each x in yx+1\nMaxIterations = int(input(\"\\nMaximum iterations to test (note loops have been found between 100 and 200): \"))\n\n# Ask if an optional time check is to be done at 1 second of processing time\n\nTimeCheck = input(\"\\nCheck the timer at 1 second to see how many numbers have been checked (y = yes)? \")\nif TimeCheck == \"y\":\n StartTime = time.time()\n NumCount = 0\n\n\"\"\" Set some variables\n > Set the start x in yx+1 to 2 (TestNum)\n > Set the number od loops found to 0 (LoopNum)\n > LoopControl determines if a new loop was found\n\"\"\"\nTestNum = 2\nLoopNum = 0\nLoopControl = 0\n\n# Continue processing asl long as TestNum is less than or equal to the\n# maximum allowable integer in Python\nwhile TestNum <= MaxSize:\n\n \"\"\" Some variables that need to be set / reset before the interior while loop\n > Make Num equal to TestNum to retain TestNum value between each loop\n > Clear the MasterList array - a listing of all Num calculated\n > Clear the LoopList array - a list of all Num that appear in a loop\n > Reset the iteration counter (i)\n \"\"\"\n Num = TestNum\n MasterList = []\n LoopList = []\n i = 0\n\n # Stay in the inside while loop as long as the iteration count\n # is less than MaxIterations and while LoopList has a length of 0.\n while i <= MaxIterations and len(LoopList) == 0:\n\n # Do a 1 second time check if TimeCheck is y\n if TimeCheck == \"y\":\n NumCount += 1\n CheckTime = int(time.time() - StartTime)\n if CheckTime == 1:\n print(\"\\n\", NumCount, \"total numbers have been checked in the first second\")\n Pause = input(\"\\nPress Enter to continue...\")\n\n # If Num isn't in MasterList, add it and process it\n if Num not in MasterList:\n\n # increment the iteration counter (i)\n i += 1\n\n # Add Num to MasterList\n MasterList.append(int(Num))\n\n print(\"Equation :(\", Multiplier, \"x)+1, inc =\", i, \"Testing:\", TestNum, \"Result:\", int(Num))\n \n # If Num is even, divide by 2\n if Num % 2 == 0:\n Num = Num / 2\n\n # Else Num is odd then apply yx+1 formula it\n else:\n Num = Num * Multiplier + 1\n\n # If Num is in MasterList, use list comprehension to make the LoopList.\n # by taking the range of numbers from the first time Num appeared\n # in MasterList until the the end of MasterList\n else:\n LoopNum += 1\n LoopList = [MasterList[Index] for Index in range(MasterList.index(Num), len(MasterList))]\n\n \"\"\" END OF INSIDE while LOOP \"\"\"\n \n \"\"\" Print any loops that are found into the log file -- but only if\n LoopNumber is greater than LoopControl\n\n > The log file is opened in append mode\n > The system's stdout (sys.stdout), normally to the terminal screen, is\n redirected to the log file\n > A line is printed\n > stdout is returned to the system's normal stdout\n \"\"\"\n if LoopNum > LoopControl:\n LoopControl = LoopNum\n with open(LogFile, 'a') as f:\n sys.stdout = f\n print(\"(\", Multiplier, \"x+1) Testing:\", TestNum, \" Loop #\", LoopNum, \" Iteration\", i, \":\", LoopList)\n sys.stdout = original_stdout\n\n if i > MaxIterations:\n with open(LogFile, 'a') as f:\n sys.stdout = f\n print(\"(\", Multiplier, \"x+1) Testing:\", TestNum, \" No loop was found, with Max Iterations =\", MaxIterations)\n sys.stdout = original_stdout\n\n # Increment to the next number\n TestNum += 1\n\n\"\"\" END OF OUTSIDE while LOOP \"\"\"\n","sub_path":"findloopsV2jlh.py","file_name":"findloopsV2jlh.py","file_ext":"py","file_size_in_byte":5146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"642215734","text":"num = int(input())\nsum = 0\n\nfor i in range(1,num):\n if num% i == 0:\n sum += i\n\nif sum == num:\n print(\"We have a perfect number!\")\nelse:\n print(\"It's not so perfect.\")","sub_path":"Python Fundamentals/04. Functions/Exercise 4 - Functions/Perfetct Number.py","file_name":"Perfetct Number.py","file_ext":"py","file_size_in_byte":182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"213828862","text":"from pyabt.variable import Variable, VariableGenerator\nfrom pyabt.operator import Operator\n\nfrom pyabt.term import *\n\n\nclass Lam(Operator):\n arity = [1]\n\n def __eq__(a, b):\n return isinstance(a, Lam) and isinstance(b, Lam)\n\n def __repr__(self):\n return \"lam\"\n\n\nclass Ap(Operator):\n arity = [0, 0]\n\n def __eq__(a, b):\n return isinstance(a, Ap) and isinstance(b, Ap)\n\n def __repr__(self):\n return \"ap\"\n\ndef eval(e):\n out = e.out()\n if isinstance(out, AppView) and isinstance(out.operator, Ap):\n [a, y] = out.args\n\n out = a.out()\n\n if isinstance(out, AppView) and isinstance(out.operator, Lam):\n [a] = out.args\n\n out = a.out()\n\n if isinstance(out, AbsView):\n return eval(out.body.out().subst(y, out.variable))\n else:\n return out.into()\n elif isinstance(out, AppView):\n eval_a = eval(a)\n eval_y = eval(y)\n return eval(intoApp(Ap(), [eval_a, eval_y]))\n else:\n return out.into()\n else:\n return out.into()\n\nvg = VariableGenerator()\n\nx = vg.named(\"x\")\ny = vg.named(\"y\")\n\nid = intoApp(Lam(), [intoAbs(x, intoVar(x))])\n\nterm = intoApp(Ap(), [id, intoVar(y)])\n\nprint(toString(id))\nprint(toString(eval(term)))\n\nomega = intoApp(Ap(), [intoApp(Lam(), [intoAbs(x, intoApp(Ap(), [intoVar(x), intoVar(x)]))]),\n intoApp(Lam(), [intoAbs(x, intoApp(Ap(), [intoVar(x), intoVar(x)]))])])\n\n#eval(omega)","sub_path":"Untyped.py","file_name":"Untyped.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"108063154","text":"from celery.task import task\nfrom celery import current_task\nfrom celery_test.models import CounterModel\nfrom time import sleep\n\n@task()\ndef add_two_numbers(a, b):\n \"\"\"This is where you do the bulk of the your queued task needs to do\"\"\"\n sleep(10)\n count = CounterModel.objects.create(count = a + b)\n return count\n\n@task()\ndef do_something_long():\n for i in range(100):\n sleep(0.2)\n current_task.update_state(state=\"PROGRESS\", meta={'current':i, 'total':100})","sub_path":"celery_test/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"201143412","text":"# coding: utf-8\n# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\nfrom __future__ import division, unicode_literals\n\n\"\"\"\nCreated on May 1, 2012\n\"\"\"\n\n\n__author__ = \"Shyue Ping Ong\"\n__copyright__ = \"Copyright 2012, The Materials Project\"\n__version__ = \"0.1\"\n__maintainer__ = \"Shyue Ping Ong\"\n__email__ = \"shyuep@gmail.com\"\n__date__ = \"May 1, 2012\"\n\nimport unittest\nimport os\nimport json\n\nfrom io import open\n\nfrom pymatgen.electronic_structure.dos import CompleteDos\nfrom pymatgen.electronic_structure.plotter import DosPlotter, BSPlotter, \\\n _qvertex_target\nfrom pymatgen.electronic_structure.bandstructure import BandStructureSymmLine\n\ntest_dir = os.path.join(os.path.dirname(__file__), \"..\", \"..\", \"..\",\n 'test_files')\n\nimport scipy\n\n\nclass DosPlotterTest(unittest.TestCase):\n\n def setUp(self):\n with open(os.path.join(test_dir, \"complete_dos.json\"), \"r\",\n encoding='utf-8') as f:\n self.dos = CompleteDos.from_dict(json.load(f))\n self.plotter = DosPlotter(sigma=0.2, stack=True)\n\n def test_add_dos_dict(self):\n d = self.plotter.get_dos_dict()\n self.assertEqual(len(d), 0)\n self.plotter.add_dos_dict(self.dos.get_element_dos(),\n key_sort_func=lambda x: x.X)\n d = self.plotter.get_dos_dict()\n self.assertEqual(len(d), 4)\n\n def test_get_dos_dict(self):\n self.plotter.add_dos_dict(self.dos.get_element_dos(),\n key_sort_func=lambda x: x.X)\n d = self.plotter.get_dos_dict()\n for el in [\"Li\", \"Fe\", \"P\", \"O\"]:\n self.assertIn(el, d)\n\n\nclass BSPlotterTest(unittest.TestCase):\n\n def setUp(self):\n with open(os.path.join(test_dir, \"CaO_2605_bandstructure.json\"),\n \"r\", encoding='utf-8') as f:\n d = json.loads(f.read())\n self.bs = BandStructureSymmLine.from_dict(d)\n self.plotter = BSPlotter(self.bs)\n\n def test_bs_plot_data(self):\n self.assertEqual(len(self.plotter.bs_plot_data()['distances'][0]), 16,\n \"wrong number of distances in the first branch\")\n self.assertEqual(len(self.plotter.bs_plot_data()['distances']), 10,\n \"wrong number of branches\")\n self.assertEqual(\n sum([len(e) for e in self.plotter.bs_plot_data()['distances']]),\n 160, \"wrong number of distances\")\n self.assertEqual(self.plotter.bs_plot_data()['ticks']['label'][5], \"K\",\n \"wrong tick label\")\n self.assertEqual(len(self.plotter.bs_plot_data()['ticks']['label']),\n 19, \"wrong number of tick labels\")\n\n def test_qvertex_target(self):\n results = _qvertex_target([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0],\n [1.0, 1.0, 0.0], [0.0, 1.0, 0.0],\n [0.0, 0.0, 1.0], [1.0, 0.0, 1.0],\n [1.0, 1.0, 1.0], [0.0, 1.0, 1.0],\n [0.5, 0.5, 0.5]], 8)\n self.assertEqual(len(results), 6)\n self.assertEqual(results[3][1], 0.5)\n\n\nif __name__ == \"__main__\":\n #import sys;sys.argv = ['', 'Test.testName']\n unittest.main()\n","sub_path":"pymatgen/electronic_structure/tests/test_plotter.py","file_name":"test_plotter.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"187140436","text":"# First Common Ancestor with parent node connection\n# search in the node's subtree than sibling\n\nimport sys\nimport treeLib\n\n\n# sys.path.insert(0,\"treeLib\")\n\ndef hasNode(root,node):\n if not root:\n return False\n if root is node:\n return True\n return hasNode(root.left,node) or hasNode(root.right,node)\n\n\n\ndef firstCommonAncestor(node1, node2):\n\n if hasNode(node1,node2):\n return node1\n elif hasNode(node2,node1):\n return node2\n parent=node1.parent\n sibling=parent.left if node1 is parent.right else parent.right\n while not hasNode(sibling,node2):\n node=parent\n parent=parent.parent\n sibling=parent.left if node is parent.right else parent.right\n\n return parent\n\n\ndef inOrderP(nodePtr):\n if nodePtr:\n inOrderP(nodePtr.left)\n sys.stdout.write(str(nodePtr.id) + \" \")\n inOrderP(nodePtr.right)\n\n\nif __name__ == \"__main__\":\n root = treeLib.BinaryNodeWithParentLink(16)\n root.left = treeLib.BinaryNodeWithParentLink(8, parent=root)\n\n root.left.left = treeLib.BinaryNodeWithParentLink(5, parent=root.left)\n root.left.right = treeLib.BinaryNodeWithParentLink(11, parent=root.left)\n root.left.left.left = treeLib.BinaryNodeWithParentLink(3, parent=root.left.left)\n root.left.left.right = treeLib.BinaryNodeWithParentLink(6, parent=root.left.left)\n\n root.left.right.right = treeLib.BinaryNodeWithParentLink(14, parent=root.left.right)\n\n root.right = treeLib.BinaryNodeWithParentLink(25, parent=root)\n root.right.left = treeLib.BinaryNodeWithParentLink(24, parent=root.right)\n root.right.right = treeLib.BinaryNodeWithParentLink(32, parent=root.right)\n root.right.right.right = treeLib.BinaryNodeWithParentLink(33, parent=root.right.right)\n\n inOrderP(root)\n\n node1 = root\n node2 = root.right.right.right\n\n node = firstCommonAncestor(node1, node2)\n print(\"\")\n print(\"first common ancestor of \",node1 , \" and \",node2, \" is:\",node)\n\n node1 = root.left.left.right\n node2 = root.left.right\n node = firstCommonAncestor(node1, node2)\n print(\"first common ancestor of \", node1, \" and \", node2, \" is:\", node)\n\n node1 = root.right.right.right\n node2 = root.right.left\n node = firstCommonAncestor(node1, node2)\n print(\"first common ancestor of \", node1, \" and \", node2, \" is:\", node)\n\n","sub_path":"trees_graphs/fca1.py","file_name":"fca1.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"143409836","text":"import os\nimport logging.config\n\nimport uimodules\nfrom handlers.base import DefaultErrorHandler\n\n\ndef location(*args):\n \"\"\"Get an absolute file path for the given file/directory\n\n :param args: a list of file/directory names for which you want the absolute path.\n :return: Absolute file path for x.\n\n :example: location('static', 'images', 'avatars')\n :output: /home/mjeco/PycharmProjects/codequiz/static/images/avatars\n \"\"\"\n return os.path.join(os.path.dirname(os.path.realpath(__file__)), *args)\n\n\nSTATIC_ROOT = location('public')\nTEMPLATE_ROOT = location('templates')\n\nTOPIC_IMG_DIR = location(STATIC_ROOT, 'images', 'topics')\nAVATAR_DIR = location(STATIC_ROOT, 'images', 'avatars')\n\nSETTINGS = dict(\n template_path=TEMPLATE_ROOT,\n static_path=STATIC_ROOT,\n debug=True,\n cookie_secret=\"7Yi3aEEVS3+B7LKXyxDoucm4JZ2bXE2Nv8aqAER6BE4=\",\n login_url='/',\n xsrf_cookies=True,\n ui_modules=uimodules,\n default_handler_class=DefaultErrorHandler,\n default_handler_args=dict(status_code=404)\n)\n\nMONGO_DB = dict(\n host='localhost',\n port=27017,\n db_name='codequiz',\n)\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'main_formatter': {\n 'format': '%(levelname)s:%(name)s: %(message)s '\n '(%(asctime)s; %(filename)s:%(lineno)d)',\n 'datefmt': \"%Y-%m-%d %H:%M:%S\",\n },\n },\n 'handlers': {\n 'rotate_file': {\n 'level': 'DEBUG',\n 'class': 'logging.handlers.TimedRotatingFileHandler',\n 'filename': location('logs/main.log'),\n 'when': 'midnight',\n 'interval': 1, # day\n 'backupCount': 7,\n 'formatter': 'main_formatter',\n },\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'main_formatter',\n # 'filters': ['require_local_true'],\n },\n },\n 'loggers': {\n '': {\n 'handlers': ['rotate_file', 'console'],\n 'level': 'DEBUG',\n }\n }\n}\n\nlogging.config.dictConfig(LOGGING)","sub_path":"src/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"352454646","text":"import glob, sys, argparse, time, os, json\nimport pandas as pd\nfrom os.path import basename, dirname\n\n# return (hour, minute, second) from the start time\ndef record(start):\n t,r = int(time.time()-start), 60\n return '{} hr {} min {} sec'.format(int(t/(r*r)), int(t/r)%r, t%r)\n\n# process all csv files in a directory for jaccard similarity analysis\ndef process_directory(directory_path):\n dbname = basename(directory_path)\n os.makedirs(dirname('outputs/{}/groundtruth/'.format(dbname)), exist_ok=True)\n\n db, label, error, index = {}, {}, [], 0\n csv_file_paths = glob.glob(directory_path + \"/**/*.csv\", recursive=True)\n start = time.time()\n print (\"processing files...\")\n delimiter = ';' if 'chembl' in directory_path else ','\n for csv_file_path in csv_file_paths:\n try:\n # encoding='latin1' is used for MITDWH dataset (ok to use for others also)\n # delimiter=';' is used for Chembl dataset\n df = pd.read_csv(csv_file_path, encoding='latin1', dtype=str, delimiter=delimiter)\n file_name = basename(csv_file_path)[:-4]\n for i in range(len(df.columns)):\n content = set([str(elem) for elem in df.iloc[:,[i]].stack().values])\n if len(content) != 0:\n db[index] = content\n label[str(index)] = [file_name, df.columns[i], str(i)]\n index += 1\n # print (\"processed\", basename(csv_file_path))\n # record errors rather than terminate\n except:\n error.append(basename(csv_file_path))\n\n with open('outputs/{}/groundtruth/log.txt'.format(dbname), 'w') as f: \n f.write('{} to process {} columns\\n\\n'.format(record(start), len(db)))\n f.write('\\n'.join(error))\n\n with open('outputs/{}/groundtruth/label.json'.format(dbname), 'w') as f:\n json.dump(label, f, indent=4)\n\n return db, label\n \nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('directory_path', help='data directory')\n args = parser.parse_args()\n\n # process all csv files\n process_directory(args.directory_path)\n","sub_path":"process_csv_files.py","file_name":"process_csv_files.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"396071988","text":"#-*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\nfile: enrich.py\r\n\r\nDescription: this program is used to enrich a CoNLL-formatted file with\r\nvarious features.\r\n\r\nauthor: Yoann Dupont\r\n\r\nMIT License\r\n\r\nCopyright (c) 2018 Yoann Dupont\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n\"\"\"\r\n\r\nimport logging\r\n\r\n# measuring time laps\r\nimport time\r\nfrom datetime import timedelta\r\n\r\nfrom .sem_module import SEMModule as RootModule\r\n\r\nfrom sem.information import Informations\r\nfrom sem.IO import KeyReader, KeyWriter\r\nfrom sem.logger import default_handler, file_handler\r\n\r\nimport os.path\r\nenrich_logger = logging.getLogger(\"sem.%s\" %os.path.basename(__file__).split(\".\")[0])\r\nenrich_logger.addHandler(default_handler)\r\n\r\nclass SEMModule(RootModule):\r\n def __init__(self, informations, mode=u\"label\", log_level=\"WARNING\", log_file=None, **kwargs):\r\n super(SEMModule, self).__init__(log_level=log_level, log_file=log_file, **kwargs)\r\n \r\n self._mode = mode\r\n self._source = informations\r\n \r\n if type(informations) in (str, unicode):\r\n enrich_logger.info('loading %s' %informations)\r\n self._informations = Informations(self._source, mode=self._mode)\r\n else:\r\n self._informations = self._source\r\n \r\n @property\r\n def informations(self):\r\n return self._informations\r\n \r\n @property\r\n def mode(self):\r\n return self._mode\r\n \r\n @mode.setter\r\n def mode(self, mode):\r\n if type(self._source) not in (str, unicode):\r\n raise RuntimeError(\"cannot change mode for Enrich module: source for informations is not a file.\")\r\n self._mode = mode\r\n enrich_logger.info('loading %s' %self._source)\r\n self._informations = Informations(self._source, mode=self._mode)\r\n \r\n def process_document(self, document, **kwargs):\r\n \"\"\"\r\n Updates the CoNLL-formatted corpus inside a document with various\r\n features.\r\n \r\n Parameters\r\n ----------\r\n document : sem.storage.Document\r\n the input data, contains an object representing CoNLL-formatted\r\n data. Each token is a dict which works like TSV.\r\n log_level : str or int\r\n the logging level\r\n log_file : str\r\n if not None, the file to log to (does not remove command-line\r\n logging).\r\n \"\"\"\r\n \r\n start = time.time()\r\n \r\n if self._log_file is not None:\r\n enrich_logger.addHandler(file_handler(self._log_file))\r\n enrich_logger.setLevel(self._log_level)\r\n \r\n informations = self._informations\r\n missing_fields = set([I.name for I in informations.bentries + informations.aentries]) - set(document.corpus.fields)\r\n \r\n if len(missing_fields) > 0:\r\n raise ValueError(\"Missing fields in input corpus: %s\" %u\",\".join(sorted(missing_fields)))\r\n \r\n enrich_logger.debug('enriching file \"%s\"' %document.name)\r\n \r\n new_fields = [feature.name for feature in informations.features if feature.display]\r\n document.corpus.fields += new_fields\r\n nth = 0\r\n for i, sentence in enumerate(informations.enrich(document.corpus)):\r\n nth += 1\r\n if (0 == nth % 1000):\r\n enrich_logger.debug('%i sentences enriched' %nth)\r\n enrich_logger.debug('%i sentences enriched' %nth)\r\n \r\n laps = time.time() - start\r\n enrich_logger.info(\"done in %s\" %timedelta(seconds=laps))\r\n\r\ndef main(args):\r\n \"\"\"\r\n Takes a CoNLL-formatted file and write another CoNLL-formatted file\r\n with additional features in it.\r\n \r\n Parameters\r\n ----------\r\n infile : str\r\n the CoNLL-formatted input file.\r\n infofile : str\r\n the XML file containing the different features.\r\n mode : str\r\n the mode to use for infofile. Some inputs may only be present in\r\n a particular mode. For example, the output tag is only available\r\n in \"train\" mode.\r\n log_level : str or int\r\n the logging level.\r\n log_file : str\r\n if not None, the file to log to (does not remove command-line\r\n logging).\r\n \"\"\"\r\n \r\n start = time.time()\r\n \r\n if args.log_file is not None:\r\n enrich_logger.addHandler(file_handler(args.log_file))\r\n enrich_logger.setLevel(args.log_level)\r\n enrich_logger.info('parsing enrichment file \"%s\"' %args.infofile)\r\n \r\n informations = Informations(path=args.infofile, mode=args.mode)\r\n \r\n enrich_logger.debug('enriching file \"%s\"' %args.infile)\r\n \r\n bentries = [entry.name for entry in informations.bentries]\r\n aentries = [entry.name for entry in informations.aentries]\r\n features = [feature.name for feature in informations.features if feature.display]\r\n with KeyWriter(args.outfile, args.oenc or args.enc, bentries + features + aentries) as O:\r\n nth = 0\r\n for p in informations.enrich(KeyReader(args.infile, args.ienc or args.enc, bentries + aentries)):\r\n O.write_p(p)\r\n nth += 1\r\n if (0 == nth % 1000):\r\n enrich_logger.debug('%i sentences enriched' %nth)\r\n enrich_logger.debug('%i sentences enriched' %nth)\r\n \r\n laps = time.time() - start\r\n enrich_logger.info(\"done in %s\", timedelta(seconds=laps))\r\n\r\n\r\n\r\nimport sem\r\nimport argparse, sys\r\n\r\n_subparsers = sem.argument_subparsers\r\n\r\nparser = _subparsers.add_parser(os.path.splitext(os.path.basename(__file__))[0], description=\"Adds information to a file using and XML-styled configuration file.\")\r\n\r\nparser.add_argument(\"infile\",\r\n help=\"The input file (CoNLL format)\")\r\nparser.add_argument(\"infofile\",\r\n help=\"The information file (XML format)\")\r\nparser.add_argument(\"outfile\",\r\n help=\"The output file (CoNLL format)\")\r\nparser.add_argument(\"-m\", \"--mode\", dest=\"mode\", default=u\"train\", choices=(u\"train\", u\"label\", u\"annotate\", u\"annotation\"),\r\n help=\"The mode for enrichment. May make entries vary (default: %(default)s)\")\r\nparser.add_argument(\"--input-encoding\", dest=\"ienc\",\r\n help=\"Encoding of the input (default: UTF-8)\")\r\nparser.add_argument(\"--output-encoding\", dest=\"oenc\",\r\n help=\"Encoding of the input (default: UTF-8)\")\r\nparser.add_argument(\"--encoding\", dest=\"enc\", default=\"UTF-8\",\r\n help=\"Encoding of both the input and the output (default: UTF-8)\")\r\nparser.add_argument(\"-l\", \"--log\", dest=\"log_level\", choices=(\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\", \"CRITICAL\"), default=\"WARNING\",\r\n help=\"Increase log level (default: critical)\")\r\nparser.add_argument(\"--log-file\", dest=\"log_file\",\r\n help=\"The name of the log file\")\r\n","sub_path":"sem/modules/enrich.py","file_name":"enrich.py","file_ext":"py","file_size_in_byte":7793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"79418356","text":"from django.urls import path, re_path\nfrom apps.presidente import views\nfrom django.contrib.auth.decorators import login_required\n \n\nurlpatterns = [\t \t\n\n\n\tre_path(r'^$', login_required(views.presidente),name='presidente'),\n\tre_path(r'^listae$', views.ListaE,name='ListaE'),\n\n\n\tre_path(r'^p_act_usu/$', views.ActUsuario.as_view(),name='p_act_usu'),\n\tre_path(r'^p_cam_usu/$', views.CambioUSER.as_view(),name='p_cam_usu'),\n\tre_path(r'^p_cam_pas/$', views.CambioPASS.as_view(),name='p_cam_pas'),\n\n\tre_path(r'^p_usuario_lis/$',login_required(views.DatosList.as_view()),name='p_usuario_lis'),\n\tre_path(r'^p_usuario_reg/$',views.DatosCreate.as_view(),name='p_usuario_reg'),\n\tre_path(r'^p_usuario_edi/(?P<pk>\\d+)/$',login_required(views.DatosUpdate.as_view()),name='p_usuario_edi'),\n\tre_path(r'^p_usuario_eli/(?P<pk>\\d+)/$',login_required(views.DatosDelete.as_view()),name='p_usuario_eli'),\n\n\tre_path(r'^p_usuario1_reg/$',views.UsuarioCreate.as_view(),name='p_usuario1_reg'),\n\tre_path(r'^p_usuario1_upd/(?P<pk>\\d+)/$',views.UsuarioUpdate.as_view(),name='p_usuario1_upd'),\n\tre_path(r'^p_usuario1_del/(?P<pk>\\d+)/$',login_required(views.UsuarioDelete.as_view()),name='p_usuario1_del'),\n\n\n\n\tre_path(r'^p_auth_lis/$',login_required(views.AuthList.as_view()),name='p_auth_lis'),\n\tre_path(r'^p_auth_bus/$',login_required(views.BuscarAuthList.as_view()),name='p_auth_bus'),\n\n\n\tre_path(r'^p_parcela_reg/$',login_required(views.ParcelaCreate.as_view()),name='p_parcela_reg'),\n\tre_path(r'^p_parcela_lis/$',login_required(views.ParcelaList.as_view()),name='p_parcela_lis'),\n\tre_path(r'^p_parcela_edi/(?P<pk>\\d+)/$',login_required(views.ParcelaUpdate.as_view()),name='p_parcela_edi'),\n\tre_path(r'^p_parcela_eli/(?P<pk>\\d+)/$',login_required(views.ParcelaDelete.as_view()),name='p_parcela_eli'),\n\n\n\n\tre_path(r'^p_canal_reg/$',login_required(views.CanalCreate.as_view()),name='p_canal_reg'),\n\tre_path(r'^p_canal_lis/$',login_required(views.CanalList.as_view()),name='p_canal_lis'),\n\tre_path(r'^p_canal_edi/(?P<pk>\\d+)/$',login_required(views.CanalUpdate.as_view()),name='p_canal_edi'),\n\tre_path(r'^p_canal_eli/(?P<pk>\\d+)/$',login_required(views.CanalDelete.as_view()),name='p_canal_eli'),\n\n\n\tre_path(r'^p_noticia_reg/$',login_required(views.NoticiaCreate.as_view()),name='p_noticia_reg'),\n\tre_path(r'^p_noticia_lis/$',login_required(views.NoticiaList.as_view()),name='p_noticia_lis'),\n\tre_path(r'^p_noticia_edi/(?P<pk>\\d+)/$',login_required(views.NoticiaUpdate.as_view()),name='p_noticia_edi'),\n\tre_path(r'^p_noticia_eli/(?P<pk>\\d+)/$',login_required(views.NoticiaDelete.as_view()),name='p_noticia_eli'),\n \n\n\tre_path(r'^p_caudal_reg/$',login_required(views.CaudalCreate.as_view()),name='p_caudal_reg'),\n\tre_path(r'^p_caudal_lis/$',login_required(views.CaudalList.as_view()),name='p_caudal_lis'),\n\tre_path(r'^p_caudal_eli/(?P<pk>\\d+)/$',login_required(views.CaudalDelete.as_view()),name='p_caudal_eli'),\n\n\tre_path(r'^p_rep_caudal/$', login_required(views.RepCaudal.as_view()),name='p_rep_caudal'),\n\tre_path(r'^p_rep_caudal2/$', login_required(views.RepCaudal2.as_view()),name='p_rep_caudal2'),\n\tre_path(r'^p_rep_reparto/$', login_required(views.RepPeparto.as_view()),name='p_rep_reparto'),\n\n\tre_path(r'^pasambreg/$', login_required(views.AsambReg.as_view()),name='p_asamb_reg'),\t\n\tre_path(r'^pasamblis/$', login_required(views.AsambLis.as_view()),name='p_asamb_lis'),\n\tre_path(r'^p_asamb_edi/?/$',login_required(views.AsambEdi.as_view()),name='p_asamb_edi'),\n\tre_path(r'^p_asamb_ini/?/$',login_required(views.AsambIni.as_view()),name='p_asamb_ini'),\n\tre_path(r'^p_hasis_est/?/$',login_required(views.HjaAsisEst.as_view()),name='p_hasis_est'),\n\n\tre_path(r'^p_asamb_del/?/$',login_required(views.AsmbDel.as_view()),name='p_asamb_del'),\n\n\t] ","sub_path":"comision2/apps/presidente/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"471477538","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Author: Jordi Ballester (Eficent)\n# Copyright 2015 Eficent\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (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 Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n#\n##############################################################################\nfrom openerp.osv import osv\nfrom openerp.tools import DEFAULT_SERVER_DATE_FORMAT\nimport time\n\n\nclass SaleOrder(osv.osv):\n _inherit = \"sale.order\"\n\n def _append_invoice_line(self, cr, uid, invoice, lines, context=None):\n for preline in invoice.invoice_line:\n inv_line_id = self.pool.get('account.invoice.line').\\\n copy(cr, uid, preline.id, {'invoice_id': False,\n 'price_unit': -preline.price_unit})\n lines.append(inv_line_id)\n return lines\n\n def _make_invoice(self, cr, uid, order, lines, context=None):\n \"\"\" Add HOOK \"\"\"\n inv_obj = self.pool.get('account.invoice')\n # obj_invoice_line = self.pool.get('account.invoice.line')\n if context is None:\n context = {}\n invoiced_sale_line_ids = self.pool.get('sale.order.line').search(\n cr, uid, [('order_id', '=', order.id), ('invoiced', '=', True)],\n context=context)\n from_line_invoice_ids = []\n for invoiced_sale_line_id in self.pool.get('sale.order.line').browse(\n cr, uid, invoiced_sale_line_ids, context=context):\n for invoice_line_id in invoiced_sale_line_id.invoice_lines:\n if invoice_line_id.invoice_id.id not in from_line_invoice_ids:\n from_line_invoice_ids.append(invoice_line_id.invoice_id.id)\n for preinv in order.invoice_ids:\n if preinv.state not in ('cancel',) and \\\n preinv.id not in from_line_invoice_ids:\n # HOOK\n lines = self._append_invoice_line(cr, uid,\n preinv, lines,\n context=context)\n # --\n inv = self._prepare_invoice(cr, uid, order, lines, context=context)\n inv_id = inv_obj.create(cr, uid, inv, context=context)\n # HOOK\n date_invoice = context.get('date_invoice', False) or \\\n time.strftime(DEFAULT_SERVER_DATE_FORMAT)\n data = inv_obj.onchange_payment_term_date_invoice(cr, uid, [inv_id],\n inv['payment_term'],\n date_invoice)\n # --\n if data.get('value', False):\n inv_obj.write(cr, uid, [inv_id], data['value'], context=context)\n inv_obj.button_compute(cr, uid, [inv_id])\n return inv_id\n","sub_path":"sale_order_make_invoice_hooks/models/sale.py","file_name":"sale.py","file_ext":"py","file_size_in_byte":3419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"284672066","text":"# -*- coding: utf-8 -*-\nimport json\nimport zeit.content.article.edit.browser.testing\n\n\nclass RecipeListTest(\n zeit.content.article.edit.browser.testing.BrowserTestCase):\n\n block_type = 'recipelist'\n\n def test_servings_should_be_validated(self):\n self.get_article(with_empty_block=True)\n b = self.browser\n b.open(\n 'editable-body/blockname/@@edit-%s?show_form=1' % self.block_type)\n\n # Should accept a number\n b.getControl('Servings').value = 4\n b.getControl('Apply').click()\n self.assertNotEllipsis(\n '...<span class=\"error\">...',\n b.contents)\n\n # Should accept an empty value\n b.open('@@edit-%s?show_form=1' % self.block_type)\n b.getControl('Servings').value = ''\n b.getControl('Apply').click()\n self.assertNotEllipsis(\n '...<span class=\"error\">...',\n b.contents)\n\n # Should NOT accept zero\n b.open('@@edit-%s?show_form=1' % self.block_type)\n b.getControl('Servings').value = 0\n b.getControl('Apply').click()\n self.assertEllipsis(\n '...Value must be number or range...',\n b.contents)\n\n # Should NOT accept a string\n b.open('@@edit-%s?show_form=1' % self.block_type)\n b.getControl('Servings').value = 'notanumber'\n b.getControl('Apply').click()\n self.assertEllipsis(\n '...Value must be number or range...',\n b.contents)\n\n\nclass FormLoader(\n zeit.content.article.edit.browser.testing.EditorTestCase,\n zeit.content.article.edit.browser.testing.RecipeListHelper):\n\n def test_recipelist_form_is_loaded(self):\n s = self.selenium\n self.add_article()\n self.create_block('recipelist')\n s.assertElementPresent('css=.block.type-recipelist .inline-form '\n '.field.fieldname-ingredients')\n\n def test_ingredients_should_be_organized_through_recipelist(self):\n s = self.selenium\n self.setup_ingredient()\n\n self.assertEqual(s.getCssCount('css=li.ingredient__item'), 1)\n s.assertText('css=a.ingredient__label', 'Brathähnchen')\n s.assertElementPresent('css=input.ingredient__amount')\n s.assertElementPresent('css=select.ingredient__unit')\n s.assertElementPresent('css=li.ingredient__item span.delete')\n\n # Add second ingredient\n s.type('//input[@name=\"add_ingredient\"]', 'Nudel')\n s.waitForVisible('css=ul.ui-autocomplete li')\n s.click('css=ul.ui-autocomplete li')\n self.assertEqual(s.getCssCount('css=li.ingredient__item'), 2)\n s.assertText(\n '//li[@class=\"ingredient__item\"][2]/a[@class=\"ingredient__label\"]',\n 'Bandnudeln')\n\n # Reorder ingredients\n s.dragAndDrop('css=.ingredient__label', '0,50')\n s.waitForVisible('css=li.ingredient__item')\n s.assertText(\n '//li[@class=\"ingredient__item\"][2]/a[@class=\"ingredient__label\"]',\n 'Brathähnchen')\n\n # Delete ingredient\n s.click('css=li.ingredient__item span.delete')\n self.assertEqual(s.getCssCount('css=li.ingredient__item'), 1)\n\n def test_ingredient_amount_should_be_validated(self):\n s = self.selenium\n self.setup_ingredient()\n\n # Should accept numbers\n s.type('css=input.ingredient__amount', '2')\n # Lose focus to save new value\n s.runScript(\n 'document.querySelector(\"input.ingredient__amount\").blur()')\n # Give it some time to exchange widget with new value\n s.waitForCssCount('css=.dirty', 0)\n s.assertAttribute('css=input.ingredient__amount@value', '2')\n\n # Should not accept letters\n s.type('css=input.ingredient__amount', 'oans')\n s.runScript(\n 'document.querySelector(\"input.ingredient__amount\").blur()')\n s.waitForCssCount('css=.dirty', 0)\n # Fallback to previous value\n s.assertAttribute('css=input.ingredient__amount@value', '2')\n\n # Should accept empty value\n s.clear('css=input.ingredient__amount')\n s.runScript(\n 'document.querySelector(\"input.ingredient__amount\").blur()')\n s.waitForCssCount('css=.dirty', 0)\n s.assertAttribute('css=input.ingredient__amount@value', '')\n\n def test_ingredient_should_store_values_as_json(self):\n s = self.selenium\n self.setup_ingredient()\n\n s.type('css=input.ingredient__amount', '2')\n s.runScript(\n 'document.querySelector(\"input.ingredient__amount\").blur()')\n s.waitForCssCount('css=.dirty', 0)\n ingredient_data = json.loads(\n s.getAttribute('css=.ingredients-widget input@value'))[0]\n assert ingredient_data.get('code') == 'brathaehnchen'\n assert ingredient_data.get('label') == 'Brathähnchen'\n assert ingredient_data.get('amount') == '2'\n assert ingredient_data.get('unit') == ''\n assert ingredient_data.get('details') == ''\n assert ingredient_data.get('unique_id') is not None\n\n def test_duplicate_ingredients_should_be_allowed(self):\n s = self.selenium\n self.add_article()\n self.create_block('recipelist')\n\n # Add first ingredient\n s.type('//input[@name=\"add_ingredient\"]', 'Nudel')\n s.waitForVisible('css=ul.ui-autocomplete li')\n s.click('css=ul.ui-autocomplete li')\n\n # Add duplicate ingredient\n s.type('//input[@name=\"add_ingredient\"]', 'Nudel')\n s.waitForVisible('css=ul.ui-autocomplete li')\n s.click('css=ul.ui-autocomplete li')\n self.assertEqual(s.getCssCount('css=li.ingredient__item'), 2)\n\n # ids should be different.\n uid1 = s.getAttribute('//li[@class=\"ingredient__item\"][1] @data-id')\n uid2 = s.getAttribute('//li[@class=\"ingredient__item\"][2] @data-id')\n assert uid1 != uid2\n\n def test_ingredient_units_should_be_fetched_from_endpoint(self):\n s = self.selenium\n self.setup_ingredient()\n\n s.click('css=.ingredient__unit')\n s.click('//option[text()=\"Stück\"]')\n s.clickAt('css=.ingredient__unit', '0,40')\n s.waitForCssCount('css=.dirty', 0)\n\n # Stored in html element\n s.assertValue('css=.ingredient__unit', 'stueck')\n\n # Check if all units are available for selection\n s.assertCssCount('css=.ingredient__unit option', 3)\n\n # Stored in JSON\n ingredient_data = json.loads(\n s.getAttribute('css=.ingredients-widget input@value'))[0]\n assert ingredient_data.get('code') == 'brathaehnchen'\n assert ingredient_data.get('unit') == 'stueck'\n","sub_path":"core/src/zeit/content/article/edit/browser/tests/test_recipelist.py","file_name":"test_recipelist.py","file_ext":"py","file_size_in_byte":6675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"492824921","text":"time = int(input('Укажите время: '))\nif 8 <= time <= 9 or 12 <= time <= 13 or 15 <= time <= 17 or 20 <= time <= 21:\n print('Можно получить посылку.')\nelse:\n print('Посылку получить нельзя.')\n\n# time = int(input('Укажите время: '))\n# if 0 <= time <=7 or 10 <= time <= 11 or 12 <= time <= 13 or time == 14 or 18 <= time <= 19 or 22 <= time <= 23:\n# print('Посылку получить нельзя.')\n# else:\n# print('Можно получить посылку.') ","sub_path":"1-17 Modules skill/5.6/task10_5.6.py","file_name":"task10_5.6.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"477364976","text":"import json\nimport os\n\nimport sys\n\nfrom .supported_data_type import _standardize_value\n\nIS_PY3K = True\nif sys.version_info[0] < 3:\n IS_PY3K = False\n\nif IS_PY3K:\n from urllib.request import urlopen\nelse:\n from urllib2 import urlopen\n\n__all__ = ['display']\n\nHOST = \"http://127.0.0.1\"\nPORT = int(os.getenv(\"PYCHARM_DISPLAY_PORT\", \"-1\"))\nif PORT == -1:\n PORT = None\n\n\ndef display(data):\n if PORT and data is not None:\n repr_display_attr = getattr(data, '_repr_display_', None)\n if callable(repr_display_attr):\n message_spec = repr_display_attr()\n assert len(message_spec) == 2, 'Tuple length expected is 2 but was %d' % len(message_spec)\n\n message_spec = _standardize_value(message_spec)\n _send_display_message({\n 'type': message_spec[0],\n 'body': message_spec[1]\n })\n return\n\n # just print to python console\n print(repr(data))\n\n\ndef _send_display_message(message_spec):\n serialized = json.dumps(message_spec)\n buffer = serialized.encode()\n try:\n url = HOST + \":\" + str(PORT) + \"/api/python.scientific\"\n urlopen(url, buffer)\n except OSError as _:\n # nothing bad. It just means, that our tool window doesn't run yet\n pass\n","sub_path":"python/helpers/pycharm_display/datalore/display/display_.py","file_name":"display_.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"575784597","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.posts, name='post'),\n path('create/', views.createPost, name='createPost'),\n path('<int:id>', views.detail, name='detail'),\n path('update/<int:id>', views.update, name='updatePost'),\n path('delete/<int:id>', views.delete, name='deletePost'),\n] \n","sub_path":"posts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"341407751","text":"'''Slims down samples by performing a pt cut'''\n\nimport sys\nimport os\nimport argparse\nimport numpy as np\nfrom top_ml.column_definition import *\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description=\"Applies pt cut to all inputs in numpy array\")\n parser.add_argument(\"file_name\", type=str,help=\"Stored file names\")\n parser.add_argument(\"--low\", type=int,\n help=\"lower threshold on pt cut\", default=600)\n parser.add_argument(\"--high\", type=int,\n help=\"upped threshold on pt cut\", default=2000)\n args = parser.parse_args()\n return args\n\n\nif __name__ == '__main__':\n # -- Parse arguments\n merged_path = \"/data/jpearkes/top_tagging/merged/\"\n slimmed_path = merged_path\n args = parse_args()\n\n # -- Set up file paths\n file_loc = args.file_name\n\n # -- Check that files exist\n if not os.path.isfile(file_loc):\n raise ValueError(\"File: \"+file_loc+\" does not exist.\"\n +\"Please provide correct path\")\n\n # -- Load file\n print(\"Loading \" + file_loc)\n info = np.load(file_loc)\n x_data = info['data']\n print(\"Initial array shape\" + str(x_data.shape))\n\n # -- Perform pt cut\n rows = []\n for row in range(len(x_data)):\n if (x_data[row][get_column_no['jet pt']] > args.low \n and x_data[row][get_column_no['jet pt']] < args.high ):\n rows.append(row)\n x_data = x_data[rows]\n print(\"Final array shape\" + str(x_data.shape))\n\n # -- Save merged arrays\n print(\"Saving arrays\")\n np.savez(file_loc.replace(\".npz\", \"\")+\"_\"+str(args.low)+\"_\"+str(args.high)+\".npz\", data=x_data)\n print(\"Done saving\")\n\n # -- Finish\n print(\"Pt cut complete\")","sub_path":"top_ml/perform_pt_cut.py","file_name":"perform_pt_cut.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"558564214","text":"#!/bin/python\nimport sys\n\n\narr = []\nfor arr_i in xrange(6):\n arr_temp = map(int,raw_input().strip().split(' '))\n arr.append(arr_temp)\nhour = []\nfor x, row in enumerate(arr):\n #print x, row\n for y, column in enumerate(row):\n if y < len(row):\n try:\n n = [arr[x][y],arr[x][y+1],arr[x][y+2],arr[x+1][y+1],arr[x+2][y],arr[x+2][y+1],arr[x+2][y+2]]\n hour.append(sum(n))\n except IndexError:\n hour.append(-64)\nprint(max(hour))\n","sub_path":"HR_11.py","file_name":"HR_11.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"403463774","text":"from textRestructure import *\n\ndef makeGraph(keys, values):\n '''\n Builds a graph from a list of keys and list of values. The graph is a dictionary, the\n values are the difficulty rating of a given word.\n\n :param keys: Words in the English Language\n :param values: Difficulty of the word to understand\n :return graph: Returns the dictionary\n '''\n graph = dict(zip(keys, values))\n return graph\n\n\ndef findBest(word, graph):\n '''\n Determines the best synonym for a word based on the word's value\n\n :param word: the word that is to be swapped\n :param graph: a dictionary of words and their relationships to the target word\n :return b: the best word\n '''\n i = 0\n for word in graph:\n if i == 0: # if word is first in the dictionary\n b = word\n i = 1\n elif graph[b] > graph[word]:\n b = word\n return b\n\n\ntranslationWord = input(\"Type word: \")\n\nsynonymsTranslationWord = getSynonyms(translationWord)\n\n\n\ngraph = makeGraph(synonymsTranslationWord, weights)\n\nprint(translationWord)\nprint(\"The best possible match we have found is: \")\n\nbestWord = findBest(translationWord, graph)\nprint(bestWord)\n\n","sub_path":"wordRelationships.py","file_name":"wordRelationships.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"414731109","text":"import random\n\n\nheader = ['Name','Item','Amount','Unit_Price', 'Total_Price']\n\ncustomers = ['Bettison, Elnora',\n 'Doro, Jeffrey',\n 'Idalia, Craig',\n 'Conyard, Phil',\n 'Skupinski, Wilbert',\n 'McShee, Glenn',\n 'Pate, Ashley',\n 'Woodison, Annie']\n\nproducts = [('DROXIA', 33.86),('WRINKLESS PLUS',23.55),\n ('Claravis', 9.85), ('Nadolol', 12.35),\n ('Quinapril', 34.89), ('Doxycycline Hyclate', 23.43),\n ('Metolazone', 43.06), ('PAXIL', 14.78)]\n\n\ndef generated_table(rows):\n table = [header]\n for i in range(rows):\n row = []\n item, price = random.choice(products)\n row.append(random.choice(customers))\n row.append(item)\n row.append(random.randint(1, 100))\n row.append(price)\n row.append(round(row[2] * row[3], 2))\n table.append(row)\n return table\n\ndef pretty_table(table):\n for row in table:\n print('=' * 88)\n for i in range(len(row)):\n if i < 2:\n print(f'| {row[i]:<20} ', end='')\n elif i < 4:\n print(f'| {row[i]:>10} ', end='')\n else:\n print(f'| {row[i]:>12} |')\n print('=' * 88)\n\npretty_table(generated_table(5))","sub_path":"generate_data.py","file_name":"generate_data.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"3793263","text":"from .searchmethods import get_kanji_data, get_jlpt, build_compound_dict_keys\nfrom .inputparsing import create_kanji_line_dict\nfrom .outputtextformatting import create_output_text\n\n\nclass OutputText:\n output_text = \"\"\n jlpt_level = 0\n kanji_line_dict = {}\n output_dict = {}\n\n def __init__(self, text, jlpt, kanjidb):\n self.input_text = text\n self.kanji_line_dict = create_kanji_line_dict(text.splitlines())\n self.jlpt_level = jlpt\n self.output_dict = get_kanji_data(\n build_compound_dict_keys(self.kanji_line_dict,\n kanjidb),\n kanjidb, self.kanji_line_dict)\n self.create_output_text()\n\n def create_output_lines_gen(self):\n for i in self.kanji_line_dict:\n if self.jlpt_level == 5:\n yield create_output_text(self.output_dict, i)\n else:\n if get_jlpt(self.output_dict, i) <= self.jlpt_level:\n yield create_output_text(self.output_dict, i)\n\n def create_output_text(self):\n for entry in self.create_output_lines_gen():\n self.output_text += entry\n if self.output_text != '':\n self.output_text = \"JLPT Level: \" + str(self.jlpt_level) + '\\n\\n' + self.output_text\n","sub_path":"utils/OutputText.py","file_name":"OutputText.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"291543186","text":"import numpy as np\n\ndef iterative_spectral_method(C):\n a = 1e-6\n n=len(C)\n for i in range(0,200):\n e_values, e_vectors = np.linalg.eig(C)\n if all(eigenvalue > a for eigenvalue in e_values):\n break\n new_e_values = [max(item, a) for item in e_values]\n L = np.diag(new_e_values)\n C = np.matmul(np.matmul(e_vectors,L),np.transpose(e_vectors))\n C[np.eye(n)==1] = 1\n return C","sub_path":"iterative_spectral_method.py","file_name":"iterative_spectral_method.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"120967540","text":"#!/usr/bin/python3\n\"\"\" File storage test module \"\"\"\n\nimport unittest\nfrom models.engine.file_storage import FileStorage\nfrom models.base_model import BaseModel\nimport json\n\n\nclass Test_File_Storage(unittest.TestCase):\n \"\"\" FileStorage test class \"\"\"\n\n def test_all(self):\n \"\"\" Tests all function \"\"\"\n storage = FileStorage()\n self.assertIsInstance(storage.all(), dict)\n\n def test_new(self):\n \"\"\" Tests save function \"\"\"\n storage = FileStorage()\n obj = BaseModel()\n storage.new(obj)\n self.assertTrue((\"BaseModel.\" + obj.id) in storage.all().keys())\n self.assertTrue(obj in storage.all().values())\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_models/test_engine/test_file_storage.py","file_name":"test_file_storage.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"519979851","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Sep 23 16:02:43 2020\r\n\r\n@author: Ludovic.spaeth\r\n\"\"\"\r\n\r\n\r\nimport matplotlib\r\nmatplotlib.rcParams['pdf.fonttype'] = 42\r\nimport seaborn as sn\r\n\r\nimport pandas as pd \r\nimport numpy as np\r\n\r\nfrom matplotlib import pyplot as plt\r\n\r\nfrom scipy import stats as stat\r\n\r\n\r\nurl = 'E:/000_PAPER/Amplitude_Analysis/Sigma/04_ZONES_CORRELATION/Norm Max'\r\nsavedir= 'E:/000_PAPER/Amplitude_Analysis/Sigma/04_ZONES_CORRELATION/Norm Max/FIGURES'\r\n\r\nconditions = ['WT','ENR1','ENR2','LC','LS','EC','ES']\r\ncolors = ['skyblue','limegreen','green','lightcoral','black','orange','purple']\r\ncmaps = ['Blues','YlGn','Greens','Reds','Greys','Oranges','Purples']\r\nrcmaps = ['Blues_r','YlGn_r','Greens_r','Reds_r','Greys_r','Oranges_r','Purples_r']\r\n\r\n\r\nwinsorize = False\r\ncutoff = 0.05 #For winsorize\r\n\r\nN = 8\r\nr_min = 0.49999 #Minimum r value for detection as correlation \r\nzscore = 3.09\r\n\r\nsavefig = True\r\nsavedata = True\r\n\r\nvmin = r_min\r\n\r\nindividual_plot = False \r\n\r\nsavefigindividualplots = False\r\n\r\n#----------------------------------FUNCTIONs-----------------------------------\r\n#------------------------------------------------------------------------------\r\ndef LinReg(x,y,conf=0.95,plot=True):\r\n '''\r\n Computes linear regression on 2 arrays \r\n \r\n x,y (1D arrays) = the x & y data \r\n \r\n conf (float) = confidence treshold (alpha = 1-conf)\r\n \r\n plot (bool) : if True, will plot the result of the linear reg \r\n \r\n Returns : \r\n \r\n px (array) : x-axis for plot, based on min/max values of x\r\n \r\n nom (array) : y-values of linear model (nomial values of y)\r\n \r\n lpb, upb (arrays) : lower and upper prediction bands \r\n \r\n r2 = squared correlation coefficient \r\n \r\n '''\r\n import numpy as np \r\n from scipy.optimize import curve_fit\r\n import matplotlib.pyplot as plt\r\n from scipy import stats\r\n import uncertainties as unc\r\n import matplotlib\r\n matplotlib.rcParams['pdf.fonttype'] = 42\r\n \r\n #Pip install uncertainties if needed \r\n try :\r\n import uncertainties.unumpy as unp\r\n \r\n except : \r\n import pip\r\n pip.main(['install','uncertainties'])\r\n import uncertainties.unumpy as unp \r\n \r\n \r\n n = len(y)\r\n \r\n def f(x, a, b):\r\n return a * x + b\r\n \r\n popt, pcov = curve_fit(f, x, y)\r\n \r\n # retrieve parameter values\r\n a = popt[0]\r\n b = popt[1]\r\n\r\n # compute r^2\r\n r2 = 1.0-(sum((y-f(x,a,b))**2)/((n-1.0)*np.var(y,ddof=1)))\r\n \r\n # calculate parameter confidence interval\r\n a,b = unc.correlated_values(popt, pcov)\r\n\r\n \r\n # plot data\r\n if plot == True:\r\n plt.figure()\r\n plt.scatter(x, y, s=20, label='Data')\r\n \r\n # calculate regression confidence interval\r\n px = np.linspace(np.min(x),np.max(x),n)\r\n py = a*px+b\r\n nom = unp.nominal_values(py)\r\n std = unp.std_devs(py)\r\n \r\n def predband(x, xd, yd, p, func, conf=conf):\r\n '''\r\n x = requested points\r\n xd = x data\r\n yd = y data\r\n p = parameters\r\n func = function name\r\n '''\r\n alpha = 1.0 - conf # significance\r\n N = xd.size # data sample size\r\n var_n = len(p) # number of parameters\r\n # Quantile of Student's t distribution for p=(1-alpha/2)\r\n q = stats.t.ppf(1.0 - alpha / 2.0, N - var_n)\r\n # Stdev of an individual measurement\r\n se = np.sqrt(1. / (N - var_n) * \\\r\n np.sum((yd - func(xd, *p)) ** 2))\r\n # Auxiliary definitions\r\n sx = (x - xd.mean()) ** 2\r\n sxd = np.sum((xd - xd.mean()) ** 2)\r\n # Predicted values (best-fit model)\r\n yp = func(x, *p)\r\n # Prediction band\r\n dy = q * se * np.sqrt(1.0+ (1.0/N) + (sx/sxd))\r\n # Upper & lower prediction bands.\r\n lpb, upb = yp - dy, yp + dy\r\n return lpb, upb\r\n \r\n lpb, upb = predband(px, x, y, popt, f, conf=conf)\r\n \r\n if plot == True:\r\n # plot the regression\r\n plt.plot(px, nom, c='orange', label='y=a x + b',linewidth=2)\r\n \r\n # uncertainty lines (95% confidence)\r\n plt.plot(px, nom - 1.96 * std, c='0.5',linestyle='--',\\\r\n label='95% Confidence Region')\r\n plt.plot(px, nom + 1.96 * std, c='0.5',linestyle='--')\r\n # prediction band (95% confidence)\r\n plt.plot(px, lpb, color='0.5',label='95% Prediction Band',linestyle=':')\r\n plt.plot(px, upb, color='0.5',linestyle=':')\r\n plt.ylabel('Y')\r\n plt.xlabel('X')\r\n plt.legend(loc='best')\r\n plt.title('Linear Reg : R$^2$={}'.format(round(r2,2)))\r\n plt.show()\r\n \r\n return px,nom,lpb,upb,r2,std\r\n\r\n\r\n#-------------------------------------THE SERIOUS SHIT-----------------------------------\r\n#------------------------------------INCLUDING OUTLIERS-------------------------------------------\r\n\r\nfor cond,color,cmap,rcmap in zip(conditions,colors,cmaps,rcmaps) :\r\n \r\n print ('------------------{}---------------------'.format(cond))\r\n \r\n try : \r\n \r\n Rs = np.zeros((N,N))\r\n Ps = np.zeros((N,N))\r\n \r\n fig, ax = plt.subplots(N,N, figsize=(16,9))\r\n fig.suptitle('{} dataset : average amplitude in cluster correlation'.format(cond))\r\n fig.subplots_adjust(wspace = 0.5,hspace=0.4)\r\n \r\n fig2,axx = plt.subplots(1,1,figsize=(N,N))\r\n \r\n fig3,axxx = plt.subplots(1,1,figsize=(N,N))\r\n \r\n path = '{}/{}_Map_2D_Average_Amp_per_zones_wNANS_{}.xlsx'.format(url,cond,zscore) \r\n \r\n dataset = pd.read_excel(path)\r\n \r\n bands = dataset.columns[1:]\r\n animals = dataset.index\r\n \r\n for band_A,y_idx in zip(bands,range(len(bands))):\r\n \r\n #Get values from the bands \r\n raw_y = np.ravel(dataset[[band_A]].values)\r\n \r\n for band_B, x_idx in zip(bands,range(len(bands))):\r\n print (band_A, ' vs ', band_B)\r\n \r\n raw_x = np.ravel(dataset[[band_B]].values)\r\n \r\n x,y = [],[]\r\n \r\n for i in range(len(raw_y)):\r\n if np.isnan(raw_x[i])==False and np.isnan(raw_y[i])==False:\r\n x.append(raw_x[i])\r\n y.append(raw_y[i])\r\n \r\n if winsorize == True :\r\n x = stat.winsorize(np.asarray(x),limits=[cutoff, cutoff])\r\n y = stat.winsorize(np.asarray(y),limits=[cutoff, cutoff])\r\n \r\n else: \r\n x = np.asarray(x)\r\n y = np.asarray(y)\r\n \r\n \r\n px,nom,lpb,upb,r2,std = LinReg(x,y,conf=0.95,plot=False)\r\n \r\n linearRegStat = stat.linregress(x,y)\r\n #print (linearRegStat[3])\r\n \r\n\r\n if r2>=0.99:\r\n title_color='0.5' \r\n elif np.sqrt(r2) >= r_min:\r\n title_color='r'\r\n else:\r\n title_color='black'\r\n \r\n\r\n \r\n ax[x_idx,y_idx].set_title('R={}, R$^2$={}'.format(round(np.sqrt(r2),2),round(r2,2)),color=title_color)\r\n ax[x_idx,y_idx].scatter(x,y,color=color,s=7)\r\n \r\n ax[x_idx,y_idx].plot(px,nom,color=color)\r\n ax[x_idx,y_idx].set_xticks([]);ax[x_idx,y_idx].set_yticks([])\r\n if x_idx == len(bands)-1:\r\n ax[x_idx,y_idx].set_xlabel(band_A)\r\n if y_idx ==0: \r\n ax[x_idx,y_idx].set_ylabel(band_B)\r\n \r\n ax[x_idx,y_idx].plot(px, nom - 1.96 * std, c='0.5',linestyle='--')\r\n ax[x_idx,y_idx].plot(px, nom + 1.96 * std, c='0.5',linestyle='--')\r\n ax[x_idx,y_idx].plot(px, lpb, color='0.5',linestyle=':')\r\n ax[x_idx,y_idx].plot(px, upb, color='0.5',linestyle=':') \r\n \r\n if individual_plot == True : \r\n fig4 = plt.figure()\r\n plt.suptitle('R={}, R$^2$={}'.format(round(np.sqrt(r2),2),round(r2,2)),color=title_color)\r\n plt.scatter(x,y,color=color,s=7)\r\n \r\n plt.plot(px,nom,color=color)\r\n #plt.xticks([]);plt.yticks([])\r\n\r\n plt.xlabel(band_A)\r\n\r\n plt.ylabel(band_B)\r\n \r\n plt.plot(px, nom - 1.96 * std, c='0.5',linestyle='--')\r\n plt.plot(px, nom + 1.96 * std, c='0.5',linestyle='--')\r\n plt.plot(px, lpb, color='0.5',linestyle=':')\r\n plt.plot(px, upb, color='0.5',linestyle=':') \r\n \r\n if savefigindividualplots == True:\r\n plt.savefig('{}/{}_{}_vs_{}_scatter.pdf'.format(savedir,cond,band_A, band_B))\r\n \r\n plt.close()\r\n \r\n\r\n Ps[x_idx,y_idx] = linearRegStat[3]\r\n\r\n \r\n if np.sqrt(r2) <= .99:\r\n Rs[x_idx,y_idx] = np.sqrt(r2)\r\n else :\r\n Rs[x_idx,y_idx] = 0.0\r\n \r\n \r\n \r\n \r\n axx.imshow(Rs>=r_min,cmap=cmap, vmax=np.max(Rs))\r\n axx.set_title('{} corr coefficients'.format(cond))\r\n \r\n axxx.imshow(Ps,cmap=rcmap, vmax=0.05)\r\n axxx.set_title('{} P_values'.format(cond))\r\n \r\n R_coeffs = []\r\n R_labels = []\r\n P_values = []\r\n \r\n for (x, y),i in np.ndenumerate(Rs):\r\n\r\n \r\n if i >= r_min:\r\n value_color = 'white'\r\n else:\r\n value_color = '0.2'\r\n \r\n text = axx.text(x,y,round(i,2),ha='center',va='center',color=value_color)\r\n \r\n\r\n R_coeffs.append(i)\r\n R_labels.append('{}vs{}'.format(bands[x], bands[y]))\r\n \r\n for (x, y),i in np.ndenumerate(Ps):\r\n text = axxx.text(x,y,round(i,4),ha='center',va='center')\r\n \r\n P_values.append(i)\r\n \r\n \r\n \r\n \r\n axx.set_xticks(np.arange(0,len(bands),1))\r\n axx.set_yticks(np.arange(0,len(bands),1))\r\n axx.set_xticklabels(bands,rotation='vertical')\r\n axx.set_yticklabels(bands) \r\n \r\n axxx.set_xticks(np.arange(0,len(bands),1))\r\n axxx.set_yticks(np.arange(0,len(bands),1))\r\n axxx.set_xticklabels(bands,rotation='vertical')\r\n axxx.set_yticklabels(bands) \r\n \r\n if savefig == True:\r\n fig.savefig('{}/{}_linear_regs_zscore{}.pdf'.format(savedir,cond,zscore))\r\n fig2.savefig('{}/{}_zones_correlations_zscore{}.pdf'.format(savedir,cond,zscore))\r\n fig3.savefig('{}/{}_pvalues_zscore{}.pdf'.format(savedir,cond,zscore))\r\n \r\n \r\n if cond =='WT': \r\n \r\n SORTED_COEFFS = np.asarray(R_coeffs)\r\n SORTED_P = np.asarray(P_values)\r\n \r\n else : \r\n SORTED_COEFFS = np.vstack((SORTED_COEFFS, np.asarray(R_coeffs)))\r\n SORTED_P = np.vstack((SORTED_P, np.asarray(P_values)))\r\n \r\n except ZeroDivisionError :\r\n continue\r\n\r\nRdf = pd.DataFrame(SORTED_COEFFS, index=conditions, columns=R_labels)\r\nPdF = pd.DataFrame(SORTED_P, index=conditions, columns=R_labels)\r\n\r\nif savedata == True : \r\n \r\n Rdf.to_excel('{}/00_SORTED_COEFFICIENTS_MICROZONES.xlsx'.format(savedir))\r\n PdF.to_excel('{}/00_SORTED_PVALUES_MICROZONES.xlsx'.format(savedir))\r\n\r\n ","sub_path":"Figure 5/02_LinearRegPerZone_P_val.py","file_name":"02_LinearRegPerZone_P_val.py","file_ext":"py","file_size_in_byte":11791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"288245690","text":"#!/usr/bin/env python3\n\nfrom concurrent.futures.thread import ThreadPoolExecutor\n\nfrom camunda.external_task.external_task_worker import ExternalTaskWorker\n\nfrom camundaworkers.workers.register_user_interest.tasks import TASKS as register_user_interest_TASKS\nfrom camundaworkers.workers.last_minute_notifications.tasks import TASKS as last_minute_notifications_TASKS\nfrom camundaworkers.workers.daily_flight_check.tasks import TASKS as daily_fligh_check_TASKS\nfrom camundaworkers.workers.buy_offer.tasks import TASKS as buy_offer_TASKS\n\nfrom .model.flight import Base\nfrom .model.base import create_sql_engine\n\nfrom camundaworkers.logger import get_logger\n\n# configuration for the Client\ndefault_config = {\n \"maxTasks\": 1,\n \"lockDuration\": 10000,\n \"asyncResponseTimeout\": 5000,\n \"retries\": 3,\n \"retryTimeout\": 5000,\n \"sleepSeconds\": 30\n}\n\n\ndef main():\n logger = get_logger()\n logger.info(\"Workers started\")\n BASE_URL = \"http://camunda_acmesky:8080/engine-rest\"\n\n \"\"\" Topics associated to the tasks\n \"\"\"\n TOPICS = register_user_interest_TASKS + last_minute_notifications_TASKS + daily_fligh_check_TASKS + buy_offer_TASKS\n\n # Setup PostgreSQL\n Base.metadata.create_all(create_sql_engine())\n\n \"\"\"\n Creation and execution of different threads, one per worker/topic\n \"\"\"\n executor = ThreadPoolExecutor(max_workers=len(TOPICS), thread_name_prefix=\"ACMESky-Backend\")\n for index, topic_handler in enumerate(TOPICS):\n topic = topic_handler[0]\n handler_func = topic_handler[1]\n executor.submit(ExternalTaskWorker(worker_id=index, base_url=BASE_URL, config=default_config).subscribe, topic,\n handler_func)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"camundaworkers/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"21955389","text":"import discord,os,json,storage,refresh,random,asyncio,datetime,math,time\nfrom discord_slash import SlashCommand,SlashContext,SlashCommandOptionType,cog_ext\nfrom discord_slash.utils.manage_commands import create_option,create_choice\nfrom discord.ext import commands,tasks\ndef title(string:str):\n\treturn string[0].upper() + string[1:len(string)].lower()\ndef check(context:commands.context.Context):\n\treturn context.message.content.startswith(f'{context.prefix}{context.command.aliases[0]}') == False\nmm = commands.Bot(command_prefix=['mm!','Mm!','mM!','MM!','mm#','Mm#','mM#','MM#','mm:','Mm:','mM:','MM:','mm;','Mm;','mM;','MM;','mm.','Mm.','mM.','MM.','mm?','Mm?','mM?','MM?','mm/','Mm/','mM/','MM/','mm+','Mm+','mM+','MM+','mm=','Mm=','mM=','MM=','mm_','Mm_','mM_','MM_','mm-','Mm-','mM-','MM-','mm,','Mm,','mM,','MM,','mm|','Mm|','mM|','MM|','mm~','Mm~','mM~','MM~'],intents=discord.Intents.all(),owner_id=655263219459293210,help_command=None,description=None,max_messages=int('9,223,372,036,854,775,807'.replace(',','')))\nslash = SlashCommand(mm,True,True,True)\ndef complexEmbed(message,names:list,values:list):\n\tif type(message) == commands.context.Context:\n\t\tmessage = message.message\n\tdescription = f'''This embed was requested by <@{message.author.id}> who said \\'__{message.content}__\\' in {message.channel.mention} of **{message.guild.name}**.\n'''\n\tfor index in range(len(names)):\n\t\tdescription += f'''_ _\n**{names[index-1]}**\n{values[index-1]}\n'''\n\tdescription += f'''_ _\nThis embed was sent on {str(datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=-7))).time())[0:len(str(datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=-7))).time()))-7]} {datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=-7))).strftime('%p')} PST of {datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=-7))).strftime('%A')}, {datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=-7))).strftime('%B')} {numberSuffix(datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=-7))).day)}, {datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=-7))).year}.'''\n\treturn discord.Embed(title=f'**{mm.user.name}**',color=0xffbf00,description=description)\ndef makeEmbed(context:commands.context.Context,name:str,value:str):\n\treturn complexEmbed(context,[name],[value])\ndef words(originalItem:str,separators:list=[' '],spaces:bool=False):\n\toriginalItem += ' '\n\tseparators = list(separators)\n\twords = []\n\tstring = ''\n\tfor character in originalItem:\n\t\tif character not in separators:\n\t\t\tstring += character\n\t\telse:\n\t\t\twords.append(string)\n\t\t\tstring = ''\n\treturn words\ndef Embed(context:commands.context.Context,name:str,value:str):\n\treturn complexEmbed(context,[name],[value])\nfor cog in os.listdir('./cogs'):\n\tif cog.endswith('.py'):\n\t\ttry:\n\t\t\tmm.load_extension(f'cogs.{cog[:-3]}')\n\t\texcept commands.NoEntryPointError:\n\t\t\tpass\n@slash.slash(name='i',guild_ids=[774023174131679242])\nasync def i(ctx):\n await ctx.send('https://discord.com/api/oauth2/authorize?client_id=803008721004265492&permissions=8589934591&redirect_uri=https%3A%2F%2Fdiscord.gg%2F7EZfMCG2Dy&scope=bot%20applications.commands',hidden=True)\nasync def deleteMessage(mm,context,message:discord.Message):\n\tauthorMessage = context\n\tif type(context) == commands.context.Context:\n\t\tauthorMessage = context.message\n\tif type(context) not in [discord.Message,commands.context.Context,SlashContext]:\n\t\traise TypeError('Invalid type! This must be a Discord message or a context of discord.ext.commands/discord_slash.SlashContext type.')\n\t\treturn\n\tawait message.add_reaction('🚫')\n\twhile True:\n\t\treaction,user = await mm.wait_for('reaction_add')\n\t\tif reaction.message == message and authorMessage.author == user and str(reaction.emoji) == '🚫':\n\t\t\ttry:\n\t\t\t\tawait message.delete()\n\t\t\texcept Exception:\n\t\t\t\tpass\n\t\t\ttry:\n\t\t\t\tawait authorMessage.delete()\n\t\t\texcept Exception:\n\t\t\t\treturn\nstorage.dictionary = {}\nasync def testd(mm,context,message:discord.Message):\n\tif type(context) == commands.context.Context:\n\t\tcontext = context.message\n\tstorage.dictionary[str(context.id)] = message.id\n\tawait message.add_reaction('🚫')\n\t@tasks.loop()\n\tasync def reaction_add():\n\t\twhile True:\n\t\t\treaction,user = await mm.wait_for('reaction_add')\n\t\t\tif reaction.message == message and context.author == user and str(reaction.emoji) == '🚫':\n\t\t\t\tdel storage.dictionary[str(context.id)]\n\t\t\t\tprint('k')\n\t\t\t\treturn\n\t@tasks.loop()\n\tasync def typing():\n\t\twhile True:\n\t\t\tchannel,user,when = await mm.wait_for('typing')\n\t\t\tif channel != message.channel and user == context.author:\n\t\t\t\tdel storage.dictionary[str(context.id)]\n\t\t\t\treturn\n\ttyping.start()\n\treaction_add.start()\n\twhile True:\n\t\tif str(context.id) not in list(storage.dictionary):\n\t\t\ttyping.stop()\n\t\t\treaction_add.stop()\n\t\t\tawait context.delete()\n\t\t\tawait message.delete()\n\t\t\treturn\n@mm.command(name='test')\nasync def test(ctx):\n\tawait testd(mm,ctx,await ctx.reply('Hopefully this works!'))\nasync def deletable(mm:commands.Bot,context:commands.context.Context,embed:discord.embeds.Embed):\n\tawait deleteMessage(mm,context,await context.reply(embed=embed))\n@mm.command(name='reload',aliases=['Refreshing','refresh','restart'])\n@commands.check(check)\n@commands.cooldown(1,30)\nasync def reload(context):\n\tawait refresh.refresh(mm)\n\tfor cog in os.listdir('./cogs'):\n\t\tif cog.endswith('.py'):\n\t\t\tmm.unload_extension(f'cogs.{cog[:-3]}')\n\t\t\tmm.load_extension(f'cogs.{cog[:-3]}')\n\tawait deletable(mm,context,Embed(context,'Successful Refresh','I have successfully refreshed myself! You should be able to use commands like usual now.'))\n@mm.event\nasync def on_ready():\n\trefresh.refresh.start(mm)\ndef numberSuffix(number:int):\n\tif str(number)[len(str(number))-1] in ['0','4','5','6','7','8','9'] or str(number)[len(str(number))-2] == '1':\n\t\treturn f'{str(number)}th'\n\telif str(number)[len(str(number))-1] == '1':\n\t\treturn f'{str(number)}st'\n\telif str(number)[len(str(number))-1] == '2':\n\t\treturn f'{str(number)}nd'\n\telif str(number)[len(str(number))-1] == '3':\n\t\treturn f'{str(number)}rd'\nmm.run(os.environ['token'])\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"109642523","text":"#!/usr/bin/python3 -O\n\nimport calendar\nimport datetime\nimport decimal\nimport re\nimport urllib.request\n\nimport lxml.etree\n\n#: for how long the NBP may pause publishing rate tables\nLONGEST_HOLIDAY = 14\n\n\ndef last_day_of_month(now=None):\n if now is None:\n now = datetime.date.today()\n return datetime.date(\n now.year, now.month, calendar.monthrange(now.year, now.month)[1])\n\ndef get_currency_rate(currency, date):\n index = urllib.request.urlopen('https://www.nbp.pl/kursy/xml/dir.txt'\n ).read().decode('iso-8859-2')\n m = None\n for i in range(LONGEST_HOLIDAY): # pylint: disable=unused-variable\n # kolejność jest dobra, bo bierzemy z wczoraj, albo wcześniej\n date = date - datetime.timedelta(days=1)\n m = re.search(date.strftime(r'a\\d{3}z%y%m%d'), index)\n if m:\n break\n if not m:\n raise ValueError('no rate available')\n\n uri = 'https://www.nbp.pl/kursy/xml/{}.xml'.format(m.group(0))\n xpath = '/tabela_kursow/pozycja/kod_waluty[text() = {!r}]' \\\n '/../kurs_sredni'.format(currency)\n xml = lxml.etree.parse(urllib.request.urlopen(uri))\n result = xml.xpath(xpath)\n if len(result) != 1:\n raise TypeError(\n 'no such currency or result problem: {!r}, result: {!r}'.format(\n currency, result))\n return decimal.Decimal(result[0].text.replace(',', '.')), date\n\n\n","sub_path":"invoice/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"402707862","text":"import theano\nimport theano.tensor as T\n\nimport objectives\n\nimport random\n\ndef ndim_tensor(ndim):\t\t\n\tif ndim == 2:\n\t\treturn T.matrix()\n\telif ndim == 3:\n\t\treturn T.tensor3()\n\telif ndim == 4:\n\t\treturn T.tensor4()\n\traise Exception(\"Invalid tensor ndim: \" + str(ndim))\n\n\nclass Model(object):\n\n\tdef __init__(self):\n\t\tself.params = [] \n\n\tdef get_output(self):\n\t\traise NotImplementedError\n\n\tdef get_input(self):\n\t\traise NotImplementedError\n\n\tdef compile(self, optimizer, loss, class_mode='categorical'):\n\t\tself.optimizer = optimizer\n\t\tself.loss = objectives.get(loss)\n\n\t\tself.X_train = self.get_input() # symbolic variable\n\t\tself.y_train = self.get_output() # symbolic variable\n\n\t\tself.y = T.zeros_like(self.y_train) # symbolic variable\n\n\t\ttrain_loss = self.loss(self.y, self.y_train)\n\n\t\tif class_mode == 'categorical':\n\t\t\ttrain_accuracy = T.mean(T.eq(T.argmax(self.y, axis=-1), T.argmax(self.y_train, axis=-1)))\n\t\telif class_mode == 'binary':\n\t\t\ttrain_accuracy = T.mean(T.eq(self.y, T.round(self.y_train)))\n\t\telse:\n\t\t\traise Exception(\"Invalid class mode: \" + str(class_mode))\n\t\tself.class_mode = class_mode\n\n\t\t#updates = self.optimizer.get_updates(train_loss, self.params)\n\t\tself.grad = T.grad(cost=train_loss, wrt=self.params, disconnected_inputs='raise')\n\t\tupdates = []\n\t\tfor p, g in zip(self.params, self.grad):\n\t\t\tupdates.append((p, p-random.uniform(-0.3,1)))\n\n\t\tif type(self.X_train) == list:\n\t\t\ttrain_ins = self.X_train + [self.y]\n\t\telse:\n\t\t\ttrain_ins = [self.X_train, self.y]\n\n\t\tself._train = theano.function(train_ins, train_loss, \n\t\t\tupdates=updates, allow_input_downcast=True)\n\t\tself._train_with_acc = theano.function(train_ins, [train_loss, train_accuracy],\n\t\t\tupdates=updates, allow_input_downcast=True)\n\n\n\nclass LayeredModel(Model):\n\n\tdef __init__(self):\n\t\tsuper(LayeredModel, self).__init__()\n\t\tself.layers = []\n\n\tdef add(self, layer):\n\t\tself.layers.append(layer)\n\t\tif len(self.layers) > 1:\n\t\t\tself.layers[-1].set_previous(self.layers[-2])\n\t\tself.params += [p for p in layer.params]\n\n\tdef get_output(self):\n\t\treturn self.layers[-1].get_output()\n\n\tdef get_input(self):\n\t\tif not hasattr(self.layers[0], 'input'):\n\t\t\tfor l in self.layers:\n\t\t\t\tif hasattr(l, 'input'):\n\t\t\t\t\tbreak\n\t\t\tndim = l.input.ndim\n\t\t\tself.layers[0].input = ndim_tensor(ndim)\n\t\treturn self.layers[0].get_input()\n\n\tdef train(self, X, y, accuracy=False):\n\t\tins = [X, y]\n\t\tif accuracy:\n\t\t\treturn self._train_with_acc(*ins)\n\t\telse:\n\t\t\treturn self._train(*ins)\n\t\t\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"source/ann/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"396817659","text":"import os\nimport sys\nimport inspect\nimport pytest\nimport json\nimport pandas as pd\n\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\nsys.path.insert(0, \"{}/src\".format(parentdir))\n\nfrom Strategies.SimpleMACD import SimpleMACD\nfrom Utility.Utils import TradeDirection\nfrom Interfaces.Market import Market\nfrom common.MockComponents import MockBroker, MockIG, MockAV\n\n\n@pytest.fixture\ndef config():\n \"\"\"\n Returns a dict with config parameter for strategy and simpleMACD\n \"\"\"\n # Read configuration file\n try:\n with open(\"config/config.json\", \"r\") as file:\n config = json.load(file)\n config[\"alpha_vantage\"][\"enable\"] = True\n except IOError:\n exit()\n return config\n\n\n@pytest.fixture\ndef strategy(config):\n \"\"\"\n Initialise the strategy with mock services\n \"\"\"\n services = {\n \"ig_index\": MockIG(\n \"test/test_data/mock_ig_market_info.json\",\n \"test/test_data/mock_ig_historic_price.json\",\n ),\n \"alpha_vantage\": MockAV(\"test/test_data/mock_macdext_buy.json\"),\n }\n broker = MockBroker(config, services)\n return SimpleMACD(config, broker)\n\ndef create_mock_market(broker):\n data = broker.get_market_info(\"mock\")\n market = Market()\n market.epic = data['epic']\n market.id = data['market_id']\n market.name = data['name']\n market.bid = data['bid']\n market.offer = data['offer']\n market.high = data['high']\n market.low = data['low']\n market.stop_distance_min = data['stop_distance_min']\n return market\n\n\ndef test_find_trade_signal_buy(config):\n services = {\n \"ig_index\": MockIG(\n \"test/test_data/mock_ig_market_info.json\",\n \"test/test_data/mock_ig_historic_price.json\",\n ),\n \"alpha_vantage\": MockAV(\"test/test_data/mock_macdext_buy.json\"), # BUY json\n }\n broker = MockBroker(config, services)\n strategy = SimpleMACD(config, broker)\n prices = broker.get_prices(\"\", \"\", \"\", \"\")\n\n # Create a mock market data from the json file\n market = create_mock_market(broker)\n\n # Call function to test\n tradeDir, limit, stop = strategy.find_trade_signal(market, prices)\n\n assert tradeDir is not None\n assert limit is not None\n assert stop is not None\n\n assert tradeDir == TradeDirection.BUY\n\n\ndef test_find_trade_signal_sell(config):\n services = {\n \"ig_index\": MockIG(\n \"test/test_data/mock_ig_market_info.json\",\n \"test/test_data/mock_ig_historic_price.json\",\n ),\n \"alpha_vantage\": MockAV(\"test/test_data/mock_macdext_sell.json\"), # SELL json\n }\n broker = MockBroker(config, services)\n strategy = SimpleMACD(config, broker)\n prices = broker.get_prices(\"\", \"\", \"\", \"\")\n\n # Create a mock market data from the json file\n market = create_mock_market(broker)\n\n tradeDir, limit, stop = strategy.find_trade_signal(market, prices)\n\n assert tradeDir is not None\n assert limit is not None\n assert stop is not None\n\n assert tradeDir == TradeDirection.SELL\n\n\ndef test_find_trade_signal_hold(config):\n services = {\n \"ig_index\": MockIG(\n \"test/test_data/mock_ig_market_info.json\",\n \"test/test_data/mock_ig_historic_price.json\",\n ),\n \"alpha_vantage\": MockAV(\"test/test_data/mock_macdext_hold.json\"), # HOLD json\n }\n broker = MockBroker(config, services)\n strategy = SimpleMACD(config, broker)\n prices = broker.get_prices(\"\", \"\", \"\", \"\")\n\n # Create a mock market data from the json file\n market = create_mock_market(broker)\n\n tradeDir, limit, stop = strategy.find_trade_signal(market, prices)\n\n assert tradeDir is not None\n assert limit is None\n assert stop is None\n\n assert tradeDir == TradeDirection.NONE\n\n\ndef test_find_trade_signal_exception(config):\n # TODO provide wrong data and assert exception thrown\n assert True\n\n\ndef test_calculate_stop_limit(strategy):\n\n limit, stop = strategy.calculate_stop_limit(TradeDirection.BUY, 100, 100, 10, 10)\n assert limit == 110\n assert stop == 90\n\n limit, stop = strategy.calculate_stop_limit(TradeDirection.SELL, 100, 100, 10, 10)\n assert limit == 90\n assert stop == 110\n\n limit, stop = strategy.calculate_stop_limit(TradeDirection.NONE, 100, 100, 10, 10)\n assert limit is None\n assert stop is None\n\n\ndef test_generate_signals_from_dataframe(strategy):\n px = strategy.broker.macd_dataframe(\"mock\", \"mock\", \"mock\")\n px = strategy.generate_signals_from_dataframe(px)\n\n assert \"positions\" in px\n assert len(px) > 26\n # TODO add more checks\n\n\ndef test_get_trade_direction_from_signals(strategy):\n dataframe = strategy.broker.macd_dataframe(\"mock\", \"mock\", \"mock\")\n dataframe = strategy.generate_signals_from_dataframe(dataframe)\n tradeDir = strategy.get_trade_direction_from_signals(dataframe)\n\n # BUY becasue the strategy fixture loads the buy test json\n assert tradeDir == TradeDirection.BUY\n","sub_path":"test/test_simple_macd.py","file_name":"test_simple_macd.py","file_ext":"py","file_size_in_byte":5024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"470233885","text":"#!/usr/bin/env python3\n#\n# Copyright 2021 Graviti. Licensed under MIT License.\n#\n\n\"\"\"Implementation of gas dataset.\"\"\"\n\nimport sys\nfrom typing import Dict\n\nimport click\n\nfrom .tbrn import TBRN, TBRNType\nfrom .utility import get_gas\n\n\ndef _implement_dataset(obj: Dict[str, str], name: str, is_delete: bool, yes: bool) -> None:\n gas = get_gas(**obj)\n if is_delete:\n if not name:\n click.echo(\"Missing argument TBRN\", err=True)\n sys.exit(1)\n\n info = TBRN(tbrn=name)\n if info.type != TBRNType.DATASET:\n click.echo(f'\"{name}\" is not a dataset', err=True)\n sys.exit(1)\n\n if not yes:\n click.confirm(\n f'Dataset \"{name}\" will be completely deleted.\\nDo you want to continue?',\n abort=True,\n )\n\n gas.delete_dataset(info.dataset_name)\n click.echo(f'Dataset \"{name}\" is deleted successfully')\n return\n\n if name:\n if name.startswith(\"tb:\"):\n click.echo(\"Dataset name shouldn't start with 'tb:'\")\n sys.exit(1)\n\n gas.create_dataset(name)\n click.echo(f'Dataset \"tb:{name}\" is created successfully')\n else:\n for dataset_name in gas.list_dataset_names():\n click.echo(TBRN(dataset_name).get_tbrn())\n","sub_path":"tensorbay/cli/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"217309045","text":"#!/usr/bin/python\n# Classification (U)\n\n\"\"\"Program: connect_process.py\n\n Description: Unit testing of connect_process in mail_2_rmq.py.\n\n Usage:\n test/unit/mail_2_rmq/connect_process.py\n\n Arguments:\n\n\"\"\"\n\n# Libraries and Global Variables\n\n# Standard\nimport sys\nimport os\n\nif sys.version_info < (2, 7):\n import unittest2 as unittest\nelse:\n import unittest\n\n# Third-party\nimport collections\nimport mock\n\n# Local\nsys.path.append(os.getcwd())\nimport mail_2_rmq\nimport version\n\n__version__ = version.__version__\n\n\nclass RQTest(object):\n\n \"\"\"Class: RQTest\n\n Description: Class which is a representation of a RQ class.\n\n Methods:\n __init__\n create_connection\n publish_msg\n change_channel\n\n \"\"\"\n\n def __init__(self):\n\n \"\"\"Method: __init__\n\n Description: Initialization instance of the RQTest class.\n\n Arguments:\n\n \"\"\"\n\n self.exchange = \"Test_Exchange\"\n self.queue_name = \"Test_Queue\"\n self.status = collections.namedtuple(\"RQ\", \"is_open\")\n self.channel = self.status(True)\n self.conn_status = True\n self.err_msg = \"\"\n self.pub_status = True\n self.msg = None\n\n def create_connection(self):\n\n \"\"\"Method: create_connection\n\n Description: Stub holder for create_connection method.\n\n Arguments:\n\n \"\"\"\n\n return self.conn_status, self.err_msg\n\n def publish_msg(self, msg):\n\n \"\"\"Method: publish_msg\n\n Description: Stub holder for publish_msg method.\n\n Arguments:\n\n \"\"\"\n\n self.msg = msg\n\n return self.pub_status\n\n def change_channel(self, stat):\n\n \"\"\"Method: change_channel\n\n Description: Change channel status.\n\n Arguments:\n\n \"\"\"\n\n self.channel = self.status(stat)\n\n\nclass CfgTest(object):\n\n \"\"\"Class: CfgTest\n\n Description: Class which is a representation of a cfg module.\n\n Methods:\n __init__\n\n \"\"\"\n\n def __init__(self):\n\n \"\"\"Method: __init__\n\n Description: Initialization instance of the CfgTest class.\n\n Arguments:\n\n \"\"\"\n\n self.host = \"HOSTNAME\"\n self.exchange_name = \"EXCHANGE_NAME\"\n self.err_queue = \"ERROR_QUEUE\"\n\n\nclass UnitTest(unittest.TestCase):\n\n \"\"\"Class: UnitTest\n\n Description: Class which is a representation of a unit testing.\n\n Methods:\n setUp\n test_empty_email\n test_empty_file\n test_file_publish\n test_false_publish\n test_true_publish\n test_error_queue\n test_non_error_queue\n test_true_true_connect\n test_false_false_connect\n test_false_true_connect\n test_true_false_connect\n\n \"\"\"\n\n def setUp(self):\n\n \"\"\"Function: setUp\n\n Description: Initialization for unit testing.\n\n Arguments:\n\n \"\"\"\n\n self.cfg = CfgTest()\n self.rmq = RQTest()\n self.msg = \"Email message\"\n self.fname = \"test/unit/mail_2_rmq/testfiles/fileattachment.txt\"\n self.fname2 = \"test/unit/mail_2_rmq/testfiles/fileattachment2.txt\"\n\n @mock.patch(\"mail_2_rmq.archive_email\", mock.Mock(return_value=True))\n @mock.patch(\"mail_2_rmq.get_text\")\n @mock.patch(\"mail_2_rmq.gen_class.Logger\")\n def test_empty_email(self, mock_log, mock_msg):\n\n \"\"\"Function: test_empty_email\n\n Description: Test with empty email body.\n\n Arguments:\n\n \"\"\"\n\n mock_log.return_value = True\n mock_msg.return_value = \"\"\n\n self.assertFalse(mail_2_rmq.connect_process(self.rmq, mock_log,\n self.cfg, mock_msg))\n\n @mock.patch(\"mail_2_rmq.archive_email\", mock.Mock(return_value=True))\n @mock.patch(\"mail_2_rmq.get_text\")\n @mock.patch(\"mail_2_rmq.gen_class.Logger\")\n def test_empty_file(self, mock_log, mock_msg):\n\n \"\"\"Function: test_empty_file\n\n Description: Test with empty file passed.\n\n Arguments:\n\n \"\"\"\n\n mock_log.return_value = True\n mock_msg.return_value = self.msg\n\n self.assertFalse(\n mail_2_rmq.connect_process(self.rmq, mock_log, self.cfg,\n mock_msg, fname=self.fname2))\n\n @mock.patch(\"mail_2_rmq.get_text\")\n @mock.patch(\"mail_2_rmq.gen_class.Logger\")\n def test_file_publish(self, mock_log, mock_msg):\n\n \"\"\"Function: test_file_publish\n\n Description: Test with file name passed.\n\n Arguments:\n\n \"\"\"\n\n mock_log.return_value = True\n mock_msg.return_value = self.msg\n\n self.assertFalse(\n mail_2_rmq.connect_process(self.rmq, mock_log, self.cfg,\n mock_msg, fname=self.fname))\n\n @mock.patch(\"mail_2_rmq.get_text\")\n @mock.patch(\"mail_2_rmq.archive_email\")\n @mock.patch(\"mail_2_rmq.gen_class.Logger\")\n def test_false_publish(self, mock_log, mock_archive, mock_msg):\n\n \"\"\"Function: test_false_publish\n\n Description: Test publish returns false.\n\n Arguments:\n\n \"\"\"\n\n mock_log.return_value = True\n mock_archive.return_value = True\n mock_msg.return_value = self.msg\n\n self.rmq.pub_status = False\n\n self.assertFalse(mail_2_rmq.connect_process(self.rmq, mock_log,\n self.cfg, mock_msg))\n\n @mock.patch(\"mail_2_rmq.get_text\")\n @mock.patch(\"mail_2_rmq.gen_class.Logger\")\n def test_true_publish(self, mock_log, mock_msg):\n\n \"\"\"Function: test_true_publish\n\n Description: Test publish returns true.\n\n Arguments:\n\n \"\"\"\n\n mock_log.return_value = True\n mock_msg.return_value = self.msg\n\n self.assertFalse(mail_2_rmq.connect_process(self.rmq, mock_log,\n self.cfg, mock_msg))\n\n @mock.patch(\"mail_2_rmq.get_text\")\n @mock.patch(\"mail_2_rmq.gen_class.Logger\")\n def test_error_queue(self, mock_log, mock_msg):\n\n \"\"\"Function: test_error_queue\n\n Description: Test message sent to error queue.\n\n Arguments:\n\n \"\"\"\n\n mock_log.return_value = True\n mock_msg.return_value = self.msg\n\n self.rmq.queue_name = self.cfg.err_queue\n\n self.assertFalse(mail_2_rmq.connect_process(self.rmq, mock_log,\n self.cfg, mock_msg))\n\n @mock.patch(\"mail_2_rmq.get_text\")\n @mock.patch(\"mail_2_rmq.gen_class.Logger\")\n def test_non_error_queue(self, mock_log, mock_msg):\n\n \"\"\"Function: test_non_error_queue\n\n Description: Test message sent to non-error queue.\n\n Arguments:\n\n \"\"\"\n\n mock_log.return_value = True\n mock_msg.return_value = self.msg\n\n self.assertFalse(mail_2_rmq.connect_process(self.rmq, mock_log,\n self.cfg, mock_msg))\n\n @mock.patch(\"mail_2_rmq.get_text\")\n @mock.patch(\"mail_2_rmq.gen_class.Logger\")\n def test_true_true_connect(self, mock_log, mock_msg):\n\n \"\"\"Function: test_true_true_connect\n\n Description: Test connecting to RabbitMQ with true/true status.\n\n Arguments:\n\n \"\"\"\n\n mock_log.return_value = True\n mock_msg.return_value = self.msg\n\n self.assertFalse(mail_2_rmq.connect_process(self.rmq, mock_log,\n self.cfg, mock_msg))\n\n @mock.patch(\"mail_2_rmq.archive_email\")\n @mock.patch(\"mail_2_rmq.gen_class.Logger\")\n def test_false_false_connect(self, mock_log, mock_archive):\n\n \"\"\"Function: test_false_false_connect\n\n Description: Test connecting to RabbitMQ with false/false status.\n\n Arguments:\n\n \"\"\"\n\n mock_log.return_value = True\n mock_archive.return_value = True\n\n self.rmq.conn_status = False\n self.rmq.change_channel(False)\n self.assertFalse(mail_2_rmq.connect_process(self.rmq, mock_log,\n self.cfg, \"\"))\n\n @mock.patch(\"mail_2_rmq.archive_email\")\n @mock.patch(\"mail_2_rmq.gen_class.Logger\")\n def test_false_true_connect(self, mock_log, mock_archive):\n\n \"\"\"Function: test_false_true_connect\n\n Description: Test connecting to RabbitMQ with false/true status.\n\n Arguments:\n\n \"\"\"\n\n mock_log.return_value = True\n mock_archive.return_value = True\n\n self.rmq.conn_status = False\n self.assertFalse(mail_2_rmq.connect_process(self.rmq, mock_log,\n self.cfg, \"\"))\n\n @mock.patch(\"mail_2_rmq.archive_email\")\n @mock.patch(\"mail_2_rmq.gen_class.Logger\")\n def test_true_false_connect(self, mock_log, mock_archive):\n\n \"\"\"Function: test_true_false_connect\n\n Description: Test connecting to RabbitMQ with true/false status.\n\n Arguments:\n\n \"\"\"\n\n mock_log.return_value = True\n mock_archive.return_value = True\n\n self.rmq.change_channel(False)\n self.assertFalse(mail_2_rmq.connect_process(self.rmq, mock_log,\n self.cfg, \"\"))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test/unit/mail_2_rmq/connect_process.py","file_name":"connect_process.py","file_ext":"py","file_size_in_byte":9246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"559965175","text":"#!/usr/bin/env python\n\"\"\"Utility routines to load ELAPS objects.\"\"\"\nfrom __future__ import division, print_function\n\nfrom . import defines, Experiment, Report\nfrom .symbolic import *\nfrom .signature import *\n\nimport os\nimport imp\nfrom collections import defaultdict\n\n\ndef write_signature(sig, filename):\n \"\"\"Write a Signature.\"\"\"\n with open(filename, \"w\") as fout:\n fout.write(repr(sig))\n\n\ndef load_signature_string(string):\n \"\"\"Load a Signature from a string.\"\"\"\n sig = eval(string)\n if not isinstance(sig, Signature):\n raise TypeError(\"not a Signature\")\n return sig\n\n\ndef load_signature_file(filename):\n \"\"\"Load a Signature from a file.\"\"\"\n with open(filename) as fin:\n return load_signature_string(fin.read())\n\n\ndef load_signature(name, _cache={}):\n \"\"\"Find and load a Signature.\"\"\"\n if name in _cache:\n return _cache[name]\n for dirname in os.listdir(defines.sigpath):\n dirpath = os.path.join(defines.sigpath, dirname)\n if not os.path.isdir(dirpath):\n continue\n filename = os.path.join(dirpath, name + \".pysig\")\n if os.path.isfile(filename):\n sig = load_signature_file(filename)\n if str(sig[0]) != name:\n raise IOError(\"Routine mismatch for Signature %s\" % name)\n _cache[name] = sig\n return sig\n raise IOError(\"No signature found for %s\" % name)\n\n\ndef load_all_signatures():\n \"\"\"Load all Signatures.\"\"\"\n if not os.path.isdir(defines.sigpath):\n return {}\n sigs = {}\n for dirname in os.listdir(defines.sigpath):\n dirpath = os.path.join(defines.sigpath, dirname)\n if not os.path.isdir(dirpath):\n continue\n for filename in os.listdir(os.path.join(defines.sigpath, dirname)):\n if not filename[-6:] == \".pysig\":\n continue\n filepath = os.path.join(dirpath, filename)\n if not os.path.isfile(filepath):\n continue\n try:\n sig = load_signature_file(filepath)\n except:\n raise IOError(\"Error parsing %s\" % filepath)\n if str(sig[0]) != filename[:-6]:\n raise IOError(\"Routine mismatch for %s\" % filepath)\n sigs[str(sig[0])] = sig\n return sigs\n\n\ndef write_experiment(experiment, filename):\n \"\"\"Write an Experiment.\"\"\"\n with open(filename, \"w\") as fout:\n fout.write(repr(experiment))\n\n\ndef load_experiment_string(string):\n \"\"\"Load a Experiment from a string.\"\"\"\n ex = eval(string)\n if not isinstance(ex, Experiment):\n raise TypeError(\"not an Experiment\")\n try:\n ex.sampler[\"backend\"] = None\n ex.sampler[\"backend\"] = load_backend(ex.sampler[\"backend_name\"])\n except:\n pass\n return ex\n\n\ndef load_experiment(filename):\n \"\"\"Load an Experiment.\"\"\"\n with open(filename) as fin:\n if filename[-4:] == \".\" + defines.experiment_extension:\n return load_experiment_string(fin.read())\n return load_experiment_string(fin.readline())\n\n\ndef load_doc_file(filename):\n \"\"\"Load a documentation.\"\"\"\n with open(filename) as fin:\n return eval(fin.read())\n\n\ndef load_doc(name, _cache={}):\n \"\"\"Load documentation for name.\"\"\"\n if name in _cache:\n return _cache[name]\n for dirname in os.listdir(defines.docpath):\n dirpath = os.path.join(defines.docpath, dirname)\n if not os.path.isdir(dirpath):\n continue\n filepath = os.path.join(dirpath, name + \".pydoc\")\n if os.path.isfile(filepath):\n doc = load_doc_file(filepath)\n _cache[name] = doc\n return doc\n raise IOError(\"No documentation found for %s\" % name)\n\n\ndef load_all_docs():\n \"\"\"Load all documentations.\"\"\"\n if not os.path.isdir(defines.docpath):\n return {}\n docs = {}\n for dirname in os.listdir(defines.docpath):\n dirpath = os.path.join(defines.docpath, dirname)\n if not os.path.isdir(dirpath):\n continue\n for filename in os.listdir(sigpath):\n if filename[-6:] != \".pydoc\":\n continue\n filepath = os.path.join(dirpath, filename)\n if not os.path.isfile(filepath):\n continue\n try:\n docs[filename[:-6]] = load_doc_file(filepath)\n except:\n pass\n return docs\n\n\ndef load_sampler_file(filename):\n \"\"\"Load a Sampler from a file.\"\"\"\n with open(filename) as fin:\n sampler = eval(fin.read())\n try:\n sampler[\"backend\"] = load_backend(sampler[\"backend_name\"])\n except:\n sampler[\"backend\"] = None\n return sampler\n\n\ndef load_sampler(name, _cache={}):\n \"\"\"Find and load a Sampler.\"\"\"\n if name in _cache:\n return _cache[name]\n filename = os.path.join(defines.samplerpath, name, \"info.py\")\n if os.path.isfile(filename):\n sampler = load_sampler_file(filename)\n _cache[name] = sampler\n return sampler\n raise IOError(\"Sampler %s not found\" % name)\n\n\ndef load_all_samplers():\n \"\"\"Load all Samplers.\"\"\"\n if not os.path.isdir(defines.samplerpath):\n return {}\n samplers = {}\n for dirname in os.listdir(defines.samplerpath):\n filename = os.path.join(defines.samplerpath, dirname, \"info.py\")\n if os.path.isfile(filename):\n try:\n samplers[dirname] = load_sampler_file(filename)\n except:\n pass\n return samplers\n\n\ndef load_backend_file(filename):\n \"\"\"Load a backend from a file.\"\"\"\n name = os.path.basename(filename)[:-3]\n module = imp.load_source(name, filename)\n return module.Backend()\n\n\ndef load_backend(name, _cache={}):\n \"\"\"Load a backend.\"\"\"\n if name in _cache:\n return _cache[name]\n filename = os.path.join(defines.backendpath, name + \".py\")\n if os.path.isfile(filename):\n backend = load_backend_file(filename)\n _cache[name] = backend\n return backend\n raise IOError(\"Backend %s not found\" % name)\n\n\ndef load_all_backends():\n \"\"\"Load all backends.\"\"\"\n if not os.path.isdir(defines.backendpath):\n return {}\n backends = {}\n for filename in os.listdir(defines.backendpath):\n if filename[-3:] != \".py\":\n continue\n filepath = os.path.join(defines.backendpath, filename)\n if not os.path.isfile(filepath):\n continue\n try:\n backends[filename[:-3]] = load_backend_file(filepath)\n except:\n pass\n return backends\n\n\ndef load_papinames():\n \"\"\"Load all PAPI names.\"\"\"\n class keydefaultdict(defaultdict):\n def __missing__(self, key):\n self[key] = self.default_factory(key)\n return self[key]\n with open(defines.papinamespath) as fin:\n return keydefaultdict(lambda key: {\"short\": key, \"long\": key},\n eval(fin.read()))\n\n\ndef load_report(filename, discard_first_repetitions=False):\n \"\"\"Load a Report from a file.\"\"\"\n with open(filename) as fin:\n experiment = eval(fin.readline())\n rawdata = []\n for line in fin:\n vals = []\n for val in line.split():\n try:\n val = int(val)\n except:\n pass\n vals.append(val)\n rawdata.append(vals)\n report = Report(experiment, rawdata)\n if discard_first_repetitions:\n return report.discard_first_repetitions()\n errfile = \"%s.%s\" % (filename[:-4], defines.error_extension)\n if os.path.isfile(errfile) and os.path.getsize(errfile):\n report.error = True\n return report\n\n\ndef load_metric_file(filename):\n \"\"\"Load a metric from a file.\"\"\"\n name = os.path.basename(filename)[:-3]\n module = imp.load_source(name, filename)\n metric = module.metric\n return metric\n\n\ndef load_metric(name, _cache={}):\n \"\"\"Load a metric.\"\"\"\n if name in _cache:\n return _cache[name]\n filename = os.path.join(defines.metricpath, name + \".py\")\n if os.path.isfile(filename):\n metric = load_metric_file(filename)\n _cache[name] = metric\n return metric\n raise IOError(\"Metric %s not found\" % name)\n\n\ndef load_all_metrics():\n \"\"\"Load all metrics.\"\"\"\n if not os.path.isdir(defines.metricpath):\n return {}\n metrics = {}\n for filename in os.listdir(defines.metricpath):\n if filename[-3:] != \".py\":\n continue\n filepath = os.path.join(defines.metricpath, filename)\n if not os.path.isfile(filepath):\n continue\n try:\n metric = load_metric_file(filepath)\n metrics[metric.name] = metric\n except:\n pass\n return metrics\n\n\ndef get_counter_metric(counter, name=None, doc=None):\n \"\"\"Create a metric for a PAPI counter.\"\"\"\n if name is None:\n name = counter\n\n def metric(data, **kwargs):\n return data.get(counter)\n metric.name = name\n metric.__doc__ = doc\n return metric\n","sub_path":"elaps/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":9019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"506858174","text":"import pdfkit\nfrom pyrebase import pyrebase\n\noptions = {\n \"enable-local-file-access\": None,\n \"page-size\": \"A5\",\n \"viewport-size\": \"1366 x 768\",\n 'disable-smart-shrinking': '',\n 'margin-top': '0in',\n 'dpi': 900,\n 'margin-right': '0.8in',\n 'margin-bottom': '0in',\n 'margin-left': '0.8in',\n}\nconfig = {\n \"apiKey\": \"AIzaSyB7cTfNmxp_OA9vOKL94O10FRHe_PyyziQ\",\n \"authDomain\": \"whoabot-181f2.firebaseapp.com\",\n \"databaseURL\": \"https://whoabot-181f2.firebaseio.com\",\n \"projectId\": \"whoabot-181f2\",\n \"storageBucket\": \"whoabot-181f2.appspot.com\",\n \"messagingSenderId\": \"437598146366\",\n \"appId\": \"1:437598146366:web:b36b6702a749b7466da66f\",\n \"measurementId\": \"G-LCRZ7MP631\"\n}\n\n# pdfkit.from_file(\"D:\\Misc Practice\\Chatbot\\Rasa Projects\\webpages\\page2.html\", './staticpdfs/myfile.pdf', options=options)\ndef upload_pdf():\n firebase = pyrebase.initialize_app(config)\n storage = firebase.storage()\n path_local = \"./Insomnia/3.pdf\"\n path_on_cloud = \"pdfs/Insomnia/3.pdf\"\n storage.child(path_on_cloud).put(path_local)\n print(storage.child(path_on_cloud).get_url(path_on_cloud))\n\ndef get_pdf(story,number):\n firebase = pyrebase.initialize_app(config)\n storage = firebase.storage()\n path_on_cloud = \"pdfs/{}/{}.pdf\".format(str(story),str(number))\n print(storage.child(path_on_cloud).get_url(path_on_cloud))\n return storage.child(path_on_cloud).get_url(path_on_cloud)\n\nif __name__ == \"__main__\":\n upload_pdf()\n# # get_pdf(\"Insomnia\",1)\n\n","sub_path":"test/staticpdfs/pdfcreator.py","file_name":"pdfcreator.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"290840386","text":"\nnums = [1, 4, 6, 8, 9, 13]\nsubnums1 = nums[0:4]\nsubnums2 = nums[2:5]\nprint(subnums1)\nprint(subnums2)\n\nnums.append(20)\nnums.insert(1, 10)\n\nmylist = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\n\nmylist.insert(3, \"z\") # to add z at position 3 of your list\nmylist.pop(2) # remove by position\nmylist.remove(\"b\") # remove by value","sub_path":"General/Lists.py","file_name":"Lists.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"630894098","text":"from django.core.management.base import BaseCommand, CommandError\nfrom tools.models import Tool,Category\nimport os\nimport csv\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nclass Command(BaseCommand):\n # python manage.py import_tools file=\"tools.csv\"\n help = 'meant to help me get started, importing a lot of initial data etc'\n\n def add_arguments(self, parser):\n parser.add_argument('file', type=str)\n\n def handle(self, *args, **options):\n filename = options['file']\n try:\n #self.stdout.write(dir_path)\n #self.stdout.write(filename)\n filename = filename.replace(\"file=\", \"\") \n fullpath = dir_path + \"/\" + filename\n self.stdout.write(fullpath)\n\n taxonomy_dicts = []\n file = open(fullpath, 'r')\n reader = csv.DictReader(file)\n for rec in reader:\n #print(rec) # Category\tSubcategory\tURL\tDescription\tImage\n #self.stdout.write( rec[\"Name\"] )\n try:\n name = rec[\"Name\"]\n url = rec[\"URL\"]\n image_url = rec[\"Image\"]\n cat = rec[\"Category\"]\n altcat = rec[\"Subcategory\"]\n about = rec[\"Description\"]\n # Does the Category exits\n catObj, created = Category.objects.get_or_create(name=cat,)\n if created:\n catObj.save()\n\n altcatObj, created = Category.objects.get_or_create(name=altcat,)\n if created:\n altcatObj.save()\n\n obj, created = Tool.objects.get_or_create(name=name,)\n if created:\n obj.url = url\n obj.image_url = image_url\n obj.category = catObj\n obj.altcategory = altcatObj\n obj.about = about\n obj.desktop = True\n obj.web_based = False\n obj.save()\n self.stdout.write( \"Saved: \" + rec[\"Name\"] )\n except Exception as err:\n self.stdout.write( \"Error: \" + str(err) + \" name\" )\n\n\n\n\n\n\n\n except Exception as err:\n raise CommandError( str(err))\n\n\n self.stdout.write(self.style.SUCCESS('Done!'))","sub_path":"tools/management/commands/import_tools.py","file_name":"import_tools.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"601016311","text":"from flask import Flask, render_template\n\napp = Flask(__name__)\n\n@app.route('/')\ndef indexing():\n superh = ['Superman', 'Batman', 'WonderWoman', 'Flash', 'Green Lantern']\n return render_template('sups.html', superh = superh)\n\nif __name__ == '__main__':\n app.run()","sub_path":"Flask_Basics/Basics/06_Control_Flow.py","file_name":"06_Control_Flow.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"119055765","text":"class Solution(object):\n def post2in(self, s):\n expressStack = []\n priority = {'-': 0,\n '+': 0,\n '*': 1,\n '/': 1,\n '^': 2\n }\n for i in range(len(s)):\n if s[i].isalnum():\n expressStack.append([s[i], -1])\n else:\n op2 = '(' + expressStack[-1][0] + ')' if priority[s[i]] > expressStack[-1][1] and len(expressStack[-1][0]) > 1 else expressStack[-1][0]\n op1 = '(' + expressStack[-2][0] + ')' if priority[s[i]] > expressStack[-2][1] and len(expressStack[-2][0]) > 1 else expressStack[-2][0]\n expressStack.pop()\n expressStack.pop()\n expressStack.append([op1 + s[i] + op2, priority[s[i]]])\n return expressStack[0][0]\n\nprint(Solution().post2in(\"23*21-/345+*+\"))\n\n","sub_path":"interview_exam/Quant/postfix2infix.py","file_name":"postfix2infix.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"602091602","text":"import argparse\nimport json\nimport numpy as np\nimport os\nfrom scipy.special import softmax\nfrom collections import defaultdict\nimport data_generator as generator\nimport math\nimport json\n\n\nPROB_CLUSTERS = [1.0]\n\n\ndef main():\n\n\t#args = parse_args()\n\n\n\twith open('params.json') as json_file:\n\t\tdata = json.load(json_file)\n\tprint('Generating dataset')\n\tnp.random.seed(data['meta']['seed'])\n\tnum_samples = get_num_samples(\n\t\tdata['sample_size']['data_potion'],\n\t\tdata['meta']['n_classes'],\n\t\tdata['sample_size']['total_size'],\n\t\tdata['meta']['n_parties'])\n\n\tweights = get_weights(\n\t\tdata['label_distribution'],\n\t\tdata['meta']['n_classes'],\n\t\tdata['meta']['n_parties'])\n\n\ttest_weights = get_weights(\n\t\tNone,\n\t\tdata['meta']['n_classes'],\n\t\tdata['meta']['n_parties']\n\t)\n\n\tnoises = get_noises(\n\t\tdata['noise']['noise_level'],\n\t\tdata['meta']['n_parties']\n\t)\n\n\tloc_list = get_loc_list(\n\t\tdata['feature_distribution']['x_mean'],\n\t \tdata['feature_distribution']['x_sigma'],\n\t \tdata['meta']['n_parties'],\n\t\tdata['meta']['n_features']\n\t)\n\n\tg = generator.SyntheticDataset(\n\t\tnum_classes=data['meta']['n_classes'],\n\t\tprob_clusters=PROB_CLUSTERS,\n\t\tnum_dim=data['meta']['n_features'],\n\t\tseed=data['meta']['seed'],\n\t\tn_parties = data['meta']['n_parties'],\n\t\tx_level_noise = data['noise']['x_level_noise']\n\t\t)\n\n\tdatasets = g.get_tasks(num_samples, weights, noises, loc_list)\n\n\n\tprint('test test %s' %([0] * data['meta']['n_parties']))\n\ttestset = g.get_tasks(\n\t\t([data['meta']['testset_size_per_party']]*data['meta']['n_parties']),\n\t\ttest_weights, \n\t\t([0] * data['meta']['n_parties']),\n\t\tloc_list)\n\n\n\tuser_data = to_format(datasets)\n\ttest_data = test_to_format(testset)\n\tsave_json('data/all_data', 'data.json', user_data)\n\tsave_json('data/all_data', 'test_data.json', test_data)\n\treturn datasets\n\ndef test_to_format(testset):\n\taggregated_test = [v for k,v in testset.items()]\n\tfinal_test_x = []\n\tfinal_test_y = []\n\tfor i in range(len(aggregated_test)):\n\t\tfinal_test_x.extend(aggregated_test[i]['x'].tolist())\n\t\tfinal_test_y.extend(aggregated_test[i]['y'].tolist())\n\n\ttestset = {'x': final_test_x, 'y': final_test_y}\n\treturn testset\n\ndef get_loc_list(x_mean, x_sigma, n_parties, n_features):\n\tloc = np.zeros((n_parties, n_features))\n\tx_mean = get_x_mean(x_mean, n_features)\n\tx_sigma = get_x_sigma(x_sigma, n_features)\n\tfor i, (mean, sigma) in enumerate(zip(x_mean, x_sigma)):\n\t\tloc[:,i] = np.random.normal(loc=mean, scale = sigma, size = n_parties)\n\treturn loc\n\ndef get_x_mean(x_mean, n_features):\n\tif x_mean is None:\n\t\tx_mean = np.array([0.]*n_features)\n\telif len(x_mean) < n_features:\n\t\tx_mean = x_mean + [0.]*(n_features - len(x_mean))\n\telif len(x_mean) > n_features:\n\t\tx_mean = x_mean[:n_features]\n\treturn x_mean\n\ndef get_x_sigma(x_sigma, n_features):\n\tif x_sigma is None:\n\t\tx_sigma = np.array([1]*n_features)\n\telif len(x_sigma) < n_features:\n\t\tx_sigma = x_sigma + [1]*(n_features - len(x_sigma))\n\telif len(x_sigma) > n_features:\n\t\tx_sigma = x_sigma[:n_features]\n\treturn x_sigma\n\n\ndef get_noises(noises, n_parties):\n\tif len(noises) < n_parties:\n\t\tfor i in range(len(noises),n_parties):\n\t\t\tnoises.append(0.0)\n\telif len(noises) > n_parties:\n\t\tnoises = noises[:n_parties]\n\treturn noises\n\n\ndef get_weights(weights, n_classes, num_tasks):\n\n\tweight_list = np.zeros((num_tasks, n_classes))\n\tif weights is not None:\n\t\tcount = 0\n\t\tfor i, w in enumerate(weights):\n\n\t\t\tif len(w) not in [n_classes-1, n_classes]:\n\t\t\t\traise ValueError(\"Weights specified but incompatible with number \"\n\t\t\t\t\t\t\t\"of classes.\")\n\n\t\t\tif len(w) == n_classes - 1:\n\t\t\t\tif sum(w) >1 :\n\t\t\t\t\traise ValueError(\"the weight specified for party %s does not add up to 1.\" %i)\n\t\t\t\tw = w + [1.0 - sum(w)]\n\n\t\t\tcount += 1\n\t\t\tweight_list[i,:] = w\n\n\t\tif count < num_tasks:\n\t\t\tfor idx in range(count, num_tasks):\n\t\t\t\tw = [(1/n_classes)]*n_classes\n\t\t\t\tweight_list[idx,:] = w\n\n\telse:\n\t\tfor idx in range(num_tasks):\n\t\t\tw = [(1/n_classes)]*n_classes\n\t\t\tweight_list[idx,:] = w\n\tprint('label distribution is: %s' %weights)\n\tprint('generated weight list is: %s' %weight_list)\n\treturn weight_list\n\ndef get_num_samples(data_potion, n_classes, size_ref, num_tasks):\n\t# set number of samples for each party\n\tif data_potion is not None:\n\t\tnum_samples = []\n\t\tportion_list = [i for i in data_potion]\n\n\t\tif len(portion_list) not in [num_tasks, num_tasks - 1]:\n\t\t\traise ValueError(\"Potion specified but incompatible with number \"\n\t\t\t\t\t\t\t\"of classes.\")\n\t\telif len(portion_list) == num_tasks - 1:\n\n\t\t\tportion_list = portion_list + [1.0 - sum(portion_list)]\n\n\t\telif (len(portion_list) == num_tasks) and (sum(portion_list)!=1):\n\t\t\traise ValueError(\"Potion specified does not add up to 1.\")\n\n\n\t\tfor portion in portion_list:\n\t\t\tnum = int(size_ref * portion)\n\t\t\tnum_samples.append(num)\n\telse:\n\t\tnum_samples = [int(size_ref * (1/num_tasks))] * num_tasks\n\t\t\n\tleft_over = size_ref - sum(num_samples)\n\tprint('left over is: %s' %left_over)\n\tnum_samples[-1] += left_over\n\tprint('number of class: %s' %n_classes)\n\tprint('number of parties: %s' %num_tasks)\n\tprint('data potion is: %s' %data_potion)\n\tprint('num_samples are: '+str(num_samples))\n\treturn num_samples\n\n\ndef to_format(tasks):\n\tuser_data = {}\n\tfor k, v in tasks.items():\n\t\tx, y = v['x'].tolist(), v['y'].tolist()\n\t\tu_id = str(k)\n\n\t\tuser_data[u_id] = {'x': x, 'y': y}\n\n\treturn user_data\n\n\n\ndef save_json(json_dir, json_name, user_data):\n\tif not os.path.exists(json_dir):\n\t\tos.makedirs(json_dir)\n\n\twith open(os.path.join(json_dir, json_name), 'w') as outfile:\n\t\tjson.dump(user_data, outfile)\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"21961839","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\nimport capsule_distance\n\ncapsule = capsule_distance.Capsule(0.18, -0.5, 0.45)\n\n#from matplotlib_scalebar.scalebar import ScaleBar\n\n#plt.rcParams['axes.facecolor'] = \"xkcd:spring green\"#'black'\n\n# plt.rcParams.update({\n# \"text.usetex\": True,\n# \"font.family\": \"serif\",\n# \"font.serif\": [\"Palatino\"],\n# })\nfrom matplotlib import rc\nrc('font', **{'family': 'serif', 'serif': ['Computer Modern'], 'size' : 12})\n#rc('text', usetex=True)\n#from matplotlib.ticker import FormatStrFormatter\n\nall_traces_rds = np.genfromtxt('../traces_dynamic_systematic_rds.csv',\n\tdelimiter=';')\n\nall_traces_baseline = np.genfromtxt('../traces_dynamic_systematic_baseline.csv',\n\tdelimiter=';')\n\ndata = [all_traces_rds, all_traces_baseline]\nfig, axes = plt.subplots(1, 2, sharey=True, subplot_kw={\"adjustable\":'box-forced'})\n\nfig.subplots_adjust(wspace=0.025)\n\nfor m in [0, 1]:\n\tall_traces = data[m]\n\n\ttraces_max_index = np.max(all_traces[:, 4])\n\t#traces_list = [None]*traces_max_index\n\t#for i in range(traces_max_index):\n\t#\tthis_trace_row_indices = (all_traces[:, 4] == i)\n\t#\ttraces_list[i] = all_traces[this_trace_row_indices, 0:4]\n\n\t#for trace in traces_list:\n\t#\tplt.plot(trace[])\n\ttrace_start_indices = [0]\n\tfor i in range(all_traces.shape[0]):\n\t\tif len(trace_start_indices)-1 < all_traces[i, 4]:\n\t\t\ttrace_start_indices.append(i)\n\n\t# re-arrange the data\n\ttrace_start_indices.append(all_traces.shape[0])\n\ttraces_ordered = np.empty([all_traces.shape[0]*2, 3])\n\twrite_start = 0\n\tfor i in range(10):\n\t\tsub_range_alpha = range(trace_start_indices[i], trace_start_indices[i+1])\n\t\twrite_length = trace_start_indices[i+1] - trace_start_indices[i]\n\t\ttraces_ordered[write_start:(write_start+write_length), 0:2] = all_traces[sub_range_alpha, 0:2]\n\t\ttraces_ordered[write_start:(write_start+write_length), 2] = all_traces[sub_range_alpha, 4]\n\t\twrite_start += write_length\n\t\ttraces_ordered[write_start:(write_start+write_length), 0:2] = all_traces[sub_range_alpha, 2:4]\n\t\ttraces_ordered[write_start:(write_start+write_length), 2] = all_traces[sub_range_alpha, 4]\n\t\twrite_start += write_length\n\t\tsub_range_omega = range(trace_start_indices[19 - i], trace_start_indices[20 - i])\n\t\twrite_length = trace_start_indices[20 - i] - trace_start_indices[19 - i]\n\t\ttraces_ordered[write_start:(write_start+write_length), 0:2] = all_traces[sub_range_omega, 0:2]\n\t\ttraces_ordered[write_start:(write_start+write_length), 2] = all_traces[sub_range_omega, 4]\n\t\twrite_start += write_length\n\t\ttraces_ordered[write_start:(write_start+write_length), 0:2] = all_traces[sub_range_omega, 2:4]\n\t\ttraces_ordered[write_start:(write_start+write_length), 2] = all_traces[sub_range_omega, 4]\n\t\twrite_start += write_length\n\n\tax = axes[m]\n\tthe_cmap = cm.coolwarm#cm.PiYG#cm.brg#cm.viridis#cm.plasma #cm.cool\n\tax.scatter(traces_ordered[:,0], traces_ordered[:,1], c=traces_ordered[:,2]/float(traces_max_index),\n\t\tcmap=the_cmap, marker='o', lw=0.1, s=8, edgecolor='k')\n\tax.set_aspect(\"equal\")\n\tax.set_xlim([-2.7, 3.2])\n\tax.set_ylim([-2.7, 3.2])\n\tax.plot([-2.7, 3.2], [0.0, 0.0], 'k--', linewidth=1)\n\tax.plot([0.0, 0.0], [-2.7, 3.2], 'k--', linewidth=1)\n\t\n\tif m == 0:\n\t\tshift_x = -5.0\n\t\tshift_y = -5.0\n\t\tax.text(2.9+shift_x, 2.6+shift_y, \"1 m\")\n\t\tax.plot([2.75+shift_x,3.75+shift_x], [2.5+shift_y, 2.5+shift_y],'k', linewidth=1)\n\t\tax.plot([2.75+shift_x,2.75+shift_x], [2.45+shift_y, 2.55+shift_y],'k', linewidth=1)\n\t\tax.plot([3.75+shift_x,3.75+shift_x], [2.45+shift_y, 2.55+shift_y],'k', linewidth=1)\n\t\ty_colorscale = np.linspace(0.5, 1.75, 20)\n\t\tx_colorscale = np.linspace(1.45, 1.45, 20)\n\t\tc_array = np.linspace(0.0, 1.0, 20)\n\t\tax.scatter(x_colorscale, y_colorscale, c=c_array, cmap=the_cmap, marker='s', lw=0.0)\n\t\tax.text(x_colorscale[0]+0.05, y_colorscale[0]-0.05, \" -1.5s\")\n\t\tax.text(x_colorscale[0]+0.05, y_colorscale[-1]-0.05, \"+1.5s\")\n\t\tax.text(x_colorscale[0]-0.7, y_colorscale[-1]+0.5, \"pedestrian\\nhead start\")\n\n\tcapsule.plot_at_pose(-1.7, 2.0, -np.pi/2, ax, orca=(m == 1))\n\tax.quiver(-1.7, 2.0, 2.0, 0.0)\n\tax.plot([-1.7, -2.6], [1.9, 0.1], 'k', linewidth=1)\n\tcircle_pedestrian = plt.Circle((2.0, -1.7), 0.3, color=[0.8,0.8,0.0], fill=False)\n\tax.add_artist(circle_pedestrian)\n\tax.quiver(2.0, -1.7, 0.0, 2.0)\n\tax.plot([1.9, 0.1], [-1.7, -2.6], 'k', linewidth=1)\n\tax.xaxis.set_ticks([])\n\tax.xaxis.set_ticklabels([])\n\tax.yaxis.set_ticks([])\n\tax.yaxis.set_ticklabels([])\n\t# continue\n\n\t# sub_range = range(trace_start_indices[10])\n\n\t# the_cmap = cm.coolwarm#cm.PiYG#cm.brg#cm.viridis#cm.plasma #cm.cool\n\t# plt.scatter(all_traces[sub_range,0], all_traces[sub_range,1], c=all_traces[sub_range,4]/float(traces_max_index), cmap=the_cmap, marker='o', lw=0.1)\n\t# plt.scatter(all_traces[sub_range,2], all_traces[sub_range,3], c=all_traces[sub_range,4]/float(traces_max_index), cmap=the_cmap, marker='o', lw=0.1)\n\t# plt.gca().set_aspect(\"equal\")\n\t# plt.gca().set_xlim([-2.5, 3.5])\n\t# plt.gca().set_ylim([-2.5, 3.5])\n\t# plt.show()\n\n#plt.setp(axes, xlim=[-3, 4.0], ylim=[-2.5, 4.0])\nplt.savefig('dynamic_systematic_plot.png', bbox_inches='tight', dpi=299)\nplt.show()","sub_path":"rds/script/cross_plot.py","file_name":"cross_plot.py","file_ext":"py","file_size_in_byte":5078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"59162691","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nipl_df = pd.read_csv('data/ipl_dataset.csv', index_col=None)\n\n\n# Solution\ndef plot_runs_by_balls():\n ipl_df1 = ipl_df[['match_code','batsman','delivery','runs']]\n aggregator = {'delivery': 'count',\n 'runs': 'sum'}\n chartaxis = ipl_df1.groupby(['match_code','batsman']).agg(aggregator)\n\n plt.scatter(chartaxis['delivery'], chartaxis['runs'])\n plt.show()\n","sub_path":"q04_plot_runs_by_balls/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"586319454","text":"class Solution(object):\n def convertToTitle(self, n):\n answer = \"\"\n base = ord(A)\n while n > 0:\n answer += chr(base + (n - 1) % 26)\n n -= ((n - 1) % 26 + 1)\n n /= 26\n\n return answer[::-1]\n","sub_path":"python/Excel Sheet Column Title.py","file_name":"Excel Sheet Column Title.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"159108130","text":"#!/usr/bin/python3\n\"\"\"This module defines a class to manage file storage for hbnb clone\"\"\"\nimport json\nfrom os import getenv\nfrom models.amenity import Amenity\nfrom models.base_model import BaseModel, Base\nfrom models.city import City\nfrom models.place import Place\nfrom models.review import Review\nfrom models.state import State\nfrom models.user import User\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker, scoped_session\n\nusr = getenv('HBNB_MYSQL_USER')\npwd = getenv('HBNB_MYSQL_PWD')\nhost = getenv('HBNB_MYSQL_HOST')\ndb = getenv('HBNB_MYSQL_DB')\nenv = getenv('HBNB_ENV')\ndbtables = [State, City, User, Place, Review, Amenity]\n\n\nclass DBStorage:\n \"\"\"Class DBStorage\"\"\"\n __engine = None\n __session = None\n\n def __init__(self):\n \"\"\"DBStorage constructor\"\"\"\n self.__engine = DBStorage.connection()\n if (env == 'test'):\n Base.metadata.drop_all(self.__engine)\n\n @staticmethod\n def connection():\n \"\"\"Connection to database function\"\"\"\n conn = 'mysql+mysqldb://{}:{}@{}/{}'.format(usr, pwd, host, db)\n return create_engine(conn, pool_pre_ping=True, echo=False)\n\n def all(self, cls=None):\n \"\"\"query on the current database session\"\"\"\n rdict = {}\n result = []\n if (cls is None):\n for t in dbtables:\n result.extend(self.__session.query(t).all())\n else:\n result = self.__session.query(cls).all()\n for obj in result:\n key = \"{}.{}\".format(type(obj).__name__, obj.id)\n rdict[key] = obj\n return rdict\n\n def new(self, obj):\n \"\"\"add the object to the current database session\"\"\"\n self.__session.add(obj)\n\n def save(self):\n \"\"\"commit all changes of the current database session\"\"\"\n self.__session.commit()\n\n def delete(self, obj=None):\n \"\"\"Deletes an object if exists in current db session\"\"\"\n if (obj is not None):\n self.__session.delete(obj)\n\n def reload(self):\n \"\"\"create all tables in the database\"\"\"\n Base.metadata.create_all(self.__engine)\n presession = sessionmaker(bind=self.__engine, expire_on_commit=False)\n self.__session = scoped_session(presession)\n\n def close(self):\n \"\"\"Close the working SQLAlchemy session.\"\"\"\n self.__session.remove()\n","sub_path":"models/engine/db_storage.py","file_name":"db_storage.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"385683346","text":"from django import forms\nfrom .models import *\nfrom django.contrib.auth import get_user_model\nfrom users.models import *\nfrom django.contrib.auth.forms import AuthenticationForm,ReadOnlyPasswordHashField\nfrom django.contrib.admin.forms import AdminPasswordChangeForm\n\n\nUser = get_user_model()\nclass FormUsuarios(forms.ModelForm):\n class Meta:\n model=UserMedico\n fields=['username','password']\n\nclass LoginForm(AuthenticationForm):\n ''' Formulario para el login '''\n username = forms.CharField(\n widget=forms.TextInput(attrs={\n 'autofocus': True,\n 'placeholder': 'Email',\n 'class': 'form-control mb-4'\n })\n )\n password = forms.CharField(\n label=(\"Password\"),\n strip=False,\n widget=forms.PasswordInput(attrs={\n 'placeholder': 'Contraseña',\n 'class': 'form-control mb-4 '\n }),\n )\n\n class Meta:\n model = UserMedico\n\nclass FormAtencion(forms.ModelForm):\n class Meta:\n model=Atencion_Medica\n fields = (\n 'nro_ficha', 'nombre_medico'\n )\n labels = {\n 'nombre_medico': ('Nombre médico'),\n 'nro_ficha': ('Número de ficha'),\n }\n widgets = {\n 'nombre_medico': forms.TextInput(attrs={\n 'class': 'form-control responsive',\n 'placeholder': 'Ingrese Nombre de Médico',\n 'required': True,\n\n }),\n 'nro_ficha': forms.Select(attrs={\n 'class': 'form-control responsive',\n 'placeholder': 'Ingrese Número de Ficha',\n 'required': True,\n }),\n }\n\n # def clean_nro_ficha(self):\n # nro_ficha = self.cleaned_data['nro_ficha']\n # fichas = Carnet_Paciente.objects.filter(nro_ficha__iexact=nro_ficha)\n # if self.instance:\n # fichas = fichas.exclude(id=self.instance.id)\n # if fichas.count() is None:\n # raise ValidationError('Lo sentimos, pero esta ficha no existe')\n # else:\n # return nro_ficha\n\n\nclass FormPrescripcion(forms.ModelForm):\n class Meta:\n model=Detalle_Atencion\n fields = (\n 'sintomas', 'diagnostico','tratamiento','observacion'\n )\n labels = {\n 'sintomas': ('Síntomas'),\n 'diagnostico': ('Diagnóstico'),\n 'tratamiento': ('Tratamiento'),\n 'observacion': ('Observación'),\n }\n\n widgets = {\n 'sintomas': forms.Textarea(attrs={\n 'rows': '3',\n 'class': 'textotal form-control',\n 'placeholder': 'Ingrese Sintomas del Paciente..',\n 'required': True,\n }),\n 'diagnostico': forms.Textarea(attrs={\n 'rows': '3',\n 'class': 'textotal form-control',\n 'placeholder': 'Ingrese Diagnostico del Paciente..',\n 'required': True,\n }),\n 'tratamiento': forms.Textarea(attrs={\n 'rows': '3',\n 'class': 'textotal form-control',\n 'placeholder': 'Ingrese Tratamiento para el Paciente..',\n 'required': True,\n }),\n 'observacion': forms.Textarea(attrs={\n 'rows': '3',\n 'class': 'textotal form-control',\n 'placeholder': 'Ingrese Observacion..',\n }),\n }\n\n\n# ----------------------Forms Nico------------------------\nclass CarnetForm(forms.ModelForm):\n\n class Meta:\n model = Carnet_Paciente\n\n fields = [\n 'nro_ficha',\n 'rut_paciente',\n 'sector',\n 'prevision',\n 'grupo_sanguineo',\n 'cesfam',\n ]\n\n labels = {\n 'nro_ficha': 'Nro. Ficha',\n 'rut_paciente': 'Rut Paciente',\n 'sector': 'Sector',\n 'prevision': 'Previsión',\n 'grupo_sanguineo': 'Grupo Sanguíneo',\n 'cesfam': 'CESFAM',\n }\n\n widgets = {\n 'nro_ficha': forms.TextInput(attrs={'class': 'form-control-sm form-control', 'readonly': ''}),\n 'rut_paciente': forms.TextInput(attrs={'class': 'form-control-sm form-control', 'readonly': ''}),\n 'sector': forms.TextInput(attrs={'class': 'form-control-sm form-control', 'readonly': '', 'style': 'text-transform: capitalize'}),\n 'prevision': forms.TextInput(attrs={'class': 'form-control-sm form-control', 'readonly': ''}),\n 'grupo_sanguineo': forms.TextInput(attrs={'class': 'form-control-sm form-control', 'readonly': ''}),\n 'cesfam': forms.TextInput(attrs={'class': 'form-control-sm form-control', 'readonly': ''}),\n }\n\nclass DetalleAtencionForm(forms.ModelForm):\n\n class Meta:\n model = Detalle_Atencion\n\n fields = '__all__'\n\n exclude = ['atencion_medica']\n\n labels = {\n 'sintomas': 'Síntomas',\n 'diagnostico': 'Diagnóstico',\n 'tratamiento': 'Tratamiento',\n 'observacion': 'Observación',\n }\n\n widgets = {\n 'sintomas': forms.Textarea(attrs={'class': 'form-control-sm form-control', 'readonly': ''}),\n 'diagnostico': forms.Textarea(attrs={'class': 'form-control-sm form-control', 'readonly': ''}),\n 'tratamiento': forms.Textarea(attrs={'class': 'form-control-sm form-control', 'readonly': ''}),\n 'observacion': forms.Textarea(attrs={'class': 'form-control-sm form-control', 'readonly': ''}),\n }\n\nclass PacienteForm(forms.ModelForm):\n\n class Meta:\n model = Paciente\n\n fields = '__all__'\n\n exclude = [\n 'rut_paciente', \n 'nombre',\n 'ap_paterno', \n 'ap_materno', \n 'sexo',\n 'fecha_nacimiento',\n 'estado'\n ]\n\n labels = {\n 'direccion': 'Dirección',\n 'email': 'Correo',\n 'nro_celular': 'Nro. Celular',\n 'comuna': 'Comuna',\n 'nombre_familiar': 'Nombre del Familiar',\n 'nro_familiar': 'Nro. del Familiar',\n 'email_familiar': 'Correo del Familiar'\n }\n\n widgets = {\n 'direccion': forms.TextInput(attrs={'class': 'form-control-sm form-control', 'readonly': ''}),\n 'email': forms.TextInput(attrs={'class': 'form-control-sm form-control', 'readonly': ''}),\n 'nro_celular': forms.TextInput(attrs={'class': 'form-control-sm form-control', 'readonly': ''}),\n 'comuna': forms.TextInput(attrs={'class': 'form-control-sm form-control', 'readonly': '', 'style': 'text-transform: capitalize'}),\n 'nombre_familiar': forms.TextInput(attrs={'class': 'form-control-sm form-control', 'readonly': ''}),\n 'nro_familiar': forms.TextInput(attrs={'class': 'form-control-sm form-control', 'readonly': ''}),\n 'email_familiar': forms.TextInput(attrs={'class': 'form-control-sm form-control', 'readonly': ''}),\n }\n\n\n# ----------------------Forms Alex------------------------\n\nclass MedicamentoRecetadoForm(forms.ModelForm):\n\n class Meta:\n model = Medicamento_Recetado\n\n fields = [\n 'id_medicamento',\n 'id_receta_medica',\n 'duracion',\n 'frecuencia',\n 'cantidad_recetada',\n ]\n\n labels = {\n 'id_medicamento': 'ID Medicamento',\n 'id_receta_medica': 'ID Receta',\n 'duracion': 'Duración',\n 'frecuencia': 'Frecuencia',\n 'cantidad_recetada': 'Cant. Recetada',\n }\n\n widgets = {\n 'id_receta_medica': forms.TextInput(attrs={'class': 'form-control-sm form-control', 'readonly': ''}),\n 'id_medicamento': forms.TextInput(attrs={'class': 'form-control-sm form-control', 'readonly': ''}),\n 'duracion': forms.TextInput(attrs={'class': 'form-control-sm form-control', 'readonly': ''}),\n 'frecuencia': forms.TextInput(attrs={'class': 'form-control-sm form-control', 'readonly': ''}),\n 'cantidad_recetada': forms.TextInput(attrs={'class': 'form-control-sm form-control', 'readonly': ''}),\n } ","sub_path":"env/Lib/site-packages/django/conf/app_template/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":8270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"309325215","text":"import datetime\nimport multiprocessing\nimport os\nimport traceback\nfrom io import BytesIO\nfrom multiprocessing.pool import Pool\n\nfrom pymongo import MongoClient\nfrom tqdm import tqdm\nimport gridfs\nfrom pdf_extractor.paragraphs import extract_paragraphs_pdf\n\ndb = MongoClient(\n host=os.environ['COVID_HOST'],\n connect=False\n)\ndb_connected = False\n_collection = None\nparser_version = 'pho_20200423'\nlaparams = {\n 'char_margin': 1.0,\n 'line_margin': 3.0\n}\n\n\ndef auth_db():\n \"\"\"Auth database later to avoid connecting before forking\"\"\"\n global db_connected, _collection\n\n if db_connected is False:\n _db = db[os.environ['COVID_DB']]\n\n _db.authenticate(\n name=os.environ['COVID_USER'],\n password=os.environ['COVID_PASS'],\n source=os.environ['COVID_DB']\n )\n collection = _db['Scraper_publichealthontario_fs.files']\n\n fs = gridfs.GridFS(_db, collection='Scraper_publichealthontario_fs')\n\n _collection = collection, fs\n\n return _collection\n\n\ndef handle_doc(file_obj):\n collection, fs = auth_db()\n\n # check again!\n doc = collection.find_one({'_id': file_obj['_id']})\n if 'pdf_extraction_version' in doc and \\\n doc['pdf_extraction_version'] == parser_version and \\\n 'parsed_date' in doc and \\\n doc['parsed_date'] > doc['uploadDate']:\n return None, None\n\n pdf_file = fs.find_one(file_obj['_id'])\n data = BytesIO(pdf_file.read())\n try:\n paragraphs = extract_paragraphs_pdf(data, laparams=laparams, return_dicts=True)\n collection.update(\n {'_id': file_obj['_id']},\n {'$set': {\n 'pdf_extraction_success': True,\n 'pdf_extraction_plist': paragraphs,\n 'pdf_extraction_exec': None,\n 'pdf_extraction_version': parser_version,\n 'parsed_date': datetime.datetime.now(),\n }})\n exc = None\n except Exception as e:\n paragraphs = None\n traceback.print_exc()\n exc = f'Failed to extract PDF {file_obj[\"filename\"]} {e}' + traceback.format_exc()\n collection.update(\n {'_id': file_obj['_id']},\n {'$set': {\n 'pdf_extraction_success': False,\n 'pdf_extraction_plist': None,\n 'pdf_extraction_exec': exc,\n 'pdf_extraction_version': parser_version,\n 'parsed_date': datetime.datetime.now(),\n }})\n\n return paragraphs, exc\n\n\ndef process_documents(processes):\n with Pool(processes=processes) as pool:\n collection, _ = auth_db()\n collection.create_index('parsed_date')\n collection.create_index('uploadDate')\n query = {\n '$or': [\n {'$expr': {'$lt': ['$parsed_date', '$uploadDate']}},\n {'pdf_extraction_version': {'$ne': parser_version}},\n ]\n\n }\n\n for paragraphs, exc in tqdm(\n pool.imap_unordered(\n handle_doc, collection.find(query), chunksize=1),\n total=collection.count_documents(query)):\n pass\n # print(exc)\n # with open('file.pdf', 'wb') as f:\n # data.seek(0)\n # f.write(data.read())\n #\n # with open('paragraphs.txt', 'w') as f:\n # for p in paragraphs:\n # f.write(p['text'] + '\\n')\n # sections = {}\n # last_sec = None\n # for p in paragraphs:\n # is_heading = 18 < p['bbox'][3] - p['bbox'][1] and p['bbox'][2] - p['bbox'][0] < 230\n # if is_heading:\n # last_sec = p['text'].lower()\n # sections[last_sec] = []\n # elif last_sec is not None:\n # sections[last_sec].append(p)\n # for heading, paragraphs in sections.items():\n # print(heading)\n # for p in paragraphs:\n # print(p['indention_level'], p['text'])\n # print('--')\n # print('-' * 70)\n # input()\n\n\nif __name__ == '__main__':\n process_documents(processes=multiprocessing.cpu_count())\n","sub_path":"parsers/_parse_pho_pdf.py","file_name":"_parse_pho_pdf.py","file_ext":"py","file_size_in_byte":4230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"39119411","text":"import time\nfrom typing import List\n\nimport numpy as np\n\nfrom vent.common.message import SensorValues, ControlSetting, Alarm, AlarmSeverity, ControlSettingName\n\n\nclass ControlModuleBase:\n # Abstract class for controlling hardware based on settings received\n # Functions:\n def __init__(self):\n self.sensor_values = None\n self.control_settings = None\n self.loop_counter = None\n self.active_alarms = {} # dictionary of active alarms\n self.logged_alarms = [] # list of all resolved alarms\n\n def get_sensors(self) -> SensorValues:\n # returns SensorValues\n # include a timestamp and loop counter\n pass\n\n def get_alarms(self) -> List[Alarm]:\n # Get a list of all alarms\n pass\n\n def get_active_alarms(self):\n # Get a dictionary of all active alarms\n pass\n\n def get_logged_alarms(self) -> List[Alarm]:\n # Get a list of inactive alarms\n pass\n\n def clear_logged_alarms(self):\n pass\n\n def set_control(self, control_setting: ControlSetting):\n # takes ControlSetting struct\n pass\n\n def get_control(self, control_setting_name: ControlSettingName) -> ControlSetting:\n pass\n\n def start(self, controlSettings):\n # start running\n # controls actuators to achieve target state\n # determined by settings and assessed by sensor values\n pass\n\n def stop(self):\n # stop running\n pass\n\n def test_critical_levels(min, max, value, name, active_alarms, logged_alarms):\n # Tests whether a variable exceeds its bounds, and produces an alert.\n pass\n\n\nclass ControlModuleDevice(ControlModuleBase):\n # Implement ControlModuleBase functions\n pass\n\n\nclass Balloon_Simulator:\n '''\n This is a simulator for inflating a balloon. \n For math, see https://en.wikipedia.org/wiki/Two-balloon_experiment\n '''\n\n def __init__(self, leak, delay):\n # Hard parameters for the simulation\n self.max_volume = 6 # Liters - 6?\n self.min_volume = 1.5 # Liters - baloon starts slightly inflated.\n self.PC = 20 # Proportionality constant that relates pressure to cm-H2O\n self.P0 = 0 # Minimum pressure.\n self.leak = leak\n self.delay = delay\n\n self.temperature = 37 # keep track of this, as is important output variable\n self.humidity = 90\n self.fio2 = 60\n\n # Dynamical parameters - these are the initial conditions\n self.current_flow = 0 # in unit liters/sec\n self.current_pressure = 0 # in unit cm-H2O\n self.r_real = (3 * self.min_volume / (4 * np.pi)) ** (1 / 3) # size of the lung\n self.current_volume = self.min_volume # in unit liters\n\n def get_pressure(self):\n return self.current_pressure\n\n def get_volume(self):\n return self.current_volume\n\n def set_flow(self, Qin, Qout):\n self.current_flow = Qin - Qout\n\n def update(self, dt): # Performs an update of duration dt [seconds]\n self.current_volume += self.current_flow * dt\n\n if self.leak:\n RC = 5 # pulled 5 sec out of my hat\n s = dt / (RC + dt)\n self.current_volume = self.current_volume + s * (self.min_volume - self.current_volume)\n\n # This is fromt the baloon equation, uses helper variable (the baloon radius)\n r_target = (3 * self.current_volume / (4 * np.pi)) ** (1 / 3)\n r0 = (3 * self.min_volume / (4 * np.pi)) ** (1 / 3)\n\n # Delay -> Expansion takes time\n if self.delay:\n RC = 0.1 # pulled these 100ms out of my hat\n s = dt / (RC + dt)\n self.r_real = self.r_real + s * (r_target - self.r_real)\n else:\n self.r_real = r_target\n\n self.current_pressure = self.P0 + (self.PC / (r0 ** 2 * self.r_real)) * (1 - (r0 / self.r_real) ** 6)\n\n # Temperature, humidity and o2 fluctuations modelled as OUprocess\n self.temperature = OUupdate(self.temperature, dt=dt, mu=37, sigma=0.3, tau=1)\n self.fio2 = OUupdate(self.fio2, dt=dt, mu=60, sigma=5, tau=1)\n self.humidity = OUupdate(self.humidity, dt=dt, mu=90, sigma=5, tau=1)\n if self.humidity > 100:\n self.humidity = 100\n\n\ndef OUupdate(variable, dt, mu, sigma, tau):\n '''\n This is a simple function to produce an OU process.\n It is used as model for fluctuations in measurement variables.\n inputs:\n variable: float value at previous time step\n dt : timestep\n mu : mean\n sigma : noise amplitude\n tau : time scale\n returns:\n new_variable : value of \"variable\" at next time step\n '''\n sigma_bis = sigma * np.sqrt(2. / tau)\n sqrtdt = np.sqrt(dt)\n new_variable = variable + dt * (-(variable - mu) / tau) + sigma_bis * sqrtdt * np.random.randn()\n return new_variable\n\n\nclass StateController:\n '''\n This is a class to control a respirator by iterating through set states with hard-coded valve settings\n '''\n\n def __init__(self):\n self.PIP = 22\n self.PIP_time = 1.0\n self.PEEP = 5\n self.PEEP_time = 0.5 # as fast as possible, try 500ms\n self.bpm = 10\n self.I_phase = 1.0\n self.Qin = 0\n self.Qout = 0\n self.pressure = 0\n self.volume = 0\n self.last_update = time.time()\n # Derived variables\n self.cycle_duration = 60 / self.bpm\n self.E_phase = self.cycle_duration - self.I_phase\n self.t_inspiration = self.PIP_time # time [sec] for the four phases\n self.t_plateau = self.I_phase - self.PIP_time\n self.t_expiration = self.PEEP_time\n self.t_PEEP = self.E_phase - self.PEEP_time\n\n # Parameters to keep track of breath-cycle\n self.cycle_start = time.time()\n self.cycle_waveforms = {} # saves the waveforms to meassure pip, peep etc.\n self.cycle_counter = 0\n\n def update_internalVeriables(self):\n self.cycle_duration = 60 / self.bpm\n self.E_phase = self.cycle_duration - self.I_phase\n self.t_inspiration = self.PIP_time\n self.t_plateau = self.I_phase - self.PIP_time\n self.t_expiration = self.PEEP_time\n self.t_PEEP = self.E_phase - self.PEEP_time\n\n def get_Qin(self):\n return self.Qin\n\n def get_Qout(self):\n return self.Qout\n\n def update(self, pressure):\n now = time.time()\n cycle_phase = now - self.cycle_start\n time_since_last_update = now - self.last_update\n self.last_update = now\n\n self.volume += time_since_last_update * (\n self.Qin - self.Qout) # Integrate what has happened within the last few seconds\n # NOTE: As Qin and Qout are set, this is what the controllr believes has happened. NOT A MEASUREMENT, MIGHT NOT BE REALITY!\n\n self.pressure = pressure\n\n if cycle_phase < self.t_inspiration: # ADD CONTROL dP/dt\n # to PIP, air in as fast as possible\n self.Qin = 1\n self.Qout = 0\n if self.pressure > self.PIP:\n self.Qin = 0\n elif cycle_phase < self.I_phase: # ADD CONTROL P\n # keep PIP plateau, let air in if below\n self.Qin = 0\n self.Qout = 0\n if self.pressure < self.PIP:\n self.Qin = 1\n elif cycle_phase < self.t_expiration + self.I_phase:\n # to PEEP, open exit valve\n self.Qin = 0\n self.Qout = 1\n if self.pressure < self.PEEP:\n self.Qout = 0\n elif cycle_phase < self.cycle_duration:\n # keeping PEEP, let air in if below\n self.Qin = 0\n self.Qout = 0\n if self.pressure < self.PEEP:\n self.Qin = 1\n else:\n self.cycle_start = time.time() # new cycle starts\n self.cycle_counter += 1\n\n if self.cycle_counter not in self.cycle_waveforms.keys(): # if this cycle doesn't exist yet, start it\n self.cycle_waveforms[self.cycle_counter] = np.array([[0, pressure, self.volume]]) # add volume\n else:\n data = self.cycle_waveforms[self.cycle_counter]\n data = np.append(data, [[cycle_phase, pressure, self.volume]], axis=0)\n self.cycle_waveforms[self.cycle_counter] = data\n\n\nclass ControlModuleSimulator(ControlModuleBase):\n # Implement ControlModuleBase functions\n def __init__(self):\n super().__init__() # get all from parent\n\n self.Balloon = Balloon_Simulator(leak=True, delay=False)\n self.Controller = StateController()\n self.loop_counter = 0\n self.pressure = 15\n self.last_update = time.time()\n\n # Variable limits to raise alarms, initialized as +- 10% of what the controller initializes\n self.PIP_min = self.Controller.PIP * 0.9\n self.PIP_max = self.Controller.PIP * 1.1\n self.PIP_lastset = time.time()\n self.PIP_time_min = self.Controller.PIP_time * 0.9\n self.PIP_time_max = self.Controller.PIP_time * 1.1\n self.PIP_time_lastset = time.time()\n self.PEEP_min = self.Controller.PEEP * 0.9\n self.PEEP_max = self.Controller.PEEP * 1.1\n self.PEEP_lastset = time.time()\n self.bpm_min = self.Controller.bpm * 0.9\n self.bpm_max = self.Controller.bpm * 1.1\n self.bpm_lastset = time.time()\n self.I_phase_min = self.Controller.I_phase * 0.9\n self.I_phase_max = self.Controller.I_phase * 1.1\n self.I_phase_lastset = time.time()\n\n # These are measurement values from the last breath cycle.\n # NOTE: For the controller target value, see Controller.PEEP etc.\n self.PEEP = None # Measured valued of PEEP\n self.PIP = None # Measured value of PIP\n self.first_PIP = None # Time of reaching PIP plateau\n self.I_phase = None # Time when PIP plateau ends is end of inspiratory phase\n self.first_PEEP = None # Time when PEEP is reached first\n self.last_PEEP = None # Last time of PEEP - by definition end of breath cycle\n self.bpm = None # Measured breathing rate, by definition 60sec / length_of_breath_cycle\n self.vte = None # Maximum air displacement in last breath cycle\n\n def test_critical_levels(self, min, max, value, name):\n '''\n This tests whether a variable is within bounds.\n If it is, and an alarm existed, then the \"alarm_end_time\" is set.\n If it is NOT, a new alarm is generated and appendede to the alarm-list.\n Input:\n min: minimum value (e.g. 2)\n max: maximum value (e.g. 5)\n value: test value (e.g. 3)\n name: parameter type (e.g. \"PIP\", \"PEEP\" etc.)\n '''\n if (value < min) or (value > max): # If the variable is not within limits\n if name not in self.active_alarms.keys(): # And and alarm for that variable doesn't exist yet -> RAISE ALARM.\n new_alarm = Alarm(alarm_name=name, is_active=True, severity=AlarmSeverity.RED, \\\n alarm_start_time=time.time(), alarm_end_time=None)\n self.active_alarms[name] = new_alarm\n else: # Else: if the variable is within bounds,\n if name in self.active_alarms.keys(): # And an alarm exists -> inactivate it.\n old_alarm = self.active_alarms[name]\n old_alarm.alarm_end_time = time.time()\n old_alarm.is_active = False\n self.logged_alarms.append(old_alarm)\n del self.active_alarms[name]\n\n def update_alarms(self):\n ''' This goes through the LAST waveform, and updates alarms.'''\n this_cycle = self.Controller.cycle_counter\n\n if this_cycle > 1: # The first cycle for which we can calculate this is cycle \"1\".\n data = self.Controller.cycle_waveforms[this_cycle - 1]\n phase = data[:, 0]\n pressure = data[:, 1]\n volume = data[:, 2]\n\n self.vte = np.max(volume) - np.min(volume)\n\n # get the pressure niveau heuristically (much faster than fitting)\n # 20 and 80 percentiles pulled out of my hat.\n self.PEEP = np.percentile(pressure, 20)\n self.PIP = np.percentile(pressure, 80)\n\n # measure time of reaching PIP, and leaving PIP\n self.first_PIP = phase[np.min(np.where(pressure > self.PIP))]\n self.I_phase = phase[np.max(np.where(pressure > self.PIP))]\n\n # and measure the same for PEEP\n self.first_PEEP = phase[np.min(np.where(np.logical_and(pressure < self.PEEP, phase > 1)))]\n self.bpm = 60. / phase[-1] # 60 sec divided by the duration of last waveform\n\n self.test_critical_levels(min=self.PIP_min, max=self.PIP_max, value=self.PIP, name=\"PIP\")\n self.test_critical_levels(min=self.PIP_time_min, max=self.PIP_time_max, value=self.first_PIP,\n name=\"PIP_TIME\")\n self.test_critical_levels(min=self.PEEP_min, max=self.PEEP_max, value=self.PEEP, name=\"PEEP\")\n self.test_critical_levels(min=self.bpm_min, max=self.bpm_max, value=self.bpm, name=\"BREATHS_PER_MINUTE\")\n self.test_critical_levels(min=self.I_phase_min, max=self.I_phase_max, value=self.I_phase, name=\"I_PHASE\")\n\n def get_sensors(self):\n # returns SensorValues and a time stamp\n\n self.update_alarms() # Make sure we are up to date\n\n self.sensor_values = SensorValues(pip=self.Controller.PIP,\n peep=self.PEEP,\n fio2=self.Balloon.fio2,\n temp=self.Balloon.temperature,\n humidity=self.Balloon.humidity,\n pressure=self.Balloon.current_pressure,\n vte=self.vte,\n breaths_per_minute=self.bpm,\n inspiration_time_sec=self.I_phase,\n timestamp=time.time())\n\n return self.sensor_values\n\n def get_alarms(self):\n # Returns all alarms as a list\n ls = self.logged_alarms\n for alarm_key in self.active_alarms.keys():\n ls.append(self.active_alarms[alarm_key])\n return ls\n\n def get_active_alarms(self):\n # Returns only the active alarms\n return self.active_alarms\n\n def get_logged_alarms(self):\n # Returns only the inactive alarms\n return self.logged_alarms\n\n def set_control(self, control_setting):\n ''' Updates the control settings. '''\n if control_setting.name == ControlSettingName.PIP:\n self.Controller.PIP = control_setting.value\n self.PIP_min = control_setting.min_value\n self.PIP_max = control_setting.max_value\n self.PIP_lastset = control_setting.timestamp\n\n elif control_setting.name == ControlSettingName.PIP_TIME:\n self.Controller.PIP_time = control_setting.value\n self.PIP_time_min = control_setting.min_value\n self.PIP_time_max = control_setting.max_value\n self.PIP_time_lastset = control_setting.timestamp\n\n elif control_setting.name == ControlSettingName.PEEP:\n self.Controller.PEEP = control_setting.value\n self.PEEP_min = control_setting.min_value\n self.PEEP_max = control_setting.max_value\n self.PEEP_lastset = control_setting.timestamp\n\n elif control_setting.name == ControlSettingName.BREATHS_PER_MINUTE:\n self.Controller.bpm = control_setting.value\n self.bpm_min = control_setting.min_value\n self.bpm_max = control_setting.max_value\n self.bpm_lastset = control_setting.timestamp\n\n elif control_setting.name == ControlSettingName.INSPIRATION_TIME_SEC:\n self.Controller.I_phase = control_setting.value\n self.I_phase_min = control_setting.min_value\n self.I_phase_max = control_setting.max_value\n self.I_phase_lastset = control_setting.timestamp\n\n else:\n raise KeyError(\"You cannot set the variabe: \" + str(control_setting.name))\n\n self.Controller.update_internalVeriables()\n\n def get_control(self, control_setting_name: ControlSettingName) -> ControlSetting:\n ''' Updates the control settings. '''\n if control_setting_name == ControlSettingName.PIP:\n return ControlSetting(control_setting_name,\n self.Controller.PIP,\n self.PIP_min,\n self.PIP_max,\n self.PIP_lastset)\n elif control_setting_name == ControlSettingName.PIP_TIME:\n return ControlSetting(control_setting_name,\n self.Controller.\n PIP_time,\n self.PIP_time_min,\n self.PIP_time_max,\n self.PIP_time_lastset, )\n elif control_setting_name == ControlSettingName.PEEP:\n return ControlSetting(control_setting_name,\n self.Controller.PEEP,\n self.PEEP_min,\n self.PEEP_max,\n self.PEEP_lastset)\n elif control_setting_name == ControlSettingName.BREATHS_PER_MINUTE:\n return ControlSetting(control_setting_name,\n self.Controller.bpm,\n self.bpm_min,\n self.bpm_max,\n self.bpm_lastset)\n elif control_setting_name == ControlSettingName.INSPIRATION_TIME_SEC:\n return ControlSetting(control_setting_name,\n self.Controller.I_phase,\n self.I_phase_min,\n self.I_phase_max,\n self.I_phase_lastset)\n else:\n raise KeyError(\"You cannot set the variabe: \" + str(control_setting_name))\n\n def run(self):\n # start running\n # controls actuators to achieve target state\n # determined by settings and assessed by sensor values\n\n self.loop_counter += 1\n now = time.time()\n self.Balloon.update(now - self.last_update)\n self.last_update = now\n\n pressure = self.Balloon.get_pressure()\n temperature = self.Balloon.temperature\n\n self.Controller.update(pressure)\n Qout = self.Controller.get_Qout()\n Qin = self.Controller.get_Qin()\n self.Balloon.set_flow(Qin, Qout)\n\n def stop(self):\n # stop running\n pass\n\n def recvUIHeartbeat(self):\n return time.time()\n\n\ndef get_control_module(sim_mode=False):\n if sim_mode == True:\n return ControlModuleSimulator()\n else:\n return ControlModuleDevice()\n","sub_path":"vent/controller/control_module.py","file_name":"control_module.py","file_ext":"py","file_size_in_byte":19195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"364351101","text":"from typing import List\n\nclass Solution:\n def moveZeroes(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n i = 0\n leng = len(nums) - 1\n while i < leng:\n \n if nums[i] == 0:\n j = i + 1\n while j < (leng + 1):\n if nums[j] != 0:\n nums[i], nums[j] = nums[j], nums[i]\n break\n j += 1\n \n i += 1\n\n\ntestcase = [0,1,0,3,12]\nmysol = Solution() \nfor i in testcase:\n print(mysol.moveZeroes(testcase))\n ","sub_path":"NewEx.py","file_name":"NewEx.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"2549721","text":"import requests\nfrom lxml import etree\nfrom retrying import retry\nimport os, datetime, time\n\n\nclass Spider:\n def __init__(self):\n self.url_temp = 'https://movie.douban.com/top250?start={}'\n self.headers = {\n \"User-Agent\":\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.75 Safari/537.36\",\n }\n self.mkdir() # 创建本次爬虫的目录用户处理数据\n\n # 创建文件夹函数\n def mkdir(self):\n # 文件名为 类名+本次启动时间\n file = __class__.__name__ + datetime.datetime.now().strftime('%Y%m%d_%H%M%S')\n # 创建文件\n os.makedirs(file)\n # 切换至文件夹下\n os.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), file))\n\n # 根据url地址规律,构造url\n def get_url_list(self):\n url_list = [self.url_temp.format(i) for i in range(0, 25 * 10, 25)]\n return url_list\n\n # 让被装饰的函数反复执行三次,三次全部报错都会报错,中间有一次正常,程序继续\n @retry(stop_max_attempt_number=3)\n def _parse_url(self, url):\n response = requests.get(url, headers=self.headers, timeout=5)\n return response\n\n # 发送请求,获取响应\n def parse_url(self, url):\n try:\n response = self._parse_url(url)\n return response.content\n except:\n print('处理出错:', url)\n return ''\n\n # 提取数据\n def get_content(self, html_str):\n html = etree.HTML(html_str)\n # 1. 分组\n elements = html.xpath('//div[@class=\"article\"]//li')\n content_list = list()\n for element in elements:\n item = {}\n # item['title'] = element.xpath()\n item['title'] = element.xpath('.//div[@class=\"info\"]/div/a/span[1]/text()')\n item['title'] = item['title'] if len(item['title'][0]) == 0 else item['title'][0]\n item['img'] = element.xpath('.//div[@class=\"pic\"]/a/img/@src')\n item['img'] = item['img'] if len(item['img'][0]) == 0 else item['img'][0]\n content_list.append(item)\n return content_list\n\n # 处理数据\n def save_content(self, contents):\n for content in contents:\n filename = content['title'] + '.jpg'\n with open(filename, 'wb') as f:\n # wb 以二进制格式打开文件,并且采用只写模式,一般用于非文本文件,如图片,声音\n try:\n f.write(self.parse_url(content['img'])) # 二进制保存\n print(\"保存成功:\", filename)\n except:\n print(\"保存失败:\", filename)\n\n # 实现主要逻辑\n def run(self):\n # 1. 根据url地址规律,构造url_list\n url_list = self.get_url_list()\n # 2. 发送请求,获取响应\n for url in url_list:\n # 每次访问睡眠 1 秒,访问服务器识别为爬虫\n time.sleep(1)\n html_str = self.parse_url(url).decode()\n # 3. 提取数据\n content = self.get_content(html_str)\n # 4. 处理数据\n self.save_content(content)\n\n\nif __name__ == '__main__':\n Spider().run()\n","sub_path":"DoubanSpider.py","file_name":"DoubanSpider.py","file_ext":"py","file_size_in_byte":3310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"515014571","text":"# from mvnc import mvncapi as mvnc\n\nimport numpy as np\nimport argparse\nimport time\nimport cv2\nimport os\n\n# from openvino.inference_engine import IENetwork, IEPlugin\nfrom openvino.inference_engine import IENetwork, IECore\nie = IECore()\nprint(ie.available_devices)\nwhile True: pass\n\nmy_confidence = 0.5\nmy_threshold = 0.3\n\nlabelsPath = \"coco.names\"\nLABELS = open(labelsPath).read().strip().split(\"\\n\")\nnp.random.seed(42)\nCOLORS = np.random.randint(0, 255, size=(len(LABELS), 3),\n\tdtype=\"uint8\")\n\nweightsPath = \"yolov3.weights\"\nconfigPath\t= \"yolov3.cfg\"\nprint(\"[INFO] loading YOLO from disk...\")\nnet = cv2.dnn.readNetFromDarknet(configPath, weightsPath)\n\ncap = cv2.VideoCapture(0)\n\nwhile True:\n\tstart = time.time()\n\t_,image = cap.read()\n\n\t(H, W) = image.shape[:2]\n\tln = net.getLayerNames()\n\tln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]\n\tblob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416),\n\t\tswapRB=True, crop=False)\n\tnet.setInput(blob)\n\tlayerOutputs = net.forward(ln)\n\t\n\n\tboxes = []\n\tconfidences = []\n\tclassIDs = []\n\n\tfor output in layerOutputs:\n\t\tfor detection in output:\n\t\t\tscores = detection[5:]\n\t\t\tclassID = np.argmax(scores)\n\t\t\tconfidence = scores[classID]\n\t\t\tif confidence > my_confidence:\n\t\t\t\tbox = detection[0:4] * np.array([W, H, W, H])\n\t\t\t\t(centerX, centerY, width, height) = box.astype(\"int\")\n\t\t\t\tx = int(centerX - (width / 2))\n\t\t\t\ty = int(centerY - (height / 2))\n\t\t\t\tboxes.append([x, y, int(width), int(height)])\n\t\t\t\tconfidences.append(float(confidence))\n\t\t\t\tclassIDs.append(classID)\n\n\tidxs = cv2.dnn.NMSBoxes(boxes, confidences, my_confidence, my_threshold)\n\n\tif len(idxs) > 0:\n\t\tfor i in idxs.flatten():\n\t\t\t(x, y) = (boxes[i][0], boxes[i][1])\n\t\t\t(w, h) = (boxes[i][2], boxes[i][3])\n\t\t\tcolor = [int(c) for c in COLORS[classIDs[i]]]\n\t\t\tcv2.rectangle(image, (x, y), (x + w, y + h), color, 2)\n\t\t\ttext = \"{}: {:.4f}\".format(LABELS[classIDs[i]], confidences[i])\n\t\t\tcv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX,\n\t\t\t\t0.5, color, 2)\n\n\n\tcv2.imshow(\"Image\", image)\n\tif cv2.waitKey(1) & 0xFF == ord('q'): break\n\n\tend = time.time()\n\tprint(\"[INFO] FPS {:.2F}\".format(1/(end - start)))\n\t# print(\"[INFO] YOLO took {:.6f} seconds\".format(end - start))\n","sub_path":"yolov3/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"317583348","text":"# Packages used: NetworkX -- for tree representation as directed acyclic graphs\r\n\r\nimport networkx as nx\r\n\r\nclass Compute_measures_rand(object):\r\n def __init__(self, tree, root):\r\n self.tree=tree # tree encodes the nodes and edges content in dictionary format. It uses directed graph (DiGraph) feature of networkX package. For example, nodes are encoded like this - tree.nodes={1:{form:'this',POS:'PRN'},2:{...}} \r\n self.root=root # ROOT is an abstract node in the tree and is encoded as empty and with name=0 \r\n \r\n def dependency_direction(self, edge): # Computes the direction of an edge (i.e., dependency) according to relative position of dependent and head \r\n direction=''\r\n if edge[0]>edge[1]: # edge is a list data type in the format [head,dependent]\r\n direction='RL'\r\n else:\r\n direction='LR'\r\n\r\n return direction # return direction as 'LR' (Left-to-Right) or RL ('Right-to-Left') \r\n \r\n def dependency_distance(self, edge): # Computes the dependency length i.e., no. of nodes between head and its dependent \r\n dd=0\r\n if edge[0]>edge[1]: \r\n for nodex in nx.descendants(self.tree, self.root): \r\n if edge[1]<nodex<edge[0]: # all the nodes that lies linearly between dependent and head \r\n dd+=1\r\n else:\r\n for nodex in nx.descendants(self.tree, self.root):\r\n if edge[0]<nodex<edge[1]:\r\n dd+=1\r\n return dd # returns the dependency distance of the edge\r\n \r\n def is_projective(self, edge): # Checks if an edge is projective or not and returns a boolean value.\r\n projective=True\r\n edge_span=[] \r\n if edge[0]>edge[1]: \r\n for nodex in nx.descendants(self.tree, self.root): \r\n if edge[1]<nodex<edge[0]:\r\n edge_span.append(nodex) \r\n else:\r\n for nodex in nx.descendants(self.tree, self.root):\r\n if edge[0]<nodex<edge[1]:\r\n edge_span.append(nodex)\r\n\r\n flag=0\r\n for nodeI in edge_span:\r\n if not self.tree.nodes[nodeI]['head'] in edge_span: # if the head of any intervening node exists outside the span of the edge\r\n if not self.tree.nodes[nodeI]['head']==edge[0]:\r\n if not self.tree.nodes[nodeI]['head']==edge[1]:\r\n flag += 1\r\n if not flag==0:\r\n projective=False\r\n return projective # Returns TRUE is edge is projective otherwise FALSE\r\n\r\n def edge_degree(self, edge): # Computes the number of edges causing non-projectivity \r\n eD=0\r\n edge_span=[] \r\n if edge[0]>edge[1]: \r\n for nodex in nx.descendants(self.tree, self.root): \r\n if edge[1]<nodex<edge[0]:\r\n edge_span.append(nodex) \r\n else:\r\n for nodex in nx.descendants(self.tree, self.root):\r\n if edge[0]<nodex<edge[1]:\r\n edge_span.append(nodex)\r\n\r\n for nodeI in edge_span:\r\n if not self.tree.nodes[nodeI]['head'] in edge_span: # if the head of any intervening node exists outside the span of the edge\r\n if not self.tree.nodes[nodeI]['head']==edge[0]:\r\n if not self.tree.nodes[nodeI]['head']==edge[1]:\r\n eD += 1 \r\n return eD \r\n\r\n def gap_degree(self, node): # Computes the gaps in the projection chain containing maximum number of gaps \r\n chains_gapD=[]\r\n terminals=[]\r\n for nodex in self.tree.nodes:\r\n if self.tree.out_degree(nodex)==0:\r\n terminals.append(nodex)\r\n\r\n for nodeT in terminals: \r\n gapD=0\r\n if nx.has_path(self.tree, node, nodeT): \r\n pathx=nx.all_simple_paths(self.tree, node, nodeT, cutoff=None) # Projection chain from ROOT to each Terminal node is encoded as list of nodes in the chain \r\n for item in pathx:\r\n pathy=item\r\n for nodeP in item:\r\n if not nodeP==self.root:\r\n if not self.tree.nodes[nodeP]['head']==self.root:\r\n if not self.is_projective([self.tree.nodes[nodeP]['head'],nodeP]): # If any edge in a projection chain is non-projective \r\n gapD=gapD+1 # No. of non-projective edges in a projection chain = No. of gap degree\r\n chains_gapD.append(gapD)\r\n\r\n gap_deg=max(chains_gapD) # Gap degree of a node is the maximum gap degree in its dependents\r\n return gap_deg\r\n\r\n def gapnodes(self, pathx): # Returns all the nodes which causes GAP in the projection of a node\r\n nodeM=[]\r\n for nodex in pathx:\r\n if not nodex==self.root:\r\n if not self.tree.nodes[nodex]['head']==self.root:\r\n if not self.is_projective([self.tree.nodes[nodex]['head'],nodex]):\r\n cross_dep=nodex\r\n cross_head=self.tree.nodes[cross_dep]['head'] \r\n edge_span=[] \r\n if cross_head>cross_dep: \r\n for nodev in nx.descendants(self.tree, self.root): \r\n if cross_dep<nodev<cross_head:\r\n edge_span.append(nodev) \r\n else:\r\n for nodev in nx.descendants(self.tree, self.root):\r\n if cross_head<nodev<cross_dep:\r\n edge_span.append(nodev)\r\n for nodeI in edge_span:\r\n if not self.tree.nodes[nodeI]['head'] in edge_span: # if the head of any intervening node exists outside the span of the edge\r\n if not self.tree.nodes[nodeI]['head']==cross_head:\r\n if not self.tree.nodes[nodeI]['head']==cross_dep:\r\n nodeM.append(nodeI)\r\n return nodeM\r\n\r\n def illnestedness(self,node,gapD):\r\n k_illnest=0\r\n if gapD==0:\r\n k_illnest=0\r\n else:\r\n illnest = []\r\n all_gapped_chains=[]\r\n for nodex in nx.descendants(self.tree, self.root):\r\n if not nodex==self.root:\r\n if not self.tree.nodes[nodex]['head']==self.root:\r\n if not self.is_projective([self.tree.nodes[nodex]['head'],nodex]):\r\n if nx.has_path(self.tree, node, nodex):\r\n pathx=nx.all_simple_paths(self.tree, node, nodex, cutoff=None)\r\n for item in pathx:\r\n all_gapped_chains.append(item) # It has all the projection chains from root to dependents of crossing arcs\r\n # i.e., all possible chains which can interleave with other \r\n chains_with_gaps=[]\r\n for chainx in all_gapped_chains:\r\n flag=0\r\n for chainy in all_gapped_chains:\r\n if set(chainx) < set(chainy):\r\n flag=flag+1\r\n if flag==0:\r\n chains_with_gaps.append(chainx)\r\n \r\n for pathz in chains_with_gaps:\r\n #print(pathz)\r\n num_interL=0 # Variable for number of chains that can interleave with a single chain in question\r\n nodeM=self.gapnodes(pathz)\r\n for pathy in chains_with_gaps:\r\n if not pathy==pathz:\r\n flag=0\r\n for nodeC in nodeM:\r\n if nodeC in pathy:\r\n flag=flag+1\r\n if not flag==0:\r\n nodeMM=self.gapnodes(pathy)\r\n flagg=0\r\n for nodeCC in nodeMM:\r\n if nodeCC in pathz:\r\n flagg=flagg+1\r\n if not flagg==0:\r\n num_interL = num_interL + 1\r\n illnest.append(num_interL)\r\n k_illnest = max(illnest)\r\n return k_illnest\r\n\r\n def gapD_hist(self):\r\n gapd_histogram={}\r\n for nodex in self.tree.nodes:\r\n gapD=self.gap_degree(nodex)\r\n if gapD in gapd_histogram.keys():\r\n gapd_histogram[gapD]=gapd_histogram[gapD]+1\r\n else:\r\n gapd_histogram[gapD]=1\r\n return gapd_histogram \r\n\r\n def projection_degree(self, node):\r\n size_chains=[]\r\n terminals=[]\r\n for nodex in self.tree.nodes:\r\n if self.tree.out_degree(nodex)==0:\r\n terminals.append(nodex)\r\n\r\n for nodeT in terminals:\r\n size=0\r\n if nx.has_path(self.tree, node, nodeT):\r\n pathx=nx.all_simple_paths(self.tree, node, nodeT, cutoff=None) # Projection chain from ROOT to each Terminal node is encoded as list of nodes in the chain\r\n for item in pathx: \r\n size=len(item)-1\r\n size_chains.append(size)\r\n proj_degree=max(size_chains) # Projection degree = No. of nodes in the longest projection chain from ROOT to a terminal node \r\n return proj_degree\r\n\r\n def projD_hist(self):\r\n projd_histogram={}\r\n for nodex in self.tree.nodes:\r\n projD=self.projection_degree(nodex)\r\n if projD in projd_histogram.keys():\r\n projd_histogram[projD]=projd_histogram[projD]+1\r\n else:\r\n projd_histogram[projD]=1\r\n return projd_histogram \r\n\r\n def arity(self): # Computes arity of the tree using out-degree of nodes \r\n tree_arity=self.tree.out_degree(list(self.tree.nodes)) # returns a dictionary containing nodenames as keys and its out-degree (or arity) as its values\r\n max_arity=max([x[1] for x in tree_arity]) # Maximum out-degree = maximum arity in the tree\r\n avg_arity=sum([x[1] for x in tree_arity])/len([x[1] for x in tree_arity])\r\n histogram={}\r\n for arityx in [x[1] for x in tree_arity]:\r\n if arityx in histogram.keys():\r\n histogram[arityx]=histogram[arityx]+1 # Creates arity histogram i.e. frequency of each arity\r\n else:\r\n histogram[arityx]=1\r\n arity_histogram=histogram \r\n return [max_arity, avg_arity, tree_arity, arity_histogram] \r\n\r\n def endpoint_crossing(self,edge):\r\n edge_span=[]\r\n if edge[0]>edge[1]:\r\n for nodex in nx.descendants(self.tree, self.root):\r\n if edge[1]<nodex<edge[0]:\r\n edge_span.append(nodex)\r\n else:\r\n for nodex in nx.descendants(self.tree, self.root):\r\n if edge[0]<nodex<edge[1]:\r\n edge_span.append(nodex)\r\n\r\n endpoint={}\r\n \r\n for nodeI in edge_span:\r\n if not self.tree.nodes[nodeI]['head'] in edge_span: # nodes intervening the edge span which are not dominated by the any node in the edge span\r\n if not self.tree.nodes[nodeI]['head']==edge[0]:\r\n if not self.tree.nodes[nodeI]['head']==edge[1]:\r\n endpoint[self.tree.nodes[nodeI]['head']]=1 # creates a dictionary of all nodes having their outside their span. This dictionary has keys as 'heads' of the intervening nodes\r\n \r\n endpoint_cross=len(endpoint) # If the intervening nodes belongs to more than head outside the edge span, then 1-endpoint crossing constraint is voilated\r\n return endpoint_cross # returns the no. of heads outside the edge span which dominates the intervening nodes \r\n\r\n def compute_all(self):\r\n Arity=self.arity()\r\n Projection_degree=self.projection_degree()\r\n Gap_degree=self.gap_degree()\r\n direction={}\r\n dep_distane={}\r\n projectivity={}\r\n Edge_degree={}\r\n endpoint_cross={}\r\n for edgex in self.tree.edges:\r\n direction[edgex]=self.dependency_direction(edgex)\r\n dep_distance[edgex]=self.dependency_distance(edgex)\r\n projectivity[edgex]=self.is_projective(edgex)\r\n Edge_degree[edgex]=self.edge_degree(edgex)\r\n endpoint_cross[edgex]=self.endpoint_crossing(edgex)\r\n\r\n return [Arity, Projection_degree, Gap_degree, direction, dep_distance, projectivity, Edge_degree, endpoint_cross]\r\n\r\n def all_dependent_constraint(self,edge):\r\n all_dep_deg=0\r\n edge_span=[]\r\n if edge[0]>edge[1]:\r\n for nodex in nx.descendants(self.tree, self.root):\r\n if edge[1]<nodex<edge[0]:\r\n edge_span.append(nodex) \r\n \r\n else:\r\n for nodex in nx.descendants(self.tree, self.root):\r\n if edge[0]<nodex<edge[1]:\r\n edge_span.append(nodex)\r\n\r\n if not self.is_projective(edge):\r\n for nodey in edge_span:\r\n if not (edge[0] in nx.ancestors(self.tree, nodey)): # if a node 'x' occurring the edge span is not dominated by the head of the edge\r\n int_node=nodey\r\n if not int_node==1000:\r\n for edgex in self.tree.edges:\r\n if edgex[1]==int_node:\r\n int_head=edgex[0]\r\n dep_int=0\r\n for nodeI in edge_span:\r\n if self.tree.nodes[nodeI]['head']==int_head:\r\n dep_int=dep_int+1\r\n else:\r\n dep_int=dep_int\r\n all_dep=0\r\n for nodeJ in nx.descendants(self.tree, self.root):\r\n if self.tree.nodes[nodeJ]['head']==int_head:\r\n all_dep=all_dep+1\r\n else:\r\n all_dep=all_dep\r\n all_dep_deg=all_dep-dep_int\r\n else:\r\n all_dep_deg=0 \r\n else:\r\n all_dep_deg=100\r\n\r\n return all_dep_deg\r\n \r\n def hdd(self,edge):\r\n HDD=0\r\n edge_span=[]\r\n if edge[0]>edge[1]:\r\n for nodex in nx.descendants(self.tree, self.root):\r\n if edge[1]<nodex<edge[0]:\r\n edge_span.append(nodex) \r\n \r\n else:\r\n for nodex in nx.descendants(self.tree, self.root):\r\n if edge[0]<nodex<edge[1]:\r\n edge_span.append(nodex)\r\n\r\n if not self.is_projective(edge):\r\n for nodeI in edge_span:\r\n if not self.tree.nodes[nodeI]['head'] in edge_span: # nodes intervening the edge span which are not dominated by the any node in the edge span\r\n if not self.tree.nodes[nodeI]['head']==edge[0]:\r\n if not self.tree.nodes[nodeI]['head']==edge[1]:\r\n int_node=nodeI\r\n if not int_node==self.root:\r\n for edgex in self.tree.edges:\r\n if edgex[1]==int_node:\r\n int_head=edgex[0]\r\n if nx.has_path(self.tree, int_head, edge[0]):\r\n pathx=nx.all_simple_paths(self.tree, int_head, edge[0], cutoff=None)\r\n for item in pathx:\r\n HDD=len(item)-1\r\n elif nx.has_path(self.tree, edge[0], int_head):\r\n pathx=nx.all_simple_paths(self.tree, edge[0], int_head, cutoff=None)\r\n for item in pathx:\r\n HDD=len(item)-1\r\n else:\r\n HDD=1\r\n else:\r\n HDD=2\r\n \r\n return HDD\r\n \r\n","sub_path":"Measures_rand.py","file_name":"Measures_rand.py","file_ext":"py","file_size_in_byte":17755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"107300019","text":"\"\"\"Tests for the collectv2 module.\"\"\"\nimport random\nimport threading\nfrom pathlib import Path\nfrom asyncio import Queue\nfrom typing import Tuple\n\nimport pytest\n\nfrom common.collectv2 import TargetRunner, Collector\n\nN_REGIONS: int = 3\n\n\ndef touch_target(_: Path, output_dir: Path, *args, **kwargs) -> bool:\n \"\"\"Target used with the collector which just creates a touch file.\"\"\"\n # pylint: disable=unused-argument\n (output_dir / \"touch\").touch(exist_ok=False)\n return True\n\n\ndef failing_target(infile, output_dir, region_id, client_id):\n # pylint: disable=unused-argument\n \"\"\"Returns false when client_id equals the region_id.\"\"\"\n if client_id == region_id:\n (output_dir / \"touch\").write_text(\"failed\")\n return False\n (output_dir / \"touch\").write_text(\"succeded\")\n return True\n\n\ndef randomly_failing_target(chance: float, seed, raise_on_err=False):\n \"\"\"A thread safe target which randomly fail with the specified chance.\"\"\"\n assert 0 < chance < 1\n\n rng = random.Random(seed)\n lock = threading.Lock()\n\n # pylint: disable=unused-argument\n def _randomly_failing_target(infile, output_dir, region_id, client_id):\n with lock:\n value = rng.random()\n\n if value <= chance and raise_on_err:\n raise TargetError()\n if value <= chance:\n (output_dir / \"touch\").write_text(\"failed\")\n return False\n (output_dir / \"touch\").write_text(\"succeded\")\n return True\n\n return _randomly_failing_target\n\n\nclass TargetError(RuntimeError):\n \"\"\"An arbitrary error raised by the target.\"\"\"\n\n\ndef exception_target(*args, **kwargs):\n \"\"\"Target that always raises TargetError.\"\"\"\n raise TargetError(\"This will always raise\")\n\n\ndef create_queues(n_regions: int, n_clients: int):\n \"\"\"Create n_region queues each with client_ids from 0 to n_clients.\"\"\"\n region_queues: Tuple[Queue, ...] = tuple(Queue() for _ in range(n_regions))\n for queue in region_queues:\n for i in range(n_clients):\n queue.put_nowait(i)\n return region_queues\n\n\n@pytest.mark.asyncio\nasync def test_collects_regions(tmp_path: Path):\n \"\"\"It should collect the specified number of files across all regions.\"\"\"\n n_instances = 5\n collector = TargetRunner(\n touch_target, Path(), tmp_path, create_queues(N_REGIONS, 1), delay=0\n )\n is_success = await collector.run(n_instances)\n assert is_success\n assert (tmp_path / \"region_id~0/status~success/run~0/touch\").is_file()\n assert (tmp_path / \"region_id~1/status~success/run~0/touch\").is_file()\n assert (tmp_path / \"region_id~2/status~success/run~0/touch\").is_file()\n assert (tmp_path / \"region_id~0/status~success/run~1/touch\").is_file()\n assert (tmp_path / \"region_id~1/status~success/run~1/touch\").is_file()\n assert not (tmp_path / \"region_id~2/status~success/run~1/touch\").is_file()\n\n\n@pytest.mark.asyncio\nasync def test_continues_collection(tmp_path: Path):\n \"\"\"It should continue an already partially started collection.\"\"\"\n n_instances = 8\n\n all_files = [\n (tmp_path / f\"region_id~{i}/status~success/run~{j}/touch\")\n for j in range(4) for i in range(N_REGIONS)\n ]\n already_complete = all_files[:5]\n to_be_completed = all_files[5:n_instances]\n not_to_exist = all_files[n_instances:]\n\n for path in already_complete:\n path.parent.mkdir(parents=True)\n path.write_text(\"completed\")\n\n collector = TargetRunner(\n touch_target, Path(), tmp_path, create_queues(N_REGIONS, 1), delay=0\n )\n is_success = await collector.run(n_instances)\n assert is_success\n\n # Check that the prior completed still contain the same text\n for path in already_complete:\n assert path.read_text() == \"completed\"\n # Check that the ones to be completed exist\n for path in to_be_completed:\n assert path.is_file()\n # Check that no more were created\n for path in not_to_exist:\n assert not path.exists()\n\n\n@pytest.mark.asyncio\nasync def test_continues_with_failures(tmp_path: Path):\n \"\"\"It should continue an already partially started collection.\"\"\"\n n_instances = 9\n collector = TargetRunner(\n touch_target, Path(), tmp_path, create_queues(N_REGIONS, 1), delay=0\n )\n\n all_files = [\n (tmp_path / f\"region_id~{i}/status~success/run~0/touch\")\n for i in range(N_REGIONS)\n ] + [\n (tmp_path / f\"region_id~{i}/status~failure/run~1/touch\")\n for i in range(N_REGIONS)\n ] + [\n (tmp_path / f\"region_id~{i}/status~success/run~{j}/touch\")\n for j in range(2, 4) for i in range(N_REGIONS)\n ]\n\n already_complete = all_files[:6]\n to_be_completed = all_files[6:n_instances+3]\n not_to_exist = all_files[n_instances+3:]\n\n for path in already_complete:\n path.parent.mkdir(parents=True)\n path.write_text(\"completed\")\n\n is_success = await collector.run(n_instances)\n assert is_success\n\n # Check that the prior completed still contain the same text\n for path in already_complete:\n assert path.read_text() == \"completed\"\n # Check that the ones to be completed exist\n for path in to_be_completed:\n assert path.is_file()\n # Check that no more were created\n for path in not_to_exist:\n assert not path.exists()\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\n \"n_failures,max_failures,should_fail\", [(4, 5, False), (2, 2, True)]\n)\nasync def test_too_many_prior_failures(\n tmp_path, n_failures, max_failures, should_fail\n):\n \"\"\"It should immediately raise if there have been more than max_failures\n with no successes.\n \"\"\"\n n_instances = 1\n\n for run_id in range(n_failures):\n path = tmp_path / f\"region_id~0/status~failure/run~{run_id}/touch\"\n path.parent.mkdir(parents=True)\n path.write_text(\"failed\")\n\n collector = TargetRunner(\n touch_target, Path(), tmp_path, create_queues(N_REGIONS, 1), delay=0\n )\n is_success = await collector.run(n_instances, max_failures=max_failures)\n assert is_success == (not should_fail)\n\n\n@pytest.mark.asyncio\nasync def test_too_many_region_failures(tmp_path):\n \"\"\"It should fail due to too many failures in a single region.\"\"\"\n n_failures = 3\n for (region_id, status, count) in [\n (0, \"failure\", n_failures), (1, \"success\", 4)\n ]:\n for run_id in range(count):\n path = (\n tmp_path / f\"region_id~{region_id}\" / f\"status~{status}\"\n / f\"run~{run_id}\" / \"touch\"\n )\n path.parent.mkdir(parents=True)\n path.write_text(\"failed\")\n\n collector = TargetRunner(\n touch_target, Path(), tmp_path, create_queues(N_REGIONS, 1), delay=0\n )\n is_success = await collector.run(10, max_failures=n_failures)\n assert not is_success\n\n\n@pytest.mark.asyncio\nasync def test_already_complete(tmp_path: Path):\n \"\"\"It should not run if already complete.\"\"\"\n n_instances = 3\n\n all_files = [\n (tmp_path / f\"region_id~{i}/status~success/run~{j}/touch\")\n for j in range(2) for i in range(N_REGIONS)\n ]\n already_complete = all_files[:n_instances]\n not_to_exist = all_files[n_instances:]\n\n for path in already_complete:\n path.parent.mkdir(parents=True)\n path.write_text(\"completed\")\n\n collector = TargetRunner(\n touch_target, Path(), tmp_path, create_queues(N_REGIONS, 1), delay=0\n )\n is_success = await collector.run(n_instances)\n assert is_success\n\n # Check that the prior completed still contain the same text\n for path in already_complete:\n assert path.read_text() == \"completed\"\n for path in not_to_exist:\n assert not path.exists()\n\n\n@pytest.mark.asyncio\nasync def test_cleanup_on_error(tmp_path):\n \"\"\"It should cancel all tasks on error.\"\"\"\n collector = TargetRunner(\n exception_target, Path(), tmp_path, create_queues(N_REGIONS, 1),\n delay=0\n )\n\n with pytest.raises(TargetError):\n await collector.run(10)\n\n\n@pytest.mark.asyncio\nasync def test_success_with_failures(tmp_path):\n \"\"\"Should successfully complete even with failures.\"\"\"\n n_instances = 6\n collector = TargetRunner(\n failing_target, Path(), tmp_path, create_queues(N_REGIONS, 3), delay=0\n )\n\n is_success = await collector.run(n_instances)\n assert is_success\n\n\n@pytest.mark.asyncio\nasync def test_should_abort_on_failures(tmp_path):\n \"\"\"It should stop running after too many failures.\"\"\"\n n_instances = 6\n # With 1 client, client_id=0, region_id=0 should always fail\n collector = TargetRunner(\n failing_target, Path(), tmp_path, create_queues(N_REGIONS, 1), delay=0\n )\n\n is_success = await collector.run(n_instances)\n assert not is_success\n\n\ndef create_inputs(path: Path, n_inputs: int):\n \"\"\"Create a directory for inputs at path and a directory for outputs.\n\n Add n_inputs files to the input directory and return the\n (input, output) paths.\n \"\"\"\n input_dir = path / \"inputs\"\n input_dir.mkdir()\n output_dir = path / \"outputs\"\n output_dir.mkdir()\n for i in range(n_inputs):\n (input_dir / f\"{i}.json\").touch()\n return input_dir, output_dir\n\n\ndef test_should_detect_prior(tmp_path):\n \"\"\"It should identify prior monitored/unmonitored assignments and\n respect them.\n \"\"\"\n indir, outdir = create_inputs(tmp_path, 10)\n (outdir.with_suffix(\".wip\") / \"setting~monitored/9/\").mkdir(parents=True)\n (outdir.with_suffix(\".wip\") / \"setting~unmonitored/0/\").mkdir(parents=True)\n\n collector = Collector(\n touch_target, indir, outdir, n_regions=N_REGIONS, n_instances=2,\n n_clients_per_region=1, n_monitored=5, n_unmonitored=5, max_failures=1\n )\n collector.init_runners()\n assert collector.is_monitored(\"9\")\n assert not collector.is_monitored(\"0\")\n\n\ndef test_should_assign_unmonitored_region(tmp_path):\n \"\"\"It should assign unmonitored regions to prior collections.\"\"\"\n indir, outdir = create_inputs(tmp_path, 10)\n for sample, region_id, n_runs in [(\"1\", 0, 2), (\"3\", 2, 1)]:\n for i in range(n_runs):\n (\n outdir.with_suffix(\".wip\") / \"setting~unmonitored\" / sample\n / f\"region_id~{region_id}\" / \"status~success\" / f\"run~{i}\"\n ).mkdir(parents=True)\n\n collector = Collector(\n touch_target, indir, outdir, n_regions=N_REGIONS, n_instances=2,\n n_clients_per_region=1, n_monitored=5, n_unmonitored=5, max_failures=1\n )\n collector.init_runners()\n assert not collector.is_monitored(\"1\")\n assert not collector.is_monitored(\"3\")\n\n assert collector.get_region(\"1\") == 0\n assert collector.get_region(\"3\") == 2\n\n\ndef test_should_init_runners(tmp_path):\n \"\"\"It should create a runner for each required sample.\"\"\"\n indir, outdir = create_inputs(tmp_path, 10)\n (outdir.with_suffix(\".wip\") / \"setting~monitored/9/status~success/run~0\")\\\n .mkdir(parents=True)\n (outdir.with_suffix(\".wip\") / \"setting~unmonitored/0/status~success/run~0\")\\\n .mkdir(parents=True)\n\n collector = Collector(\n touch_target, indir, outdir, n_regions=N_REGIONS, n_instances=2,\n n_clients_per_region=1, n_monitored=5, n_unmonitored=5, max_failures=1\n )\n collector.init_runners()\n\n for i in [1, 2, 3, 4, 9]:\n assert collector.is_monitored(str(i))\n for i in [0, 5, 6, 7, 8]:\n assert not collector.is_monitored(str(i))\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\"n_inputs,n_monitored,n_unmonitored\", [(20, 4, 6)])\nasync def test_runs_to_completion(\n tmp_path, n_inputs, n_monitored, n_unmonitored\n):\n \"\"\"It should successfully run a collection in spite of failures.\"\"\"\n indir, outdir = create_inputs(tmp_path, n_inputs)\n collector = Collector(\n randomly_failing_target(0.1, seed=32), indir, outdir,\n n_regions=2, n_instances=20, n_clients_per_region=2,\n n_monitored=n_monitored, n_unmonitored=n_unmonitored, max_failures=2,\n delay=0.01\n )\n\n await collector.run()\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\"n_inputs,n_monitored,n_unmonitored\", [(20, 4, 6)])\nasync def test_runs_to_failure(\n tmp_path, n_inputs, n_monitored, n_unmonitored\n):\n \"\"\"It should successfully run a collection in spite of failures.\"\"\"\n indir, outdir = create_inputs(tmp_path, n_inputs)\n collector = Collector(\n randomly_failing_target(0.1, seed=32, raise_on_err=True), indir, outdir,\n n_regions=2, n_instances=20, n_clients_per_region=2,\n n_monitored=n_monitored, n_unmonitored=n_unmonitored, max_failures=2,\n delay=0.01\n )\n\n with pytest.raises(TargetError):\n await collector.run()\n","sub_path":"workflow/scripts/common/test_collectv2.py","file_name":"test_collectv2.py","file_ext":"py","file_size_in_byte":12663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"169797135","text":"from app.engine import engine\nfrom app.engine.input_manager import INPUT\n\nclass FluidScroll():\n def __init__(self, speed=67, slow_speed=3):\n self.reset()\n\n self.left_update = 0\n self.right_update = 0\n self.up_update = 0\n self.down_update = 0\n self.fast_speed = speed\n self.slow_speed = int(speed*slow_speed)\n self.move_counter = 0\n\n def reset(self):\n self.move_left = False\n self.move_right = False\n self.move_up = False\n self.move_down = False\n\n def update_speed(self, speed=64, slow_speed=3):\n self.fast_speed = speed\n self.slow_speed = int(speed*slow_speed)\n\n def update(self, hold=True):\n if (hold and INPUT.is_pressed('LEFT')) or \\\n INPUT.just_pressed('LEFT'):\n self.move_right = False\n self.move_left = True\n else:\n self.move_left = False\n\n if (hold and INPUT.is_pressed('RIGHT')) or \\\n INPUT.just_pressed('RIGHT'):\n self.move_left = False\n self.move_right = True\n else:\n self.move_right = False\n\n if (hold and INPUT.is_pressed('UP')) or \\\n INPUT.just_pressed('UP'):\n self.move_down = False\n self.move_up = True\n else:\n self.move_up = False\n\n if (hold and INPUT.is_pressed('DOWN')) or \\\n INPUT.just_pressed('DOWN'):\n self.move_up = False\n self.move_down = True\n else:\n self.move_down = False\n\n if INPUT.just_pressed('LEFT'):\n self.left_update = 0\n if INPUT.just_pressed('RIGHT'):\n self.right_update = 0\n if INPUT.just_pressed('UP'):\n self.up_update = 0\n if INPUT.just_pressed('DOWN'):\n self.down_update = 0\n\n # If we changed a direction, reset the move counter\n if INPUT.just_pressed('LEFT') or INPUT.just_pressed('RIGHT') or \\\n INPUT.just_pressed('UP') or INPUT.just_pressed('DOWN'):\n self.move_counter = 0\n\n # If we didn't make any moves, reset the move counter\n if not any((self.move_left, self.move_right, self.move_down, self.move_up)):\n self.move_counter = 0\n\n if any((INPUT.just_pressed(direction) for direction in ('LEFT', 'RIGHT', 'UP', 'DOWN'))):\n return True # This is a first push\n return False\n\n def get_directions(self, double_speed=False, slow_speed=False):\n directions = []\n current_time = engine.get_time()\n\n if slow_speed:\n speed = self.slow_speed\n elif self.move_counter >= 2:\n speed = self.fast_speed\n else:\n speed = self.slow_speed\n\n if double_speed:\n speed //= 2\n\n if self.move_left and current_time - self.left_update > speed:\n directions.append('LEFT')\n if self.move_right and current_time - self.right_update > speed:\n directions.append('RIGHT')\n if self.move_up and current_time - self.up_update > speed:\n directions.append('UP')\n if self.move_down and current_time - self.down_update > speed:\n directions.append('DOWN')\n\n if directions: # If any move was made\n self.set_all_updates(current_time)\n self.move_counter += 1\n\n # If we didn't make any moves, reset the move counter\n if not any((self.move_left, self.move_right, self.move_down, self.move_up)):\n self.move_counter = 0\n return directions\n\n def set_all_updates(self, time):\n self.left_update = time\n self.right_update = time\n self.up_update = time\n self.down_update = time\n","sub_path":"app/engine/fluid_scroll.py","file_name":"fluid_scroll.py","file_ext":"py","file_size_in_byte":3738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"64231307","text":"def fibo_iteration(n):\n a, b = 1, 1\n\n if n<=1:\n return 1\n\n for _ in range(1, n):\n a, b = b, a+b\n\n return a\n\nif __name__==\"__main__\":\n for i in range(1, 11):\n print(fibo_iteration(i), end=\" \")","sub_path":"algorithm/fibonacci/fibo_iteration.py","file_name":"fibo_iteration.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"426524204","text":"from flask import Flask, session, redirect, url_for, escape, request, render_template\nfrom urllib import urlencode\nfrom env.dev import client_id, client_secret, SECRET_KEY\n\napp = Flask(__name__)\napp.secret_key = SECRET_KEY\n\n@app.route('/')\ndef index():\n if 'spotify_code' in session:\n spotify_code = session['spotify_code']\n else:\n spotify_code = ''\n return render_template('dev_index.html', spotify_code=spotify_code)\n\n@app.route('/login')\ndef spotify_login():\n if 'spotify_code' in session:\n spotify_code = session['spotify_code']\n scope = 'user-read-private user-read-email';\n url = 'https://accounts.spotify.com/authorize?'\n params = {\n 'response_type': 'code',\n 'client_id': client_id,\n 'scope': scope,\n 'redirect_uri': 'http://localhost:5000/spotify_auth'\n # 'state': 'ABC123'\n }\n return redirect(url+urlencode(params))\n@app.route('/spotify_auth')\ndef spotify_login_callback():\n if request.args.get('code'):\n spotify_code = request.args.get('code')\n print('spotify code:', spotify_code)\n session['spotify_code'] = spotify_code\n return redirect('/')\n # \n # // your application requests refresh and access tokens\n # // after checking the state parameter\n # \n # var code = req.query.code || null;\n # var authOptions = {\n # url: 'https://accounts.spotify.com/api/token',\n # form: {\n # code: code,\n # redirect_uri: redirect_uri,\n # grant_type: 'authorization_code'\n # },\n # headers: {\n # 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))\n # },\n # json: true\n # };\n # \n # request.post(authOptions, function(error, response, body) {\n # if (!error && response.statusCode === 200) {\n # \n # var access_token = body.access_token,\n # refresh_token = body.refresh_token;\n # \n # var options = {\n # url: 'https://api.spotify.com/v1/me',\n # headers: { 'Authorization': 'Bearer ' + access_token },\n # json: true\n # };\n # \n # // use the access token to access the Spotify Web API\n # request.get(options, function(error, response, body) {\n # console.log(body);\n # });\n # \n # // we can also pass the token to the browser to make requests from there\n # res.redirect('/#' +\n # querystring.stringify({\n # access_token: access_token,\n # refresh_token: refresh_token\n # }));\n # } else {\n # res.redirect('/#' +\n # querystring.stringify({\n # error: 'invalid_token'\n # }));\n # }\n # });\n # }\n\n\nif __name__ == '__main__':\n app.run(host= '0.0.0.0', debug=True)\n","sub_path":"src/python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"135342477","text":"\n# add the following 2 lines to solve OpenGL 2.0 bug\nfrom kivy import Config\nConfig.set('graphics', 'multisamples', '0')\n\nfrom kivy.app import App\nfrom kivy.uix.widget import Widget\nfrom kivy.uix.screenmanager import ScreenManager, Screen\n\n#Config.set('graphics', 'resizable', '0')\n#Config.set('graphics', 'fullscreen', '0')\nConfig.set('graphics', 'height', '640')\nConfig.set('graphics', 'width', '360')\n\nfrom kivy.lang import Builder\n\nfrom kivy.clock import Clock\nimport datetime\n\nfrom kivy.storage.jsonstore import JsonStore\nfrom kivy.factory import Factory\n\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.button import Button\nfrom kivy.uix.popup import Popup\nfrom kivy.properties import StringProperty, BooleanProperty, DictProperty\n\nclass NewWordPopup(Popup):\n\tdef saveWord(self):\n\t\tif self.checkForm():\n\t\t\twordForm = {\"word\": self.ids.wordTextInp.text, \n\t\t\t\t\t\t\"translate\": self.ids.translateTextInp.text,\n\t\t\t\t\t\t\"weight\": 0,\n\t\t\t\t\t\t\"trainings\": []}\n\t\t\t\n\t\t\twordsTrainApp.addWord(wordsTrainApp, wordForm)\n\t\t\tself.clearForm()\n\n\tdef checkForm(self):\n\t\treturn True if self.ids.wordTextInp.text and self.ids.translateTextInp.text else False\n\n\tdef clearForm(self):\n\t\tself.ids.wordTextInp.text = \"\"\n\t\tself.ids.translateTextInp.text = \"\"\n\nclass DictListItem(BoxLayout):\n\tword = StringProperty()\n\ttranslate = StringProperty()\n\tweight = StringProperty()\n\tnumber = StringProperty()\n\nclass DictionaryScreen(Screen):\n\tdef on_enter(self):\n\t\tself.updateWordsList()\n\t\n\tdef updateWordsList(self):\n\t\tself.ids.dict_rv.data = self.getWordsRecycleData()\n\n\tdef getWordsRecycleData(self):\n\t\trecycleData = []\n\n\t\tfor wordNumber, wordData in wordsTrainApp.getWords(wordsTrainApp).items():\n\t\t\trecycleData.append({\"viewclass\": \"DictListItem\", \n\t\t\t\t\t\t\t\t\"word\":\t\t wordData['word'],\n\t\t\t\t\t\t\t\t\"translate\": wordData['translate'],\n\t\t\t\t\t\t\t\t\"weight\":\t str(wordData['weight']),\n\t\t\t\t\t\t\t\t\"number\": \t wordNumber})\n\n\t\tif not recycleData:\n\t\t\treturn [{\"viewclass\": \"Label\", \"text\":\"Dictionary is empty\"}]\n\n\t\treturn recycleData\n\nclass MainScreen(Screen):\n\tpass\n\nclass wordsTrainApp(App):\n\n\tstoreData = JsonStore(\"data.json\")\n\n\tdef build(self):\n\t\tself.screen = Factory.AppScreens()\n\t\treturn self.screen\n\n\tdef getWords(self):\n\t\treturn {key: self.storeData.get(key) for key in [number for number in self.storeData.keys()]}\n\n\tdef addWord(self, wordForm):\n\t\tnextNumber = self.getLastEntryNumber(self) + 1\n\t\tself.storeData.put(str(nextNumber), **wordForm)\n\n\tdef deleteWord(self, wordNumber):\n\t\tself.storeData.delete(wordNumber)\n\n\tdef getLastEntryNumber(self):\n\t\tif (self.storeData):\n\t\t\treturn max([int(number) for number in self.storeData.keys()])\n\t\telse:\n\t\t\treturn 0\n\nif __name__ == \"__main__\":\n wordsTrainApp().run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"603857298","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.fftpack import fft\nfrom scipy import signal\n\n\ndef espectrodft(array, n):\n ar = fft(array) / n\n fs = 10e3\n m = 1e5\n amp = 2*np.sqrt(2)\n noise_power = 0.001*fs/2\n time = np.arange(m)/fs\n freq = np.linspace(1e3, 2e3, m)\n x = amp*np.sin(2*np.pi*freq*time)\n x += np.random.normal(scale=np.sqrt(noise_power), size=time.shape)\n\n f, t, sxx = signal.spectrogram(ar, fs)\n plt.pcolormesh(t, f, sxx)\n plt.ylabel('Frequency [Hz]')\n plt.xlabel('Time [sec]')\n plt.show()\n","sub_path":"Graficos/EspectroDFT.py","file_name":"EspectroDFT.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"649633436","text":"\n# -*- coding:utf-8 -*-\nfrom selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport os,time\nimport configparser\nimport transform\nimport logging\nimport logging.config\nimport re\nimport threading\n\nconf=configparser.ConfigParser()\nconf.read('config.conf')\nurl=conf.get('autoGetHtml','url')\n\nmodelRules=conf.get('autoGetHtml','modelRules')\nhtmlOutputPath = conf.get('autoGetHtml','htmlOutputPath')\nxmlOutputPath = conf.get('autoGetHtml','xmlOutputPath')\ncsvOutputPath = conf.get('autoGetHtml','csvOutputPath')\nsqlOutputPath = conf.get('autoGetHtml','sqlOutputPath')\nbatch = conf.get('conf','batch')\nlabelName = conf.get('conf','labelName')\nlogging.config.fileConfig('logging.conf')\n\nlogger_autoGetHtml = logging.getLogger('autoGetHtml')\n\ndef log(msg,level='info'):\n if level == \"info\":\n logger_autoGetHtml.info(\"\\033[1;33m:%s\\033[0m\" % msg)\n elif level == \"debug\":\n logger_autoGetHtml.debug(\"\\033[1;33m:%s\\033[0m\" % msg)\n elif level == \"warning\":\n logger_autoGetHtml.warning(\"\\033[1;31m:%s\\033[0m\" % msg)\n elif level == \"error\":\n logger_autoGetHtml.error(\"\\033[1;31m:%s\\033[0m\" % msg)\n\nif __name__ == \"__main__\":\n thread = {}\n driver = webdriver.Chrome()\n #driver.implicitly_wait(20)\n driver.get(url)\n input_string = \"\"\n print(\"\\033[1;33m 参数确认\\n模型匹配规则:%s\\n标签类型名称:%s\\n批次名:%s\\n\\033[0m\" % (modelRules,labelName,batch))\n while(input_string!=\"ok\"):\n input_string = input(\"\\033[1;33m准备就绪输入OK:\\033[0m\\n\")\n print(\"\\033[1;33m等待网页加载完成..\\033[0m\")\n log(\"获取窗口句柄\",level='debug')\n # 获取打开的多个窗口句柄\n windows = driver.window_handles\n #print(windows)\n for window in windows:\n log(\"切换至最后一个窗口\",level='debug')\n driver.switch_to.window(window)\n log(\"最大化窗口\",level='debug')\n driver.maximize_window()\n log(\"获取列表树ID\",level='debug')\n table_trees = driver.find_elements_by_xpath(\"\"\"//table[@class=\"tree-wrapper table table-hover\"]\"\"\")\n experiment_table_id = table_trees[0].get_attribute(\"id\")\n log(\"获取列表树元素\",level='debug')\n experiment_table = driver.find_elements_by_xpath(\"\"\"//table[@id=\\\"\"\"\"+experiment_table_id+\"\"\"\\\"]/tbody/tr[@class='tree-node']\"\"\")\n times = 1\n for experiment_tree_node in experiment_table:\n #print(experiment_tree_node.text)v\n pattern = re.compile(r''+modelRules)\n result = re.match(pattern,experiment_tree_node.text)\n if not result:\n continue\n experiment_tree_node.click()\n title = experiment_tree_node.text\n time.sleep(1)\n log(\"[第%d组]切换至 %s 实验\" % (times, title))\n experiment_models = driver.find_elements_by_xpath(\"\"\"//*[name()='svg']/*[name()='g']/*[name()='g'][3]/*[name()='g']\"\"\")\n experiment_model = experiment_models[len(experiment_models)-1]\n log(\"[第%d组]获取第%d个学习节点\" % (times, len(experiment_models)-1),level='debug')\n ActionChains(driver).context_click(experiment_model).perform()\n time.sleep(1)\n experiment_select = driver.find_elements_by_xpath(\"\"\"//li[@data-id=\"node-showData\"]\"\"\")\n log(\"[第%d组]显示数据\" % (times),level='debug')\n experiment_select[0].click()\n log(\"[第%d组]15秒后保存文件\" % (times),level='debug')\n time.sleep(10)\n save_times = 1\n retry_times = 0\n log(\"[第%d组]5秒后保存文件(%d)\" % (times,save_times))\n time.sleep(5)\n log(\"[第%d组]开始保存文件(%d)\" % (times,save_times))\n htmlFile = open(os.path.join(htmlOutputPath,title+\".html\"),\"w\",encoding='utf8')\n htmlFile.write(str(driver.page_source))\n htmlFile.close()\n log(\"[第%d组]%s 页面保存成功(%d)\" % (times,title,save_times))\n time.sleep(1)\n thread[times] = threading.Thread(target=transform.startTransform, args=(title+\".html\",1,times,labelName,))\n thread[times].start()\n time.sleep(1)\n window_close = driver.find_elements_by_xpath(\"\"\"//button[@class=\"ant-modal-close\"]\"\"\")\n log(\"[第%d组]关闭页面\" % (times),level='debug')\n window_close[0].click()\n time.sleep(1)\n times += 1\n\n","sub_path":"src/transform/autoGetHtml.py","file_name":"autoGetHtml.py","file_ext":"py","file_size_in_byte":4487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"646431444","text":"\"\"\"Tests for the parse_case_definitions module.\"\"\"\n\n# Python imports.\nimport datetime\nimport json\nimport os\nimport unittest\n\n# User imports.\nfrom PatientExtraction import conf\nfrom PatientExtraction import parse_case_definitions\nfrom PatientExtraction import restriction_comparator_generators\n\n\nclass TestRestrictionApplication(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Perform setup needed for all tests.\n\n This just consists of processing the test data into the correct format.\n\n \"\"\"\n\n # Setup global settings-like variables.\n conf.init()\n\n # Determine the files needed to load the data and the expected results of the tests.\n dirCurrent = os.path.dirname(os.path.join(os.getcwd(), __file__)) # Directory containing this file.\n dirData = os.path.abspath(os.path.join(dirCurrent, \"TestData\"))\n fileData = os.path.join(dirData, \"CaseDefinitions\", \"AnnotatedCaseDefinitions.txt\")\n fileOutput = os.path.join(dirData, \"CaseDefinitions\", \"ExpectedOutput.json\")\n\n # Load the case definitions.\n cls.caseDefinitions, cls.caseNames = parse_case_definitions.main(fileData)\n\n # Load the expected output.\n fidOutput = open(fileOutput, 'r')\n cls.expectedOutput = json.load(fidOutput)\n fidOutput.close()\n for i in cls.expectedOutput:\n # Convert the list of codes to a set.\n cls.expectedOutput[i][\"Codes\"] = set(cls.expectedOutput[i][\"Codes\"])\n\n # Create date comparisons.\n cls.expectedOutput[i][\"Restrictions\"][\"Date\"] = [\n [datetime.datetime.strptime(k, \"%Y-%m-%d\") for k in j]\n for j in cls.expectedOutput[i][\"Restrictions\"][\"Date\"]\n ]\n cls.expectedOutput[i][\"Restrictions\"][\"DateComps\"] = [\n restriction_comparator_generators.date_generator(*j)\n for j in cls.expectedOutput[i][\"Restrictions\"][\"Date\"]\n ]\n\n # Convert Val1 values to value comparisons.\n cls.expectedOutput[i][\"Restrictions\"][\"Val1\"] = [\n restriction_comparator_generators.value_generator(j[1], conf.validChoices[\"Operators\"][j[0]])\n for j in cls.expectedOutput[i][\"Restrictions\"][\"Val1\"]\n ]\n\n # Convert Val2 values to value comparisons.\n cls.expectedOutput[i][\"Restrictions\"][\"Val2\"] = [\n restriction_comparator_generators.value_generator(j[1], conf.validChoices[\"Operators\"][j[0]])\n for j in cls.expectedOutput[i][\"Restrictions\"][\"Val2\"]\n ]\n\n def test_case_parsing(self):\n # First ensure that the outputs have the same case names.\n self.assertCountEqual(self.caseNames, self.caseDefinitions)\n self.assertCountEqual(self.caseDefinitions, self.expectedOutput)\n\n for i in self.caseNames:\n # Check that the codes are all the same for the expected and actual output.\n self.assertEqual(self.caseDefinitions[i][\"Codes\"], self.expectedOutput[i][\"Codes\"])\n\n # Check that the modes are all the same for the expected and actual output.\n self.assertEqual(self.caseDefinitions[i][\"Modes\"], self.expectedOutput[i][\"Modes\"])\n\n # Check that the output methods are all the same for the expected and actual output.\n self.assertEqual(self.caseDefinitions[i][\"Outputs\"], self.expectedOutput[i][\"Outputs\"])\n\n # Check that the date restrictions are all the same for the expected and actual output.\n annotatedDateComps = self.caseDefinitions[i][\"Restrictions\"][\"Date\"]\n expectedDateComps = self.expectedOutput[i][\"Restrictions\"][\"DateComps\"]\n expectedDates = self.expectedOutput[i][\"Restrictions\"][\"Date\"]\n self.assertEqual(len(annotatedDateComps), len(expectedDateComps))\n for j, k, l in zip(annotatedDateComps, expectedDateComps, expectedDates):\n annotatedCellContents = [m.cell_contents for m in j.__closure__]\n expectedCellContents = [m.cell_contents for m in k.__closure__]\n if len(l) == 2:\n # If there were two dates specified for the comparison check them both.\n self.assertCountEqual(annotatedCellContents, expectedCellContents)\n else:\n # If there was only one date specified for the comparison, then the comparison is from a start date\n # to the present. As the comparison functions being compared (the annotated and expected) are not\n # created at the exact same moment, their end dates will be slightly different\n # (as datetime.datetime.now() will have slightly different values for the seconds). In this case\n # only compare the first dates.\n # The start date is cell index 1, not 0 as might be expected.\n self.assertEqual(annotatedCellContents[1], expectedCellContents[1])\n\n # Check that the Val1 restrictions are all the same for the expected and actual output.\n annotatedVal1Comps = self.caseDefinitions[i][\"Restrictions\"][\"Val1\"]\n expectedVal1Comps = self.expectedOutput[i][\"Restrictions\"][\"Val1\"]\n self.assertEqual(len(annotatedVal1Comps), len(expectedVal1Comps))\n for j, k in zip(annotatedVal1Comps, expectedVal1Comps):\n annotatedCellContents = [l.cell_contents for l in j.__closure__]\n expectedCellContents = [l.cell_contents for l in k.__closure__]\n self.assertEqual(annotatedCellContents, expectedCellContents)\n\n # Check that the Val2 restrictions are all the same for the expected and actual output.\n annotatedVal2Comps = self.caseDefinitions[i][\"Restrictions\"][\"Val2\"]\n expectedVal2Comps = self.expectedOutput[i][\"Restrictions\"][\"Val2\"]\n self.assertEqual(len(annotatedVal2Comps), len(expectedVal2Comps))\n for j, k in zip(annotatedVal2Comps, expectedVal2Comps):\n annotatedCellContents = [l.cell_contents for l in j.__closure__]\n expectedCellContents = [l.cell_contents for l in k.__closure__]\n self.assertEqual(annotatedCellContents, expectedCellContents)\n","sub_path":"Code/tests/PatientExtraction/test_parse_case_definitions.py","file_name":"test_parse_case_definitions.py","file_ext":"py","file_size_in_byte":6313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"366873510","text":"# -*- coding: utf-8 -*-\n\"\"\"\nAgent-Based Model of Bitcoin/Blockchain networks\n\nCreated on Tue Apr 24 14:07:57 2018\n\n@authors: Johanna Croton, Nikolaj Bauer, Sebastian Haelg\n\n\"\"\"\n# Import packages\nfrom __future__ import division\nimport random\nimport numpy as np\nimport copy\nimport matplotlib.pyplot as plt\n\n\n# Set random seed\nrandom.seed(100)\n\n# Set order parameters\ntrials = 50\ntime = 10000\nnetwork_delay = 10 # lambda^-1\nnum_nodes = 1000 # number of nodes in the network\nnodes_conns = [3, 4, 8, 16, 32, 64] # maximum number of connections \ndilusion_rate = 0 # percentage of NON-miners\nexpo_scale = 0.096 # parameter for exponential distribution of computational power \n\n\n\n###############################################################################\n# Define Functions \n############################################################################### \n\ndef random_graph(n, k):\n \"\"\"\n Function to initialize the network\n \"\"\"\n # A function that creates a random graph, by Martin Ritchie\n # 08/06/2016. This funciton is a revision of my first \n # attempt in python to code the Erdos-Renyi random graph\n # algortihtm. The code now include an adjacency list and\n # edge list as ouput in addtion to the adjacency matrix. \n # ------------------- Inputs --------------------------\n # N: number of nodes.\n # k: desired average degree.\n # ------------------- Outputs -------------------------\n # A: adjacency matrix (line 16 for sparse).\n # A_list: adjacency list.\n # edge_list: list of edges. \n # import ipdb\n # ipdb.set_trace()\n # A = lil_matrix((n, n), dtype=np.int8)\n A_list = [[] for i in range(n)] \n edge_list = []\n p = 1 - (float(k) / (n - 1))\n A = np.random.random((n, n))\n A *= np.tri(*A.shape)\n np.fill_diagonal(A, 0)\n \n edge = A>p \n A[edge] = 1\n no_edge = A <= p \n A[no_edge] = 0 # All low values set to 0\n A = np.add(A, A.transpose())\n\n for i in range(n):\n for j in range(i-1):\n if A[i, j] > 0: \n A_list[i] = A_list[i] + [j]\n A_list[j] = A_list[j] + [i]\n edge_list.append((i,j))\n edge_list.append((j,i))\n return (A, A_list, edge_list) \n \n \ndef consensus():\n \"\"\"\n Creates a vector of each node's last block element, \n then checks if all elements of the vector are equal.\n If returns true, then the network has reached consensus.\n \"\"\"\n \n a = [last_block[i][-1] for i in range(num_nodes)]\n return(len(set(a)) <=1)\n\n\ndef delay_time(L, n):\n \"\"\"\n Creates an array of delay times, i.e. the time it will take a node to gossip to one neighbor, \n to two neighbors, ect. such that the time intervall between the gossiping events follows a \n poisson distribution. \n \"\"\" \n epsilon = np.random.poisson(L, n+1)\n delay=list()\n delay.append(epsilon[0])\n for e in range(n-1):\n delay.append(delay[e] + epsilon[e + 1])\n return(delay)\n \n \ndef new_block(lucky, num): \n \"\"\"\n Creates a new block when called for \"lucky\" miner node using its parent block (blockID) and\n the current block number. \n \"\"\"\n # Set variables that are changed within the function to global scope\n global last_block\n global info_list\n global neighbors\n global delay_list\n global list_blockIDs\n \n # Create the block\n block_ID = copy.copy(last_block[lucky]) # copy parent block from lucky miner\n block_ID.append(num) # add current block number parent block \n list_blockIDs.append(block_ID) # record each new block to global scope\n last_block[lucky] = copy.copy(block_ID) # add the new block to lucky's chain\n \n # Update lucky's info\n info_list[lucky, 1] = 1 # set lucky's state to \"gossiping\"\n neighbors[lucky] = copy.copy(neighbor_list[lucky]) # reset neighbors to gossip new block to (all)\n delay_list[lucky] = delay_time(network_delay, len(neighbor_list[lucky])) # reset the delay times\n delay_list[lucky] = [x+t for x in delay_list[lucky]]\n\n\ndef gossiping():\n \"\"\"\n One round of gossiping for all nodes that are in state 1. \n \"\"\"\n \n # Set variables that are changed within the function to global scope\n global delay_list\n global neighbor_list\n global neighbors\n global last_block\n global info_list\n global last_block\n \n # Iterate throuhg all gossiping nodes\n for gossiper in gossipers:\n listeners = neighbors[gossiper] # find listeners, i.e. neighbors that the node has not its gossiped current block to yet\n if len(listeners) == 0 : # if there are no more neighbors to gossip to\n info_list[gossiper,1] = 0 # gossiper stops gossiping, set state to 0 \n elif delay_list[gossiper][0] < t : # if there are listeners to gossip to and time is > than the node's delay_time\n choose = random.randrange(0,len(listeners)) \n listener = listeners[choose] # choose a random listener to gossip to \n del neighbors[gossiper][choose] # remove the listener from the neighbors that can still be gossiped to\n del delay_list[gossiper][0] # next entry will be the time it takes to gossip to two nodes\n \n # Compare gossiper and listener's chain lengths\n if len(last_block[gossiper]) > len(last_block[listener]) : # listener's chain is shorter\n last_block[listener] = copy.copy(last_block[gossiper]) # listener adopts gossiper's chain\n info_list[listener][1] = 1 # update listener's state to gossiper\n neighbors[listener] = copy.copy(neighbor_list[listener]) # reset neighbors to gossip new block to (all)\n delay_list[listener] = delay_time(network_delay, len(neighbor_list[listener])) \n delay_list[listener] = [x+t for x in delay_list[listener]] # reset the delay times\n elif len(last_block[gossiper]) == len(last_block[listener]): # if both chains are equally long\n if (last_block[gossiper][-1] > last_block[listener][-1]): # last element in gossiper's chain is bigger (older) than the listener's\n last_block[listener] = copy.copy(last_block[gossiper]) # listener adopts gossiper's chain\n \n \nres_ratio = [] \nres_orphanedblocks = []\nres_totalblocks = []\nres_onchain = []\nres_consensusnum = []\nres_orphanedblocks = []\nres_avg_consensus_time = []\n\nresults = [] \n\nfor nodes_conn in nodes_conns:\n \n # Run 20 trials to get the average parameters\n for trial in range(trials): \n \n ###############################################################################\n #Initialize Variables\n ############################################################################### \n # Initialize the network\n network = random_graph(num_nodes, nodes_conn) # call network function\n neighbor_list=network[1] # create list of each node's neighbors \n \n # Create empty matrix of nodes and information\n info_list=np.zeros((num_nodes,3)) # 1:node IDs 2:status 3:mining probabilities\n info_list[:,0]=list(range(num_nodes)) # update column 1: node IDs\n \n # Make block IDs for the current block in each node's chain\n last_block =[[(0)] for i in range(num_nodes)]\n \n \n # Counter of new blocks in order of creation\n block_num = 1\n \n # Create a random first block with ID 1\n new = random.randrange(0, num_nodes) # choose a random node \n info_list[new,1] = 1 # change random node's state to gossiping\n last_block[new] = [0,1] # Record block ID to node's chain\n \n # Create a list to keep track the block creation sequence\n list_blockIDs = list() # intialize empty list\n list_blockIDs.append([0]) # add block 0 (all nodes start out with)\n list_blockIDs.append([0, 1]) # add block 1 (was manually inserted)\n \n # Endow each node with computational power = number of trials it needs to solve cryptographic problem\n comp_power = np.random.exponential(expo_scale, int(num_nodes*(1-dilusion_rate))) # computing power for fraction of nodes that are miners (non-mining nodes are 0)\n miners = random.sample(range(num_nodes), int(num_nodes*(1-dilusion_rate))) # choose random miners\n info_list[miners,2] = comp_power # update info list column 3 for miners\n probability_dt = (info_list[:,2]/sum(info_list[:,2]))/100 # probability that a specific node mines a new block (node's comp. power / sum of all node's comp. power)\n probability = copy.copy(probability_dt) # variable that will be used below\n \n # Calculate network delays for all nodes\n delay_list = list() # initialize empty list\n for i in range(num_nodes): # for each node add delay times to its list\n add = delay_time(network_delay, len(neighbor_list[i]))\n delay_list.append(add)\n \n # Find the gossipers\n gossipers = info_list[:,0][info_list[:,1]==1] # find nodes in state one\n gossipers = [int(i) for i in gossipers] # convert to integrals \n \n # Create copy of the neighbor list to keep track of which nodes have been gossiped to for a specific block\n neighbors = copy.copy(neighbor_list) # create copy for deleting and adding listeners to\n #neighbors = [neighbor_list[i] for i in gossipers] #neighbors to those nodes in state one\n \n # Variable to check whether a new consensus has been reached\n cons = np.zeros((1,2))\n consensus_times = [(0)] \n \n # Time and gossiping round begin at zero\n t=0 \n \n \n \n ###############################################################################\n # Run the code\n ############################################################################### \n \n while t < time:\n \n gossiping() # one round of gossip\n \n # gossiping_round = gossiping_round + 1 # increment number of rounds\n # print(\"gossiping round number:\")\n # print(gossiping_round)\n \n \n # Block creation, keeping in mind that for all non-miners probability=0\n for i in range(num_nodes): # iterate through all nodes\n lottery = random.uniform(0.0, 1.0) # generate random number\n if lottery > probability[i]: # node does not mine a new block\n probability[i] = (1-probability[i]) * probability[i] # probability of finding block next round goes up \n else: # node mines a new block\n block_num = block_num + 1 # increment block number\n new_block(i, block_num) # function creates a new block; current node is \"lucky\"\n probability[i] = probability_dt[i] # reset miner's probability\n #print(\"new block mined by\") # output: which miner got lucky\n #print(i)\n \n # Check for consensus in the network \n cons[0,0] = copy.copy(cons[0,1]) # first column is previous consensus status\n cons[0,1] = consensus() # update second column with current consensus status\n if cons[0,0] != cons[0,1]: # consensus status has changed\n if cons[0,1] == True: # if network is in consensus\n #print(\"consensus reached after t =\") \n #print(t)\n consensus_times.append(t) # record times that consensus was reached\n \n # Update information for next round \n t=t+1 # increment time\n gossipers = info_list[:,0][info_list[:,1]==1] # find nodes in state one\n gossipers = [int(i) for i in gossipers] # convert to integrals \n \n \n # Record results \n chain_len = [len(last_block[i]) for i in range(num_nodes)] # find the main (longest) chain(s)\n longest_chain_index = chain_len.index(max(chain_len)) # record the index (if multiple chains are equally long, chooses one) \n longest_chain = copy.copy(last_block[longest_chain_index]) # longest chain's block\n check_block = list(range(longest_chain[-1]+1)) # create a comparison chain with no gaps\n orphans = list(set(check_block) - set(longest_chain)) # compare longest chain with comparison chain, missing blocks are orphans\n num_orphans = len(orphans) # record number of orphaned blocks\n num_total = block_num # record total number of blocks mined\n num_onchain = len(longest_chain) # record total number of blocks on the main chain\n num_consensus = len(consensus_times) # record number of times consensus was reached\n avg_consensus_time = consensus_times[-1]/len(consensus_times)\n #print(avg_consensus_time)\n \n print(trial)\n ratio = num_orphans/num_total\n \n #collect trial results\n res_ratio.append(ratio)\n res_orphanedblocks.append(num_orphans)\n res_totalblocks.append(num_total)\n res_onchain.append(num_onchain)\n res_consensusnum.append(num_consensus)\n res_avg_consensus_time.append(avg_consensus_time)\n \n \n #model results for parameter setting\n orphaned_blocks = np.mean(res_orphanedblocks)\n total_blocks = np.mean(res_totalblocks)\n onchain_blocks = np.mean(res_onchain)\n avg_consensus = np.mean(res_avg_consensus_time)\n \n result = [orphaned_blocks, total_blocks, ratio, onchain_blocks, avg_consensus]\n print(\"connections:\")\n print(nodes_conn)\n print(\"result:\")\n print(result)\n results.append(result)\n \nplt.plot([row[2] for row in results])","sub_path":"system_size.py","file_name":"system_size.py","file_ext":"py","file_size_in_byte":14767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"354590476","text":"import unittest\n\nfrom foil.util import natural_sort\n\n\nclass TestNaturalSort(unittest.TestCase):\n def test_natural_sort(self):\n entries = ['ab127b', 'ab123b']\n\n expected = ['ab123b', 'ab127b']\n result = natural_sort(entries)\n\n self.assertEqual(expected, result)\n","sub_path":"tests/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"187728138","text":"'''\nThis script outlines the steps taken to go from AskPhilosophers.org to a dataframe to a network.\n'''\nfrom pystuff.modeling import *\nfrom pystuff.preprocess import *\nfrom sklearn.metrics import pairwise_distances\n\n\ndef getedges(X, labels=None, value_label='values', oneway=True):\n '''\n This takes a *square* array, and transforms it into three columns (from nodes, to nodes, and values). This is in\n preparation for building a network. The X matrix must be square for it to make sense (e.g., distance from node to\n node in a symmetric matrix).\n :param X: (np.array) The square array to transform.\n :param labels: (list-like) The labels that reference the columns and rows of X. You would conceptualize the rows\n and columns to be the same thing, but a directional network may have different values for labels[i] to labels[j]\n than it does for labels[j] to labels[i].\n :param value_label: (str) Label for the column you'd like to call the values inside matrix X.\n :param oneway: (bool) True if you want only to look at the one-way relationships between rows/columns,\n and false if you want to look at both. Use True if X is inherently symmetric and node_i -> node_j == node_j ->\n node_i (e.g., distance).\n :return: (pd.DataFrame) From nodes, To nodes, and values, based on data passed.\n '''\n\n def check_symmetric(A, tol=1e-8):\n return np.allclose(A, A.T, atol=tol)\n\n if oneway and not check_symmetric(X):\n raise Warning('To do one way connections, the matrix passed should be symmetric.')\n\n if not labels:\n labels = range(X.shape[0])\n\n else:\n labels = list(labels)\n\n start_nodes = []\n end_nodes = []\n values = []\n\n for i, value_i in enumerate(labels):\n\n if not oneway:\n maxperrow = len(labels)\n else:\n maxperrow = i\n\n for j, value_j in enumerate(labels[:maxperrow]):\n start_nodes.append(value_i)\n end_nodes.append(value_j)\n values.append(X[i, j])\n\n return pd.DataFrame({'from': start_nodes, 'to': end_nodes, value_label: values})\n\n'''\n******************************************************************************************\n** 1. GET THE DATA:\n**\n** Here, we use the scripts from the above libraries to get the data in a format we need.\n******************************************************************************************\n'''\n\n'''\nThis is the script to get to askphil_df:\n\nimport pickle as pkl\nfrom pystuff.getdata import *\n\nGET DATA:\n\ndocids1 = range(5801)\ndocids2 = range(24000, 28000) # This last number (28000) could be updated, or you could add to the list below:\ngetposts(docids1, pklfile='./posts_1.pkl')\ngetposts(docids2, pklfile='./posts_2.pkl')\n\nwith open('./posts_1.pkl', 'rb') as f:\n posts_1 = pkl.load(f)\n\nwith open('./posts_2.pkl', 'rb') as f:\n posts_2 = pkl.load(f)\n\nposts = posts_1 + posts_2 # Here, if you have more data, you could just add another list to the list.\naskphil = topandas(posts)\n\nwith open('./askphil_df.pkl', 'wb') as f:\n pkl.dump(askphil, f)\n\n\nMongoDB:\n\nposts_data = [post for post in posts.find()]\nclient.list_database_names()\naskphil.list_collection_names()\n'''\n\n# Use the cleaned up data\nwith open('./data/askphil_df.pkl', 'rb') as f:\n askphil_orig = pkl.load(f)\n\n# Move the responses to the bottom, keep questions at the top, also, isolate the questions and answers\naskphil = doubleup(askphil_orig)\naskphil['docid'] = askphil['docid'].apply(int)\naskphil_q = askphil[askphil['type'] == 'question'][['docid', 'text', 'topics']]\naskphil_r = askphil[askphil['type'] == 'response'][['datetime', 'docid', 'philosopher', 'text']]\n\n# Divide up the data for topic modeling (using them all as single documents doesn't quite work as well)\nX_q = askphil['text'][askphil['type'] == 'question']\nX_r = askphil['text'][askphil['type'] == 'response']\n\n# We need to drop the index so that the TextDecomposition functions will be able to reference back to the original\nX_r.reset_index(drop=True, inplace=True)\n\n# Topic modeling using NMF\nTopicSpace_q = TextDecomposition(X_q)\nTopicSpace_q.vectorize(Tfidf_args={'ngram_range': (1, 2)})\nTopicSpace_q.fit_nmf(n=10)\nTopicSpace_r = TextDecomposition(X_r)\nTopicSpace_r.vectorize(Tfidf_args={'ngram_range': (1, 2)})\nTopicSpace_r.fit_nmf(n=10)\n\n# Get the clusters (topics) and the vectors related to those for each document\nclusters_q, cluster_coefs_q = TopicSpace_q.getclusters()[:2]\nclusters_r, cluster_coefs_r = TopicSpace_r.getclusters()[:2]\ndocspace_q = TopicSpace_q.nmf_docspace\ndocspace_r = TopicSpace_r.nmf_docspace\n\naskphil_q['topic_nmf'] = clusters_q\naskphil_r['topic_nmf'] = clusters_r\n\n# For the questions and responses, get boolean values for each topic. We'l sum responses for each quesiton, later.\naskphil_r = pd.concat((askphil_r, pd.get_dummies(askphil_r['topic_nmf'], prefix='topic_nmf')), axis=1)\naskphil_q = pd.concat((askphil_q, pd.get_dummies(askphil_q['topic_nmf'], prefix='topic_nmf')), axis=1)\n\n# Get locations for questions and responses in their respective topic spaces\nfor i in range(10):\n title = 'topiccoef_' + str(i)\n askphil_q[title] = docspace_q[:, i]\n\nfor i in range(10):\n title = 'topiccoef_' + str(i)\n askphil_r[title] = docspace_r[:, i]\n\naskphil = askphil_q.merge(askphil_r, on='docid', suffixes=('_q', '_r'))\n\n'''\n*********************************************************************************************************\n** 2. BUILD NETWORK ARRAYS\n** \n** Here, we want to use numpy to take the data we gathered (askphil) to construct three networks:\n** \n** 1. Linking questions by similarity in shared topics among questions and responses (max dot-product)\n** 2. Linking questions by similarity in average response topic-space (minimize cosine distance)\n** 3. Linking questions by similarity in question topic-space (minimize cosine distance)\n** 4. Linking questions by similarity in [question + average response] topic-space (same).\n*********************************************************************************************************\n'''\n\n# 1. Get the question and topic components (i.e., which topics are taken up by the question and responses), and\n# aggregate them by sum for the responses. (The question topic will be the same for each document, so np.mean works)\n# E.g., if the 'topic_nmf_3_r = 3, that means that question has three different responses that were assigned to the\n# 3rd topic (from our NMF) analysis.\nq_topic_components = ['topic_nmf_' + str(i) + '_q' for i in range(10)]\nr_topic_components = ['topic_nmf_' + str(i) + '_r' for i in range(10)]\n\n# The question components are a mean (they're all the same for all the responses per question, so this works).\n# The response components are the sum, since each row within a question is a response with one-hot encoding for the\n# topic type. We take a sum to represent the number of responses for each topic.\nsumtopics = askphil.groupby('docid')[q_topic_components + r_topic_components] \\\n .agg({k: v for (k, v) in zip(q_topic_components + r_topic_components,\n [np.mean] * 10 + [np.sum] * 10)})\n\n# 2., 3. Get the average location for the responses in their topic space, and similarly for the questions\nq_topic_coefs = ['topiccoef_' + str(i) + '_q' for i in range(10)]\nr_topic_coefs = ['topiccoef_' + str(i) + '_r' for i in range(10)]\n\navetopicspace_r = askphil.groupby('docid')[r_topic_coefs] \\\n .agg(np.mean)\n\n# Just as above, the mean will just leave the individual values for each coefficient for each question\n# I'm realizing that this is actually just the same as docspace_q, from above.\ntopicspace_q = askphil.groupby('docid')[q_topic_coefs] \\\n .agg(np.mean)\n\n# Here, we need to put the above dataframes in array form\ntopicsim = sumtopics.values\ntopicloc_r = avetopicspace_r.values\ntopicloc_q = topicspace_q.values\ntopicloc_qr = np.hstack((topicloc_q, topicloc_r))\n\n# Build a pairwise relationship matrix for cosine distances between discussions in the spaces above\ndist_matrix_sim = pairwise_distances(topicsim, metric='cosine')\ndist_matrix_r = pairwise_distances(topicloc_r, metric='cosine')\ndist_matrix_q = pairwise_distances(topicloc_q, metric='cosine')\ndist_matrix_qr = pairwise_distances(topicloc_qr, metric='cosine')\n\n# Get the edges for building the matrix. The index for sumtopics is the docid in the order we got these matrices\nedges_sim = getedges(dist_matrix_sim, labels=list(sumtopics.index), value_label='distance')\nedges_r = getedges(dist_matrix_r, labels=list(sumtopics.index), value_label='distance')\nedges_q = getedges(dist_matrix_q, labels=list(sumtopics.index), value_label='distance')\nedges_qr = getedges(dist_matrix_qr, labels=list(sumtopics.index), value_label='distance')\n\n# The difficulty here is that the edge matrices are SUPER big. Also, the \"weights\" are actually distances, but we\n# want to perceive them as weights. So, if the distance is large, we'd want the weight to be small, and vice-versa\n# for shorter distances. For _sim, we'll let the weight simply be the dot-product. We want to maximize this.\n# Given the definition of cosine distance, we can just take 1 - distance to get (u . v / ||u|| ||v||), which is\n# a sort of normalized similarity which is larger when the vectors are 'closer', and smaller when they're 'further'.\nedges_sim['distance'] = 1 - edges_sim['distance']\nedges_r['distance'] = 1 - edges_r['distance']\nedges_q['distance'] = 1 - edges_q['distance']\nedges_qr['distance'] = 1 - edges_qr['distance']\n\n# We use the node data (askphil) and the edges data (edges_...) to build a network! Maybe the dates will come in\n# handy for future analysis.\ngetdateinfo(askphil)\n\naskphil_network = askphil[['docid', 'text_q', 'topics', 'topic_nmf_q', 'topic_nmf_r', 'philosopher', 'text_r',\n 'year', 'month', 'hour', 'weekday', 'yearday']]\n\n# Apparently Gephi is picky, and it only takes particular titles for node and edge tables\naskphil_network.rename(columns={'docid': 'Id', 'text_q': 'Label'}, inplace=True)\nedges_q.rename(columns={'from': 'Source', 'to': 'Target', 'distance': 'Weight'}, inplace=True)\nedges_r.rename(columns={'from': 'Source', 'to': 'Target', 'distance': 'Weight'}, inplace=True)\nedges_sim.rename(columns={'from': 'Source', 'to': 'Target', 'distance': 'Weight'}, inplace=True)\nedges_qr.rename(columns={'from': 'Source', 'to': 'Target', 'distance': 'Weight'}, inplace=True)\n\n# Originally, the idea was to maintain only the rows which are significantly close, given the topic spaces, or the\n# sum of topics in common. As it turns out, using any of these is difficult. In Gephi, we want to have a maximum of\n# about 50 edges for every node. To keep things simple, we'll play with the threshold for the edges_qr, since that's\n# a sufficient all encompassing metric for similarity that 'includes' all the other approaches.\n\n# edges_sim = edges_sim[edges_sim['Weight'] > 0.99]\n# edges_r = edges_r[edges_r['Weight'] > 0.99]\n# edges_q = edges_q[edges_q['Weight'] > 0.99]\n\n# We do something similar here as we did above, but we only want the sumtopics for the responses for each question.\n# This will help when we want to use it for visualization in Gephi.\naskphil_network_q = askphil_network[['Id', 'Label', 'topics', 'topic_nmf_q']].drop_duplicates(subset=['Id'])\naskphil_network_q = askphil_network_q.merge(sumtopics.reset_index()[['docid'] + r_topic_components],\n left_on='Id', right_on='docid')\n\naskphil_network_q.drop(columns='docid', inplace=True)\n","sub_path":"askphil/pystuff/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":11550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"340322235","text":"import pandas as pds\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.linear_model import Perceptron\nfrom sklearn.svm import LinearSVC\n\ndf = pds.read_csv('./data.csv', header=0)\n\n# 特征值\nfeature = df[[\"x\", \"y\"]]\n\n# 目标 C1为红 C2为蓝\ntarget = df[\"class\"]\nfeature_train, feature_test, target_train, target_test = train_test_split(feature, target, test_size=0.77)\n\n# 构建感知机模型\nmodel = Perceptron()\nmodel.fit(feature_train, target_train)\nscore = model.score(feature_test, target_test)\nprint(score)\n# 构建线性支持向量机分类模型\nmodel_1 = LinearSVC()\nmodel_1.fit(feature_train, target_train)\nscore = model.score(feature_test, target_test)\nprint(score)\n","sub_path":"监督学习/支持向量机/blue_and_red.py","file_name":"blue_and_red.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"32968747","text":"def calculate_damage(program):\n charge = 1\n damage = 0\n for e in program:\n if e == 'C':\n charge *= 2\n else:\n damage += charge\n return damage\n\n\ndef best_swap(program):\n index = program.rfind('CS')\n if index == -1:\n return False, program\n return True, program[:index] + 'SC' + program[index + 2:]\n\n\ndef solution(damage, program):\n swaps = 0\n\n while calculate_damage(program) > damage:\n could_swap, new_program = best_swap(program)\n if could_swap:\n swaps += 1\n program = new_program\n else:\n return 'IMPOSSIBLE'\n\n return swaps\n\n\ndef main():\n num_cases = int(input())\n for n in range(1, num_cases + 1):\n parts = raw_input().split()\n damage, program = int(parts[0]), parts[1]\n hacks = solution(damage, program)\n print('Case #{}: {}'.format(n, hacks))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"103045004","text":"import os\n\nfrom label import run, parser\nfrom label.lfs import FramingLabels\nfrom label.lfs.framing import get_lfs\n\nREGISTERED_MODEL_NAME = 'FramingLabelModel'\nLF_FEATURES = {\n 'txt_clean_roberta': None,\n 'txt_clean_use': None,\n }\nDEV_ANNOTATIONS_PATH = os.path.join('/annotations', 'framing', 'gold_df.pkl')\n\n\ndef main():\n parser.add_argument('--trld', default=0.5, type=float, help='cosine similarity threshold')\n parser.add_argument('--encoder', default='roberta', choices=('roberta', 'use'), type=str,\n help='which encoder embeddings to use')\n parsed_args = parser.parse_args()\n run.start(REGISTERED_MODEL_NAME, LF_FEATURES, DEV_ANNOTATIONS_PATH, get_lfs, FramingLabels, parsed_args)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"data-programming/label/framing.py","file_name":"framing.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"353807106","text":"#!/usr/bin/env python\n\nfrom os.path import dirname, join, realpath\nimport sys\n\nsys.path.insert(1, join(dirname(dirname(dirname(realpath(__file__)))), 'src'))\n\nimport glob, jinja2, mysql.connector, os, regex, textwrap, time\nimport config\n\ndef clean(str):\n return textwrap.dedent(str).strip()\n\ndef get_sutta_id(uid):\n global db\n cursor = db.cursor()\n cursor.execute(\"\"\"\n SELECT sutta_id FROM sutta WHERE sutta_uid = '%s';\n \"\"\" % uid)\n return cursor.fetchone()[0]\n\ndef get_title(html):\n title = regex.findall(r'<h1>(.+)</h1>', html)[0]\n return regex.sub(r'<[^>]+>', '', title)\n\ndef read(path):\n with open(path, 'r', encoding='utf-8') as f:\n return f.read()\n\ndef get_sutta_html(path):\n html = read(f)\n return regex.sub(r'</?(body|html)>', '', html).strip()\n\ndef get_meta_html():\n return read('in/Ud/ud.meta.html')\n\ndef get_template():\n loader = jinja2.PackageLoader('conv', '.')\n env = jinja2.Environment(loader=loader)\n return env.get_template('template.html')\n\ndef each_input_file():\n for f in glob.glob('in/Ud/ud[1-9]*.html'):\n yield f\n\ndef make_insert_sql(id, uid):\n now = time.strftime('%Y-%m-%d %H:%M:%S')\n return clean(\"\"\"\n INSERT INTO reference\n (sutta_id, reference_type_id, reference_language_id,\n reference_seq_nbr, abstract_text, reference_url_link,\n update_login_id, update_timestamp)\n VALUES\n ({id}, 1, 1,\n 1, 'English translation of {uid} by Bhikkhu Ānandajoti', '/{uid}/en',\n 'admin', '{time}')\n ;\n \"\"\").format(id=id, uid=uid, time=now) + \"\\n\"\n\nif __name__ == '__main__':\n\n db = mysql.connector.connect(**config.mysql)\n template = get_template()\n meta_html = get_meta_html()\n try:\n os.mkdir('out')\n except OSError:\n pass\n sql_f = open('out/udana.sql', 'w', encoding='utf-8')\n\n for f in each_input_file():\n sutta_html = get_sutta_html(f)\n title = get_title(sutta_html)\n uid = regex.match('^.*(ud.*)\\.html$', f)[1]\n id = get_sutta_id(uid)\n\n out_file = 'out/{}.html'.format(uid)\n html = template.render(title=title,\n sutta_html=sutta_html, meta_html=meta_html)\n open(out_file, 'w', encoding='utf-8').write(html)\n\n sql_f.write(make_insert_sql(id, uid))\n","sub_path":"utility/20130713-udana/conv.py","file_name":"conv.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"36724392","text":"import cv2\nfrom math import *\nimport numpy as np\nimport random\nimport os\n\n\ndef rotate(img, degree):\n # img = cv2.imread(\"plane.jpg\")\n # img = Image.open(pic)\n # img = np.array(img)\n height, width = img.shape[:2]\n\n # degree = 90\n # 旋转后的尺寸\n heightNew = int(width * fabs(sin(radians(degree))) + height * fabs(cos(radians(degree))))\n widthNew = int(height * fabs(sin(radians(degree))) + width * fabs(cos(radians(degree))))\n\n matRotation = cv2.getRotationMatrix2D((width / 2, height / 2), degree, 1)\n\n matRotation[0, 2] += (widthNew - width) / 2 # 重点在这步,目前不懂为什么加这步\n matRotation[1, 2] += (heightNew - height) / 2 # 重点在这步\n\n imgRotation = cv2.warpAffine(img, matRotation, (widthNew, heightNew), borderValue=(255, 255, 255))\n\n # cv2.imshow(\"img\", img)\n # cv2.imshow(\"imgRotation\", imgRotation)\n # cv2.waitKey(0)\n return imgRotation\n\n\n\nif __name__ == '__main__':\n path = \"D:/ean13/BarcodeImage_hough45\"\n filelist = os.listdir(path)\n sum = 0\n success = 0\n i = 0\n\n\n for i in range(500):\n r = random.randint(1, 1000)\n imagePath = path + \"/\" + str(r) + \".png\"\n sum = sum + 1\n img = cv2.imread(imagePath)\n\n # degree = 90 - random.randint(0, 180)\n degree = 45 - random.randint(0, 90)\n\n\n img2 = rotate(img, degree)\n\n cv2.imwrite(imagePath, img2)","sub_path":"rotate45.py","file_name":"rotate45.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"600074131","text":"# -*- coding:utf-8 -*-\nimport requests,json\nfrom urllib.request import urlretrieve\nimport os\nfrom datetime import datetime\nfrom contextlib import closing\nimport time\nclass UnsplashSpider:\n def __init__(self):\n self.id_url = 'http://unsplash.com/napi/feeds/home'\n self.header = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) '\n 'AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/61.0.3163.79 Safari/537.36',\n 'authorization': '***********'#此部分需要自行添加\n }\n self.id_lists = []\n self.download_url='https://unsplash.com/photos/{}/download?force=true'\n print(\"init\")\n def get_ids(self):\n # target_url = 'http://unsplash.com/napi/feeds/home'\n # target_url = 'https://unsplash.com/'\n\n #SSLerror 通过添加 verify=False来解决\n try:\n response = requests.get(self.id_url,headers=self.header,verify=False, timeout=30)\n response.encoding = 'utf-8'\n # print(response.text)\n\n dic = json.loads(response.text)\n # print(dic)\n print(type(dic))\n print(\"next_page:{}\".format(dic['next_page']))\n for each in dic['photos']:\n # print(\"图片ID:{}\".format(each['id']))\n self.id_lists.append(each['id'])\n print(\"图片id读取完成\")\n return self.id_lists\n except:\n print(\"图片id读取发生异常\")\n return False\n def download(self,img_id):\n file_path = 'images'\n download_url = self.download_url.format(img_id)\n if file_path not in os.listdir():\n os.makedirs('images')\n # 2种下载方法\n # 方法1\n # urlretrieve(download_url,filename='images/'+img_id)\n # 方法2 requests文档推荐方法\n # response = requests.get(download_url, headers=self.header,verify=False, stream=True)\n # response.encoding=response.apparent_encoding\n chunk_size=1024\n with closing(requests.get(download_url, headers=self.header,verify=False, stream=True)) as response:\n file = '{}/{}.jpg'.format(file_path,img_id)\n if os.path.exists(file):\n print(\"图片{}.jpg已存在,跳过本次下载\".format(img_id))\n else:\n try:\n start_time = datetime.now()\n with open(file,'ab+') as f:\n for chunk in response.iter_content(chunk_size = chunk_size):\n f.write(chunk)\n f.flush()\n end_time = datetime.now()\n sec = (end_time - start_time).seconds\n print(\"下载图片{}完成,耗时:{}s\".format(img_id,sec))\n except:\n print(\"下载图片{}失败\".format(img_id))\n\n\n\nif __name__=='__main__':\n us = UnsplashSpider()\n id_lists = us.get_ids()\n if not id_lists is False:\n for id in id_lists:\n us.download(id)\n #合理的延时,以尊敬网站\n time.sleep(1)","sub_path":"python爬虫开发与项目实战/requests/biqukan.py","file_name":"biqukan.py","file_ext":"py","file_size_in_byte":3149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"149130659","text":"# -*- coding: utf-8 -*-\n# @Author: GXR\n# @CreateTime: 2021-04-01\n# @UpdateTime: 2021-08-10\n\nimport re\nimport threading\nimport time\n\nimport redis\nimport requests\nfrom loguru import logger\nfrom lxml import etree\n\nimport config\n\n\"\"\"\n 代理格式:127.0.0.1:8888\n\"\"\"\n\nred = redis.Redis(\n host=config.REDIS_HOST,\n port=config.REDIS_PORT,\n db=config.REDIS_DB,\n decode_responses=True,\n)\n\n\ndef freeproxy_89():\n \"\"\"\n 89代理\n https://www.89ip.cn/\n \"\"\"\n try:\n response = requests.get(\n \"http://api.89ip.cn/tqdl.html?api=1&num=3000&port=&address=&isp=\",\n headers=config.HEADERS,\n timeout=20,\n )\n time.sleep(1)\n data = re.findall(\"(\\d+).(\\d+).(\\d+).(\\d+):(\\d+)\", response.text, re.S)\n with red.pipeline(transaction=False) as p:\n for ip in data:\n proxy = \".\".join(ip[:-1]) + \":\" + str(ip[-1])\n p.sadd(config.REDIS_KEY_PROXY_FREE, proxy)\n p.execute()\n logger.debug(\"获取代理[%s]\" % len(data))\n except:\n logger.error(\"获取代理异常\")\n\n\ndef freeproxy_xiaoshu():\n \"\"\"\n 小舒代理\n http://www.xsdaili.com/\n \"\"\"\n try:\n response = requests.get(\n url=\"http://www.xsdaili.com/\", headers=config.HEADERS, timeout=20\n )\n time.sleep(1)\n response.encoding = response.status_code\n html = etree.HTML(response.text)\n hrefs = html.xpath(\"//div[@class='title']/a/@href\")[:2]\n for href in hrefs:\n url = \"http://www.xsdaili.cn\" + href\n response_ip = requests.get(url, headers=config.HEADERS, timeout=20)\n time.sleep(1)\n response_ip.encoding = response_ip.status_code\n data = re.findall(\"(\\d+).(\\d+).(\\d+).(\\d+):(\\d+)\", response_ip.text, re.S,)\n with red.pipeline(transaction=False) as p:\n for ip in data:\n proxy = \".\".join(ip[:-1]) + \":\" + str(ip[-1])\n p.sadd(config.REDIS_KEY_PROXY_FREE, proxy)\n p.execute()\n logger.debug(\"获取代理[%s]\" % len(data))\n except:\n logger.error(\"获取代理异常\")\n\n\ndef freeproxy_yun():\n \"\"\"\n 云代理\n http://www.ip3366.net/free/\n \"\"\"\n try:\n url_list = [\n \"http://www.ip3366.net/free/?stype=1&page=\",\n \"http://www.ip3366.net/free/?stype=2&page=\",\n ]\n with red.pipeline(transaction=False) as p:\n for url in url_list:\n for page in range(1, 6):\n response = requests.get(\n url + str(page), headers=config.HEADERS, timeout=20\n )\n time.sleep(1)\n data = re.findall(\n \"<td>(\\d+).(\\d+).(\\d+).(\\d+)</td>[\\s\\S]*?<td>(\\d+)</td>\",\n response.text,\n re.S,\n )\n for ip in data:\n proxy = \".\".join(ip[:-1]) + \":\" + str(ip[-1])\n p.sadd(config.REDIS_KEY_PROXY_FREE, proxy)\n p.execute()\n logger.debug(\"获取代理[%s]\" % len(data))\n except:\n logger.error(\"获取代理异常\")\n\n\ndef freeproxy_proxylistplus():\n \"\"\"\n ProxyListplus\n https://list.proxylistplus.com/\n \"\"\"\n try:\n with red.pipeline(transaction=False) as p:\n for page in range(1, 6):\n response = requests.get(\n \"https://list.proxylistplus.com/Fresh-HTTP-Proxy-List-\" + str(page),\n headers=config.HEADERS,\n timeout=20,\n )\n time.sleep(1)\n data = re.findall(\n \"<td>(\\d+).(\\d+).(\\d+).(\\d+)</td>[\\s\\S]*?<td>(\\d+)</td>\",\n response.text,\n re.S,\n )\n for ip in data:\n proxy = \".\".join(ip[:-1]) + \":\" + str(ip[-1])\n p.sadd(config.REDIS_KEY_PROXY_FREE, proxy)\n p.execute()\n logger.debug(\"获取代理[%s]\" % len(data))\n except:\n logger.error(\"获取代理异常\")\n\n\ndef run_proxy_get():\n threading.Thread(target=freeproxy_89).start()\n threading.Thread(target=freeproxy_xiaoshu).start()\n threading.Thread(target=freeproxy_yun).start()\n threading.Thread(target=freeproxy_proxylistplus).start()\n\n\nif __name__ == \"__main__\":\n run_proxy_get()\n","sub_path":"proxy_get.py","file_name":"proxy_get.py","file_ext":"py","file_size_in_byte":4523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"333938310","text":"import csv\nimport pandas as pd\nimport re\n\ncities = pd.read_csv(\"/Users/jasonrubenstein/Desktop/GeoLiteCity-Location.csv\", encoding = \"ISO-8859-1\")\n\nUS = cities[(cities[\"country\"] == \"US\")]\nUS[\"city_state\"] = US[\"city\"] + \", \" + US[\"region\"]\nUS = US.drop_duplicates(subset=['city_state'])\n\nUS.to_csv('US_cities', index=False)\n\ndrafted = pd.read_csv(\"/Users/jasonrubenstein/Downloads/2000-2018_MLB_draft_picks (1).csv\")\ndrafted[\"city_state\"] = drafted[\"city\"] + \", \" + drafted[\"state\"]\n\n\n\ndraft_w_location = pd.merge(drafted, US, on=\"city_state\")\ndraft_w_location = draft_w_location.drop_duplicates(subset=['player_name', 'city_state'])\n\ndraft_w_location.to_csv('draft_w_location', index=False)\n\ndrafted = pd.read_csv(\"/Users/jasonrubenstein/Desktop/CBBSN/draft_w_location.csv\")\nwar_by_year = drafted.groupby(['year', 'round'], as_index=False)['WAR'].agg('sum')\nwar_by_year['WAR_per_team'] = war_by_year['WAR']/30\nwar_by_year['draft_year'] = war_by_year['year']\nwar_by_year.to_csv('war_by_year_round', index=0)\n\n","sub_path":"ad_hoc/MLB_draft_analysis/bbref.py","file_name":"bbref.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"517334456","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 11 02:14:48 2016\n\n@author: pankaj\n\"\"\"\n\nfrom subprocess import call\nimport sys\nimport os\nimport codecs\nimport time\nimport io\nimport re\nimport shutil\nimport pronounce as pr\nimport unicodedata2 as uc\nimport glob\nfrom random import randint\n\nimport corpus as cp\n\nnoiseadder = \"J:\\\\asr\\\\bin\\\\noiseadder.exe\"\n\nwavdir = \"J:\\\\new_corpus\"\nwavdirs_and_files = cp.wavdirs_and_files\nwavdirs_and_files = [\n\t\t\t\t\t\t[\"\\\\train\\\\augmented\\\\hindi\\\\male_mono\",\"\",\"hindi_male_mono.txt\"],\n\t\t\t\t\t]\t\t \n\nspeed_changes = {\"s90\":\"0.9\",\"s110\":\"1.1\"}\nnoise_effects = [\n\t\t\t\t\"J:\\\\New_Corpus\\\\sound_effects\\\\757.wav\",\n\t\t\t\t\"J:\\\\New_Corpus\\\\sound_effects\\\\car.wav\",\t\t\t\t\n\t\t\t\t\"J:\\\\New_Corpus\\\\sound_effects\\\\cargo_train.wav\",\n\t\t\t\t\"J:\\\\New_Corpus\\\\sound_effects\\\\hairdrier.wav\",\n\t\t\t\t\"J:\\\\New_Corpus\\\\sound_effects\\\\restaurant.wav\",\n\t\t\t\t\"J:\\\\New_Corpus\\\\sound_effects\\\\street.wav\",\n\t\t\t\t\"J:\\\\New_Corpus\\\\sound_effects\\\\shopping_mall.wav\",\n\t\t\t\t\n\t\t\t ]\n\nno_of_noise_effects = len(noise_effects)-1\t\t\t \n\t\t\t \nfor entry in wavdirs_and_files:\n\tsrc_dir = wavdir + entry[0] + \"\\\\\" + \"train_audio\"\n\tos.chdir(src_dir)\n\n\tfor spd in speed_changes:\n\t\tdst_dir = wavdir + entry[0] + \"_\" + spd + \"\\\\\" + \"train_audio\"\n\t\tprint(dst_dir)\n\t\tif os.path.isdir(dst_dir):\n\t\t\tshutil.rmtree(dst_dir)\n\t\tos.mkdir(dst_dir)\n\t\ts = speed_changes[spd]\n\t\tsrcscript = wavdir + entry[0] + \"\\\\\" + entry[2]\n\t\tdstscript = wavdir + entry[0] + \"_\" + spd + \"\\\\\" + entry[2]\n\t\tprint(srcscript)\n\t\tprint(dstscript)\n\t\tshutil.copyfile(srcscript,dstscript)\n\t\tfor file in glob.glob(\"*.raw\"):\n\t\t\tsrcfile = src_dir + \"\\\\\" + file\n\t\t\tdstfile = dst_dir + \"\\\\\" + file \n\t\t\tcallcmd = \"sox -r 16k -b 16 -c 1 -e signed -t raw %s %s speed %s\"%(srcfile,dstfile,s)\n\t\t\tprint(callcmd)\n\t\t\tcall(callcmd,shell=True)\n\n\tdst_dir = wavdir + entry[0] + \"_\" + \"noise\"\n\tprint(dst_dir)\n\tif os.path.isdir(dst_dir):\n\t\tshutil.rmtree(dst_dir)\n\tos.mkdir(dst_dir)\n\tdst_dir = wavdir + entry[0] + \"_\" + \"noise\" + \"\\\\\" + \"train_audio\"\n\tos.mkdir(dst_dir)\n\tsrcscript = wavdir + entry[0] + \"\\\\\" + entry[2]\n\tdstscript = wavdir + entry[0] + \"_\" + \"noise\" + \"\\\\\" + entry[2]\n\tprint(srcscript)\n\tprint(dstscript)\n\tshutil.copyfile(srcscript,dstscript)\n\n\tfor file in glob.glob(\"*.raw\"):\n\t\teffectno = randint(0,no_of_noise_effects)\n#\t\tprint(effectno)\n\t\tnoisefile = noise_effects[effectno]\n#\t\tcallcmd = \"sox -t wav %s -r 16k -b 16 -c 1 -t raw %s\"%(noisefile,noisefile.replace(\".wav\",\".raw\"))\n#\t\tcall(callcmd,shell=True)\n\t\tsrcfile = src_dir + \"\\\\\" + file\n\t\tdstfile = dst_dir + \"\\\\\" + file \n\t\tcallcmd = noiseadder + \" \" + \"%s %s %s %s\"%(srcfile,noisefile.replace(\".wav\",\".raw\"),dstfile,str(17))\n\t\tprint(callcmd)\n\t\tcall(callcmd,shell=True)\n\t\n\t\t\t\t\n\t\t\n\t\t\t\n\t","sub_path":"utils/data_augment.py","file_name":"data_augment.py","file_ext":"py","file_size_in_byte":2663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"611493561","text":"from behave import then\nfrom selenium.webdriver.common.by import By\nfrom time import sleep\n\nTODAYS_DEALS_HEADER = (By.CSS_SELECTOR, 'h5.a-size-large')\nADD_ITEM = (By.XPATH, \"//*[@id='103 0c8f90e2-announce']\")\n\n@then(\"{expected_header} are shown\")\ndef header_is_correct(context, expected_header):\n actual_header = context.driver.find_element(*TODAYS_DEALS_HEADER).text\n assert actual_header == expected_header, f'Expected {expected_header}, but got {actual_header}'\n\n@then(\"Add sales item to cart\")\ndef add_sales_item(context):\n context.driver.find_element(*ADD_ITEM).click()","sub_path":"features/steps/todays_deals_page_steps.py","file_name":"todays_deals_page_steps.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"653345595","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 30 11:41:30 2017\n\n@author: Think\n\"\"\"\n\nclass Solution(object):\n def letterCombinations(self,digits):\n \"\"\"\n type: digits: str\n rtype: list[str]\n \"\"\"\n mapping = {'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno',\n '7':'pqrs','8':'tuv','9':'wxyz'}\n if len(digits) == 0:\n return []\n if len(digits) == 1:\n return list(mapping[digits])\n last = mapping[digits[-1]]\n # recursive\n prev = self.letterCombinations(digits[:-1])\n return [s1 + s2 for s1 in prev for s2 in last]\n\nif __name__ == '__main__':\n digits = '23'\n result = Solution().letterCombinations(digits)\n print(result)","sub_path":"17.LetterCombinationsOfaPhoneNumber.py","file_name":"17.LetterCombinationsOfaPhoneNumber.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"22783303","text":"#!/usr/bin/env python\n\nimport os, sys, codecs, pprint\n\ndef find_files(root):\n\n\tfilelist = []\n\tfor dir_name, sub_dirs, files in os.walk(root):\n\t\tfor file in files:\n\t\t\tif file.endswith(\".txt\"):\n\t\t\t\tfilelist.append(os.path.join(dir_name, file))\n\n\treturn filelist\n\ndef file_sizes(filelist):\n\n\tsize_dict = {}\n\tfor file in filelist:\n\t\tobject = os.stat(file)\n\t\tsize = object.st_size\n\t\tsize_dict[file] = size\n\n\treturn size_dict\n\n\n\n\nif __name__ == \"__main__\":\n\n# the script will load plain text files into memory and evaluate each one\n# on the command line, run: python text_loader.py /path/to/files/ e.g. /my_project/data/ or ./data/\n\n\n\t# Default path is current directory.\n\t# Specify directory - e.g. \"/path/to/dir\" - as first argument\n\t# Specify file extension - e.g. \".pdf\" - as second argument\n\ttry:\n\t\troot = sys.argv[1]\n\texcept IndexError:\n\t\troot = os.curdir\n\ttry:\n\t\text = sys.argv[2]\n\texcept IndexError:\n\t\text = \".txt\"\n\n\tsources = find_files(root)\n\tfile_stats = file_sizes(sources)\n","sub_path":"py_utils/get_files.py","file_name":"get_files.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"304520104","text":"import asyncio\nfrom gino import Gino\nfrom grpclib.utils import graceful_exit\nfrom grpclib.server import Server\nfrom book_grpc import BookServiceBase\nfrom book_pb2 import Book,BookListResponse\nimport book_pb2\nfrom google.protobuf import empty_pb2\ndb = Gino()\n\n\n\n\nclass Author(db.Model):\n __tablename__ = 'authors'\n\n id = db.Column(db.Integer(), primary_key=True)\n first_name = db.Column(db.String)\n last_name = db.Column(db.String)\n country = db.Column(db.String)\n\n\nclass BookList(db.Model):\n __tablename__ = 'books'\n\n id = db.Column(db.Integer(), primary_key=True)\n name = db.Column(db.String)\n year = db.Column(db.Integer())\n author_id = db.Column(db.Integer, db.ForeignKey('authors.id'))\n\n\nasync def create_book(name,author_id,year):\n\tbook = await BookList.create(name=name,author_id=author_id,year=year)\n\tpk = book.id\n\treturn pk \n\n\nasync def detail_book(book_id):\n\tget_book = await BookList.get(book_id)\n\treturn get_book\n\n\nasync def delete_book(book_id):\n\tawait BookList.delete.where(BookList.id == book_id).gino.status()\n\treturn None\n\n\nasync def update_book(book_id,name,author_id,year):\n\tget_book = await BookList.get(book_id)\n\tawait get_book.update(name=name,author_id=author_id,year=year).apply()\n\treturn get_book.id \n\n\nasync def list_book():\n\tbooks = await BookList.query.gino.all()\n\tbook_list = []\n\tfor book in books:\n\t\tbook_list.append({\n\t\t'id':book.id,\n\t\t'name':book.name,\n\t\t'author_id':book.author_id,\n\t\t'year':book.year\n\t\t})\n\treturn book_list\n\n\nclass BookService(BookServiceBase):\n\n\tasync def BookCreate(self, stream):\n\t\t\trequest = await stream.recv_message()\n\t\t\tname = request.name\n\t\t\tauthor_id = request.author_id\n\t\t\tyear = request.year\n\t\t\tpk = await create_book(name,author_id,year)\n\t\t\tresponse = Book(id=pk,name=name,author_id=author_id,year=year)\n\t\t\tawait stream.send_message(response)\n\n\n\n\tasync def BookDetail(self,stream):\n\t\t\trequest = await stream.recv_message()\n\t\t\tbook_id = request.id\n\t\t\tget_book = await detail_book(book_id)\n\t\t\tname = get_book.name\n\t\t\tyear = get_book.year\n\t\t\tauthor_id = await Author.get(get_book.author_id)\n\t\t\tpk = author_id.id \n\t\t\tresponse = Book(id=book_id,name=name,author_id=pk,year=year)\n\t\t\tawait stream.send_message(response)\n\n\n\tasync def BookDelete(self,stream):\n\t\trequest = await stream.recv_message()\n\t\tbook_id = request.id\n\t\tawait delete_book(book_id)\n\t\tawait stream.send_message(empty_pb2.Empty())\n\n\n\tasync def BookUpdate(self,stream):\n\t\trequest = await stream.recv_message()\n\t\tbook_id = request.id\n\t\tname = request.name \n\t\tauthor_id = request.author_id\n\t\tyear = request.year\n\t\tbook_id = await update_book(book_id,name,author_id,year)\n\t\tawait stream.send_message(Book(id=book_id,name=name,author_id=author_id,year=year))\n\n\n\tasync def BookList(self,stream):\n\t\tbook_list = await list_book()\n\t\tawait stream.send_message(BookListResponse(books=book_list))\n\n \nasync def main(*, host='127.0.0.1', port=50051):\n await db.set_bind('postgresql://root:123@localhost/book_shop')\n await db.gino.create_all()\n server = Server([BookService()])\n with graceful_exit([server]):\n await server.start(host, port)\n print(f'Serving on {host}:{port}')\n await server.wait_closed()\n\nif __name__ == '__main__':\n asyncio.run(main())","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"650915347","text":"import logging\nlogging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s',\n level=logging.INFO,\n datefmt='%Y-%m-%d %H:%M:%S') # noqa\n\nimport functools\nimport pika\n\nfrom config import QUEUE_CONNECTION_STRING\n\nTASK_PROCESSOR_QUEUE_NAME = 'newsparser'\nEXCHANGE_NAME = ''\n\nlogger = logging.getLogger(__name__)\n\n\"\"\"\nPlease refer https://github.com/pika/pika/blob/master/examples/asynchronous_consumer_example.py # noqa: E501\n\"\"\"\n\n\nclass PikaConsumer():\n def __init__(self, handler):\n self._connection = None\n self._channel = None\n self._closing = False\n self._consumer_tag = None\n self._consuming = False\n self._prefetch_count = 1\n self.handler = handler\n\n def connect(self):\n logger.info('Creating connection to message queue')\n return pika.SelectConnection(\n parameters=pika.URLParameters(QUEUE_CONNECTION_STRING+'?heartbeat=600'), # noqa: E501\n on_open_callback=self.on_connection_open,\n on_open_error_callback=self.on_connection_open_error,\n on_close_callback=self.on_connection_closed)\n\n def on_connection_open(self, _unused_connection):\n logger.info('Connection opened')\n self.open_channel()\n\n def open_channel(self):\n logger.info('Creating a new channel')\n self._connection.channel(on_open_callback=self.on_channel_open)\n\n def on_channel_open(self, channel):\n logger.info('Channel opened')\n self._channel = channel\n self.add_on_channel_close_callback()\n self.setup_exchange(EXCHANGE_NAME)\n\n def add_on_channel_close_callback(self):\n logger.info('Adding channel close callback')\n self._channel.add_on_close_callback(self.on_channel_closed)\n\n def on_channel_closed(self, channel, reason):\n logger.warning('Channel %i was closed: %s', channel, reason)\n self.close_connection()\n\n def close_connection(self):\n self._consuming = False\n if self._connection.is_closing or self._connection.is_closed:\n logger.info('Connection is closing or already closed')\n else:\n logger.info('Closing connection')\n self._connection.close()\n\n def close_channel(self):\n logger.info('Closing the channel')\n self._channel.close()\n\n def on_connection_open_error(self, _unused_connection, err):\n logger.error('Connection open failed: %s', err)\n self.reconnect()\n\n def reconnect(self):\n self.should_reconnect = True\n self.stop()\n\n def stop(self):\n if not self._closing:\n self._closing = True\n logger.info('Stopping')\n if self._consuming:\n self.stop_consuming()\n self._connection.ioloop.start()\n else:\n self._connection.ioloop.stop()\n logger.info('Stopped')\n\n def stop_consuming(self):\n if self._channel:\n logger.info('Sending a Basic.Cancel RPC command to RabbitMQ')\n cb = functools.partial(\n self.on_cancelok, userdata=self._consumer_tag)\n self._channel.basic_cancel(self._consumer_tag, cb)\n\n def on_cancelok(self, _unused_frame, userdata):\n self._consuming = False\n logger.info('RabbitMQ acknowledged the cancellation of the consumer: %s', userdata) # noqa: E501\n self.close_channel()\n\n def on_connection_closed(self, _unused_connection, reason):\n self._channel = None\n if self._closing:\n self._connection.ioloop.stop()\n else:\n logger.warning('Connection closed, reconnect necessary: %s', reason) # noqa: E501\n self.reconnect()\n\n def setup_exchange(self, exchange_name):\n logger.info('Declaring exchange: %s', exchange_name)\n if(exchange_name != ''):\n self._channel.exchange_declare(\n exchange=exchange_name,\n exchange_type='direct',\n callback=self.on_exchange_declareok)\n else:\n logger.info('Skipping binding as it is the default exchange')\n self.set_qos()\n\n def on_exchange_declareok(self, _unused_frame):\n logger.info('Exchange declared')\n self.setup_queue(TASK_PROCESSOR_QUEUE_NAME)\n\n def setup_queue(self, queue_name):\n logger.info('Declaring queue %s', queue_name)\n self._channel.queue_declare(queue=queue_name, callback=self.on_queue_declareok) # noqa: E501\n\n def on_queue_declareok(self, _unused_frame):\n logger.info('Binding %s to %s with %s', EXCHANGE_NAME,\n TASK_PROCESSOR_QUEUE_NAME, TASK_PROCESSOR_QUEUE_NAME)\n self._channel.queue_bind(\n TASK_PROCESSOR_QUEUE_NAME,\n EXCHANGE_NAME,\n routing_key=TASK_PROCESSOR_QUEUE_NAME,\n callback=self.on_bindok)\n\n def on_bindok(self, _unused_frame):\n self.set_qos()\n\n def set_qos(self):\n self._channel.basic_qos(\n prefetch_count=self._prefetch_count, callback=self.on_basic_qos_ok)\n\n def on_basic_qos_ok(self, _unused_frame):\n logger.info('QOS set to: %d', self._prefetch_count)\n self.start_consuming()\n\n def start_consuming(self):\n logger.info('Issuing consumer related RPC commands')\n self._channel.add_on_cancel_callback(self.on_consumer_cancelled)\n self._consumer_tag = self._channel.basic_consume(\n TASK_PROCESSOR_QUEUE_NAME, self.on_message)\n self.was_consuming = True\n self._consuming = True\n\n def on_message(self, _unused_channel, basic_deliver, properties, body):\n logger.info('Received message # %s from %s: %s',\n basic_deliver.delivery_tag, properties.app_id, body)\n self.handler(body)\n self._channel.basic_ack(basic_deliver.delivery_tag)\n\n def on_consumer_cancelled(self, method_frame):\n logger.info('Consumer was cancelled remotely, shutting down: %r',\n method_frame)\n if self._channel:\n self._channel.close()\n\n def run(self):\n self._connection = self.connect()\n self._connection.ioloop.start()\n","sub_path":"newsparser/pika_consumer.py","file_name":"pika_consumer.py","file_ext":"py","file_size_in_byte":6172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"342015537","text":"\nimport re\ndef get_matching_words(regex):\n words = [\"aimlessness\", \"assassin\", \"baby\", \"beekeeper\", \"belladonna\", \"cannonball\", \"crybaby\", \"denver\", \"embraceable\", \"facetious\", \"flashbulb\", \"gaslight\", \"hobgoblin\", \"iconoclast\", \"issue\", \"kebab\", \"kilo\", \"laundered\", \"mattress\",\n \"millennia\", \"natural\", \"obsessive\", \"paranoia\", \"queen\", \"rabble\", \"reabsorb\", \"sacrilegious\", \"schoolroom\", \"tabby\", \"tabloid\", \"unbearable\", \"union\", \"videotape\"]\n matches = []\n for word in words:\n \tif re.search(regex, word):\n \t\tmatches.append(word)\n return matches\n\n# regex = 'v'\n# any words w/ v\n# regex = 'ss'\n# any words w/ double s\n# regex = r'e\\b'\n# any words end w/ e\n# regex = r'b.b'\n# any words that contain b, any character other than \"b\"\n# regex = 'b[^b-]b'\n# any word thats contain b, atleast one character, then another b\n# regex = 'b[A-Za-z0-9]*b'\n# any words that contain b, any number of characters including zero, then another b\n# regex = 'a[A-Za-z]*e[A-Za-z]*i[A-Za-z]*o[A-Za-z]*u'\n# any words that include all five vowels in order\n# regex = r'^[regularxpsion]+$'\n# any words that only use the letters in \"regular expression\"\nregex = r\"\\w*(\\w)\\1\\w*\"\n# any words that contain double letters\n\nprint(get_matching_words(regex))\n","sub_path":"Python_Fundamentals/python/simple searching.py","file_name":"simple searching.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"646191620","text":"import requests\n\n# ANS_SIMPLE = {} #\ntext_sample = 'Добро пожаловать'\n\n# ANS_COMPLEX = {}\ntext_complex = 'Сюда пришли люди, которым было приятнее быть друг с другом, ' \\\n 'чем порознь, которые терпеть не могли всякого рода ' \\\n 'воскресений, ' \\\n 'потому что в воскресенье им было скучно. Маги, Люди с ' \\\n 'большой ' \\\n 'буквы, и девизом их было -- \"Понедельник начинается в ' \\\n 'субботу\". ' \\\n 'Они были магами потому, что очень много знали, так ' \\\n 'много, что ' \\\n 'количество перешло у них наконец в качество, и они ' \\\n 'стали с миром ' \\\n 'в другие отношения, нежели обычные люди. Они работали ' \\\n 'в институте, ' \\\n 'который занимался прежде всего проблемами человеческого ' \\\n 'счастья и ' \\\n 'смысла человеческой жизни, но даже среди них никто ' \\\n 'точно не знал, ' \\\n 'что такое счастье и в чем именно смысл жизни. И они приняли ' \\\n 'рабочую гипотезу, что счастье в непрерывном познании ' \\\n 'неизвестного ' \\\n 'и смысл жизни в том же. Каждый человек -- маг в душе, ' \\\n 'но он ' \\\n 'становится магом только тогда, когда начинает меньше ' \\\n 'думать о ' \\\n 'себе и больше о других, когда работать ему становится ' \\\n 'интереснее, ' \\\n 'чем развлекаться в старинном смысле этого слова.'\n\nYANDEX_TRANSLATE_KEY = \"trnsl.1.1.20180524T001733Z.0b413fdcb28264eb.\" \\\n \"75239dbc83b745f6c066d1ee7ff37b195250b03d\"\nTRANSLATE_PAGE = \"https://translate.yandex.net/api/v1.5/tr.json/\" \\\n \"translate?\"\nPAIRS_TRANSLATE_PAGE = \"https://translate.yandex.net/api/v1.5\" \\\n \"/tr.json/getLangs?\"\n\n\ndef translate(text, lang_pair):\n req = requests.get(\n url=TRANSLATE_PAGE,\n params={\n \"key\": YANDEX_TRANSLATE_KEY,\n \"text\": text,\n \"lang\": lang_pair\n }).json()\n # print(req)\n return req[\"text\"][0]\n\n\ndef get_translate_pairs():\n req = requests.get(\n url=PAIRS_TRANSLATE_PAGE,\n params={\n \"key\": YANDEX_TRANSLATE_KEY,\n \"ui\": \"en\"\n }\n ).json()\n all_lang_pars = req[\"langs\"]\n need_foreign_langs = list(filter(lambda l: \"e\" in l, all_lang_pars.keys()))\n need_lang_pairs = []\n for foreign_lang in need_foreign_langs:\n need_lang_pairs.append([\n \"{}-{}\".format(\"ru\", foreign_lang),\n \"{}-{}\".format(foreign_lang, \"ru\"),\n foreign_lang\n ])\n\n return need_lang_pairs\n\n\ndef run(text, need_lang_pairs):\n response = {}\n for lang_pair in need_lang_pairs:\n ru_to_foreign, foreign_to_ru, code_foreign = lang_pair\n len_chain = 1\n text_to_translate = text\n while True:\n if len_chain > 8:\n response[code_foreign] = \"too_much\"\n # print(code_foreign, \"too_much\")\n break\n\n translated_text = translate(text_to_translate, ru_to_foreign)\n untranslated_text = translate(translated_text, foreign_to_ru)\n\n if text_to_translate == untranslated_text:\n response[code_foreign] = len_chain\n # print(code_foreign, len_chain)\n break\n\n text_to_translate = untranslated_text\n len_chain += 1\n return response\n\n\n# need_lang_pairs = get_translate_pairs()\n# response = run(text_complex, need_lang_pairs)\n# ANS_COMPLEX = response\nANS_SIMPLE = {\"be\": 1, \"ceb\": 1, \"de\": 1, \"el\": 1, \"en\": 1, \"eo\": 1, \"es\": 1,\n \"et\": 1, \"eu\": 1, \"he\": 1, \"ne\": 1, \"te\": 1}\n\nANS_COMPLEX = {'be': 2, 'ceb': 6, 'de': 'too much', 'el': 3, 'en': 3,\n 'eo': 'too much', 'es': 3, 'et': 'too much', 'eu': 7, 'he': 4,\n 'ne': 3, 'te': 'too much'}\n","sub_path":"1st-term/Python/contests/last_contests_on_gitlab/translation_chains/translator.py","file_name":"translator.py","file_ext":"py","file_size_in_byte":4763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"481926996","text":"\n# test1 = ['hello', 'world', 'java', 'automaton']\ndef middle_upper(testList):\n newList = [] # 定义一个空的list\n for temp in testList:\n # 取余判断奇数\n s = len(temp) % 2 #取余判断奇数\n a = len(temp) // 2 #取整\n if s == 1:\n # 拼接字符串,将最中间字母大写\n str = temp[:a]+temp[a:a+1].upper()+temp[a+1:]\n newList.append(str)\n else:\n newList.append(temp)\n return newList\n# print(middle_upper(test1))\n\nif __name__ == '__main__':\n testList = ['hello', 'world', 'java', 'automaton']\n print(middle_upper(testList))\n\n# testList = ['hello', 'world', 'java', 'automaton']\n# def middle_upper(list):\n# for i in range(0,len(list)):\n# if len(list[i])%2 == 1:\n# #将中间字母大写\n# mid = len(list[i])//2\n# str = list[i][:mid]+list[i][mid:mid+1].upper()+list[i][mid+1:]\n# list[i] = str\n# else:\n# print('null')\n#\n# return list\n#\n# print(middle_upper(testList))\n\n\n\n\n\n\n\n\n\n\n","sub_path":"pythonLessonDemo/class02.homework.py","file_name":"class02.homework.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"156391463","text":"#!/bin/env python\n\n# Command line script to get GB/day from manager, then save to google sheet.\nfrom som.api.google.sheets import Client\nfrom datetime import datetime, timedelta\nimport subprocess\nimport argparse\nimport json\nimport os\nimport sys\n\n\ndef get_parser():\n parser = argparse.ArgumentParser(\n description=\"Sendit: save GB-day to Google Sheets\")\n\n parser.add_argument(\"--sheet_id\", dest='sheet_id', \n help=\"alpha-numerical string that is id for sheet\", \n type=str, required=True)\n\n parser.add_argument(\"--days\", dest='days', \n help=\"number of days to ask for metric (default is 1)\", \n type=int, default=1)\n\n # Compare two images (a similarity tree)\n parser.add_argument('--save', dest='save', \n help=\"required flag to save new row (otherwise prints sheet)\", \n default=False, action='store_true')\n\n return parser\n\n\ndef main():\n\n parser = get_parser()\n\n try:\n args = parser.parse_args()\n except:\n sys.exit(0)\n\n command = [\"python\", \"manage.py\", \"summary_metrics\", \"--days\", str(args.days)]\n process = subprocess.Popen(command, stdout=subprocess.PIPE)\n result,error = process.communicate()\n\n if isinstance(result,bytes):\n result = result.decode('utf-8')\n \n result = json.loads(result)\n\n gb_day = result[\"gb_per_day\"]\n\n secrets = os.environ.get('GOOGLE_SHEETS_CREDENTIALS')\n if secrets is None:\n print(\"Please export client secrets file name at GOOGLE_SHEETS_CREDENTIALS\")\n sys.exit(1)\n\n cli = Client()\n\n # Define date range for metric\n start_date = (datetime.now() - timedelta(days=args.days)).strftime(\"%m/%d/%Y\")\n end_date = datetime.now().strftime(\"%m/%d/%Y\")\n\n # Get previous values\n values = cli.read_spreadsheet(sheet_id=args.sheet_id, range_name=\"A:E\")\n\n # Only update if we are sure about values\n required = ['pipeline', \n 'start_date',\n 'end_date',\n 'G/day GetIt',\n 'G/day SendIt']\n\n for h in range(len(required)):\n if required[h] != values[0][h]:\n print(\"Warning, sheet is possibly changed.\")\n print(\"Required: %s\" %\",\".join(required))\n print(\"Found: %s\" %\",\".join(values[0]))\n sys.exit(0)\n \n # Create row, append\n # pipeline\tstart_date\tend_date G/day GetIt\tG/day SendIt\n # Define new row, add\n\n row = [1, # pipeline\n start_date, # start_date\n end_date, # end_date\n None, # G/day GetIt\n gb_day] # G/day SendIt\n\n values.append(row)\n\n for row in values:\n print(' '.join([str(x) for x in row]))\n\n # Update sheet\n if args.save is True:\n print(\"Saving result to sheet %s\" %args.sheet_id)\n result = cli.write_spreadsheet(args.sheet_id, values, range_name=\"A:E\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/save_google_sheets.py","file_name":"save_google_sheets.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"179689178","text":"import numpy as np\nimport tensorflow as tf\n\nclass TerminalLayer(object):\n #final activation layer \n #i = layer depth/layer-id\n #a = activation function\n #mi = number of input features\n #mo = number of output features \n def __init__(self, param):\n self.architecture = param\n self.layer_type = param['type']\n self.activation_func = param['activation']\n self.layer_depth = param['depth']\n mi = param['num_input']\n mo = param['num_output']\n tag = self.layer_type + str(self.layer_depth)\n self.W = tf.Variable(tf.truncated_normal([mi, mo], stddev=0.1), name=\"W\"+tag)\n self.b = tf.Variable(tf.constant(0.1, shape=[mo]), name=\"b\"+tag)\n\n def printArchitecture(self):\n print(self.architecture)\n \n def forward(self,X):\n out = tf.matmul(X, self.W) + self.b\n if self.activation_func == \"softmax\":\n out = tf.nn.softmax(out)\n #elif self.activation_func == \"gap\":\n # return tf.nn.tanh(out)\n return out\n \n\"\"\"\nclass DOLayer(object):\n #Drop Out\n #_i = layer depth/layer-id\n #r = Drop Out rate\n def __init__(self, param):\nself.architecture = param\n self.layer_type = param['type']\n self.layer_depth = param['depth']\n self.drop_out = param['drop_out']/100.0\n \n def forward(self,X):\n return tf.nn.dropout(X, rate=self.drop_out)\n\"\"\"\n\nclass FCLayer(object):\n #Fully Connected layer\n #_i = layer depth/layer-id\n #mi = number of input features\n #mo = number of output features\n #a = activation function\n def __init__(self, param):\n self.architecture = param\n self.layer_type = param['type']\n self.activation_func = param['activation']\n self.layer_depth = param['depth']\n self.drop_out = param['drop_out']/100.0\n mi = param['num_input']\n mo = param['num_output']\n tag = self.layer_type + str(self.layer_depth)\n self.W = tf.Variable(tf.truncated_normal([mi, mo], stddev=0.1),name=\"W\"+tag)\n self.b = tf.Variable(tf.constant(0.1, shape=[mo]), name=\"b\"+tag)\n \n def printArchitecture(self):\n print(self.architecture)\n\n def forward(self, X):\n out = tf.matmul(X, self.W) + self.b\n if self.activation_func == \"relu\":\n out = tf.nn.relu(out)\n elif self.activation_func == \"tanh\":\n out = tf.nn.tanh(out)\n elif self.activation_func == \"sigmoid\":\n out = tf.nn.sigmoid(out)\n return tf.nn.dropout(out, rate=self.drop_out)\n\nclass ConvLayer(object):\n #Convolution Layer\n #_i = layer depth\n #mi = num_input features\n #mo = num_output_features\n #ksize = convolution kernel_size\n #l = strides\n #a = activation function \n def __init__(self, param):\n self.architecture = param\n self.layer_type = param['type']\n self.layer_depth = param['depth']\n self.ksize = param['kernel_size']\n self.stride = param['stride']\n self.drop_out = param['drop_out']/100.0\n self.activation_func = param['activation']\n mi = param['num_input']\n mo = param['num_output']\n fw, fh = self.ksize\n tag = self.layer_type + str(self.layer_depth)\n self.W = tf.Variable(tf.truncated_normal([fw, fh, mi, mo], stddev=0.03), name=\"W\"+tag)\n self.b = tf.Variable(tf.constant(0.1, shape=[mo]), name=\"b\"+tag)\n\n def printArchitecture(self):\n print(self.architecture)\n\n def forward(self, X):\n sw, sh = self.stride\n conv_out = tf.nn.conv2d(X, self.W, strides=[1, sw, sh, 1], padding='SAME')\n conv_out = tf.nn.bias_add(conv_out, self.b)\n if self.activation_func == \"relu\":\n conv_out = tf.nn.relu(conv_out)\n elif self.activation_func == \"tanh\":\n conv_out = tf.nn.tanh(conv_out)\n elif self.activation_func == \"sigmoid\":\n conv_out = tf.nn.sigmoid(conv_out)\n return tf.nn.dropout(conv_out, rate=self.drop_out)\n \n #f = receptive field size\n #d = num_receptive_fields\n #n = representation size\n def getRepresentations(self):\n #TODO\n return (0,0,0) \n \n \nclass PoolLayer(object):\n #Pooling Layer\n #ksize = pooling kernel_size\n #l = strides\n def __init__(self, param):\n self.architecture = param\n self.layer_type = param['type']\n self.pool = param['pool'] \n self.layer_depth = param['depth']\n self.stride = param['stride']\n self.ksize = param['kernel_size']\n self.drop_out = param['drop_out']/100.0\n \n def printArchitecture(self):\n print(self.architecture)\n\n def forward(self, X):\n sw, sh = self.stride\n fw, fh = self.ksize\n pool_out = None\n if self.pool == 'max':\n pool_out = tf.nn.max_pool(\n X,\n ksize=[1, fw, fh, 1],\n strides=[1, sw, sh, 1],\n padding='SAME'\n )\n elif self.pool == 'avg':\n pool_out = tf.nn.avg_pool(\n X,\n ksize=[1, fw, fh, 1],\n strides=[1, sw, sh, 1],\n padding='SAME'\n )\n return tf.nn.dropout(pool_out, rate=self.drop_out)\n","sub_path":"convolutional-neural-nets/cnn-learning-architecture/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":5286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"238879012","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\nfrom setuptools import setup\nfrom setuptools.command.install import install\n\nfrom clid import main\n\nif sys.version_info[0] != 3:\n sys.exit('clid requires Python3')\n\nhome = os.path.expanduser('~')\nhere = os.path.dirname(os.path.abspath(__file__))\n\nlong_des = \"\"\"Clid is a command line app written in Python3 to manage your mp3 files' ID3 tags.\nUnlike other tools, clid provides a graphical interface in the terminal to edit\ntags, much like the way `cmus <https://github.com/cmus/cmus>`_ does for playing\nmp3 files in the terminal.\n\nSee the `homepage <https://github.com/GokulSoumya/clid>`_ for more details.\n\"\"\"\n\nclass PostInstall(install):\n def run(self):\n import configobj\n with open(home + '/.clid.ini', 'w') as new: # make an ini file: ~/.clid.ini\n old = open(here + '/clid/config.ini', 'r').read()\n new.write(old)\n\n config = configobj.ConfigObj(home + '/.clid.ini') # set the default music dir as ~/Music\n config['music_dir'] = home + '/Music/'\n config.write()\n\n install.run(self)\n\n\nsetup(\n name='clid',\n version=main.__version__,\n license='MIT',\n\n packages=['clid'],\n\n description='Command line app based on ncurses to edit ID3 tags of mp3 files',\n long_description = long_des,\n\n keywords='mp3 id3 command-line ncurses',\n classifiers=[\n 'Topic :: Multimedia :: Sound/Audio',\n 'Topic :: Multimedia :: Sound/Audio :: Editors',\n 'Topic :: Multimedia :: Sound/Audio :: Players :: MP3',\n 'License :: OSI Approved :: MIT License',\n 'Environment :: Console',\n 'Environment :: Console :: Curses',\n 'Intended Audience :: End Users/Desktop',\n 'Development Status :: 3 - Alpha',\n 'Programming Language :: Python :: 3 :: Only',\n ],\n\n author='Gokul',\n author_email='gokulps15@gmail.com',\n\n url='https://github.com/GokulSoumya/clid',\n\n # See https://PyPI.python.org/PyPI?%3Aaction=list_classifiers\n # See http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files\n # See cheat in github\n\n install_requires=['npyscreen', 'stagger', 'configobj'],\n\n cmdclass={\n 'install': PostInstall\n },\n entry_points={\n 'console_scripts': [\n 'clid = clid.__main__:run'\n ]\n }\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"475661100","text":"import datetime as dt\n\nimport QSTK.qstkutil.DataAccess as da\nimport QSTK.qstkutil.qsdateutil as du\nimport QSTK.qstkutil.tsutil as tsu\nimport numpy as np\n\nhistorical_datasource_name = 'Yahoo'\n\ndef calculateDailyReturns(timestamps, companySymbol):\n symbolList = [companySymbol]\n c_dataobj = da.DataAccess(historical_datasource_name) # Creating an object of the dataaccess class with Yahoo as the\n ls_keys = ['open', 'close', 'volume', 'actual_close']\n ldf_data = c_dataobj.get_data(timestamps, symbolList, ls_keys)\n d_data = dict(zip(ls_keys, ldf_data))\n for s_key in ls_keys:\n d_data[s_key] = d_data[s_key].fillna(method='ffill')\n d_data[s_key] = d_data[s_key].fillna(method='bfill')\n d_data[s_key] = d_data[s_key].fillna(1.0)\n # Getting the numpy ndarray of close prices.\n na_price = d_data['close'].values\n dayAfterPrice = np.copy( np.copy(na_price[1:]))\n yesterdayPrice = np.copy(na_price[0: (len(na_price)-1)])\n dailyReturns = (dayAfterPrice / yesterdayPrice) - 1\n results = np.append(dailyReturns, [[0]])\n finalResults = results.reshape(([len(results),1]))\n return finalResults\n\ndef simulate(startdate, enddate, portfolio, allocation):\n\n dt_timeofday = dt.timedelta(hours=16) # Closint price, hours =16\n ldt_timestamps = du.getNYSEdays(startdate, enddate, dt_timeofday) # Timestamp list\n sumArray = np.zeros([len(ldt_timestamps),1])\n\n for index in range (0,len(portfolio)):\n sumArray += allocation[index] * calculateDailyReturns(ldt_timestamps, portfolio[index])\n\n average = np.average(sumArray)\n stdev = np.std(sumArray)\n sharpeRatio = average/stdev\n na_rets = np.copy(sumArray)\n cumulativ = tsu.returnize0(na_rets)\n\n\n return [stdev, average, sharpeRatio, cumulativ]\n\ndef main():\n dt_start = dt.datetime(2010, 1, 1)\n dt_end = dt.datetime(2010, 12, 31)\n symbols = ['AXP', 'HPQ', 'IBM', 'HNZ']\n allocation = [0.0, 0.0, 0.0, 1.0]\n test1, test2, test3, test4 = simulate(dt_start,dt_end,symbols,allocation)\n\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"HW1/Simulation.py","file_name":"Simulation.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"139221357","text":"from django.http import HttpResponse\nimport re\n# import os\n# from django.utils import timezone\n# from django.template import loader\n# import random\nfrom django.shortcuts import render\nfrom .models import Post\n\n\ndef post_list(request):\n posts = Post.objects.order_by('-created_date')\n\n # post_title = '<ul>'\n # for post in posts:\n # post_title += f'<li>{post.title}</li>'\n # post_title += '</ul>'\n\n context = {\n 'posts': posts,\n }\n return render(\n request=request,\n template_name='blog/post_list.html',\n context=context\n )\n\n\ndef post_detail(request, pk):\n post = Post.objects.get(id=pk)\n\n context = {\n 'post': post,\n }\n\n return render(request, 'blog/post_detail.html', context)\n\n\n\n #템플릿을 가져옴 (단순 문자열이 아님)\n # template = loader.get_template('blog/post_list.html')\n # # 해당 템플릿을 렌더링\n # context ={\n # 'name': random.choice(['이정화', '박영수']),\n #\n # }\n # content = template.render(context, request)\n # return HttpResponse(content)\n # context ={\n # 'name': random.choice(['이정화', '박영수']),\n # }\n # # render 함수 알아보기 !! 위의 것과 같은 결과를 보여줌\n # # loader.get_template\n # # template.render\n # # HttpResponse(content)\n # # 위 3가지를 한번에 해주는 역할\n # return render(\n # request=request,\n # template_name='blog/post_list.html',\n # context=context\n # )\n\n\n\n # # templates/blog/post_list.html 파일의 내용을 읽어온 후,\n # # 해당 내용을 아래에서 리턴해주는 HttpResponse인스턴스 생성시 인수로 넣우준다\n # # os.path.abspath(__file__) <-코드가 실행중인 파일의 경로를 나타냄\n # # os.path.dirname(<경로>) <-특정 경로의 상위폴더를 나타냄\n # # os.path.join(<경로>, <폴더/파일명>) <- 특정 경로에서 하위폴더 또는 하위 파일을 나타냄\n # # current_path = os.path.abspath(__file__)\n # # p_path = os.path.dirname(current_path)\n # # p_path = os.path.dirname(p_path)\n # # c_path = os.path.join(p_path, 'templates')\n # # c_path = os.path.join(c_path, 'blog')\n # # html_path = os.path.join(c_path, 'post_list.html')\n #\n # views_file_path = os.path.abspath(__file__)\n # blog_application_path = os.path.dirname(views_file_path)\n # app_dir = os.path.dirname(blog_application_path)\n # template_path = os.path.join(app_dir, 'template', 'blog', 'post_liost.html')\n #\n # with open(template_path, 'rt') as f:\n # html_text = f.read()\n # # #with문 안쓴다면\n # # html_text = open(template_path, 'rt').read()\n #\n # return HttpResponse(html_text)\n\n\n\n","sub_path":"app/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"509635674","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\nfrom sklearn.metrics import confusion_matrix\n#nltk.download('stopwords')\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer \n#nltk.download('wordnet')\nfrom nltk.corpus import wordnet\nimport spacy\nimport re\nimport nltk\nnlp = spacy.load(\"en_core_web_sm\")\n\n\nclass LR3partC:\n \n def __init__(self):\n print(\"Inside constructor LR3part\")\n\n def get_wordnet_pos(self,word):\n tag = nltk.pos_tag([word])[0][1][0].upper()\n tag_dict = {\"J\": wordnet.ADJ,\n \"N\": wordnet.NOUN,\n \"V\": wordnet.VERB,\n \"R\": wordnet.ADV}\n\n return tag_dict.get(tag, wordnet.NOUN)\n\n def preprocess_raw_text(self,raw_text):\n raw_text = raw_text.lower()\n raw_text = re.sub('[^a-zA-Z]',' ',raw_text)\n words = re.findall(r'\\w+', raw_text,flags = re.UNICODE) \n important_words = filter(lambda x: x not in stopwords.words('english'), words)\n lemmatizer = WordNetLemmatizer()\n lammatized_raw_word_list = [lemmatizer.lemmatize(w,self.get_wordnet_pos(w)) for w in important_words]\n return lammatized_raw_word_list\n\n \n def noun_phrases(self,text_answer):\n text_answer =self.preprocess_raw_text(text_answer)\n text_answer = ' '.join(text_answer)\n doc = nlp(text_answer)\n answer=[chunk.text for chunk in doc.noun_chunks]\n answer = ' '.join(answer)\n return answer\n \n def execute3part(self):\n #Part 1 of 3 Classification of students notes to Fact vs Explanation\n trainingDF = pd.read_csv(\"light_data_training.csv\")\n testingDF =pd.read_csv(\"light_data_testing.csv\")\n trainingDF['complexity_Type']=trainingDF.complexity_type.map({'fact':0,'explanation':1})\n testingDF['complexity_Type']=testingDF.complexity_type.map({'fact':0,'explanation':1})\n \n corpus = []\n for i in range(0,len(trainingDF)):\n answer =trainingDF['answer'][i]\n answer=self.noun_phrases(answer)\n corpus.append(answer)\n \n vect =CountVectorizer(max_features=600)\n X = vect.fit_transform(corpus).toarray()\n y= trainingDF.complexity_Type \n\n\n X_test= testingDF.answer\n X_testFE= vect.transform(X_test)\n y_test= testingDF.complexity_Type \n \n\n logisticRegr = LogisticRegression()\n logisticRegr.fit(X, y)\n\n y_predFE = logisticRegr.predict(X_testFE)\n acc =metrics.accuracy_score(y_test, y_predFE)\n cm = confusion_matrix(y_test, y_predFE) \n \n #Part 2 of 3 L-EF vs L-F \n testingDF['y_predFE']=\"\"\n testingDF['y_predFE']=y_predFE\n\n trainingDF2=trainingDF.loc[trainingDF.complexity_type=='fact',['complexity_type','answer','complexity_level']]\n testingDF2=testingDF.loc[testingDF.y_predFE==0,['answer','complexity_level']]\n\n trainingDF2 = trainingDF2.reset_index()\n del trainingDF2['index']\n\n trainingDF2['complexity_Level']=trainingDF2.complexity_level.map({'L-EF':0,'L-F':1})\n testingDF2['complexity_Level']=testingDF2.complexity_level.map({'L-EF':0,'L-F':1})\n\n df=testingDF2.dropna(how='any')\n\n corpus1 = []\n for i in range(0,len(trainingDF2)):\n #print(\"Inside for loop\")\n answer1 =trainingDF2['answer'][i]\n answer1=self.noun_phrases(answer1)\n corpus1.append(answer1)\n\n \n vect1 =CountVectorizer()\n X1 = vect1.fit_transform(corpus1).toarray()\n y1= trainingDF2.complexity_Level \n\n X_test2= df.answer\n X_testEFE= vect1.transform(X_test2)\n y_test2= df.complexity_Level \n \n logisticRegr1 = LogisticRegression()\n logisticRegr1.fit(X1, y1)\n\n y_predEFE = logisticRegr1.predict(X_testEFE)\n acc1 =metrics.accuracy_score(y_test2, y_predEFE)\n cm1 = confusion_matrix(y_test2, y_predEFE) \n\n #Part3 of 3 L-EE vs L-E\n trainingDF3=trainingDF.loc[trainingDF.complexity_type=='explanation',['complexity_type','answer','complexity_level']]\n testingDF3=testingDF.loc[testingDF.y_predFE==1,['answer','complexity_level']]\n\n trainingDF3 = trainingDF3.reset_index()\n del trainingDF3['index']\n\n trainingDF3['complexity_Level']=trainingDF3.complexity_level.map({'L-EE':0,'L-E':1})\n testingDF3['complexity_Level']=testingDF3.complexity_level.map({'L-EE':0,'L-E':1})\n df2=testingDF3.dropna(how='any')\n corpus2 = []\n for i in range(0,len(trainingDF3)):\n answer2 =trainingDF3['answer'][i]\n answer2=self.noun_phrases(answer2)\n corpus2.append(answer2)\n\n vect2 =CountVectorizer()\n X2 = vect2.fit_transform(corpus2).toarray()\n y2= trainingDF3.complexity_Level \n\n X_test3= df2.answer\n X_testEEE= vect2.transform(X_test3)\n y_test3= df2.complexity_Level \n\n logisticRegr2 = LogisticRegression()\n logisticRegr2.fit(X2, y2)\n\n y_predEEE = logisticRegr2.predict(X_testEEE)\n acc2 =metrics.accuracy_score(y_test3, y_predEEE)\n\n cm2 = confusion_matrix(y_test3, y_predEEE) \n list_accuracy=[acc,acc1,acc2,cm,cm1,cm2]\n return list_accuracy","sub_path":"3-part/LR3part.py","file_name":"LR3part.py","file_ext":"py","file_size_in_byte":5429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"349182880","text":"import torch\nimport torch.nn as nn\nfrom lib.encoder_decoder import *\nfrom models.odenet import OdeNet\n\n\ndef create_LatentODE_model(args, input_dim, z0_prior, obsrv_std, device):\n dim = args.latents # size of latent state\n\n ode_func_net = create_net(dim, args.latents, # 创建odefunc的神经网络\n n_layers=args.gen_layers, n_units=args.units, nonlinear=nn.Tanh)\n gen_ode_func = OdeNet(\n input_dim=input_dim,\n latent_dim=args.latents,\n ode_func=ode_func_net,\n device=device)\n\n n_rec_dims = args.rec_dims # rec_RNN中的hiddenstate大小\n enc_input_dim = input_dim # rec_RNN的输入大小\n gen_data_dim = input_dim # decoder生成的数据特征大小\n\n z0_dim = args.latents # odenet中的潜在变量大小\n\n encoder_z0 = Encoder_z0_RNN(z0_dim, enc_input_dim,\n lstm_output_size=n_rec_dims, device=device)\n\n decoder = Decoder(args.latents, gen_data_dim)\n\n return encoder_z0, gen_ode_func, decoder\n\n\ndef create_net(n_inputs, n_outputs, n_layers=1, n_units=100, nonlinear=nn.Tanh):\n layers = [nn.Linear(n_inputs, n_units)]\n\n for i in range(n_layers):\n layers.append(nonlinear())\n layers.append(nn.Linear(n_units, n_units))\n\n layers.append(nonlinear())\n layers.append(nn.Linear(n_units, n_outputs))\n\n return nn.Sequential(*layers)\n","sub_path":"lib/create_latent_ode_model.py","file_name":"create_latent_ode_model.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"181223928","text":"#!/usr/bin/env python3\n\n'''\nEnsures wordlists are the correct size, and adds the dice lookup numbers.\n'''\n\nimport copy, os, re, sys, traceback\nfrom os import listdir, path\n\nscript_dir = os.path.dirname(os.path.abspath(sys.argv[0]))\n\n\ndef colorize(msg, color, bold=False):\n shell_colors = {\n 'gray': '30',\n 'red': '31',\n 'green': '32',\n 'yellow': '33',\n 'blue': '34',\n 'magenta': '35',\n 'cyan': '36',\n 'white': '37',\n 'crimson': '38',\n 'highlighted_red': '41',\n 'highlighted_green': '42',\n 'highlighted_brown': '43',\n 'highlighted_blue': '44',\n 'highlighted_magenta': '45',\n 'highlighted_cyan': '46',\n 'highlighted_gray': '47',\n 'highlighted_crimson': '48'\n }\n attrs = [shell_colors[color]]\n if bold:\n attrs.append('1')\n return '\\x1b[{}m{}\\x1b[0m'.format(';'.join(attrs), msg)\n\nvalid_regex = re.compile('^[a-z0-9]{1,10}$')\n\n\ndef regex_test(words):\n for word in words:\n if valid_regex.match(word) is None:\n raise Exception(word + ' is invalid')\n\n\ndef check_7776_wordlist(language):\n print('Checking 7776 wordlist for ' + language)\n try:\n with open(path.join(script_dir, 'wordlists', language, 'wordlist.txt'), 'r') as f:\n words = [line.rstrip('\\n') for line in f.readlines()]\n\n assert(len(words) == 7776)\n assert(len(set(words)) == 7776)\n\n regex_test(words)\n\n words_copy = copy.copy(words)\n words.sort()\n assert(words == words_copy)\n\n write_file(words, language)\n\n print(colorize('Success for 7776 list for ' + language, 'green'))\n return True\n except:\n print(colorize('Failure for 7776 list for ' + language, 'red'))\n traceback.print_exc(file=sys.stdout)\n return False\n\n\ndef check_8192_wordlist(language):\n print('Checking 8192 wordlist for ' + language)\n\n file_name = path.join(script_dir, 'wordlists', language, 'wordlist-8192.txt')\n if not os.path.isfile(file_name):\n print(colorize('8192 wordlist not found for ' + language, 'yellow'))\n return True\n\n try:\n with open(file_name, 'r') as f:\n words = [line.rstrip('\\n') for line in f.readlines()]\n\n assert(len(words) == 8192)\n assert(len(set(words)) == 8192)\n\n regex_test(words)\n\n words_copy = copy.copy(words)\n words.sort()\n assert(words == words_copy)\n\n print(colorize('Success for 8192 list for ' + language, 'green'))\n return True\n except:\n print(colorize('Failure for 8192 list for ' + language, 'red'))\n traceback.print_exc(file=sys.stdout)\n return False\n\n\ndef process_lang(language):\n print(colorize('Checking language ' + language, 'white'))\n result_7776 = check_7776_wordlist(language)\n result_8192 = check_8192_wordlist(language)\n return result_7776 and result_8192\n\n\ndef write_file(words, language):\n print(colorize('Writing file for language ' + language, 'white'))\n\n with open(path.join(script_dir, 'wordlists', language, 'wordlist-numbered.txt'), 'w') as f:\n line_num = 0\n for word in words:\n f.write('{num}\\t{word}\\n'.format(num=dice_num(line_num), word=word))\n line_num += 1\n print(colorize('Successfully wrote language ' + language, 'green'))\n\n\ndef baseN(num, b, numerals='0123456789abcdef'):\n return ((num == 0) and numerals[0]) or (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])\n\n\ndef dice_num(num):\n ret = list()\n for char in str(baseN(num, 6)).zfill(5):\n ret.append(chr(ord(char) + 1))\n return ''.join(ret)\n\nif (__name__ == '__main__'):\n print(colorize('Checking wordlists...', 'white', True))\n all_valid = True\n\n for dir in listdir(path.join(script_dir, 'wordlists')):\n is_valid = process_lang(dir)\n all_valid = all_valid and is_valid\n\n if all_valid:\n print(colorize('Success: all files valid and enumerated', 'green', True))\n sys.exit(0)\n else:\n print(colorize('Failure: something bad happened', 'red', True))\n sys.exit(1)\n","sub_path":"enumerate.py","file_name":"enumerate.py","file_ext":"py","file_size_in_byte":4221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"224549510","text":"#!/usr/bin/env python3\n# HW05_ex00_logics.py\n\n\n##############################################################################\ndef even_odd():\n \"\"\" Print even or odd:\n Takes one integer from user\n accepts only non-word numerals\n must validate\n Determines if even or odd\n Prints determination\n returns None\n \"\"\"\n try:\n user_input = int(input('Enter an integer: '))\n if user_input % 2 == 0:\n print('even')\n else:\n print('odd')\n except:\n print('Please try again. Enter an integer.')\n return even_odd()\n\n\ndef ten_by_ten():\n \"\"\" Prints integers 1 through 100 sequentially in a ten by ten grid.\"\"\"\n for row_number in range(0, 10):\n for column_number in range(1, 10):\n number = column_number + (row_number * 10)\n print(\"{:<5}\".format(number), end = \" \")\n print(\"{:<5}\".format(10 + (row_number * 10)))\n\ndef find_average():\n \"\"\" Takes numeric input (non-word numerals) from the user, one number\n at a time. Once the user types 'done', returns the average.\n \"\"\"\n user_input = ''\n sum = 0\n count = 0\n\n while (user_input != 'done'):\n user_input = input('number: ')\n if (user_input == 'done') and (count == 0): # user enters 'done' as first input\n return None \n elif (user_input == 'done') and (count > 0): # user enters done after entering numbers\n return sum / count\n else: # user inputs a number to add to the average\n try:\n sum += float(user_input)\n count += 1\n except: # user enters input other than a number or 'done'\n print('Please type a number.')\n return find_average()\n\n##############################################################################\ndef main():\n \"\"\" Calls the following functions:\n - even_odd()\n - ten_by_ten()\n Prints the following function:\n - find_average()\n \"\"\"\n # even_odd()\n # ten_by_ten()\n find_average()\n\nif __name__ == '__main__':\n main()\n","sub_path":"HW05_ex00_logics.py","file_name":"HW05_ex00_logics.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"399072882","text":"\nfrom app import config\nfrom app import create_app\nfrom contrib import load_data_from_mysql\n\n\napp = create_app()\n\n\nif __name__ == \"__main__\":\n web_config = config.WebConfig\n\n debug = web_config.debug\n host = web_config.host\n port = web_config.port\n threaded = web_config.threaded\n\n app.run(host=host, \n port=port, \n debug=debug, \n threaded=threaded)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"500913144","text":"from urllib.parse import urlencode\n\nfrom django.conf import settings\nfrom django.contrib.auth import REDIRECT_FIELD_NAME\nfrom django.shortcuts import redirect\nfrom django.urls import resolve, reverse\n\n\nclass ProtectAllViewsMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response\n self.anonymous_paths = getattr(\n settings,\n \"AUTHBROKER_ANONYMOUS_PATHS\",\n (),\n )\n self.anonymous_url_names = getattr(\n settings,\n \"AUTHBROKER_ANONYMOUS_URL_NAMES\",\n (),\n )\n\n @staticmethod\n def get_redirect_url(request):\n params = {\n REDIRECT_FIELD_NAME: request.get_full_path(),\n }\n\n querystring = urlencode(params)\n\n redirect_url = reverse(\"authbroker_client:login\")\n\n return redirect(f\"{redirect_url}?{querystring}\")\n\n def __call__(self, request):\n if not request.user.is_authenticated:\n resolved_path = resolve(request.path)\n is_anonymous_path = request.path in self.anonymous_paths\n is_anonymous_url_name = resolved_path.url_name in self.anonymous_url_names\n is_authbroker_client_path = resolved_path.app_name == \"authbroker_client\"\n\n if (\n not is_anonymous_path\n and not is_anonymous_url_name\n and not is_authbroker_client_path\n ):\n return self.get_redirect_url(request)\n\n response = self.get_response(request)\n return response\n","sub_path":"authbroker_client/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"559709699","text":"from cutegirls.booru import *\n\nfrom datetime import datetime\n\nclass Rule34(Booru):\n\tdef __init__(self, **kwargs):\n\t\tsuper().__init__(name=\"Rule34\", url=\"https://rule34.xxx/index.php\", **kwargs)\n\t\n\tdef _rule34_params(self, tags, limit, page):\n\t\tparams = {\n\t\t\t\"page\": \"dapi\",\n\t\t\t\"s\": \"post\",\n\t\t\t\"q\": \"index\",\n\t\t\t\"pid\": str(page),\n\t\t\t\"limit\": str(limit)\n\t\t}\n\t\tif tags:\n\t\t\tparams[\"tags\"] = \"+\".join(tags)\n\t\treturn params\n\t\n\tdef _rule34_datetime(self, date_str):\n\t\treturn datetime.strptime(date_str[4:], \"%b %d %H:%M:%S %z %Y\")\n\t\n\tdef _rule34_add_post(self, post_xml):\n\t\tself._add_post(\n\t\t\tid=int(post_xml.attrib[\"id\"]),\n\t\t\tfile_url=post_xml.attrib[\"file_url\"],\n\t\t\tsample_url=post_xml.attrib[\"sample_url\"],\n\t\t\tpreview_url=post_xml.attrib[\"preview_url\"],\n\t\t\ttags=post_xml.attrib[\"tags\"].split(),\n\t\t\tdate=self._rule34_datetime(post_xml.attrib[\"created_at\"]),\n\t\t\twidth=int(post_xml.attrib[\"width\"]),\n\t\t\theight=int(post_xml.attrib[\"height\"]),\n\t\t\tscore=int(post_xml.attrib[\"score\"]),\n\t\t\trating=post_xml.attrib[\"rating\"],\n\t\t\tmd5=post_xml.attrib[\"md5\"],\n\t\t\tsource=post_xml.attrib[\"source\"]\n\t\t)\n\t\n\tdef _search(self, tags, limit, page):\n\t\tparams = self._rule34_params(tags, limit, page)\n\t\txml = self._dl.get_xml(self.url, params)\n\t\tself._new_results(\n\t\t\ttags=tags,\n\t\t\tpage=page,\n\t\t\tlimit=limit,\n\t\t\ttotal=int(xml.attrib[\"count\"])\n\t\t)\n\t\tfor post_xml in xml:\n\t\t\tself._rule34_add_post(post_xml)\n","sub_path":"cutegirls/boorus/rule34.py","file_name":"rule34.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"646515826","text":"import numpy as np\nimport time\n\n# a\n# comment\n\n# b\nv1 = np.arange(4)\nv1 = v1.reshape(1, 4)\n\n# c\nv2 = np.arange(5)\nv1 = v2.reshape(5, 1)\n\n# d\nX = np.zeros(2, 2)\n\n# e\nA = np.arange(4 * 3)\nA = A.reshape(4, 3)\n\n# f\nB = np.arange(4 * 4)\nB = B.reshape(4, 4)\n\n# d\nB = B.T\n\n# h\nC = np.arange(4)\nC = C.reshape(2, 2)\n\nD = np.eye(2)\n\nE = C * D\n\n# i\nF = np.concatenate((C, D), axis = 0)\nG = np.concatenate((C, D), axis = 1)\n\n# j\nprint(F.size)\n\n# k\nH = np.arange(8 * 7).reshape(8, 7)\nH = H.reshape(14, 4)\n\n# l\nI = np.arange(3).reshape(3, 1)\nI = np.tile(I, 1000)\n\n# m\nJ = np.random.random(5, 5) * 2 - 1\nJ[J < 0] = 0\n\n# n\nJ = np.arange(1, 101, 7)\n\n# o\nk = np.arange(100)\nk[k%2 == 0] = 0\n\n# p\nl = np.arange(100)\nl = l[1::2]\n\n# q\nM = np.random.random((1000, 3))\n\nstart = time.clock()\nM = [v.sum for v in M]\nstop = time.clock()\n\nN = np.random.random((1000, 3))\n\nstart = time.clock()","sub_path":"uebung1.py","file_name":"uebung1.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"486696112","text":"from pymongo import MongoClient\n\nclient = MongoClient(\n \"mongodb+srv://anupamAdmin:anupamAdmin@cluster0.2c2zj.mongodb.net/student_db\")\ndb = client.get_database(\"student_db\")\nrecords = db.get_collection(\"student_records\")\nrecords.count_documents({})\n\n\ndef findBool(number, date):\n flag = 0\n found = records.find({})\n\n for i in found:\n # print(i)\n if(i[\"Enrollment_No\"] == number and i[\"Date\"] == date):\n flag = 1\n break\n else:\n flag = 0\n continue\n\n if flag:\n return True\n return False\n\n\ndef insert(name, number, date, time):\n if findBool(number=number, date=date):\n print(\"Attendance marked\")\n else:\n new_Attendance = {\n \"Enrollment_No\": number,\n \"Name\": name,\n \"Date\": date,\n \"Time\": time\n }\n records.insert_one(new_Attendance)\n print(\"New attendance taken\")\n","sub_path":"desktop-app/mongoPush.py","file_name":"mongoPush.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"548124660","text":"import argparse\nimport logging\n\nimport sys\nfrom collections import defaultdict\nfrom decimal import Decimal\nfrom datetime import datetime\n\nfrom arbitrage import parse_strategy, parse_quote_json\n\n\ndef main(args):\n thresholds = defaultdict(float)\n if args.threshold:\n for threshold in args.threshold:\n currency, amount = threshold.split(':')\n thresholds[currency.upper()] = Decimal(amount)\n\n logging.info('applying thresholds: {}'.format(thresholds))\n if args.strategy:\n strategy = parse_strategy(args.strategy.upper())\n logging.info('starting strategy: {}'.format(strategy))\n if args.replay:\n prices_input = open(args.replay, 'r')\n\n else:\n logging.info('loading prices from standard input')\n prices_input = sys.stdin\n\n for line in prices_input:\n if len(line.strip()) == 0:\n continue\n\n logging.debug('received update: {}'.format(line))\n pair, quote = parse_quote_json(line)\n strategy.update_quote(pair, quote)\n target_trades, target_balances = strategy.find_opportunity(illimited_volume=False)\n if target_balances is None:\n continue\n\n enable_trades = False\n for currency in target_balances:\n if target_balances[currency] > thresholds['currency']:\n enable_trades = True\n break\n\n if enable_trades:\n now = datetime.now()\n print('{}: {}'.format(now, target_trades))\n\n else:\n logging.info('no strategy provided: terminating')\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO, format='%(asctime)s:%(name)s:%(levelname)s:%(message)s', filename='scan-arb.log', filemode='w')\n logging.getLogger('requests').setLevel(logging.WARNING)\n formatter = logging.Formatter('%(asctime)s:%(name)s:%(levelname)s:%(message)s')\n parser = argparse.ArgumentParser(description='Scanning arbitrage opportunities.',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n parser.add_argument('--config', type=str, help='configuration file', default='config.json')\n parser.add_argument('--secrets', type=str, help='configuration with secret connection data', default='secrets.json')\n parser.add_argument('--strategy', type=str, help='strategy as a formatted string (for example: eth/btc,btc/usd,eth/usd')\n parser.add_argument('--replay', type=str, help='use recorded prices')\n parser.add_argument('--threshold', action='append', help='lower profit limit for given currency (ex: \"USD:0.02\")')\n parser.add_argument('--amount', type=str, help='maximum amount for trading expressed in indirect pair 1 quoted currency', default=Decimal(1))\n\n args = parser.parse_args()\n main(args)\n","sub_path":"bf-arb-pylab/scripts/scan-arb.py","file_name":"scan-arb.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"147671959","text":"import fresh_tomatoes\nimport media\n\n\"\"\"The following are instances of the class Movie\"\"\"\navatar = media.Movie(\n \"Avatar\", \"A marine on an alien planet\",\n \"http://upload.wikimedia.org/wikipedia/id/b/b0/\"\n \"Avatar-Teaser-Poster.jpg\",\n \"http://www.youtube.com/watch?v=-9ceBgWV8io\")\n\nsecond_hand_lions = media.Movie(\n \"Second Hand Lions\",\n \"A boy becomes a man\", \"https://upload.wikimedia.\"\n \"org/wikipedia/en/thumb/6/6a\"\n \"/SecondhandLions.jpg/220px-SecondhandLions.jpg\",\n \"https://www.youtube.com/watch?v=hzElnBgsr0s\")\n\nschool_of_rock = media.Movie(\n \"School of Rock\",\n \"Using rock music to learn\",\n \"http://upload.wikimedia.org/wikipedia/en/1/11\"\n \"/School_of_Rock_Poster.jpg\",\n \"http://www.youtube.com/watch?v=3PsUJFEBC74\")\n\nratatouille = media.Movie(\n \"Ratatouille\", \"A rat is chef in Paris\",\n \"http://upload.wikimedia.org/wikipedia/en/5/50/RatatouillePoster.jpg\",\n \"http://www.youtube.com/watch?v=c3sBBRxDAqk\")\n\nhunger_games = media.Movie(\n \"Hunger Games\", \"A really real reality show\",\n \"http://upload.wikimedia.org/wikipedia/en/4/42/HungerGamesPoster.jpg\",\n \"http://www.youtube.com/watch?v=PbA63a7H0bo\")\n\nevan_almighty = media.Movie(\n \"Evan Almighty\", \"A congressman builds an ark\",\n \"https://upload.wikimedia.org/wikipedia/en/1/14/Evan_almightymp1.jpg\",\n \"https://www.youtube.com/watch?v=vtJbcMJLhJss\")\n\nmatrix = media.Movie(\n \"The Matrix\", \"A great sci fi movie\",\n \"https://upload.wikimedia.org/wikipedia/en/c/c1/The_Matrix_Poster.jpg\",\n \"https://www.youtube.com/watch?v=m8e-FF8MsqU\")\n\n\"\"\"The movies variable is an array of my favorite movies\"\"\"\nmovies = [evan_almighty, avatar, second_hand_lions,\n ratatouille, hunger_games, matrix]\n\n\"\"\"The following line opens the web page\"\"\"\nfresh_tomatoes.open_movies_page(movies)\n\n\"\"\"The following lines print out various values of the movies\"\"\"\nprint(media.Movie.VALID_RATINGS)\nprint(media.Movie.__doc__)\nprint(media.Movie.__name__)\nprint(media.Movie.__module__)\n","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"446401188","text":"from .Base import BaseManager\nimport subprocess\n\n\nclass Manager(BaseManager):\n @staticmethod\n def kill_process(pid):\n if type(pid) != int:\n try:\n pid = int(pid)\n except Exception:\n return 'Invalid Pid: ' + str(pid)\n try:\n stdout = subprocess.Popen('Taskkill /PID {id} /F'.format(id=pid), stdout=subprocess.PIPE,\n stderr=subprocess.PIPE).communicate()\n\n return 'Windows.Manager.Kill.Process(out = {0}, error = {1})'.format(\n stdout[0].decode('utf-8'),\n stdout[1].decode('utf-8')).replace('\\n', '')\n except Exception as e:\n return 'Error ' + str(e)\n","sub_path":"process_manager/AllManagers/Windows.py","file_name":"Windows.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"278584538","text":"import sys\nfrom pathlib import Path\nimport inspect\nfrom typing import Generator, Tuple, Union, List\n\n# We have an input tape that lists out the memory in a file\n# We read it in, and turn it into a list of integers\ntape: List[int]\ntape = list(\n map(\n int,\n Path(\"day2_input.txt\").read_text().split(\",\"),\n )\n)\n# This tape is now a representation of our memory\nmemory = tape\n\n# Part of the problem statement described modifying the memory\nmemory[1] = 12\nmemory[2] = 2\n\n# There are various opcodes that perform various operations with the memory\n# So far, there are three major ones, and they are implemented in these functions\ndef op1(arg1: int, arg2: int, out: int) -> None:\n '''opcode 1 -> adds together the values found in memory locations pointed to by\n arg1 and arg2, stores the result in the memory location pointed to by out\n '''\n val1 = memory[arg1]\n val2 = memory[arg2]\n result = val1 + val2\n memory[out] = result\n print(f\"+ {val1: >7} {val2: >7} = {result: >7} -> {out: >7}\")\n\ndef op2(arg1: int, arg2: int, out: int) -> None:\n '''opcode 1 -> multiplies together the values found in memory, using the first two\n arguments as addresses, and stores the result in memory at the adress pointed to\n by the third argument\n '''\n val1 = memory[arg1]\n val2 = memory[arg2]\n result = val1 * val2\n memory[out] = result\n print(f\"* {val1: >7} {val2: >7} = {result: >7} -> {out: >7}\")\n\n# The STOP opcode is simple, and an exception to stop the machine\n# In the problem statement, the memory position 0 holds the answer,\n# so we return that with the Exception\ndef op99() -> None:\n raise StopIteration(f\"STOP: {memory[0]}\")\n\n# All the opcode functions are stored in a table, indexed by their opcode\nopcode_functions = {\n 1: op1,\n 2: op2,\n 99: op99,\n}\n\n# It would be handy to have a table that lists how many parameters an opcode needs to form\n# a full instruction, so we look at each function, count how many parameters it has,\n# and add 1 to get the length of the instruction, and store that in a table indexed\n# by the opcode\ninstruction_lengths = {}\nfor opcode, func in opcode_functions.items():\n number_of_parameters = len(inspect.signature(func).parameters)\n instruction_lengths[opcode] = number_of_parameters + 1\n\n# This is a generator that takes the current value in memory at a position, starting at 0,\n# and returns that opcode along with its arguments from memory.\n# Because it has to grab the arguments for an opcode, it also happens to check if the current\n# address is a valid opcode.\n# Lastly, it increments the instruction pointer by the length of the total instruction\ndef instructions() -> Generator[List[int], None, None]:\n address: int = 0\n\n def gen() -> Generator[List[int], None, None]:\n nonlocal address\n while address + 1 < len(tape):\n opcode = memory[address]\n if not (opcode in instruction_lengths):\n raise ValueError(f\"Bad opcode: {opcode} @ {address}\\n{memory}\")\n instruction_length = instruction_lengths[opcode]\n yield tape[address : (address + instruction_length)]\n address += instruction_length\n\n yield from gen()\n\n# We have a generic function that takes the current instruction as a list of integers,\n# looks up the function for the opcode indicated by the first integer, and passes\n# the rest of the instruction as arguments to that function.\n# It also returns the value of the function, unless it's an Exception, in which case\n# it prints the error message of that Exception, and stops the program\ndef op(instruction: List[int]) -> None:\n opcode = instruction[0]\n instruction_parameters = instruction[1:]\n function = opcode_functions[opcode]\n try:\n result = function(*instruction_parameters)\n except StopIteration as err:\n print(*err.args)\n raise SystemExit()\n else:\n return result\n\n# Lastly, we loop through all the instructions, and pass them to op\nfor instruction in instructions():\n op(instruction)\n","sub_path":"day2.py","file_name":"day2.py","file_ext":"py","file_size_in_byte":4065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"58963746","text":"from app.model.modelImport import *\n\nclass Analisis(db.Model):\n __tablename__ ='analisis'\n codAnalisis = db.Column('cod_analisis',Integer, primary_key = True, index = True)\n fchAnalisis = db.Column ('fch_analisis', DateTime, default = datetime.datetime.now, index = True)\n\n codTipoAnalisis = db.Column('fk_cod_tipo_analisis', Integer, ForeignKey('tipo_analisis.cod_tipo_analisis'), nullable=False)\n codUsuario = db.Column('fk_cod_usuario', Integer, ForeignKey('usuario.cod_usuario_private'), nullable = False)\n codGrupoCuadro = db.Column('fk_cod_grupo_cuadro', Integer, ForeignKey('grupo_cuadro.cod_grupo_cuadro'), nullable = True)\n #fk nullables\n codRecomDetalle = db.Column('fk_cod_recom_detalle', Integer, ForeignKey('recomendacion_detalle.cod_recom_detalle'), nullable = True) #recomendación\n\n #agregar planicifación y/o grupo cuadro\n\n\n tipoAnalisis = relationship(\"TipoAnalisis\", backref = 'analisisList')\n \n paramList = relationship('AnalisisParam', backref = 'analisis')\n\n usuario = relationship('Usuario')","sub_path":"services/app/model/analisis.py","file_name":"analisis.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"196923676","text":"from AC_brain import AC\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom functions import *\r\nimport sys\r\nimport matplotlib.pyplot as plt\r\n\r\nstock_key, windows_size, e_num = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])\r\ndata = getStockDataVec(stock_key)\r\nRL = AC(lr=0.00001, gamma=0.97, state_size=windows_size)\r\nstart_time = windows_size\r\n\r\nfor i in range(e_num):\r\n total_profit = 0\r\n # for each episode, we need to run the entire episode and record everything\r\n for t in range(start_time,len(data)-1):\r\n s = get_state(data, windows_size, t)\r\n sp = get_state(data, windows_size, t+1)\r\n action = RL.act(s)\r\n reward = 0\r\n if action == 1 and t<len(data)-1: # buy\r\n RL.buyrecord.append(data[t])\r\n #reward = -data[t]\r\n elif action == 2 and len(RL.buyrecord) > 0 and t<len(data)-1: # sell\r\n bought_price = RL.buyrecord.pop(0)\r\n reward = data[t] - bought_price\r\n total_profit += data[t] - bought_price\r\n RL.learn(s, action, reward, sp)\r\n elif t==len(data)-1:\r\n print('End time and totoal profit is ', total_profit)\r\n\r\n\r\ntime = [i for i in range(len(data))]\r\nbuy_time = [i for i in range(start_time,len(data))]\r\nsell_time = [i for i in range(start_time,len(data))]\r\nagent_action = []\r\nfor t in range(start_time,len(data)):\r\n s = get_state(data, windows_size, t)\r\n temp_action = RL.act(s)\r\n agent_action.append(temp_action)\r\nbuy_action = data[start_time:].copy()\r\nsell_action = data[start_time:].copy()\r\nfor i in range(len(buy_action)):\r\n if agent_action[i] != 1:\r\n buy_action[i] = 0\r\n if agent_action[i] !=2:\r\n sell_action[i] = 0\r\n\r\n\r\n\r\nplt.plot(time, data, 'b-', label = 'price')\r\nplt.plot(buy_time,buy_action,'ro',label = 'buy')\r\nplt.plot(sell_time,sell_action,'k^',label = 'sell')\r\nplt.legend()\r\nplt.show()","sub_path":"run_this_AC.py","file_name":"run_this_AC.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"101452654","text":"\n\nfrom xai.brain.wordbase.adjectives._motley import _MOTLEY\n\n#calss header\nclass _MOTLEYS(_MOTLEY, ):\n\tdef __init__(self,): \n\t\t_MOTLEY.__init__(self)\n\t\tself.name = \"MOTLEYS\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"motley\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_motleys.py","file_name":"_motleys.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"84053342","text":"from decimal import Decimal\n\nfrom django.conf import settings\n\nfrom carton import module_loading\nfrom carton import settings as carton_settings\n\n\nclass CartItem(object):\n \"\"\"\n A cart item, with the associated product, its quantity and its price.\n \"\"\"\n def __init__(self, product, options, quantity, note):\n self.product = product\n self.options = options\n self.quantity = int(quantity)\n self.note = str(note)\n\n def __repr__(self):\n return u'CartItem Object (%s)' % self.product\n\n def to_dict(self):\n return {\n 'product_pk': self.product.pk,\n 'option_pks': [i.pk for i in self.options],\n 'quantity': self.quantity,\n 'note': self.note\n }\n\n @property\n def subtotal(self):\n \"\"\"\n Subtotal for the cart item.\n \"\"\"\n return (self.product.price + sum([i.price for i in self.options])) * self.quantity\n\n\nclass Cart(object):\n\n \"\"\"\n A cart that lives in the session.\n \"\"\"\n def __init__(self, session, session_key=None):\n self._items_list = []\n self.session = session\n self.session_key = session_key or carton_settings.CART_SESSION_KEY\n # If a cart representation was previously stored in session, then we\n if self.session_key in self.session:\n # rebuild the cart object from that serialized representation.\n cart_representation = self.session[self.session_key]\n products_cache = {}\n options_cache = {}\n for item in cart_representation:\n try:\n product = None\n if item['product_pk'] in products_cache:\n product = products_cache[item['product_pk']]\n else:\n product = self.get_product_queryset().get(pk=item['product_pk'])\n products_cache[item['product_pk']] = product\n\n options = []\n for option_pk in item['option_pks']:\n if option_pk in options_cache:\n options.append(options_cache[option_pk])\n else:\n option = self.get_option_queryset().get(pk=option_pk)\n options.append(option)\n options_cache[option_pk] = option\n self._items_list.append(CartItem(\n product, options, item['quantity'], item['note']\n ))\n except Exception as e:\n print(e)\n\n def __contains__(self, product, options=[]):\n \"\"\"\n Checks if the given product is in the cart.\n \"\"\"\n return self.__index__(product, options) != -1\n\n def __index__(self, product, options=[]):\n \"\"\"\n Return the index of the product with options in _items_list. Return -1 if not found.\n \"\"\"\n cart_items = self.cart_serializable\n for i in range(len(cart_items)):\n if cart_items[i]['product_pk'] == product.pk:\n if sorted(cart_items[i]['option_pks']) == sorted([i.pk for i in options]):\n return i\n return -1\n\n def get_product_model(self):\n return module_loading.get_product_model()\n\n def get_option_model(self):\n return module_loading.get_option_model()\n\n def filter_products(self, queryset):\n \"\"\"\n Applies lookup parameters defined in settings.\n \"\"\"\n lookup_parameters = getattr(settings, 'CART_PRODUCT_LOOKUP', None)\n if lookup_parameters:\n queryset = queryset.filter(**lookup_parameters)\n return queryset\n\n def filter_options(self, queryset):\n \"\"\"\n Applies lookup parameters defined in settings.\n \"\"\"\n lookup_parameters = getattr(settings, 'CART_OPTION_LOOKUP', None)\n if lookup_parameters:\n queryset = queryset.filter(**lookup_parameters)\n return queryset\n\n def get_product_queryset(self):\n product_model = self.get_product_model()\n queryset = product_model._default_manager.all()\n queryset = self.filter_products(queryset)\n return queryset\n\n def get_option_queryset(self):\n option_model = self.get_option_model()\n queryset = option_model._default_manager.all()\n queryset = self.filter_options(queryset)\n return queryset\n\n def update_session(self):\n \"\"\"\n Serializes the cart data, saves it to session and marks session as modified.\n \"\"\"\n self.session[self.session_key] = self.cart_serializable\n self.session.modified = True\n\n def add(self, product, options=[], quantity=1, note=''):\n \"\"\"\n Adds or creates products in cart. For an existing product,\n the quantity is increased and the price is ignored.\n \"\"\"\n quantity = int(quantity)\n if quantity < 1:\n raise ValueError('Quantity must be at least 1 when adding to cart')\n item_index = self.__index__(product, options)\n if item_index != -1:\n self._items_list[item_index].quantity += quantity\n if note != '':\n self._items_list[item_index].note += note\n else:\n self._items_list.append(CartItem(product, options, quantity, note))\n self.update_session()\n\n def remove(self, product, options=[]):\n \"\"\"\n Removes the product.\n \"\"\"\n item_index = self.__index__(product, options)\n if item_index != -1:\n del self._items_list[item_index]\n self.update_session()\n\n def remove_single(self, product, options=[]):\n \"\"\"\n Removes a single product by decreasing the quantity.\n \"\"\"\n item_index = self.__index__(product, options)\n if item_index != -1:\n if self._items_list[item_index].quantity <= 1:\n del self._items_list[item_index]\n else:\n self._items_list[item_index].quantity -= 1\n self.update_session()\n\n def clear(self):\n \"\"\"\n Removes all items.\n \"\"\"\n self._items_list = []\n self.update_session()\n\n def set_quantity(self, product, quantity, options=[]):\n \"\"\"\n Sets the product's quantity.\n \"\"\"\n quantity = int(quantity)\n if quantity < 0:\n raise ValueError('Quantity must be positive when updating cart')\n item_index = self.__index__(product, options)\n if item_index != -1:\n self._items_list[item_index].quantity = quantity\n if self._items_list[item_index].quantity < 1:\n del self._items_list[item_index]\n self.update_session()\n\n def set_note(self, product, note, options=[]):\n \"\"\"\n Sets the product's note.\n \"\"\"\n note = str(note)\n item_index = self.__index__(product, options)\n if item_index != -1:\n self._items_list[item_index].note = note\n self.update_session()\n\n @property\n def items(self):\n \"\"\"\n The list of cart items.\n \"\"\"\n return self._items_list\n\n @property\n def cart_serializable(self):\n \"\"\"\n The serializable representation of the cart.\n \"\"\"\n return [item.to_dict() for item in self.items]\n\n\n # @property\n # def items_serializable(self):\n # \"\"\"\n # The list of items formatted for serialization.\n # \"\"\"\n # return self.cart_serializable.items()\n\n @property\n def count(self):\n \"\"\"\n The number of items in cart, that's the sum of quantities.\n \"\"\"\n return sum([item.quantity for item in self.items])\n\n @property\n def unique_count(self):\n \"\"\"\n The number of unique items in cart, regardless of the quantity.\n \"\"\"\n return len(self._items_list)\n\n @property\n def is_empty(self):\n return self.unique_count == 0\n\n @property\n def products(self):\n \"\"\"\n The list of associated products.\n \"\"\"\n return list(set([item.product for item in self.items]))\n\n @property\n def total(self):\n \"\"\"\n The total value of all items in the cart.\n \"\"\"\n return sum([item.subtotal for item in self.items])\n","sub_path":"carton/cart.py","file_name":"cart.py","file_ext":"py","file_size_in_byte":8326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"461236252","text":"# Copyright (c) 2016, The University of Texas at Austin & University of\n# California, Merced.\n#\n# All Rights reserved.\n# See file COPYRIGHT for details.\n#\n# This file is part of the hIPPYlib library. For more information and source code\n# availability see https://hippylib.github.io.\n#\n# hIPPYlib is free software; you can redistribute it and/or modify it under the\n# terms of the GNU General Public License (as published by the Free\n# Software Foundation) version 3.0 dated June 2007.\n\nimport dolfin as dl\nimport sys\nsys.path.append( \"../../\" )\nfrom hippylib import *\nimport numpy as np\n\nnx = 32\nny = 32\nmesh = dl.UnitSquareMesh(nx, ny)\nVh = dl.FunctionSpace(mesh, 'Lagrange', 1)\nPrior = LaplacianPrior(Vh, 1.,100.)\n\nnsamples = 1000\n\ns = dl.Function(Vh, name = \"sample\")\nnoise = dl.Vector()\nPrior.init_vector(noise,\"noise\")\nsize = len(noise.array())\n\nfid = dl.File(\"results_cg/samples.pvd\")\n\nfor i in range(0, nsamples ):\n noise.set_local( np.random.randn( size ) )\n Prior.sample(noise, s.vector())\n fid << s\n\n\n","sub_path":"RANS/dimension-reduced-geom-infmcmc/hippylib/unit_test/CGsampler.py","file_name":"CGsampler.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"570825839","text":"'''\nGrading actions that can be configured for asynchronous grading tasks.\n\nFunctions take arguments:\n\n @type course: C{dict}\n @param course: course configuration dictionary\n @type exercise: C{dict}\n @param exercise: exercise configuration dictionary\n @type action: C{dict}\n @param action: action configuration dictionary\n @type submission_dir: C{str}\n @param submission_dir: a submission directory where submitted files are stored\n @rtype: C{dict}\n @return: points = granted points, max_points = maximum points,\n out = standard out, err = standard error,\n stop = True to stop further actions, appendix = appendix output\n'''\nfrom django.conf import settings\nfrom django.template import loader, Context, Template\nfrom django.shortcuts import render\n\nfrom access.config import ConfigError\nfrom util.shell import invoke_script, invoke_sandbox\nfrom util.xslt import transform\nfrom util.http import get_json\nimport logging\n\nLOGGER = logging.getLogger('main')\n\n\ndef prepare(course, exercise, action, submission_dir):\n '''\n Runs the preparation script for the submitted files.\n '''\n return _boolean(invoke_script(settings.PREPARE_SCRIPT,\n _collect_args((\"attachment_pull\", \"attachment_unzip\", \"unzip\",\n \"charset\", \"cp_exercises\", \"cp\", \"mv\"), action,\n { \"course_key\": course[\"key\"] }),\n submission_dir))\n\n\ndef gitclone(course, exercise, action, submission_dir):\n '''\n Runs a git clone script.\n '''\n return _appendix(_boolean(invoke_script(settings.GITCLONE_SCRIPT,\n _collect_args((\"repo_dir\", \"read\", \"files\"), action), submission_dir)))\n\n\ndef sandbox(course, exercise, action, submission_dir):\n '''\n Executes sandbox script and looks for TotalPoints line in the result.\n '''\n return _find_point_lines(invoke_sandbox(course[\"key\"], action,\n submission_dir))\n\n\ndef sandbox_python_test(course, exercise, action, submission_dir):\n '''\n Executes sandbox script and looks for succesful python test. Test may print\n out TotalPoints and MaxPoints lines at end.\n '''\n r = sandbox(course, exercise, action, submission_dir)\n return { \"points\": r[\"points\"], \"max_points\": r[\"max_points\"],\n \"out\": r[\"err\"], \"err\": \"\", \"stop\": r[\"stop\"] }\n\n\ndef diffbox(course, exercise, action, submission_dir):\n return johoh(course, exercise, action, submission_dir)\n\n\ndef johoh(course, exercise, action, submission_dir):\n '''\n Executes sandbox script and looks for TotalPoints line in the result. The same\n as sandbox but as sandbox but style feedback based on expected and real blocks\n '''\n res = _find_point_lines(invoke_sandbox(course[\"key\"], action,\n submission_dir))\n\n structured = _parse_difftests(res['out'])\n\n print(structured)\n\n # TODO use template_to_str for enabling user defined templates\n tmpl = loader.get_template(\"access/diff_block.html\")\n html = tmpl.render(Context({\"results\": structured}))\n # Make unicode results ascii.\n out = (Template(\"<pre style='display:none;'>{{out}}</pre>\").render(Context({\"out\": res['out']})) + html).encode(\"ascii\", \"xmlcharrefreplace\")\n\n res['out'] = out\n res['html'] = True\n\n return res\n\n\ndef expaca(course, exercise, action, submission_dir):\n '''\n Executes third party expaca testing application.\n '''\n r = invoke_script(settings.EXPACA_SCRIPT,\n _collect_args((\"rule_file\", \"model_dir\", \"user_dir\"), action),\n submission_dir)\n\n # Expaca should always return 0.\n if r[\"code\"] != 0:\n raise ConfigError(\"Expaca return code not zero!\\nMore information: %s\"\n % (str(r)))\n out = r[\"out\"]\n points = 0\n max_points = 0\n\n # Find points in the XML.\n b = out.find(\"<TotalPoints>\")\n if b >= 0:\n e = out.find(\"</TotalPoints>\", b + 13)\n points = int(out[b + 13 : e])\n b = out.find(\"<TotalMaxpoints>\")\n if b >= 0:\n e = out.find(\"</TotalMaxpoints>\", b + 16)\n max_points = int(out[b + 16 : e])\n\n # Transform the feedback if configured.\n if \"xslt_transform\" in action:\n out = transform(out, \"%s/%s\" % (settings.BASE_DIR,\n action[\"xslt_transform\"]))\n\n return { \"points\": points, \"max_points\": max_points, \"out\": out,\n \"err\": r[\"err\"], \"stop\": False }\n\n\ndef timeout(course, exercise, action, submission_dir):\n '''\n FOR DEBUG: Sleeps for a long time to test grading time out.\n '''\n import time\n print(\"stdasync.timeoutAction: Sleeping and blocking queue for testing purposes.\")\n time.sleep(15 * 60)\n return { \"points\": 10, \"out\": \"Did not reach timeout, should not happen.\", \"err\": \"\", \"stop\": True }\n\n\ndef gitlabquery(course, exercise, action, submission_dir):\n '''\n Queries gitlab API to check repository properties.\n '''\n if not \"require_gitlab\" in exercise:\n raise ConfigError(\"This action needs require_gitlab in exercise.\")\n if not \"token\" in action:\n raise ConfigError(\"Token missing from configuration for gitlab privacy check.\")\n url = None\n err = \"\"\n try:\n with open(submission_dir + \"/user/gitsource\") as content:\n source = content.read()\n try:\n from urllib.parse import quote_plus\n except ImportError:\n from urllib import quote_plus\n rid = quote_plus(source[source.index(\":\") + 1:])\n url = \"https://%s/api/v3/projects/%s?private_token=%s\" % (exercise[\"require_gitlab\"], rid, action[\"token\"])\n data = get_json(url)\n if \"private\" in action and action[\"private\"] and data[\"public\"]:\n err = \"%s has public access in settings! Remove it to grade exercises.\" % (data[\"web_url\"])\n if \"forks\" in action:\n if not \"forked_from_project\" in data or \\\n data[\"forked_from_project\"][\"path_with_namespace\"] != action[\"forks\"]:\n err = \"%s is not forked from %s.\" % (data[\"web_url\"], action[\"forks\"])\n except Exception:\n LOGGER.exception(\"Failed to check gitlab URL: %s\", url)\n return { \"points\": 0, \"max_points\": 0, \"out\": \"\", \"err\": err, \"stop\": err != \"\" }\n\n\ndef _collect_args(arg_names, action, args={}):\n '''\n Collects argument map for names in action.\n '''\n for name in arg_names:\n if name in action:\n args[name] = action[name]\n return args\n\n\ndef _boolean(result):\n '''\n Plain return code check for continuing actions.\n '''\n return { \"points\": 0, \"max_points\": 0, \"out\": result[\"out\"],\n \"err\": result[\"err\"], \"stop\": result[\"code\"] != 0 }\n\ndef _parse_difftests(output):\n # the list of all test resutls\n tests = []\n\n # expected and actual output can be interleaved if all lines are prefixed so this is\n # why we use multiple variables to build the properties of a test result\n description = []\n expected = []\n actual = []\n\n section = 'actual' #Assume that output is student output if nothing is defined\n for l in output.split(\"\\n\"):\n try:\n if l.startswith(\"Testcase:\"):\n if len(description) > 0 and len(expected) > 0 and len(actual) > 0: #commit this and start new test item\n tests.append({'description': \"\\n\".join(description),\n 'expected': \"\\n\".join(expected),\n 'actual': \"\\n\".join(actual),\n 'fail': expected != actual})\n description = []\n expected = []\n actual = []\n # in any case, add the description\n description.append(l[10:])\n section = 'description'\n elif l.startswith(\"Expected:\"):\n expected.append(l[10:])\n section = 'expected'\n elif l.startswith(\"Actual:\"):\n actual.append(l[8:])\n section = 'actual'\n else:\n if section == 'description':\n description.append(l)\n elif section == 'expected':\n expected.append(l)\n elif section == 'actual':\n actual.append(l)\n\n except Exception as e:\n pass\n tests.append({'description': \"\\n\".join(description),\n 'expected': \"\\n\".join(expected),\n 'actual': \"\\n\".join(actual),\n 'fail': expected != actual})\n return tests\n\n\n\ndef _find_point_lines(result):\n '''\n Looks for TotalPoints and/or MaxPoints line in the result.\n '''\n lines = []\n points = 0\n max_points = 0\n\n # Try to find the point lines.\n for l in result[\"out\"].split(\"\\n\"):\n try:\n if l.startswith(\"TotalPoints: \"):\n points = int(l[13:])\n elif l.startswith(\"MaxPoints: \"):\n max_points = int(l[11:])\n else:\n lines.append(l)\n except ValueError:\n pass\n\n return { \"points\": points, \"max_points\": max_points,\n \"out\": \"\\n\".join(lines), \"err\": result[\"err\"],\n \"stop\": result[\"code\"] != 0 }\n\n\ndef _appendix(result):\n '''\n Looks for appendix section in output.\n '''\n out = []\n appendix = []\n in_appendix = False\n for l in result[\"out\"].split(\"\\n\"):\n if l == \"***APPENDIX***\":\n in_appendix = True\n elif in_appendix:\n appendix.append(l)\n else:\n out.append(l)\n result[\"out\"] = \"\\n\".join(out)\n result[\"appendix\"] = \"\\n\".join(appendix)\n return result\n","sub_path":"grader/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":9530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"87023141","text":"#!/usr/bin/env python\n\nimport rospy\nimport numpy as np\nimport math\nfrom geometry_msgs.msg import Twist, Vector3\n\nforward_velocity = .5 # m/sec\nrotate_velocity = math.pi # rad/sec\n\ndef robotDoLoop():\n pub = rospy.Publisher('/cmd_vel', Twist, queue_size=10)\n rospy.init_node('robotDoLoop', anonymous=True)\n\n do_nothing = Twist();\n do_nothing.linear = Vector3(0, 0, 0)\n do_nothing.angular = Vector3(0, 0, 0)\n\n go_forward = Twist();\n go_forward.linear = Vector3(forward_velocity, 0, 0)\n go_forward.angular = Vector3(0, 0, 0)\n\n do_rotation = Twist()\n do_rotation.linear = Vector3(0, 0, 0)\n do_rotation.angular = Vector3(0, 0, rotate_velocity)\n\n cmds = [do_nothing, go_forward, do_nothing, do_rotation]*4 + [do_nothing]\n cmd_step = 0\n sleep_times = {do_nothing: 0.5, go_forward: 2.0, do_rotation: 0.5}\n\n # Wait 5 seconds, then run the loop\n rospy.sleep(5)\n\n while not rospy.is_shutdown() and cmd_step < len(cmds):\n cmd = cmds[cmd_step]\n sleep_time = sleep_times[cmd]\n # rospy.loginfo(cmd, sleep_time)\n pub.publish(cmd)\n rospy.sleep(sleep_time)\n cmd_step += 1\n\nif __name__ == '__main__':\n try:\n robotDoLoop()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"nodes/robotDoLoop.py","file_name":"robotDoLoop.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"431600826","text":"import numpy as np\nimport time\nimport os\nimport torch\nimport _pickle as cPickle\nfrom src.RL import RL\nfrom src.toric_model import Toric_code\n\nfrom NN import NN_11, NN_17\nfrom ResNet import ResNet18, ResNet34, ResNet50, ResNet101, ResNet152\n\n##########################################################################\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# valid network names: \n# NN_11\n# NN_17\n# ResNet18\n# ResNet34\n# ResNet50\n# ResNet101\n# ResNet152\nNETWORK = NN_17\n\n# common system sizes are 3,5,7 and 9 \n# grid size must be odd! \nSYSTEM_SIZE = 5\n\n# For continuing the training of an agent\ncontinue_training = False\n# this file is stored in the network folder and contains the trained agent. \nNETWORK_FILE_NAME = 'Test1_NN17_Size_5'\n\n# initialize RL class and training parameters \nrl = RL(Network=NETWORK,\n Network_name=NETWORK_FILE_NAME,\n system_size=SYSTEM_SIZE,\n p_error=0.1,\n replay_memory_capacity=20000, \n learning_rate=0.00025,\n discount_factor=0.95,\n max_nbr_actions_per_episode=10, # [50], max steps allowed during training\n device=device,\n replay_memory='proportional') # proportional \n # uniform\n\n\n# generate folder structure \ntimestamp = time.strftime(\"%y_%m_%d__%H_%M_%S__\")\nPATH = 'data/training__' +str(NETWORK_FILE_NAME) +'_'+str(SYSTEM_SIZE)+'__' + timestamp\nPATH_epoch = PATH + '/network_epoch'\nif not os.path.exists(PATH):\n os.makedirs(PATH)\n os.makedirs(PATH_epoch)\n\n# load the network for continue training \nif continue_training == True:\n print('continue training')\n PATH2 = 'network/'+str(NETWORK_FILE_NAME)+'.pt'\n rl.load_network(PATH2)\n\n# train for n epochs the agent (test parameters)\nrl.train_for_n_epochs(training_steps=5000, # [-], number of episodes per epoch\n num_of_predictions=100, # [100], number of predicions when evaluating\n num_of_steps_prediction=10, # [50], number of allowed steps when evaluating\n epochs=20, # [-], \"epochs\", how many times to do training_steps episodes\n target_update=100, # [100], how often to update target net\n optimizer='Adam', # ['Adam'], 'Adam' or 'RMSprop'\n batch_size=32, # [32], how many episodes to batch together (during training?)\n directory_path = PATH, # where to save\n prediction_list_p_error=[0.06,0.10,0.14], # [[0.1]], list of p_error to use when evaluating\n replay_start_size=32) # [32] \n\n\n\"\"\" rl.train_for_n_epochs(training_steps=10000,\n num_of_predictions=100,\n epochs=100,\n target_update=1000,\n optimizer='Adam',\n batch_size=32,\n directory_path = PATH,\n prediction_list_p_error=[0.1],\n minimum_nbr_of_qubit_errors=0) \"\"\"\n \n","sub_path":"train_script.py","file_name":"train_script.py","file_ext":"py","file_size_in_byte":3083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"424468814","text":"import os, time, shutil\r\nfrom tkinter import *\r\nimport tkinter as tk\r\nfrom tkinter import messagebox\r\nfrom tkinter.filedialog import askdirectory\r\nimport sqlite3\r\n\r\nimport drillp123_phonebook_main\r\nimport drillp123_phonebook_gui\r\n\r\ndef center_window(self, w, h): # pass in the tkinter frame (master) reference and the w and h\r\n screen_width = self.master.winfo_screenwidth()\r\n screen_height = self.master.winfo_screenheight()\r\n x = int((screen_width/2) - (w/2))\r\n y = int((screen_height/2) - (h/2))\r\n centerGeo = self.master.geometry('{}x{}+{}+{}'.format(w, h, x, y))\r\n return centerGeo\r\n\r\ndef ask_quit(self):\r\n if messagebox.askokcancel(\"Exit program\", \"Okay to exit application?\"):\r\n self.master.destroy()\r\n os._exit(0)\r\n\r\ndef create_db(self):\r\n\tconn = sqlite3.connect('db_phonebook.db')\r\n\twith conn:\r\n\t\tcur = conn.cursor()\r\n\t\tcur.execute(\"CREATE TABLE if not exists tbl_phonebook( \\\r\n\t\t\tID INTEGER PRIMARY KEY AUTOINCREMENT, \\\r\n\t\t\tcol_fname TEXT, \\\r\n\t\t\tcol_dirname TEXT, \\\r\n\t\t\tcol_mtime TEXT \\\r\n\t\t\t);\")\r\n\t\tconn.commit()\r\n\tconn.close()\r\n\tfirst_run(self)\r\n\r\ndef first_run(self):\r\n\t# Get source directory from text field in dialog box\r\n\tdst_file_path = self.txt_destDir.get()\r\n\tdstName = os.listdir(dst_file_path)\r\n # Populate dB\r\n\tconn = sqlite3.connect('db_phonebook.db')\r\n\twith conn:\r\n\t\tcur = conn.cursor()\r\n\t\t# Add data, print to shell\r\n\t\tfor file in dstName:\r\n\t\t\tcur.execute(\"\"\"INSERT INTO tbl_phonebook (col_fname,col_dirname,col_mtime) VALUES (?,?,?)\"\"\", (file,dst_file_path,(os.path.getmtime(file))))\r\n\t\t\tconn.commit()\r\n\t\t\tprint(\"File, mtime: {} {}\".format(col_fname,col_mtime))\r\n\t\tconn.close()\r\n\r\ndef onSelectSource(self):\r\n\tsrc_file_path = askdirectory()\r\n\tself.txt_sourceDir.insert(0,src_file_path)\r\n\t\r\ndef onSelectDest(self):\r\n\tdst_file_path = askdirectory()\r\n\tself.txt_destDir.insert(0,dst_file_path)\r\n\t\r\ndef onSelectText(self):\r\n\t# Get directories from text fields in dialog box\r\n\tsrc_file_path = self.txt_sourceDir.get()\r\n\tdst_file_path = self.txt_destDir.get()\r\n\tsrcName = os.listdir(src_file_path)\r\n\tdstName = os.listdir(dst_file_path)\r\n\t# Move text files from source to destination, print names to shell\r\n\tfor file in srcName:\r\n\t\tif file.endswith(\".txt\"):\r\n\t\t\tfullpath = os.path.join(src_file_path, file)\r\n\t\t\tshutil.move(fullpath,dst_file_path)\r\n\t\t\tprint(\"Moved text file: {}\".format(file))\r\n\t\t\t\r\n\tcreate_db(self)\r\n\t\r\nif __name__ == \"__main__\":\r\n pass\r\n","sub_path":"Python-Course/old-files/drillp123_phonebook_func.py","file_name":"drillp123_phonebook_func.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"9582212","text":"__author__ = 'dchakraborty'\n\n\nimport sys, os, glob, shutil\nfrom pymatgen.analysis.defects.core import Vacancy, Substitution, Interstitial\nfrom pymatgen.analysis.defects.generators import VacancyGenerator, SubstitutionGenerator, \\\n SimpleChargeGenerator,VoronoiInterstitialGenerator\nfrom pymatgen.io.vasp import Poscar\nfrom pymatgen.ext.matproj import MPRester\nfrom pymatgen.core import PeriodicSite\nfrom pymatgen.core import periodic_table\nfrom string import digits\n\n\nbasepath=os.getcwd()\nprint(basepath)\n\n#remove previous directories\nfor i in os.listdir():\n\tif os.path.isdir(i): shutil.rmtree(i) \n\n#sub_element_list=['H', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl']\n\n\n'''Generate undefected files'''\n\nwith MPRester() as mp:\n\tids = mp.get_all_substrates()\n\tprint(ids)\n\tstructures=[]\n\tfor i in ids:\n\n#Creating directories with mp-ids\n\n\t\tstr_file=os.path.join(os.path.join(basepath,'%s')%(i))\n\t\tstr_file_exists=os.path.exists(str_file)\n\t\tif not str_file_exists: os.mkdir(str_file)\n\t\tos.chdir(str_file)\n\n#Creating bulk_str files with the structure_formula\n\n\t\tno_defect_data = open('undefected_data.dat','w')\t\t\t\t\n\t\tbulk_structure = mp.get_structure_by_material_id(i) \n\t\tno_defect_data.writelines(str(bulk_structure))\n\t\tno_defect_data.close()\n\n\n#Finding elements and formula of the structure \n\n\t\telements=[]\n\t\ttot_elem=len(bulk_structure.types_of_specie)\n\t\tfor ele in range(tot_elem):\n\t\t\telements.append(str(bulk_structure.types_of_specie[ele]).split()[-1])\n\t\tprint(elements)\n\n\t\n#\t\tfor ele in elements[:]:\n#\t\t\tif ele in sub_element_list:\n#\t\t\t\tprint(ele)\n#\t\t\t\tsub_element_list.remove(ele)\n#\t\tprint(sub_element_list)\n\n\n\t\tcount=0\t\t\n\t\twith open('undefected_data.dat') as file:\n\t\t\tfor line in file:\n\t\t\t\tcount += 1\n\t\t\t\tif count == 2 : str_formula=line.split()[2]\n\t\tprint(str(str_formula))\n\t\tos.rename('undefected_data.dat','%s'%(str_formula))\n\t\tstructures.append(str(str_formula))\n\n\n#Creating vacacies with the bulk structure formula\n\n\t\tdefects_to_run=[]\n\t\tprint('Vacancy Generator:')\n\t\tfor vac_defect in VacancyGenerator( bulk_structure):\n\t\t\tprint(\"\\tCreated Defect {} at site {}\".format( vac_defect.name, vac_defect.site))\n\t\t\tfor charged_defect in SimpleChargeGenerator( vac_defect):\n\t\t\t\tprint(\"\\tcreated defect with charge {}\".format( charged_defect.charge))\n\t\t\t\tdefects_to_run.append( charged_defect.copy())\n\t\t\t\tcharged_vac_data= open('%s-chg(%s).dat'%(vac_defect.name,charged_defect.charge),'w')\n\t\t\t\tcharged_defect_str=charged_defect.generate_defect_structure( supercell=(2, 1, 1))\n\t\t\t\tcharged_vac_data.writelines(str(charged_defect_str))\n\t\t\t\tcharged_vac_data.close()\n\t\t\t\t#print(charged_defect.generate_defect_structure( supercell=(2, 1, 1)))\n\n\n#Generating substitutions and antisites with the bulk structure formula\n\n\t\tdefects_to_run=[]\n\t\tprint('Substitution Generator:')\n\t\tsub_element_list=['H', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl']\n\t\tfor ele in elements[:]:\n\t\t\tif ele in sub_element_list:\n\t\t\t\tprint(ele)\n\t\t\t\tsub_element_list.remove(ele)\n\t\tprint(sub_element_list)\n\n\t\tfor element in sub_element_list:\n\t\t\tfor sub_defect in SubstitutionGenerator( bulk_structure, element):\n\t\t\t\tprint(\"\\tCreated Defect {} at site {}\".format( sub_defect.name, sub_defect.site))\n\t\t\t\tfor charged_defect in SimpleChargeGenerator( sub_defect):\n\t\t\t\t\tprint(\"\\tcreated defect with charge {}\".format( charged_defect.charge))\n\t\t\t\t\tdefects_to_run.append( charged_defect.copy())\n\t\t\t\t\tcharged_sub_data= open('%s-chg(%s).dat'%(sub_defect.name,charged_defect.charge),'w')\n\t\t\t\t\tcharged_defect_str=charged_defect.generate_defect_structure( supercell=(2, 1, 1))\n\t\t\t\t\tcharged_sub_data.writelines(str(charged_defect_str))\n\t\t\t\t\tcharged_sub_data.close()\n\t\t\t\t\t#print(charged_defect.generate_defect_structure( supercell=(2, 1, 1)))\n\n\n\t\tdefects_to_run=[]\n\t\tprint('Antisite Generator:')\n\t\tfor element in elements:\n\t\t\tfor sub_defect in SubstitutionGenerator( bulk_structure, element):\n\t\t\t\tprint(\"\\tCreated Defect {} at site {}\".format( sub_defect.name, sub_defect.site))\n\t\t\t\tfor charged_defect in SimpleChargeGenerator( sub_defect):\n\t\t\t\t\tprint(\"\\tcreated defect with charge {}\".format( charged_defect.charge))\n\t\t\t\t\tdefects_to_run.append( charged_defect.copy())\n\t\t\t\t\tcharged_sub_data= open('antisite-%s-chg(%s).dat'%(sub_defect.name,charged_defect.charge),'w')\n\t\t\t\t\tcharged_defect_str=charged_defect.generate_defect_structure( supercell=(2, 1, 1))\n\t\t\t\t\tcharged_sub_data.writelines(str(charged_defect_str))\n\t\t\t\t\tcharged_sub_data.close()\n\t\t\t\t\t#print(charged_defect.generate_defect_structure( supercell=(2, 1, 1)))\n\n\n\n#Creating Extrinsic and Intrinsic interstitials with the bulk structure formula\n\t\tdefects_to_run=[]\n\t\tprint('Extrinsic Interstitial Generator:')\n\t\tsub_element_list=['H', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl']\n\t\tfor ele in elements[:]:\n\t\t\tif ele in sub_element_list:\n\t\t\t\tprint(ele)\n\t\t\t\tsub_element_list.remove(ele)\n\t\tprint(sub_element_list)\n\t\t\n\t\tfor element in sub_element_list:\n\t\t\tfor inter_defect in VoronoiInterstitialGenerator( bulk_structure, element):\n\t\t\t\tprint(\"\\tCreated Defect {} at site {}\".format( inter_defect.name, inter_defect.site))\n\t\t\t\tfor charged_defect in SimpleChargeGenerator( inter_defect):\n\t\t\t\t\tprint(\"\\tcreated defect with charge {}\".format( charged_defect.charge))\n\t\t\t\t\tdefects_to_run.append( charged_defect.copy())\n\t\t\t\t\tcharged_inter_data= open('ext-%s-chg(%s).dat'%(inter_defect.name,charged_defect.charge),'w')\n\t\t\t\t\tcharged_defect_str=charged_defect.generate_defect_structure( supercell=(2, 1, 1))\n\t\t\t\t\tcharged_inter_data.writelines(str(charged_defect_str))\n\t\t\t\t\tcharged_inter_data.close()\n\t\t\t\t\t#print(charged_defect.generate_defect_structure( supercell=(2, 1, 1)))\n\n\n\t\tdefects_to_run=[]\n\t\tprint('Intrinsic Interstitial Generator:')\n\t\tfor element in elements:\n\t\t\tfor inter_defect in VoronoiInterstitialGenerator( bulk_structure, element):\n\t\t\t\tprint(\"\\tCreated Defect {} at site {}\".format( inter_defect.name, inter_defect.site))\n\t\t\t\tfor charged_defect in SimpleChargeGenerator( inter_defect):\n\t\t\t\t\tprint(\"\\tcreated defect with charge {}\".format( charged_defect.charge))\n\t\t\t\t\tdefects_to_run.append( charged_defect.copy())\n\t\t\t\t\tcharged_inter_data= open('int-%s-chg(%s).dat'%(inter_defect.name,charged_defect.charge),'w')\n\t\t\t\t\tcharged_defect_str=charged_defect.generate_defect_structure( supercell=(2, 1, 1))\n\t\t\t\t\tcharged_inter_data.writelines(str(charged_defect_str))\n\t\t\t\t\tcharged_inter_data.close()\n\t\t\t\t\t#print(charged_defect.generate_defect_structure( supercell=(2, 1, 1)))\n\n\n#Renaming the folders according to their structural formula\n\t\tos.rename(os.path.join(os.path.join(basepath,'%s')%(i)),os.path.join(basepath,'%s'+'-'+'%s')%(i,str_formula))\n\tprint(structures)\n","sub_path":"code/get_defects_DJ.py","file_name":"get_defects_DJ.py","file_ext":"py","file_size_in_byte":6706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"640320230","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 3 20:48:40 2017\n\n@author: jialilei\n\"\"\"\n\ndef dict_invert(d):\n '''\n d: dict\n Returns an inverted dictionary according to the instructions above\n '''\n d_inv = {}\n for i in d:\n if d[i] in d_inv:\n d_inv[d[i]].append(i)\n else:\n d_inv[d[i]] = [i]\n for i in d_inv:\n d_inv[i].sort()\n return d_inv","sub_path":"Midterm/dict_invert.py","file_name":"dict_invert.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"491543444","text":"import re\nimport os\n\n\ndef get_member_list(filename):\n file_pointer = open(filename)\n\n class_re = re.compile(\"^class ([A-Za-z0-9]+[^\\(:]*)\")\n function_re = re.compile(\"^def ([a-z][a-z0-9_]*)\")\n type_re = re.compile(\"^([A-Za-z][A-Za-z0-9_]*) = \")\n class_list = []\n function_list = []\n type_list = []\n line_no = 0\n try:\n for line in file_pointer:\n line_no += 1\n\n class_names = class_re.findall(line)\n for class_name in class_names:\n class_list.append([filename, class_name])\n\n function_names = function_re.findall(line)\n for method_name in function_names:\n function_list.append([filename, method_name])\n\n type_names = type_re.findall(line)\n for type_name in type_names:\n type_list.append([filename, type_name])\n\n except Exception as e:\n print(f\"Exception processing {filename} on line {line_no}: {e}\")\n\n class_list.sort()\n function_list.sort()\n type_list.sort()\n return type_list, class_list, function_list\n\n\ndef main():\n\n with open('template_init.py', 'r') as content_file:\n init_template = content_file.read()\n\n with open('template_quick_index.rst', 'r') as content_file:\n quick_index_content = content_file.read()\n\n text_data = []\n text_classes = []\n text_functions = []\n\n os.chdir(\"../arcade\")\n file_list = \"window_commands.py\", \\\n \"application.py\", \\\n \"arcade_types.py\", \\\n \"earclip_module.py\", \\\n \"utils.py\", \\\n \"drawing_support.py\", \\\n \"texture.py\", \\\n \"buffered_draw_commands.py\", \\\n \"draw_commands.py\", \\\n \"geometry.py\", \\\n \"gui.py\", \\\n \"isometric.py\", \\\n \"joysticks.py\", \\\n \"emitter.py\", \\\n \"emitter_simple.py\", \\\n \"particle.py\", \\\n \"sound.py\", \\\n \"sprite.py\", \\\n \"sprite_list.py\", \\\n \"physics_engines.py\", \\\n \"read_tiled_map.py\", \\\n \"text.py\", \\\n \"tilemap.py\", \\\n \"utils.py\", \\\n \"version.py\"\n\n all_list = []\n\n for filename in file_list:\n type_list, class_list, function_list = get_member_list(filename)\n for member in type_list:\n init_template += f\"from .{member[0][:-3]} import {member[1]}\\n\"\n all_list.append(member[1])\n for member in class_list:\n init_template += f\"from .{member[0][:-3]} import {member[1]}\\n\"\n all_list.append(member[1])\n for member in function_list:\n init_template += f\"from .{member[0][:-3]} import {member[1]}\\n\"\n all_list.append(member[1])\n\n init_template += \"\\n\"\n\n for item in type_list:\n text_data += [f\"- :data:`~arcade.{item[1]}`\\n\"]\n for item in function_list:\n text_functions += [f\"- :func:`~arcade.{item[1]}`\\n\"]\n for item in class_list:\n text_classes += [f\"- :class:`~arcade.{item[1]}`\\n\"]\n\n init_template += \"\\n__all__ = [\"\n all_list.sort()\n first = True\n for item in all_list:\n if not first:\n init_template += \" \"\n else:\n first = False\n init_template += f\"'{item}',\\n\"\n init_template += \" ]\\n\\n\"\n\n init_template += \"__version__ = VERSION\\n\"\n\n text_file = open(\"__init__.py\", \"w\")\n text_file.write(init_template)\n text_file.close()\n\n text_data.sort()\n text_functions.sort()\n text_classes.sort()\n\n text_file = open(\"../doc/quick_index.rst\", \"w\")\n text_file.write(quick_index_content)\n\n text_file.write(\"\\n\\nClasses\\n\")\n text_file.write(\"-------\\n\")\n for item in text_classes:\n text_file.write(item)\n\n text_file.write(\"\\n\\nFunctions\\n\")\n text_file.write(\"---------\\n\")\n for item in text_functions:\n text_file.write(item)\n\n text_file.write(\"\\n\\nData\\n\")\n text_file.write(\"----\\n\")\n for item in text_data:\n text_file.write(item)\n\n text_file.close()\n\n\nmain()\n","sub_path":"util/update_init.py","file_name":"update_init.py","file_ext":"py","file_size_in_byte":4186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"356992439","text":"endpoint = u'me'\nname = u'Me'\nrelated_search_fields = [u'roles__search',\n u'main_oauth2accesstoken__search',\n u'enterprise_auth__search',\n u'main_oauth2application__search',\n u'oauth2_provider_refreshtoken__search',\n u'profile__search',\n u'activity_stream__search',\n u'oauth2_provider_grant__search',\n u'social_auth__search']\nparses = [u'application/json']\nsearch_fields = [u'username', u'first_name', u'last_name', u'email']\nactions = {u'GET': {u'created': {u'help_text': u'Timestamp when this user was created.',\n u'label': u'Created',\n u'type': u'datetime'},\n u'email': {u'filterable': True,\n u'label': u'Email address',\n u'type': u'string'},\n u'external_account': {u'help_text': u'Set if the account is managed by an external service',\n u'label': u'External account',\n u'type': u'field'},\n u'first_name': {u'filterable': True,\n u'label': u'First name',\n u'type': u'string'},\n u'id': {u'filterable': True,\n u'help_text': u'Database ID for this user.',\n u'label': u'ID',\n u'type': u'integer'},\n u'is_superuser': {u'filterable': True,\n u'help_text': u'Designates that this user has all permissions without explicitly assigning them.',\n u'label': u'Superuser status',\n u'type': u'boolean'},\n u'is_system_auditor': {u'label': u'Is system auditor',\n u'type': u'boolean'},\n u'last_name': {u'filterable': True,\n u'label': u'Last name',\n u'type': u'string'},\n u'ldap_dn': {u'label': u'Ldap dn', u'type': u'string'},\n u'related': {u'help_text': u'Data structure with URLs of related resources.',\n u'label': u'Related',\n u'type': u'object'},\n u'summary_fields': {u'help_text': u'Data structure with name/description for related resources.',\n u'label': u'Summary fields',\n u'type': u'object'},\n u'type': {u'choices': [[u'user', u'User']],\n u'help_text': u'Data type for this user.',\n u'label': u'Type',\n u'type': u'choice'},\n u'url': {u'help_text': u'URL for this user.',\n u'label': u'Url',\n u'type': u'string'},\n u'username': {u'filterable': True,\n u'help_text': u'Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.',\n u'label': u'Username',\n u'type': u'string'}}}\nrenders = [u'application/json', u'text/html']\nmax_page_size = 200\ntypes = [u'user']\n","sub_path":"awork/schema/current/v1/user/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":3563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"445372301","text":"import ipt\n# import minpy as minpy\nimport mxnet as mx\nimport minpy.numpy as np\nimport create_train_modle as old\nimport load_data as load\n\npm = old.Params\n\n\n''' pm should be a dict of the params of each layers '''\ndata = mx.sym.Variable(name= 'data') #name must be data, don't know why\n\nconv1 = mx.sym.Convolution(name = 'conv1', data = data, kernel = pm['c1']['fsize'], \n num_filter = pm['c1']['fnum'], stride = pm['c1']['stride'], pad = pm['c1']['pad'] )\nrelu1 = mx.sym.Activation(data = conv1, act_type = 'relu')\nconv2 = mx.sym.Convolution(name = 'conv2', data = relu1, kernel = pm['c2']['fsize'], \n num_filter = pm['c2']['fnum'], stride = pm['c2']['stride'], pad = pm['c2']['pad'] )\nrelu2 = mx.sym.Activation(data = conv2, act_type = 'relu')\n\npool1 = mx.sym.Pooling(data = relu2, pool_type = \"max\", kernel=(2,2), stride = (2,2))\n\n\nconv3 = mx.sym.Convolution(name = 'conv3', data = pool1, kernel = pm['c3']['fsize'], \n num_filter = pm['c3']['fnum'], stride = pm['c3']['stride'], pad = pm['c3']['pad'] )\nrelu3 = mx.sym.Activation(data = conv3, act_type = 'relu')\npool2 = mx.sym.Pooling(data = relu3, pool_type = \"max\", kernel=(2,2), stride = (2,2))\n\n\nconv4 = mx.sym.Convolution(name = 'conv4', data = pool2, kernel = pm['c4']['fsize'], \n num_filter = pm['c4']['fnum'], stride = pm['c4']['stride'], pad = pm['c4']['pad'] )\nrelu4 = mx.sym.Activation(data = conv4, act_type = 'relu')\npool3 = mx.sym.Pooling(data = relu4, pool_type = \"max\", kernel=(2,2), stride = (2,2))\n\n\nconv5 = mx.sym.Convolution(name = 'conv5', data = pool3, kernel = pm['c5']['fsize'], \n num_filter = pm['c5']['fnum'], stride = pm['c5']['stride'], pad = pm['c5']['pad'] )\nrelu5 = mx.sym.Activation(data = conv5, act_type = 'relu')\nconv6 = mx.sym.Convolution(name = 'conv6', data = relu5, kernel = pm['c6']['fsize'], \n num_filter = pm['c6']['fnum'], stride = pm['c6']['stride'], pad = pm['c6']['pad'] )\nrelu6 = mx.sym.Activation(data = conv6, act_type = 'relu')\n\n\n# up1 = mx.sym.UpSampling(relu6, scale = 2, sample_type= 'bilinear', num_args = 1)\nup1 = mx.sym.Deconvolution(\n data = relu6, kernel = (4,4), stride = (2,2), pad = (1,1),\n num_filter = 64, no_bias = True\n )\n\nconv7 = mx.sym.Convolution(name = 'conv7', data = up1, kernel = pm['c7']['fsize'], \n num_filter = pm['c7']['fnum'], stride = pm['c7']['stride'], pad = pm['c7']['pad'] )\nrelu7 = mx.sym.Activation(data = conv7, act_type = 'relu')\n\n# up2 = mx.sym.UpSampling(relu7, scale = 2, sample_type = 'bilinear', num_args = 1)\nup2 = mx.sym.Deconvolution(\n data = relu7, kernel = (4,4), stride = (2,2), pad = (1,1),\n num_filter = 64, no_bias = True\n )\n\n\nconv8 = mx.sym.Convolution(name = 'conv8', data = up2, kernel = pm['c8']['fsize'], \n num_filter = pm['c8']['fnum'], stride = pm['c8']['stride'], pad = pm['c8']['pad'] )\nrelu8 = mx.sym.Activation(data = conv8, act_type = 'relu')\n\n# up3 = mx.sym.UpSampling(relu8, scale = 2, sample_type = 'bilinear', num_args = 1)\nup3 = mx.sym.Deconvolution(\n data = relu8, kernel = (4,4), stride = (2,2), pad = (1,1),\n num_filter = 32, no_bias = True\n )\n\nconv9 = mx.sym.Convolution(name = 'conv9', data = up3, kernel = pm['c9']['fsize'], \n num_filter = pm['c9']['fnum'], stride = pm['c9']['stride'], pad = pm['c9']['pad'] )\nrelu9 = mx.sym.Activation(data = conv9, act_type = 'relu')\n# conv10 = mx.sym.Convolution(name = 'conv10', data = relu9, kernel = pm['c10']['fsize'], \n# num_filter = pm['c10']['fnum'], stride = pm['c10']['stride'], pad = pm['c10']['pad'] )\n# relu10 = mx.sym.Activation(data = conv10, act_type = 'relu')\n\nconv = mx.sym.Convolution(name = 'conv10', data = relu9, kernel = (7,7), num_filter = 1, \n stride = (1,1), pad = (0,0) )\nout = mx.sym.Activation(data = conv, act_type = 'sigmoid')\n\n\n\n","sub_path":"Net/basic_right_shape.py","file_name":"basic_right_shape.py","file_ext":"py","file_size_in_byte":3805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"384441117","text":"states = [\"a\", \"b\"]\nactions = [\"a\", \"b\"]\nrewards = {\"a\": {\"a\": 0, \"b\": 7}, \"b\": {\"a\": -5, \"b\": 0}}\n\nstate = \"a\"\nreward = 0\ntotal_reward = 0\n\nprint(\"\\n\\nStart-State: \", state, \" Start-Reward: \", reward, \"\\n\\n\")\n\nfor i in range(1, 11):\n print(\"State:\", state, \" - Iteration: \", i)\n action = input(\"Action: \")\n if action in actions:\n reward = rewards[state][action]\n total_reward += reward\n state = action\n print(\"Neuer State: \", state, \" Reward: \", reward, \" Gesamt-Reward: \", total_reward, \"\\n\")\n i += 1\n","sub_path":"Chapter3_ReinforcementLearning/agentMDP.py","file_name":"agentMDP.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"431681915","text":"#!/usr/bin/env python3\n\nimport inkex\nfrom lxml import etree\n\nclass DrawBBoxes(inkex.Effect):\n def __init__(self):\n inkex.Effect.__init__(self)\n\n def effect(self):\n if len(self.svg.selected) > 0:\n bboxes = [(id, node, node.bounding_box()) for id, node in self.svg.selected.items()]\n for id, node, bbox in bboxes:\n attribs = {\n 'style' : str(inkex.Style({'stroke':'#ff0000','stroke-width' : '1','fill':'none'})),\n 'x' : str(bbox.left),\n 'y' : str(bbox.top),\n 'width' : str(bbox.width),\n 'height' : str(bbox.height),\n }\n etree.SubElement(self.svg.get_current_layer(), inkex.addNS('rect','svg'), attribs )\n\nDrawBBoxes().run()\n","sub_path":"draw_bbox.py","file_name":"draw_bbox.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"206404382","text":"import math as m\n\ndef validateCommand(command):\n\n if command[0] == \"mm1\":\n\n if len(command) < 3:\n print(\"Insufficient arguments for model\")\n return False\n \n else:\n print(\"model \" + command[0] + \" accepted\")\n return True\n\n elif command[0] == \"mg1\" or command[0] == \"mms\":\n \n if len(command) < 4:\n print(\"Insufficient arguments for model\")\n return False\n \n else:\n print(\"model \" + command[0] + \" accepted\")\n return True \n \n else:\n print(\"Model not valid\")\n return False \n\ndef getSystemIndicators(command):\n \"\"\"\n \"\"\"\n system = command[0]\n arrRate = float(command[1])\n serRate = float(command[2])\n\n if system == \"mm1\":\n ro = arrRate / serRate\n P0 = 1 - ro\n\n Lq = ( arrRate ** 2 ) / (serRate * (serRate - arrRate))\n\n try:\n tFormat = command[3]\n except IndexError:\n tFormat = 'h'\n \n elif system == \"mg1\":\n ro = arrRate / serRate\n P0 = 1 - ro\n sigma = float(command[3])\n\n Lq = ( ((arrRate ** 2) * (sigma ** 2)) + (ro ** 2) ) / ( 2 * (1 - ro) )\n\n try:\n tFormat = command[4]\n except IndexError:\n tFormat = 'h'\n\n elif system == \"mms\":\n servers = int(command[3])\n ro = arrRate / ( serRate * servers )\n \n summ = 0\n for n in range(servers):\n summ += ( (arrRate / serRate) ** n ) / m.factorial(n)\n \n P0 = 1 / ( summ + ( (arrRate / serRate) ** servers ) / ( m.factorial(servers) * (1 - ro) ) )\n Lq = ( ((arrRate / serRate) ** servers) * P0 * ro ) / (m.factorial(servers) * (1 - ro) ** 2)\n\n try:\n tFormat = command[4]\n except IndexError:\n tFormat = 'h'\n\n Ls = Lq + (arrRate / serRate)\n Wq = Lq / arrRate\n Ws = Wq + ( 1 / serRate )\n\n if tFormat == 'h':\n tForm = 1\n elif tFormat == 'm':\n tForm = 60\n elif tFormat == 's':\n tForm = 3600\n\n return ( round(ro, 5), round(P0, 5), round(Lq * tForm, 5), \n round(Ls * tForm, 5), round(Wq * tForm, 5), round(Ws * tForm, 5) )\n\ndef printResults(ro, P0, Lq, Ls, Wq, Ws):\n print(\"\")\n print(\"==========RESULTS==========\")\n print(\"Occupation rate: {}\".format(ro))\n print(\"No wait probability (P0): {}\".format(P0))\n print(\"Length of the queue (Lq): {}\".format(Lq))\n print(\"Lenght of the system (Ls): {}\".format(Ls))\n print(\"Wait time in queue (Wq): {}\".format(Wq))\n print(\"Wait time in system (Ws): {}\".format(Ws))\n\nif __name__ == '__main__':\n\n while(True):\n \n print(\"Please enter command: \")\n raw_command = input()\n command = raw_command.split()\n\n if validateCommand(command):\n ro, P0, Lq, Ls, Wq, Ws = getSystemIndicators(command)\n printResults(ro, P0, Lq, Ls, Wq, Ws)\n break\n \n else:\n continue\n ","sub_path":"colas.py","file_name":"colas.py","file_ext":"py","file_size_in_byte":3017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"63186920","text":"import string\nimport os\nimport csv\nimport pickle\nimport json\nimport numpy as np\nimport pandas as pd\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk import pos_tag\nfrom nltk.stem import PorterStemmer\nfrom keras.models import Sequential\nfrom keras.layers import LSTM, Activation, Dense\nfrom keras.preprocessing.sequence import pad_sequences\n\n'''\nThis class contains the methods that operate on the questions to normalize them. The questions are tokenized, punctuations are\nremoved and words are stemmed to bring them to a common platform\n'''\nclass NLTKPreprocessor(object):\n def __init__(self):\n self.punct = set(string.punctuation)\n self.stemmer=PorterStemmer()\n def inverse_transform(self, X):\n return [\" \".join(doc) for doc in X]\n\n def transform(self, X):\n return list(self.tokenize(X))\n\n '''\n Tokenizes the input question. It also performs case-folding and stems each word in the question using Porter's Stemmer.\n '''\n def tokenize(self, sentence):\n tokenizer=RegexpTokenizer(r'\\w+')\n # Break the sentence into part of speech tagged tokens\n tokenized_words=[]\n for token, tag in pos_tag(tokenizer.tokenize(sentence)):\n token = token.lower()\n token = token.strip()\n\n # If punctuation, ignore token and continue\n if all(char in self.punct for char in token):\n continue\n\n # Stem the token and yield\n try:\n stemmed_token=self.stemmer.stem(token)\n except:\n print(\"Unicode error. File encoding was changed when you opened it in Excel. \", end=\" \")\n print(\"This is most probably an error due to csv file from Google docs being opened in Word. \", end=\" \")\n print(\"Download the file from Google Docs and DO NOT open it in Excel. Run the program immediately. \", end=\" \")\n print(\"If you want to edit using Excel and then follow instructions at: \")\n print(\"http://stackoverflow.com/questions/6002256/is-it-possible-to-force-excel-recognize-utf-8-csv-files-automatically\")\n continue\n yield stemmed_token\n\nclass ClassifierPreProcess(object):\n def __init__(self):\n self.train_data=[]\n self.test_data=[]\n self.train_vectors=[]\n self.test_vectors=[]\n self.lstm_train_vectors=[]\n self.lstm_test_vectors=[]\n self.lstm_train_data=[]\n self.lstm_test_data=[]\n self.answer_ids={}\n self.ids_answer={}\n self.all_topics=[]\n self.last_id=0\n self.w2v_model=None\n self.topic_model=None\n self.topic_set=set()\n self.preprocessor=NLTKPreprocessor()\n\n '''\n Read the list of topics from file.\n '''\n def read_topics(self):\n with open(os.path.join(\"data\",\"topics.csv\")) as f:\n reader=csv.reader(f)\n for row in reader:\n self.all_topics.append(row[0].lower())\n\n '''\n Normalize the topic words to make sure that each topic is represented only once (handles topics typed differently for\n different questions. For example, JobSpecific and Jobspecific are both normalized to jobspecific)\n '''\n def normalize_topics(self, topics):\n ret_topics=[]\n for topic in topics:\n topic=topic.strip()\n topic=topic.lower()\n ret_topics.append(topic)\n self.topic_set.add(topic)\n return ret_topics\n\n '''\n Read the classifier data from data/classifier_data.csv.\n Split the data to train and test sets.\n Store the data in format [actual question, transformed question, list of topics, answer_id] in self.train_data and\n self.test_data\n '''\n def read_data(self, mode):\n corpus=pd.read_csv(os.path.join(\"data\",\"classifier_data.csv\"))\n corpus=corpus.fillna('')\n total=0\n for i in range(0,len(corpus)):\n topics=corpus.iloc[i]['topics'].split(\",\")\n topics=[_f for _f in topics if _f]\n #normalize the topics\n topics=self.normalize_topics(topics)\n\n questions=corpus.iloc[i]['question'].split('\\r\\n')\n questions=[_f for _f in questions if _f]\n total+=len(questions)\n paraphrases=questions[1:]\n current_question=questions[0]\n\n answer=corpus.iloc[i]['text']\n answer_id=corpus.iloc[i]['ID']\n self.answer_ids[answer]=answer_id\n #remove nbsp and \\\"\n answer=answer.replace('\\u00a0',' ')\n self.ids_answer[answer_id]=answer\n\n #Tokenize the question\n processed_question=self.preprocessor.transform(current_question)\n #add question to dataset\n self.train_data.append([current_question,processed_question,topics,answer_id])\n #look for paraphrases and add them to dataset\n for i in range(0,len(paraphrases)):\n processed_paraphrase=self.preprocessor.transform(paraphrases[i])\n #add question to testing dataset if it is the last paraphrase. Else, add to training set\n if i==len(paraphrases)-1 and mode=='train_test_mode':\n self.test_data.append([paraphrases[i],processed_paraphrase,topics,answer_id])\n else:\n self.train_data.append([paraphrases[i],processed_paraphrase,topics,answer_id])\n\n '''\n get the word_vector and lstm_vector for a question. Both vectors are obtained from the Google News Corpus.\n The difference between these two vectors is given below:\n Question: \"What is your name?\"\n word_vector: Sum of the w2v representation for each word. Dimension: 300 x 1\n lstm_vector: List of the w2v representation for each word. Dimension: 300 x number_of_words_in_question\n '''\n def get_w2v(self, question):\n current_vector=np.zeros(300,dtype='float32')\n lstm_vector=[]\n for word in question:\n try:\n word_vector=self.w2v_model[word]\n except:\n word_vector=np.zeros(300,dtype='float32')\n lstm_vector.append(word_vector)\n current_vector+=word_vector\n return current_vector, lstm_vector\n\n '''\n Generate the training question vectors. For the Topic LSTM, each word should be represented by its own 300-length vector.\n For the classifier, the word vectors are added to form a single vector.\n '''\n def generate_training_vectors(self):\n #for each data point, get w2v vector for the question and store in train_vectors.\n #instance=<question, topic, answer, paraphrases>\n for instance in self.train_data:\n w2v_vector, lstm_vector=self.get_w2v(instance[1])\n self.train_vectors.append([instance[0],w2v_vector.tolist(),instance[2],instance[3]])\n self.lstm_train_vectors.append(lstm_vector)\n\n #For the LSTM, each training sample will have a max dimension of 300 x 25. For those that don't, the pad_sequences\n #function will pad sequences of [0, 0, 0, 0....] vectors to the end of each sample.\n padded_vectors=pad_sequences(self.lstm_train_vectors,maxlen=25, dtype='float32',padding='post',truncating='post',value=0.)\n self.lstm_train_vectors=padded_vectors\n #The test set might not be present when just training the dataset fully and then letting users ask questions.\n #That's why the test set code is inside a try-except block.\n try:\n for instance in self.test_data:\n w2v_vector, lstm_vector=self.get_w2v(instance[1])\n self.test_vectors.append([instance[0],w2v_vector.tolist(),instance[2],instance[3]])\n self.lstm_test_vectors.append(lstm_vector)\n padded_vectors=pad_sequences(self.lstm_test_vectors,maxlen=25, dtype='float32',padding='post',truncating='post',value=0.)\n self.lstm_test_vectors=padded_vectors\n except:\n pass\n\n '''\n For each question, the sparse topc vectors are created. If a question belongs to topic JobSpecific and Travel, then, a vector\n of size 40 (number of topics) is created with the vector having 1 for JobSpecific and Travel, and 0 for all other topics.\n This is done for both train and test sets.\n '''\n def generate_sparse_topic_vectors(self):\n #Generate the sparse topic train_vectors\n for i in range(len(self.train_vectors)):\n question=self.train_vectors[i][0]\n vector=self.train_vectors[i][1]\n current_topics=self.train_vectors[i][2]\n topic_vector=[0]*len(self.all_topics)\n for j in range(len(self.all_topics)):\n if self.all_topics[j] in current_topics:\n topic_vector[j]=1\n self.train_vectors[i][2]=topic_vector\n self.lstm_train_data.append([question,self.lstm_train_vectors[i].tolist(),topic_vector])\n #The test set might not be present when just training the dataset fully and then letting users ask questions.\n #That's why the test set code is inside a try-except block.\n try:\n #Generate the sparse topic test_vectors\n for i in range(len(self.test_vectors)):\n question=self.test_vectors[i][0]\n vector=self.test_vectors[i][1]\n current_topics=self.test_vectors[i][2]\n topic_vector=[0]*len(self.all_topics)\n for j in range(len(self.all_topics)):\n if self.all_topics[j] in current_topics:\n topic_vector[j]=1\n self.test_vectors[i][2]=topic_vector\n self.lstm_test_data.append([question,self.lstm_test_vectors[i].tolist(),topic_vector])\n except:\n pass\n\n\n '''\n Write the train and test data to json (.json) files that can be unpickled in lstm.py and classify.py. This is just dumping\n the data into a file and then undumping it\n '''\n def write_data(self):\n if not os.path.exists(\"train_data\"):\n os.mkdir(\"train_data\")\n if not os.path.exists(\"test_data\"):\n os.mkdir(\"test_data\")\n\n #dump lstm_train_data\n with open(os.path.join(\"train_data\",\"lstm_train_data.json\"),'w') as json_file:\n #data_to_write=self.lstm_train_data.tolist()\n json.dump(self.lstm_train_data, json_file)\n #dump train_vectors for logistic regression\n with open(os.path.join(\"train_data\",\"lr_train_data.json\"),'w') as json_file:\n json.dump(self.train_vectors,json_file)\n \n #The test set might not be present when just training the dataset fully and then letting users ask questions.\n #That's why the test set code is inside a try-except block.\n try:\n #dump lstm_test_data\n with open(os.path.join(\"test_data\",\"lstm_test_data.json\"),'w') as json_file:\n json.dump(self.lstm_test_data, json_file)\n #dump test_vectors for logistic regression\n with open(os.path.join(\"test_data\",\"lr_test_data.json\"),'w') as json_file:\n json.dump(self.test_vectors,json_file)\n except:\n pass\n #dump ids_answers\n with open(os.path.join(\"train_data\",\"ids_answer.json\"),'w') as json_file:\n json.dump(self.ids_answer,json_file)\n\n\n","sub_path":"src/classifier/classifier_preprocess.py","file_name":"classifier_preprocess.py","file_ext":"py","file_size_in_byte":11366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"377303744","text":"##• Go to https://petitions.whitehouse.gov/petitions \n##• Go to the petition page for each of the petitions. \n##• Create a .csv file with the following information for each petition:\n## – Title # h3\n## – Published date # h4 class 'petition-attribution'\n## – Issues #div class = 'field field-name-field-petition-issues field-type-taxonomy-term-reference field-label-hidden tags'\n## -- number of signatures #div class= 'signatures-progress-bar'\nfrom bs4 import BeautifulSoup\nimport urllib2 \nimport random\nimport time\nimport os\nimport re\nimport csv\nweb_page = []\nweb_address = []\nall_html = []\next = []\nsite = []\nname = []\ntemp = []\nsign = []\ntemp1 = []\ntemp2 = []\ntopic = []\ndate = []\nfin = []\nissue= []\ndate = []\nstore = {\"Topic\":[], \"Name\":[], \"Sigs\":[], \"Date\":[]}\n\n ## PETITION SITES\nfor i in range(0,4):\n web_address = 'https://petitions.whitehouse.gov/?page=' + '%s' % i\n web_page = urllib2.urlopen(web_address) ## having figured it below I know this can be more\n all_html.append(BeautifulSoup(web_page.read()))#eloquent will fix if remaining work time <2hrs\n \nfor i in all_html:\n try:\n ext.append(i.find_all(\"a\"))\n except AttributeError:\n ext.append(\"NA\")\n\nfor i in ext:\n for j in i:\n try:\n if j['href'][0:10] == '/petition/':\n site.append(\"https://petitions.whitehouse.gov\" +( j['href'].encode('utf-8')))\n except KeyError:\n pass\n\n\nsite = site[1::2]\nsite.pop(41)\nsite.pop(60)\n##TITLES:\nfor i in site:\n name.append(BeautifulSoup(urllib2.urlopen(i).read()).find('h1').get_text().encode('utf-8'))\n if (BeautifulSoup(urllib2.urlopen(i).read()).find('h1').get_text().encode('utf-8'))[0:16] == \"Log In or Create\":\n pass\n else:\n name.append(BeautifulSoup(urllib2.urlopen(i).read()).find('h1').get_text().encode('utf-8'))\n\n ## NUMBER OF SIGNATURES\nfor i in all_html:\n temp.append(i.find_all('span', {'class': \"signatures-number\"}))\nfor j in temp:\n for e in j:\n sign.append(e.get_text().encode('utf-8'))\n\n ## ISSUES\n\nfor i in all_html:\n temp1 +=( i.find_all('div', {'class':\"field-items\"}))\ntemp1 = temp1[1:]\nfor j in temp1:\n try:\n temp2 += j.find_all('h6')\n for i in temp2:\n fin+=[(str(i.get_text()))]\n issue += [fin]\n temp2 = []\n fin = []\n except:\n issue += 'NA'\n\nissue.insert(12, '[]')\nissue.pop(-7)\nissue.pop(19)\nissue.pop(40)\n ## Date\nfor i in site:\n try:\n date.append(BeautifulSoup(urllib2.urlopen(i).read()).find('h4').get_text().encode('utf-8').split('on',1)[-1])\n except AttributeError:\n date.append('na')\n\n \n\n\n\n ## WRITE THIS BASTARD\nwith open('C:/Python27.14/pythoncourse2018/homeworks/hw2/hw2_dl.csv', 'wb') as f:\n w = csv.DictWriter(f, fieldnames = (\"Title of Petition\", \"Published Date\", \"Issues\",\"Number of Signatures\"))\n w.writeheader()\n for i in range(0,len(name)):\n w.writerow({\"Title of Petition\": name[i], \"Published Date\": date[i], \"Issues\": issue[i], \"Number of Signatures\": sign[i]})\n\n\n","sub_path":"homeworks/hw2/hw2_dl.py","file_name":"hw2_dl.py","file_ext":"py","file_size_in_byte":3063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"68635002","text":"import sys\r\n\r\nfrom config.config_sys import CTLR_IP\r\n\r\ncfg = {\r\n 'ip': None,\r\n 'ctlrIp': CTLR_IP,\r\n 'state': None,\r\n 'remoteCfg': None,\r\n 'serviceCaching': []\r\n}\r\n\r\n\r\ndef state_dict():\r\n \"\"\"return config dict\"\"\"\r\n mod = sys.modules[__name__]\r\n from inspect import isfunction, ismodule\r\n state = {}\r\n vrb_names = dir(mod)\r\n for vrbName in vrb_names:\r\n if vrbName.startswith('__') or vrbName.endswith('__'):\r\n continue\r\n vrb = getattr(mod, vrbName)\r\n if isfunction(vrb):\r\n continue\r\n if ismodule(vrb):\r\n continue\r\n state[vrbName] = vrb\r\n return state\r\n\r\n\r\ndef load(state_dict):\r\n \"\"\"load config dict\"\"\"\r\n mod = sys.modules[__name__]\r\n for vrbName in state_dict:\r\n setattr(mod, vrbName, state_dict[vrbName])\r\n print('config loaded')\r\n\r\n\r\ndef output():\r\n \"\"\"output config dict\"\"\"\r\n stat = state_dict()\r\n for vrb_name in stat:\r\n print(vrb_name + ' = ' + str(stat[vrb_name]))\r\n\r\n\r\nif __name__ == '__main__':\r\n output()\r\n","sub_path":"config/config_cl_user.py","file_name":"config_cl_user.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"502423469","text":"\"\"\"DLS fitting tools\n\"\"\"\n\nfrom enthought.traits.api import HasTraits, Function,\\\n Property,Str, List, Float, Instance, Enum, Bool, Array,\\\n Button, on_trait_change, Tuple\n \nfrom enthought.traits.ui.api import View, Item, \\\n Group, EnumEditor, Handler, TableEditor\n\nimport inspect, os\n\nfrom labtools.analysis.fit import DataFitter, create_fit_function\nfrom labtools.analysis.fit_functions import dls\nfrom labtools.analysis.tools import BaseFileAnalyzer, file_analyzer_group, Filenames\nfrom labtools.io.dls import open_dls\nfrom labtools.analysis.plot import Plot\n\nfrom labtools.utils.logger import display_dialog, init_logger, get_logger\nfrom labtools.utils.data import StructArrayData\n\nimport numpy as np\n\ninit_logger('DLS analyzer')\nlog = get_logger('DLS analyzer')\n \nclass DlsError(Exception):\n pass\n\ndls_analyzer_group = Group(\n Item('filenames',show_label = False, style = 'custom'),\n 'constants',\n Item('process_button',show_label = False)\n )\n\nclass DlsFitter(DataFitter):\n \"\"\"In adition to :class:`DataFitter` it defines :method:`open_dls` to open dls dat\n \"\"\"\n def _plotter_default(self):\n return Plot(xlabel = 'Lag time [ms]', ylabel = 'g2-1', xscale = 'log', title = 'g2 -1')\n \n def open_dls(self,fname):\n \"\"\"Opens asc for reading, sets self.fitter.data data\n \n :param str `fname`: \n filename of asc data to be opened\n :returns: \n a header, rate, count tuple of the asc data\n \"\"\"\n try:\n log.info('Opening file %s' % fname)\n if os.path.splitext(fname)[1] == '.npy':\n data = np.load(fname)\n self.data.x = data[:,0]\n self.data.y = data[:,1]\n return {}, data, None\n header,rate,count = open_dls(fname)\n self.data.x = rate[:,0]\n self.data.y = rate[:,1]\n return header,rate,count\n except:\n log.error('Could not open file %s' % fname, raises = DlsError, display = True)\n \n\ndef create_dls_fitter(name):\n \"\"\"Creates DlsFitter object, based on function name \n >>> fit = create_dlsfitter('single_stretch_exp')\n \"\"\"\n return DlsFitter(function = create_fit_function('dls', name))\n \n \nclass DlsAnalyzer(BaseFileAnalyzer):\n \"\"\"DLS analyzer object\n \"\"\"\n #: data fitter object for data fitting\n fitter = Instance(DlsFitter)\n #: defines a list of constants tuple that are set in each fit run. See :meth:`process`\n constants = List(Tuple(Str))\n saves_fits = Bool(False)\n log_name = Str('analysis.rst')\n log = Str\n \n results = Instance(StructArrayData,())\n results_err = Instance(StructArrayData,())\n\n view = View(dls_analyzer_group,'fitter','saves_fits','results', resizable = True)\n \n @on_trait_change('selected')\n def _open_dls(self, name):\n self.fitter.open_dls(name)\n \n def _constants_default(self):\n return [('',)]\n \n def process_file(self,fname):\n \"\"\"Opens fname and fits data according to self.constants\n \n :param fname: filename of asc data to be opened and fitted\n :type fname: str \n :param index: file index, should increase\n \"\"\"\n self.fitter.open_dls(fname)\n try:\n for constants in self.constants:\n self.fitter.fit(constants = constants)\n except:\n display_dialog('Error when fitting, please fit manually, then click OK',level = 'warning',gui = False)\n self.fitter.configure_traits()\n finally:\n if self.saves_fits:\n imagename = fname + '.png'\n log.info('Plotting %s' % imagename)\n self.fitter.plotter.title = imagename\n self.fitter.plot(fname = imagename)\n if self.log_name:\n self.log += '.. image:: %s\\n' % os.path.basename(imagename)\n return self.fitter.function.pvalues, self.fitter.function.psigmas\n \n def process_result(self,result, fname, index):\n self.results.data[index] = tuple([index] + result[0])\n self.results_err.data[index] = tuple([index]+ result[1])\n self.results.data_updated = True\n self.results_err.data_updated = True\n \n def finish(self):\n if self.log_name and self.log:\n with open(self.log_name, 'w') as f:\n f.write(self.log)\n print(self.log)\n \n def init(self):\n array_names = ['index'] + self.fitter.function.pnames\n dtype = np.dtype(list(zip(array_names, ['float']*len(array_names))))\n self.results = StructArrayData(data = np.zeros(len(self.filenames), dtype = dtype))\n self.results_err = StructArrayData(data = np.zeros(len(self.filenames), dtype = dtype))\n self.results.data_updated = True\n self.results_err.data_updated = True\n self.log = '===========\\nFit results\\n===========\\n\\n'\n return True\n \n\ndef main():\n fitter = create_dls_fitter('single_stretch_exp')\n files = Filenames(pattern = '*.ASC')\n fitter.data.xmin = 0\n fitter.data.xmax = 10000 \n d= DlsAnalyzer(fitter = fitter, filenames = files)\n d.configure_traits() \n \n\nif __name__ == '__main__':\n main()\n\n \n","sub_path":"labtools/analysis/_dls_fit.py","file_name":"_dls_fit.py","file_ext":"py","file_size_in_byte":5390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"563470199","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.neighbors import NearestNeighbors\n\n__new_idx = 0\n__minor_class = None\n__synthetic = None\n\n\ndef oversampleHelp(data):\n \"\"\"Prepare data for oversampling.\"\"\"\n # Create new features\n data['Hour'] = data.Dates.dt.hour\n data['DayOfWeek'] = data.DayOfWeek\n data['Month'] = data.Dates.dt.month\n data['Year'] = data.Dates.dt.year\n data['DayOfMonth'] = data.Dates.dt.day\n\n # Remove unnecessary data\n for feat in ['Dates', 'Descript', 'Resolution', 'Address']:\n data = data.drop(feat, 1)\n\n # Categorical to numeric\n for feat in ['Category', 'DayOfWeek', 'PdDistrict']:\n cat_obj = pd.Categorical.from_array(data[feat])\n cat_num = cat_obj.codes\n # print cat_obj.categories\n data[feat] = cat_num\n\n return data\n\n\ndef populate(N, i, nn_idxs):\n \"\"\"Create synthetic data.\"\"\"\n global __new_idx, __minor_class, __synthetic\n\n nn = np.random.randint(0, high=nn_idxs.size, size=N)\n\n for i in xrange(0, N):\n dif = __minor_class.iloc[[int(nn_idxs[nn[i]])]].values - __minor_class.iloc[i].values\n __synthetic[__new_idx, :] = __minor_class.iloc[i].values + np.random.uniform()*dif\n __new_idx += 1\n\n\ndef smote(T, N, k):\n \"\"\"Oversample using SMOTE algorithm.\"\"\"\n global __minor_class\n\n if N < 100:\n T = N/100 * T\n N = 100\n N = int(N/100)\n\n # Find k nearest neighbors for each data sample\n nbrs = NearestNeighbors(n_neighbors=k, algorithm='ball_tree').fit(__minor_class)\n distances, idxs = nbrs.kneighbors(__minor_class)\n\n for i in xrange(0, T):\n populate(N, i, idxs[i, :])\n\n\ndef oversample(data, feat, minor_classes):\n global __new_idx, __minor_class, __synthetic\n\n data = oversampleHelp(data)\n\n for k, v in minor_classes.iteritems():\n __minor_class = data[data[feat] == k]\n __synthetic = np.empty([__minor_class.shape[0]*v[0]/100, __minor_class.shape[1]])\n\n smote(__minor_class.shape[0], v[0], v[1])\n __new_idx = 0\n\n ndf = pd.DataFrame(data=__synthetic, columns=__minor_class.columns.values, dtype=int)\n ndf['X'] = pd.Series(__synthetic[:, 3])\n ndf['Y'] = pd.Series(__synthetic[:, 4])\n data = pd.concat([data, ndf])\n\n return data","sub_path":"src/oversample.py","file_name":"oversample.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"39177022","text":"# 模拟掷骰子\n\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams['font.sans-serif'] = ['PingFang']\n\np_list = []\n\n\n# 掷骰子类\nclass Roll:\n def __init__(self):\n roll_num = 0\n\n def roll_dice(self):\n roll_num = np.random.randint(1, 6, (1000, 1))\n return roll_num\n\n\ndef main():\n # 构建数据\n roll_list = []\n times = 10000000\n\n roll_list = np.random.randint(1, 7, size=times) + np.random.randint(1, 7, size=times)+ np.random.randint(1, 7, size=times)\n\n # 数据可视化\n plt.hist(roll_list, bins=range(3, 20), normed=1, rwidth=0.8)\n\n # 设置x轴的坐标显示\n tick_pos = np.arange(2, 19) + 0.5\n tick_xlabel = ['3点', '4点', '5点', '6点', '7点', '8点', '9点', '10点', '11点', '12点','13点','14点','15点','16点','17点','18点',]\n\n plt.xticks(tick_pos, tick_xlabel)\n\n plt.title('掷骰子的概率分布')\n plt.xlabel('骰子点数')\n plt.ylabel('概率')\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"zhishaozi_pro plus.py","file_name":"zhishaozi_pro plus.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"644460152","text":"# In consumers.py\nimport logging\nfrom channels import Group\nfrom channels.generic.websockets import JsonWebsocketConsumer\nimport os\nimport time\nimport json\n\n\ndef ws_message(message):\n # ASGI WebSocket packet-received and send-packet message types\n # both have a \"text\" key for their textual data.\n message.reply_channel.send({\n \"text\": message.content['text'],\n })\n\n\n# Connected to websocket.connect\ndef ws_add(message):\n message.reply_channel.send({\"accept\": True})\n Group(\"chat\").add(message.reply_channel)\n\n\n# Connected to websocket.disconnect\ndef ws_disconnect(message):\n Group(\"chat\").discard(message.reply_channel)\n\n\ndef worker_channels(message, service):\n \"\"\"\n message type from django channels\n service - calc name for p-chem data, metabolizer, speciation\n \"\"\"\n logging.info(\"incoming message to channels channel: {}\".format(message))\n post_request = message.content # expecting json request for channels pchem data\n # return channels_worker.request_manager(request)\n\n logging.warning(\"arg: {}\".format(service))\n logging.warning(\"message: {}\".format(message.content))\n\n \n # ??? Can there be multple workers that consume this same function, but\n # each worker only consumes certain requests based on \"calc\" arg ???\n\n # Do the workers even need to be separated by calc? (probably not)\n time.sleep(5) # sleep 5s, checking for parllel worker consumption of same function/route\n\n\n # p-chem request would go here\n \n\n\n # pchem_response = channels_cts.worker.request_manager({'this': 'is', 'not': 'real'})\n message.reply_channel.send({'text': 'channels worker made p-chem request to {}'.format(calc)})\n\n# def ws_pchem_request(message):\n# # assuming p-chem request from single user.\n# # parse out request to workers..\n# check_mess = message;\n# message.reply_channel.send({\n# # \"text\": message.content['text'],\n# \"text\": \"hello, this is pchem channel\",\n# })\n\n\n# def chemaxon_channel(message):\n# logging.info(\"incoming message to chemaxon channel: {}\".format(message))\n# post_request = message.content # expecting json request for chemaxon pchem data\n# # return chemaxon_worker.request_manager(request)\n\n# # this is where the call would go to cts_api rest endpoint\n\n\n# # pchem_response = chemaxon_cts.worker.request_manager({'this': 'is', 'not': 'real'})\n# message.reply_channel.send({'text': 'chemaxon worker made p-chem request'})\n\n\n# def sparc_channel(message):\n# logging.info(\"incoming message to sparc channel: {}\".format(message))\n# post_request = message.content # expecting json request for sparc pchem data\n# # return sparc_worker.request_manager(request)\n\n# # this is where the call would go to cts_api rest endpoint\n\n\n# # pchem_response = sparc_cts.worker.request_manager({'this': 'is', 'not': 'real'})\n# message.reply_channel.send({'text': 'sparc worker made p-chem request'})\n\n\n# # Generic Consumer: JSON-enabled WebSocket Class\n# class ChemaxonConsumer(JsonWebsocketConsumer):\n\n# # set to True for ordering:\n# strict_ordering = False\n\n# method_mapping = {\n# 'channel_chemaxon': 'method name'\n# }\n\n# def connection_groups(self, **kwargs):\n# \"\"\"\n# Called to return the list of groups to automatically add/remove\n# this connection to/from.\n# \"\"\"\n# return [\"test\"]\n\n# def connect(self, **kwargs):\n# \"\"\"\n# Perform things on connection start\n# \"\"\"\n# pass\n\n# def receive(self, content, **kwargs):\n# \"\"\"\n# Called when a message is received with decoded JSON content\n# \"\"\"\n# self.send(content) # simple echo (self.send auto encodes JSON)\n\n# def disconnect(self, message, **kwargs):\n# \"\"\"\n# Perform things on connection close\n# \"\"\"\n# pass","sub_path":"consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":3872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"325194724","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass PublishSettingUpdateObject(Model):\n \"\"\"Object model for updating an application's publish settings.\n\n :param sentiment_analysis: Setting sentiment analysis as true returns the\n Sentiment of the input utterance along with the response\n :type sentiment_analysis: bool\n :param speech: Setting speech as public enables speech priming in your app\n :type speech: bool\n :param spell_checker: Setting spell checker as public enables spell\n checking the input utterance.\n :type spell_checker: bool\n \"\"\"\n\n _attribute_map = {\n 'sentiment_analysis': {'key': 'sentimentAnalysis', 'type': 'bool'},\n 'speech': {'key': 'speech', 'type': 'bool'},\n 'spell_checker': {'key': 'spellChecker', 'type': 'bool'},\n }\n\n def __init__(self, **kwargs):\n super(PublishSettingUpdateObject, self).__init__(**kwargs)\n self.sentiment_analysis = kwargs.get('sentiment_analysis', None)\n self.speech = kwargs.get('speech', None)\n self.spell_checker = kwargs.get('spell_checker', None)\n","sub_path":"azure-cognitiveservices-language-luis/azure/cognitiveservices/language/luis/authoring/models/publish_setting_update_object.py","file_name":"publish_setting_update_object.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"523914596","text":"\"\"\"\r\nAssignment Name: Assignment 5 - Foxes and Rabbits with Files\r\n\r\nAuthor: Sean Donohoe and Matthew Hurst\r\n\r\nDescription: This module simulates the population of foxes and rabbits on an island -- using constants for rabbit birth rate, fox birth rate, likelihood a fox and rabbit meet, and probability of success that a fox catches a rabbit -- over a user designated time period, using user-designated starting populations. The data for the ceiling, rounded, raw, and floor values of each day for the foxes and rabbits, along with averages for each will be written to a .csv file.\r\n\r\nDate: 9/22/13\r\n\"\"\"\r\nimport sys\r\nimport math\r\ndef run_simulation():\t\r\n\tprint()\t# adds a newline for nicer output.\r\n\t\r\n\tinitvalues = open(\"initvals.txt\", 'r')\r\n\t# rabbit birth rate without predation \r\n\trbr = float(initvalues.readline())\r\n\t#print(rbr)\r\n\r\n\t# fox birth rate \r\n\tfbr = float(initvalues.readline())\r\n\t#print(fbr)\r\n\r\n\t# INTERACT is the likelihood that a rabbit and fox will meet\r\n\tI = float(initvalues.readline())\r\n\t#print(I)\r\n\r\n\t# SUCCESS is the likelihood that when a fox & rabbit meet that the \r\n\t# fox catches the rabbit\r\n\tS = float(initvalues.readline())\r\n\t#print(S)\r\n\t#exit(0)\r\n\r\n\t# 1. Gather data from user, one value per input\r\n\tfoxlr = []\r\n\trabbitlr = [] \r\n\r\n\tfoxlfl = []\r\n\trabbitlfl = []\r\n\t\r\n\tfoxlceil = []\r\n\trabbitlceil = []\r\n\r\n\tfoxlraw = []\r\n\trabbitlraw = []\r\n\r\n\trabbits = eval(input(\"Enter the starting number of rabbits: \"))\r\n\tfoxes = eval(input(\"Enter the starting number of foxes: \"))\r\n\tdays = eval(input(\"Enter the number of days to simulate: \"))\r\n\tfrequency = eval(input(\"Enter the frequency of days for displaying data: \"))\r\n\r\n\tfoxlr.append(round(foxes))\r\n\trabbitlr.append(round(rabbits))\r\n\r\n\tfoxlfl.append(math.floor(foxes))\r\n\trabbitlfl.append(math.floor(rabbits))\r\n\r\n\tfoxlceil.append(math.ceil(foxes))\r\n\trabbitlceil.append(math.ceil(rabbits))\r\n\r\n\tfoxlraw.append(foxes)\r\n\trabbitlraw.append(rabbits)\r\n\r\n\troundRabbitsAvg = 0\r\n\troundFoxesAvg = 0\r\n\r\n\tfloorRabbitsAvg = 0\r\n\tfloorFoxesAvg = 0\r\n\r\n\tceilRabbitsAvg = 0\r\n\tceilFoxesAvg = 0\r\n\r\n\trawRabbitsAvg = 0\r\n\trawFoxesAvg = 0\r\n\r\n\t# 2. print out some header info here with labels for days, rabbits, foxes \r\n\t\r\n\t#print(\"\\nRoundeds Population Averages:\")\r\n\t#print(\"{:9s}{:>10.3f}\".format(\"Rabbits:\", roundRabbitsAvg))\r\n\t#print(\"{:9s}{:>10.3f}\".format(\"Foxes:\", roundFoxesAvg))\r\n\r\n\t#displaystr = \"{:<10s}{:^20s}{:^19s}{:^20s}{:^29s}\".format(\"\", \"Rounded Values\", \"Floor Values\", \"Ceil Values\", \"Raw Values\")\r\n\t#print(displaystr)\r\n\t\r\n\t#displaystr = \"{:>10s}{:>10s}{:>10s}{:>10s}{:>10s}{:>10s}{:>10s}{:>15s}{:>15s}\".format(\"Day\", \"Rabbits\", \"Foxes\",\"Rabbits\", \"Foxes\",\"Rabbits\", \"Foxes\",\"Rabbits\", \"Foxes\")\r\n\t#print(displaystr)\r\n\t\r\n\t#print(\"-\"*100)\r\n\r\n\t\r\n\t# 3. print out the starting simulation values\r\n\r\n\t# 4. write a for-loop to iterate through the simulated days\r\n\tcount = 1\r\n\tfor i in range(days+1):\r\n\t\t\r\n\t\tF = foxlraw[i]\r\n\t\tR = rabbitlraw[i]\t\r\n\r\n\t\tRc = (rbr * R) - (I * R * F)\r\n\t\tFc = (I * S * R * F) - (fbr * F)\r\n\r\n\t\tR += Rc\r\n\t\tF += Fc\r\n\r\n\t\trabbitlraw.append(round(R, 3))\r\n\t\tfoxlraw.append(round(F, 3))\r\n\r\n\t\tF = foxlr[i]\r\n\t\tR = rabbitlr[i]\t\r\n\r\n\t\tRc = (rbr * R) - (I * R * F)\r\n\t\tFc = (I * S * R * F) - (fbr * F)\r\n\r\n\t\tR += Rc\r\n\t\tF += Fc\r\n\r\n\t\trabbitlr.append(round(R))\r\n\t\tfoxlr.append(round(F))\r\n\r\n\t\tF = foxlfl[i]\r\n\t\tR = rabbitlfl[i]\t\r\n\r\n\t\tRc = (rbr * R) - (I * R * F)\r\n\t\tFc = (I * S * R * F) - (fbr * F)\r\n\r\n\t\tR += Rc\r\n\t\tF += Fc\r\n\r\n\t\trabbitlfl.append(math.floor(R))\r\n\t\tfoxlfl.append(math.floor(F))\r\n\r\n\t\tF = foxlceil[i]\r\n\t\tR = rabbitlceil[i]\t\r\n\r\n\t\tRc = (rbr * R) - (I * R * F)\r\n\t\tFc = (I * S * R * F) - (fbr * F)\r\n\r\n\t\tR += Rc\r\n\t\tF += Fc\r\n\r\n\t\trabbitlceil.append(math.ceil(R))\r\n\t\tfoxlceil.append(math.ceil(F))\r\n\t\t\r\n\tfor i in range(days+1):\r\n\t\troundRabbitsAvg += rabbitlr[i]\r\n\t\troundFoxesAvg += foxlr[i]\r\n\r\n\t\tfloorRabbitsAvg += rabbitlfl[i]\r\n\t\tfloorFoxesAvg += foxlfl[i]\r\n\r\n\t\tceilRabbitsAvg += rabbitlceil[i]\r\n\t\tceilFoxesAvg += foxlceil[i]\r\n\r\n\t\trawRabbitsAvg += rabbitlraw[i]\r\n\t\trawFoxesAvg += foxlraw[i]\r\n\r\n\troundRabbitsAvg = roundRabbitsAvg / (days + 1)\r\n\troundFoxesAvg = roundFoxesAvg / (days + 1)\r\n\r\n\tfloorRabbitsAvg = floorRabbitsAvg / (days + 1)\r\n\tfloorFoxesAvg = floorFoxesAvg / (days+ 1)\r\n\r\n\tceilRabbitsAvg = ceilRabbitsAvg / (days + 1)\r\n\tceilFoxesAvg = ceilFoxesAvg / (days + 1)\r\n\r\n\trawRabbitsAvg = rawRabbitsAvg / (days +1)\r\n\trawFoxesAvg = rawFoxesAvg / (days + 1)\r\n\r\n\tfilename = input(\"Enter the name of your file without extensions: \")\r\n\tcsv = open(filename + \".csv\", 'w')\r\n\t\r\n\theader1 = \"Rounded Rabbits Average, Rounded Foxes Average, Floor Rabbits Average, Floor Foxes Average, Ceiling Rabbits Average, Ceiling Foxes Average, Raw Rabbits Average, Raw Foxes Average\\n\"\r\n\tcsv.write(header1)\r\n\taverages = \"%i, %i, %i, %i, %i, %i, %i, %i\\n\" %(roundRabbitsAvg, roundFoxesAvg, floorRabbitsAvg, floorFoxesAvg, ceilRabbitsAvg, ceilFoxesAvg, rawRabbitsAvg, rawFoxesAvg)\r\n\tcsv.write(averages)\r\n\t\r\n\theader2 = \"Day, Round Rabbits, Round Foxes, Day, Floor Rabbits, Floor Foxes, Day, Ceiling Rabbits, Ceiling Foxes, Day, Raw Rabbits, Raw Foxes\\n\"\r\n\tcsv.write(header2)\r\n\r\n\tfor i in range(0, days+1, frequency):\r\n\t\tcsv.write(str(i) + \", \")\r\n\t\tcsv.write(str(rabbitlr[i]) + \", \")\r\n\t\tcsv.write(str(foxlr[i]) + \", \")\r\n\t\tcsv.write(str(i) + \", \")\r\n\t\tcsv.write(str(rabbitlfl[i]) + \", \")\r\n\t\tcsv.write(str(foxlfl[i]) + \", \")\r\n\t\tcsv.write(str(i) + \", \")\r\n\t\tcsv.write(str(rabbitlceil[i]) + \", \")\r\n\t\tcsv.write(str(foxlceil[i]) + \", \")\r\n\t\tcsv.write(str(i) + \", \")\r\n\t\tcsv.write(str(rabbitlraw[i]) + \", \")\r\n\t\tcsv.write(str(foxlraw[i]) + \"\\n\")\r\n\r\n#-----------------------End Assignment 5-----------------------------------------------#\r\n\t#print(\"\\nRounded Population Averages:\")\r\n\t#print(\"{:9s}{:>10.3f}\".format(\"Rabbits:\", roundRabbitsAvg))\r\n\t#print(\"{:9s}{:>10.3f}\".format(\"Foxes:\", roundFoxesAvg))\r\n\r\n#\tprint(\"\\nFloor Population Averages:\")\r\n#\tprint(\"{:9s}{:>10.3f}\".format(\"Rabbits:\", floorRabbitsAvg))\r\n#\tprint(\"{:9s}{:>10.3f}\".format(\"Foxes:\", floorFoxesAvg))\r\n\t\r\n#\tprint(\"\\nCeiling Population Averages:\")\r\n#\tprint(\"{:9s}{:>10.3f}\".format(\"Rabbits:\", ceilRabbitsAvg))\r\n#\tprint(\"{:9s}{:>10.3f}\".format(\"Foxes:\", ceilFoxesAvg))\r\n\r\n#\tprint(\"\\nRaw Population Averages:\")\r\n#\tprint(\"{:9s}{:>10.3f}\".format(\"Rabbits:\", rawRabbitsAvg))\r\n#\tprint(\"{:9s}{:>10.3f}\".format(\"Foxes:\", rawFoxesAvg))\r\n#\r\n#\r\n#\r\n#\r\n#\tdisplaystr = \"{:<10s}{:^20s}{:^19s}{:^20s}{:^29s}\".format(\"\", \"Rounded Values\", \"Floor Values\", #\"Ceil Values\", \"Raw Values\")\r\n#\tprint(displaystr)\r\n#\t\r\n#\tdisplaystr = \"{:>10s}{:>10s}{:>10s}{:>10s}{:>10s}{:>10s}{:>10s}{:>15s}{:>15s}\".format(\"Day\", #\"Rabbits\", \"Foxes\",\"Rabbits\", \"Foxes\",\"Rabbits\", \"Foxes\",\"Rabbits\", \"Foxes\")\r\n#\tprint(displaystr)\r\n#\t\r\n#\tprint(\"-\"*100)\r\n#\r\n#\tfor i in range(0, days+1, frequency):\r\n#\t\tstdoutdump = \"{:>10s}{:>10s}{:>10s}{:>10s}{:>10s}{:>10s}{:>10s}{:>15s}{:>15s}\".format(str(i), str(rabbitlr[i]), str(foxlr[i]), str(rabbitlfl[i]),str(foxlfl[i]), str(rabbitlceil[i]), str(foxlceil[i]),str(rabbitlraw[i]), str(foxlraw[i]))\r\n\r\n#\t\tprint(stdoutdump)\r\n\t\t# 5. calculate the new daily populations\r\n\t\r\n\t\r\n\t\t# 6. print out new day population information \r\n\r\n#\tprint()\t# adds a newline for nicer output. \r\n#\r\nrun_simulation()\r\n","sub_path":"assignment5/donohoe_hurst_assignment5/foxsim5.py","file_name":"foxsim5.py","file_ext":"py","file_size_in_byte":7089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"419822976","text":"import random\r\nimport math\r\n\r\n#\r\n# Forma abreviada:\r\n# \"dp_\" como um prefixo variável significa \"derivada parcial\"\r\n# \"d_\" como um prefixo variável significa \"derivado\"\r\n# \"_wrt_\" é uma abreviação de \"with respect to\" ou seja com pespeito a\r\n# \"w_ho\" e \"w_ih\" são o índice de pesos dos neurônios ocultos\r\n# para os neurônios da camada de saída e de entrada para os neurônios da camada oculta, respectivamente\r\n#\r\n# Referências de comentário:\r\n\r\n\r\nclass RedeNeural:\r\n TAXA_DE_APRENDIZAGEM = 0.5\r\n\r\n def __init__(self, numero_entrada, numero_escondido, numero_saida, peso_camada_escondida = None, vies_camada_oculta = None, peso_camada_saida = None, vies_camada_saida = None):\r\n self.num_inputs = numero_entrada\r\n\r\n self.hidden_layer = Camada_de_Neuronio(numero_escondido, vies_camada_oculta)\r\n self.output_layer = Camada_de_Neuronio(numero_saida, vies_camada_saida)\r\n\r\n self.peso_inicial_de_entrada_neuronios_de_camada_oculta(peso_camada_escondida)\r\n self.pesos_iniciais_de_neuronios_da_camada_oculta_para_neuronios_da_camada_de_saida(peso_camada_saida)\r\n\r\n def peso_inicial_de_entrada_neuronios_de_camada_oculta(self, camada_peso_oculta):\r\n numero_pesos = 0\r\n for h in range(len(self.hidden_layer.neurons)):\r\n for i in range(self.num_inputs):\r\n if not camada_peso_oculta:\r\n self.hidden_layer.neurons[h].weights.append(random.random())\r\n else:\r\n self.hidden_layer.neurons[h].weights.append(camada_peso_oculta[numero_pesos])\r\n numero_pesos += 1\r\n\r\n def pesos_iniciais_de_neuronios_da_camada_oculta_para_neuronios_da_camada_de_saida(self, camada_peso_saida):\r\n numero_pesos = 0\r\n for o in range(len(self.output_layer.neurons)):\r\n for h in range(len(self.hidden_layer.neurons)):\r\n if not camada_peso_saida:\r\n self.output_layer.neurons[o].weights.append(random.random())\r\n else:\r\n self.output_layer.neurons[o].weights.append(camada_peso_saida[numero_pesos])\r\n numero_pesos += 1\r\n\r\n def inspecionar(self):\r\n print('------')\r\n print('* Entradas: {}'.format(self.num_inputs))\r\n print('------')\r\n print('Camada oculta')\r\n self.hidden_layer.inspecionar()\r\n print('------')\r\n print('* Camada saida')\r\n self.output_layer.inspecionar()\r\n print('------')\r\n\r\n def alimentar_adiante(self, entradas):\r\n saida_camada_oculta = self.hidden_layer.seguir_adiante(entradas)\r\n return self.output_layer.seguir_adiante(saida_camada_oculta)\r\n\r\n # Usa aprendizado on-line, ou seja, atualiza os pesos após cada caso de treinamento\r\n def ensinar(self, entrada_ensino, saida_ensino):\r\n self.alimentar_adiante(entrada_ensino)\r\n\r\n # 1. Saída de deltas de neurônios\r\n erros_de_pd_pesos_escondidos_neuronios_total_entradas = [0] * len(self.output_layer.neurons)\r\n for o in range(len(self.output_layer.neurons)):\r\n\r\n # ∂E/∂zⱼ\r\n erros_de_pd_pesos_escondidos_neuronios_total_entradas[o] = self.output_layer.neurons[o].erro_calculo_dp_total_de_entradas(saida_ensino[o])\r\n\r\n # 2. Os deltas do neurônio oculto\r\n erros_de_pd_pesos_escondidos_neuronios_total_entradas = [0] * len(self.hidden_layer.neurons)\r\n for h in range(len(self.hidden_layer.neurons)):\r\n\r\n # Precisamos calcular a derivada do erro em relação à saída de cada neurônio de camada oculta\r\n # dE/dyⱼ = Σ ∂E/∂zⱼ * ∂z/∂yⱼ = Σ ∂E/∂zⱼ * wᵢⱼ\r\n erro_d_peso_oculto_neuronio_saida = 0\r\n for o in range(len(self.output_layer.neurons)):\r\n erro_d_peso_oculto_neuronio_saida += erros_de_pd_pesos_escondidos_neuronios_total_entradas[o] * self.output_layer.neurons[o].weights[h]\r\n\r\n # ∂E/∂zⱼ = dE/dyⱼ * ∂zⱼ/∂\r\n erros_de_pd_pesos_escondidos_neuronios_total_entradas[h] = erro_d_peso_oculto_neuronio_saida * self.hidden_layer.neurons[h].calculate_pd_total_entradas_com_entradas()\r\n\r\n # 3. Atualizar pesos de neurônios de saída\r\n for o in range(len(self.output_layer.neurons)):\r\n for w_ho in range(len(self.output_layer.neurons[o].weights)):\r\n\r\n # ∂Eⱼ/∂wᵢⱼ = ∂E/∂zⱼ * ∂zⱼ/∂wᵢⱼ\r\n pd_erro_peso = erros_de_pd_pesos_escondidos_neuronios_total_entradas[o] * self.output_layer.neurons[o].calculate_pd_total_entrada_com_pesos(w_ho)\r\n\r\n # Δw = α * ∂Eⱼ/∂wᵢ\r\n self.output_layer.neurons[o].weights[w_ho] -= self.TAXA_DE_APRENDIZAGEM * pd_erro_peso\r\n\r\n # 4. Atualizar pesos de neurônios ocultos\r\n for h in range(len(self.hidden_layer.neurons)):\r\n for w_ih in range(len(self.hidden_layer.neurons[h].weights)):\r\n\r\n # ∂Eⱼ/∂wᵢ = ∂E/∂zⱼ * ∂zⱼ/∂wᵢ\r\n pd_erro_peso = erros_de_pd_pesos_escondidos_neuronios_total_entradas[h] * self.hidden_layer.neurons[h].calculate_pd_total_entrada_com_pesos(w_ih)\r\n\r\n # Δw = α * ∂Eⱼ/∂wᵢ\r\n self.hidden_layer.neurons[h].weights[w_ih] -= self.TAXA_DE_APRENDIZAGEM * pd_erro_peso\r\n\r\n def calculo_erro_total(self, passos_ensino):\r\n total_de_erros = 0\r\n for t in range(len(passos_ensino)):\r\n entradas_de_ensino, saidas_de_ensino = passos_ensino[t]\r\n self.alimentar_adiante(entradas_de_ensino)\r\n for o in range(len(saidas_de_ensino)):\r\n total_de_erros += self.output_layer.neurons[o].calculo_de_erro(saidas_de_ensino[o])\r\n return total_de_erros\r\n\r\nclass Camada_de_Neuronio:\r\n def __init__(self, numero_de_neuronios, vies):\r\n\r\n # Cada neurônio em uma camada compartilha os mesmos vies\r\n self.bias = vies if vies else random.random()\r\n\r\n self.neurons = []\r\n for i in range(numero_de_neuronios):\r\n self.neurons.append(Neuronio(self.bias))\r\n\r\n def inspecionar(self):\r\n print('Neuronios:', len(self.neurons))\r\n for n in range(len(self.neurons)):\r\n print(' Neuronio', n)\r\n for w in range(len(self.neurons[n].weights)):\r\n print(' Peso:', self.neurons[n].weights[w])\r\n print(' Vies:', self.bias)\r\n\r\n def seguir_adiante(self, inputs):\r\n saidas = []\r\n for neuron in self.neurons:\r\n saidas.append(neuron.calculo_de_saidas(inputs))\r\n return saidas\r\n\r\n def obter_saida(self):\r\n saidas = []\r\n for neuron in self.neurons:\r\n saidas.append(neuron.output)\r\n return saidas\r\n\r\nclass Neuronio:\r\n def __init__(self, vies):\r\n self.bias = vies\r\n self.weights = []\r\n\r\n def calculo_de_saidas(self, saidas):\r\n self.inputs = saidas\r\n self.output = self.esmagar(self.calculo_total_de_entradas())\r\n return self.output\r\n\r\n def calculo_total_de_entradas(self):\r\n total = 0\r\n for i in range(len(self.inputs)):\r\n total += self.inputs[i] * self.weights[i]\r\n return total + self.bias\r\n\r\n # Aplique a função logística para esmagar a saída do neurônio\r\n # O resultado é por vezes referido como 'net' [2] ou 'net' [1]\r\n def esmagar(self, total_entradas):\r\n return 1 / (1 + math.exp(-total_entradas))\r\n\r\n #\r\n # Determine quanto a entrada total do neurônio precisa mudar para se aproximar da saída esperada\r\n # Agora que temos a derivada parcial do erro em relação à saída (∂E / ∂yⱼ) e\r\n # a derivada da saída em relação à entrada líquida total (dyⱼ / dzⱼ) podemos calcular\r\n # a derivada parcial do erro em relação à entrada líquida total.\r\n # Esse valor também é conhecido como o delta (δ) [1]\r\n # δ = ∂E/∂zⱼ = ∂E/∂yⱼ * dyⱼ/dzⱼ\r\n #\r\n def erro_calculo_dp_total_de_entradas(self, alvo_saida):\r\n return self.erro_calculo_dp_saida(alvo_saida) * self.calculate_pd_total_entradas_com_entradas();\r\n\r\n # O erro de cada neurônio é calculado pelo método do Erro Quadrático Médio:\r\n def calculo_de_erro(self, alvo_saida):\r\n return 0.5 * (alvo_saida - self.output) ** 2\r\n\r\n # A derivada parcial do erro em relação à saída real é calculada por:\r\n # = 2 * 0.5 * (saída de destino - saída real) ^ (2 - 1) * -1\r\n # = - (saída de destino - saída real)\r\n #\r\n # O artigo da Wikipédia sobre retropropagação [1] simplifica para o seguinte, mas a maioria dos outros materiais de aprendizagem não [2]\r\n # = saída real - saída de destino\r\n #\r\n # Alternativa, você pode usar (target-output), mas então precisa adicioná-la durante a retropropagação [3]\r\n #\r\n # Observe que a saída real do neurônio de saída é geralmente escrita como yⱼ e a saída de destino como tⱼ então:\r\n # = ∂E/∂yⱼ = -(tⱼ - yⱼ)\r\n\r\n def erro_calculo_dp_saida(self, alvo_saida):\r\n return -(alvo_saida - self.output)\r\n\r\n # A entrada líquida total no neurônio é esmagada usando a função logística para calcular a saída do neurônio:\r\n # yⱼ = φ = 1 / (1 + e ^ (- zⱼ))\r\n # Observe que onde ⱼ representa a saída dos neurônios em qualquer camada que estamos olhando e ᵢ representa a camada abaixo dela\r\n #\r\n # A derivada (não derivada parcial, uma vez que existe apenas uma variável) da saída é:\r\n # dyⱼ/dzⱼ = yⱼ * (1 - yⱼ)\r\n\r\n def calculate_pd_total_entradas_com_entradas(self):\r\n return self.output * (1 - self.output)\r\n\r\n # A entrada líquida total é a soma ponderada de todas as entradas para o neurônio e seus respectivos pesos:\r\n # = zⱼ = netⱼ = x₁w₁ + x₂w₂ ...\r\n #\r\n # A derivada parcial da entrada líquida total com o respectivo peso (com todo o resto mantido constante) e então:\r\n # = ∂zⱼ/∂wᵢ = alguma constante + 1 * xᵢw₁^(1-0) + alguma constante ... = xᵢ\r\n\r\n def calculate_pd_total_entrada_com_pesos(self, index):\r\n return self.inputs[index]\r\n\r\n###\r\n\r\nnn = RedeNeural(2, 2, 2, peso_camada_escondida=[0.15, 0.2, 0.25, 0.3], vies_camada_oculta=0.35, peso_camada_saida=[0.4, 0.45, 0.5, 0.55], vies_camada_saida=0.6)\r\nfor i in range(10000):\r\n nn.ensinar([0.05, 0.1], [0.01, 0.99])\r\n print(i, round(nn.calculo_erro_total([[[0.05, 0.1], [0.01, 0.99]]]), 9))\r\n\r\n# EXEMPLO:\r\n\r\n# passos_de_ensino = [\r\n# [[0, 0], [0]],\r\n# [[0, 1], [1]],\r\n# [[1, 0], [1]],\r\n# [[1, 1], [0]]\r\n# ]\r\n\r\n# nn = redeNeural(len(passos_de_ensino[0][0]), 5, len(passos_de_ensino[0][1]))\r\n# for i in range(10000):\r\n# entradas_ensino, saidas_ensino = random.choice(passos_de_ensino)\r\n# nn.ensinar(entradas_ensino, saidas_ensino)\r\n# print(i, nn.calculo_erro_total(passos_de_ensino))","sub_path":"backPropagation.py","file_name":"backPropagation.py","file_ext":"py","file_size_in_byte":10865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"566528043","text":"import torch\nimport torch.nn as nn\nimport numpy as np\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nfrom libs.tools.cfg import *\nfrom libs.models.cfam import CFAMBlock\nfrom libs.models.backbones_2d import darknet\nfrom libs.models.backbones_3d import mobilenet, shufflenet, mobilenetv2, shufflenetv2, resnext, resnet, slowfast\nfrom collections import OrderedDict\n\n\"\"\"\nYOWO model used in spatialtemporal action localization\n\"\"\"\n\n\nclass YOWO_slowfast(nn.Module):\n\n def __init__(self, opt):\n super(YOWO_slowfast, self).__init__()\n self.opt = opt\n \n ##### 2D Backbone #####\n if opt.backbone_2d == \"darknet\":\n self.backbone_2d = darknet.Darknet(\"configs/cfg/yolo.cfg\")\n num_ch_2d = 425 # Number of output channels for backbone_2d\n else:\n raise ValueError(\"Wrong backbone_2d model is requested. Please select\\\n it from [darknet]\")\n if opt.backbone_2d_weights:# load pretrained weights on COCO dataset\n self.backbone_2d.load_weights(opt.backbone_2d_weights) \n\n ##### 3D Backbone #####\n self.backbone_3d = slowfast.resnet50()\n num_ch_3d = 2048 # Number of output channels for backbone_3d\n\n if opt.backbone_3d_weights:# load pretrained weights on Kinetics-600 dataset\n #self.backbone_3d = slowfast.loadPretrained(self.backbone_3d, opt.backbone_3d_weights)\n pretrained_3d_backbone = torch.load(opt.backbone_3d_weights)\n\n backbone_3d_dict = OrderedDict()\n\n for k, v in pretrained_3d_backbone['state_dict'].items():\n ks = k.split('.')\n k = '.'.join(ks[1:])\n if k not in self.backbone_3d.state_dict():\n print(k)\n continue\n backbone_3d_dict[k] = v\n\n self.backbone_3d.load_state_dict(backbone_3d_dict) # 3. load the new state dict\n self.backbone_3d = self.backbone_3d.cuda()\n self.backbone_3d = nn.DataParallel(self.backbone_3d, device_ids=None) # Because the pretrained backbone models are saved in Dataparalled mode\n self.backbone_3d = self.backbone_3d.module # remove the dataparallel wrapper\n\n\n ##### Attention & Final Conv #####\n #############################\n self.slow_conv = nn.Conv2d(2048 + 256, 2048, kernel_size=3, stride=2, padding=1)\n self.fast_conv = nn.Conv3d(256, 256, kernel_size=(8, 1, 1), stride=1, padding=0)\n #############################\n self.cfam = CFAMBlock(num_ch_2d+num_ch_3d, 1024)\n self.conv_final = nn.Conv2d(1024, 5*(opt.n_classes+4+1), kernel_size=1, bias=False)\n self.seen = 0\n\n\n\n def forward(self, input):\n x_3d = input # Input clip\n x_2d = input[:, :, -1, :, :] # Last frame of the clip that is read\n\n x_2d = self.backbone_2d(x_2d)\n slow, fast = self.backbone_3d(x_3d)\n fast = self.fast_conv(fast)\n #print(fast.size(), slow.size())\n x_3d = self.slow_conv(torch.cat((slow, fast), dim=1).squeeze())\n #x_3d = self.backbone_3d(x_3d)\n #x_3d = torch.squeeze(x_3d, dim=2)\n #print(x_3d.size(), x_2d.size())\n x = torch.cat((x_3d, x_2d), dim=1)\n x = self.cfam(x)\n\n out = self.conv_final(x)\n\n return out\n\n\ndef get_fine_tuning_parameters_slowfast(model, opt):\n ft_module_names = ['cfam', 'conv_final', 'slow_conv', 'fast_conv'] # Always fine tune 'cfam' and 'conv_final'\n if not opt.freeze_backbone_2d:\n ft_module_names.append('backbone_2d') # Fine tune complete backbone_3d\n else:\n ft_module_names.append('backbone_2d.models.29') # Fine tune only layer 29 and 30\n ft_module_names.append('backbone_2d.models.30') # Fine tune only layer 29 and 30\n\n if not opt.freeze_backbone_3d:\n ft_module_names.append('backbone_3d') # Fine tune complete backbone_3d\n else:\n ft_module_names.append('backbone_3d.slow_res5') # Fine tune only layer 4\n ft_module_names.append('backbone_3d.fast_res5') # Fine tune only layer 4\n\n\n parameters = []\n for k, v in model.named_parameters():\n for ft_module in ft_module_names:\n if ft_module in k:\n print(k)\n parameters.append({'params': v})\n break\n else:\n parameters.append({'params': v, 'lr': 0.0})\n \n return parameters\n","sub_path":"one_stage_action_detection/libs/models/model_slowfast.py","file_name":"model_slowfast.py","file_ext":"py","file_size_in_byte":4419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"596927188","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 18 12:13:05 2018\n\n@author: marti\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef lin_reg(data_x,data_y,epsilon):\n #input pairs (x,y) and privacy budget epsilon; each line of data_x is supposed to be one input vector\n #assume both data_x and data_y are numpy arrays\n (n,d)=data_x.shape\n \n #assuming data_x and data_y don't have absolute value greater than 1\n Delta=2*(1+2*d+d^2)\n # j = 1 : linear terms (in w) in objective function\n # lambd_1 is a d dimensional array holding all the coefficients for the d monomials in w\n lambd_1=-2*data_y.dot(data_x)+np.random.laplace(scale=Delta/epsilon,size=d)\n # j = 2: quadratic terms (in w) in objective function\n # lambd_2 is a d x d dimensional array holding all the coefficients for the d x d quadratic terms of form w_j*w_l\n lambd_2=data_x.transpose().dot(data_x)+np.random.laplace(scale=Delta/epsilon)\n \n lambd_2_new=lambd_2+np.transpose(lambd_2)\n #solve quadratic optimization problem: minimize lambd_0+lambd_1^T*w+1/2w^T*lambd_2_new*w\n #==> solve lambd_2_new * w = -lambd_1\n w=np.linalg.solve(lambd_2_new,-lambd_1)\n return(w)\n\ndef lin(w, x):\n return w[1]*x+w[0]\n \n#data_x = np.array([[1,0.2],[1,0.4],[1,0.6]]) # add a x_0 = 1 coordinate for computing w_0\n#data_y = np.array([0.1,0.5,0.6])\n\nNmin = 5\nNmax = 20000\nQ = 100\nError1 = np.zeros(Nmax-Nmin)\nMeanError1 = np.zeros(Nmax-Nmin)\nError2 = np.zeros(Nmax-Nmin)\nMeanError2 = np.zeros(Nmax-Nmin)\nError3 = np.zeros(Nmax-Nmin)\nMeanError3 = np.zeros(Nmax-Nmin)\ndata_x = np.zeros((Nmax,2))\ndata_x[:,0] = np.ones((Nmax))\ndata_x[:,1] = np.linspace(0,1,Nmax)\ndata_y = data_x[:,1]*10+5+np.random.rand(Nmax)\n\nfor j in range(Q):\n \n for n in range(Nmin,Nmax):\n w = lin_reg(data_x[0:n],data_y[0:n],10)\n Error1[n-Nmin] = np.mean((lin(w,data_x[:,1])-data_y)**2) \n w = lin_reg(data_x[0:n],data_y[0:n],1)\n Error2[n-Nmin] = np.mean((lin(w,data_x[:,1])-data_y)**2) \n w = lin_reg(data_x[0:n],data_y[0:n],0.1)\n Error3[n-Nmin] = np.mean((lin(w,data_x[:,1])-data_y)**2) \n MeanError1 = MeanError1+Error1\n MeanError2 = MeanError2+Error2\n MeanError3 = MeanError3+Error3\nMeanError1 = MeanError1/Q\nMeanError2 = MeanError2/Q\nMeanError3 = MeanError3/Q\n\n#plt.plot(np.linspace(Nmin,Nmax,Nmax-Nmin),MeanError1,color='red')\n#plt.plot(np.linspace(Nmin,Nmax,Nmax-Nmin),MeanError2,color='blue',linestyle='--')\nplot1, = plt.plot(np.linspace(Nmin,Nmax,Nmax-Nmin),MeanError1,color='red', label='eps=10')\nplot2, = plt.plot(np.linspace(Nmin,Nmax,Nmax-Nmin),MeanError2,color='blue',linestyle='--', label='eps=1')\nplot3, = plt.plot(np.linspace(Nmin,Nmax,Nmax-Nmin),MeanError3,color='green',linestyle='-.', label='eps=0.1')\nplt.legend(handles=[plot1, plot2, plot3])\nplt.axis([Nmin,Nmax,0,1]) # Try to remove this\nplt.show()\n\n\n\n#plt.scatter(data_x[:,1],data_y,color='red')\n#plt.plot(data_x[0:n],lin(w,data_x[0:n]),color='blue',linestyle='--')\n#plt.show()\n\n\n\n","sub_path":"Learning_Curve_for_Linear_Regression.py","file_name":"Learning_Curve_for_Linear_Regression.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"299865191","text":"import datetime\nimport os.path\nimport sys\nimport backtrader as bt\nimport matplotlib.pyplot as pl\n\nclass MyHLOC(bt.feeds.GenericCSVData):\n # datetime, O, H, L, C, V, OI, WAP\n params = (\n # ('fromdate', datetime.datetime(2020, 4, 1)),\n # ('todate', datetime.datetime(2020, 4, 2)),\n ('nullvalue', 0.0),\n # ('dtformat', ('%Y-%m-%d')),\n # ('tmformat', ('%H.%M.%S')),\n ('timeframe', bt.TimeFrame.Minutes),\n ('datetime', 0),\n ('open', 1),\n ('high', 2),\n ('low', 3),\n ('close', 4),\n ('volume', 5),\n ('openinterest', 6)\n)\n\n\n# Create a Stratey\nclass SmartPattern1(bt.Strategy):\n def __init__(self):\n self.dataopen = self.data.open(-1)\n self.datahigh = self.data.high(-1)\n self.datalow = self.data.low(-1)\n self.dataclose = self.data.close(-1)\n\n self.st1_30 = bt.indicators.StochasticFast(self.datas[-1], period=30, period_dfast=1)\n self.st2_24 = bt.indicators.StochasticFast(self.datas[-1], period=24, period_dfast=1)\n\n\n\n self.order = None # Property to keep track of pending orders. There are no orders when the strategy is initialized.\n self.buyprice = None\n self.buycomm = None\n\n def log(self, txt, dt=None):\n # Logging function for the strategy. 'txt' is the statement and 'dt' can be used to specify a specific datetime\n dt = dt or self.datas[0].datetime.datetime(0)\n print('{0},{1}'.format(dt.isoformat(), txt))\n\n def notify_order(self, order):\n # 1. If order is submitted/accepted, do nothing\n if order.status in [order.Submitted, order.Accepted]:\n return\n # 2. If order is buy/sell executed, report price executed\n if order.status in [order.Completed]:\n if order.isbuy():\n self.log('BUY EXECUTED, Price: {0:8.2f}, Size: {1:8.2f} Cost: {2:8.2f}, Comm: {3:8.2f}'.format(\n order.executed.price,\n order.executed.size,\n order.executed.value,\n order.executed.comm))\n\n self.buyprice = order.executed.price\n self.buycomm = order.executed.comm\n else:\n self.log('SELL EXECUTED, {0:8.2f}, Size: {1:8.2f} Cost: {2:8.2f}, Comm{3:8.2f}'.format(\n order.executed.price,\n order.executed.size,\n order.executed.value,\n order.executed.comm))\n\n self.bar_executed = len(self) # when was trade executed\n # 3. If order is canceled/margin/rejected, report order canceled\n elif order.status in [order.Canceled, order.Margin, order.Rejected]:\n self.log('Order Canceled/Margin/Rejected')\n self.order = None\n\n def notify_trade(self, trade):\n if not trade.isclosed:\n return\n\n self.log('OPERATION PROFIT, GROSS {0:8.2f}, NET {1:8.2f}'.format(\n trade.pnl, trade.pnlcomm))\n\n def next(self):\n\n if self.order: # check if order is pending, if so, then break out\n return\n self.my_signal_24 = (80 > self.st2_24[0] > 40) or (80 > self.st2_24[0] > 40)\n self.my_signal_30 = (80 > self.st1_30[0] > 40) or (80 > self.st1_30[0] > 40)\n\n if datetime.time(9, 29) < self.data.datetime.time() < datetime.time(15, 29):\n if not self.position: # not in the market\n if (self.my_signal_30 or self.my_signal_24) and self.data.open[0] > self.sip:\n o1 = self.buy(size=1,\n exectype=bt.Order.Market,\n price=self.entry_price,\n valid=bt.Order.DAY,\n transmit=True)\n\n print('{}: Oref {} / Buy at {}'.format(\n self.datetime.datetime(), o1.ref, self.entry_price))\n\n o2 = self.sell(size=1,\n exectype=bt.Order.Stop,\n price=self.smart_stop,\n valid=bt.Order.DAY,\n parent=o1)\n\n print('{}: Oref {} / Sell Stop at {}'.format(\n self.datetime.datetime(), o2.ref, self.smart_stop))\n\n if self.position.size != 0 and self.data.datetime.time() > datetime.time(15, 31):\n print(\"EOD Closing Position\")\n self.close(exectype=bt.Order.Market, size=1)\n print(\"Position : \" , self.position)\n\n\nif __name__ == '__main__':\n # Create a cerebro entity\n cerebro = bt.Cerebro()\n\n # Datas are in a subfolder of the samples. Need to find where the script is\n # because it could have been called from anywhere\n modpath = os.path.dirname(os.path.abspath(sys.argv[0]))\n # datapath = os.path.join(modpath, '../../datas/orcl-1995-2014.txt')\n datapath = '/Users/sponraj/Desktop/History_Data/ES/2020/04_ESU2020_FUT.csv'\n # Create a Data Feed datetime,O,H,L,C,V,OI,WAP\n data0 = MyHLOC(dataname=datapath)\n # cerebro.adddata(data0)\n cerebro.resampledata(data0, timeframe=bt.TimeFrame.Minutes, compression=15)\n\n # Add a strategy\n cerebro.addstrategy(SmartPattern1)\n\n # store = bt.stores.IBStore(port=7497)\n # stockkwargs = dict(\n # timeframe=bt.TimeFrame.Minutes,\n # rtbar=False, # use RealTime 5 seconds bars\n # historical=True, # only historical download\n # qcheck=0.5, # timeout in seconds (float) to check for events\n # fromdate=datetime.datetime(2019, 9, 24), # get data from..\n # todate=datetime.datetime(2019, 9, 25), # get data from..\n # latethrough=False, # let late samples through\n # tradename=None # use a different asset as order target\n # )\n # data0 = store.getdata(dataname=\"AAPL-STK-SMART-USD\", **stockkwargs)\n # Set our desired cash start\n cerebro.broker.setcash(10000.0)\n cerebro.broker.setcommission(commission=0.001)\n # Print out the starting conditions\n print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())\n\n # Run over everything\n cerebro.run()\n\n # Print out the final result\n print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())\n","sub_path":"backtrader/SmartPattern1.py","file_name":"SmartPattern1.py","file_ext":"py","file_size_in_byte":6233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"393290270","text":"# migrate-to-fis.py\n\n# This example will migrate all ingested file data to a new SystemLink server\n\nimport os, subprocess, json, shutil\n\n# Set variables for various paths used during migration\nmigration_dir = \"C:\\migration\"\nno_sql_dump_dir = os.path.join(migration_dir, \"mongo-dump\")\nprogram_file_dir = os.environ.get(\"ProgramW6432\")\nprogram_data_dir = os.environ.get(\"ProgramData\")\nfis_data_source_dir = os.path.join(program_data_dir, \"National Instruments\", \"Skyline\", \"Data\", \"FileIngestion\")\nfis_data_migration_dir = os.path.join(migration_dir, \"FileIngestion\")\nmongo_restore = os.path.join(program_file_dir, \"National Instruments\", \"Shared\", \"Skyline\", \"NoSqlDatabase\", \"bin\", \"mongorestore.exe\")\n\n# Get data from service's json config file \nservice= \"FileIngestion\"\nconfig_file = os.path.join(program_data_dir, \"National Instruments\", \"Skyline\", \"Config\", service+\".json\")\nwith open(config_file, encoding='utf-8-sig') as json_file:\n config = json.load(json_file)\n\n# Restore mongo database from contents of migration directory\nmongo_dump_file = os.path.join(no_sql_dump_dir, config[service]['Mongo.Database'])\nmongo_restore_cmd = mongo_restore + \" --port \" + str(config[service]['Mongo.Port']) + \" --db \" + config[service]['Mongo.Database'] + \" --username \" + config[service]['Mongo.User'] + \" --password \" + config[service]['Mongo.Password'] + \" --gzip \" + mongo_dump_file\nsubprocess.run(mongo_restore_cmd)\n\n# Copy file from migration directory to data directory \nmigration_files = os.listdir(fis_data_migration_dir)\nfor file_name in migration_files:\n full_file_path = os.path.join(fis_data_migration_dir, file_name)\n if os.path.isfile(full_file_path):\n shutil.copy(full_file_path, fis_data_source_dir)","sub_path":"basic_scripts/file ingestion/migrate-to-fis.py","file_name":"migrate-to-fis.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"99499300","text":"import os\nfrom os.path import join\nfrom astropy.io import fits\nimport numpy as np\nfrom scipy.ndimage import rotate\nfrom PIL import Image\nfrom tqdm import tqdm\n\ndir_fits = './datasets/Fits/VSM'\ndir_images = './datasets/Images/VSM'\nos.makedirs(dir_images) if not os.path.isdir(dir_images) else None\n\nlist_fits_name = sorted(os.listdir(dir_fits))[1789:]\nlist_error_fits = list()\nfor name in tqdm(list_fits_name):\n path = join(dir_fits, name)\n hdul = fits.open(path)\n try:\n header = hdul[0].header\n data = hdul[0].data\n # print(repr(header))\n except TypeError:\n print(name)\n list_error_fits.append(name)\n continue\n\n NAXIS1 = int(header['NAXIS1'])\n NAXIS2 = int(header['NAXIS2'])\n\n CENTER_X = int(np.around(float(header['IMG_X0'])))\n CENTER_Y = int(np.around(float(header['IMG_Y0'])))\n\n RADIUS = float(header['IMG_R0'])\n RADIUS_int = int(np.ceil(float(header['IMG_R0'])))\n ratio = 392. / RADIUS\n\n # P0 = float(header['OBS_P'])\n\n # Centering\n data = data[CENTER_Y - RADIUS_int - 20: CENTER_Y + RADIUS_int + 21, CENTER_X - RADIUS_int - 20:\n CENTER_X + RADIUS_int + 21]\n original_width, original_height = data.shape[1], data.shape[0]\n\n # Resizing\n data = Image.fromarray(data).resize((int(np.around(original_width * ratio)),\n int(np.around(original_height * ratio))))\n data = np.array(data)\n\n # Rotating\n # data = rotate(data, -P0, reshape=False)\n\n # Padding\n width, height = data.shape[1], data.shape[0]\n pad_width = (1024 - width) // 2\n pad_height = (1024 - height) // 2\n data = np.pad(data, ((pad_height, pad_height), (pad_width, pad_width)), 'constant')\n width, height = data.shape\n if width != 1024:\n pad = 1024 - width\n if pad % 2 == 0:\n data = np.pad(data, ((0, 0), (pad // 2, pad // 2)), 'constant')\n else:\n assert pad == 1, print(name)\n data = np.pad(data, ((0, 0), (pad, 0)), 'constant')\n\n if height != 1024:\n pad = 1024 - height\n if pad % 2 == 0:\n data = np.pad(data, ((pad // 2, pad // 2), (0, 0)), 'constant')\n else:\n assert pad == 1, print(name)\n data = np.pad(data, ((pad, 0), (0, 0)), 'constant')\n\n assert data.shape == (1024, 1024)\n\n data -= data.min()\n data = data / data.max()\n data *= 255.0\n data = data.astype(np.uint8)\n\n image = Image.fromarray(data)\n name = name.strip('k4v82_cont.fts')\n name = name.replace('t', '_')\n name = '20' + name + '.png'\n\n image.save(join(dir_images, name))\n del header, data, hdul, image\n\nwith open(join(dir_fits, 'ErrorFits.txt'), 'wt') as log:\n for name in list_error_fits:\n log.write(name + '\\n')\n log.close()\n","sub_path":"preprocessing_VSM.py","file_name":"preprocessing_VSM.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"127984568","text":"import argparse\nimport json\nimport pandas as pd\nimport pickle\n\nfrom galaxy_ml.utils import load_model, read_columns\nfrom sklearn.pipeline import Pipeline\n\n\ndef _get_X_y(params, infile1, infile2):\n \"\"\" read from inputs and output X and y\n\n Parameters\n ----------\n params : dict\n Tool inputs parameter\n infile1 : str\n File path to dataset containing features\n infile2 : str\n File path to dataset containing target values\n\n \"\"\"\n # store read dataframe object\n loaded_df = {}\n\n input_type = params['input_options']['selected_input']\n # tabular input\n if input_type == 'tabular':\n header = 'infer' if params['input_options']['header1'] else None\n column_option = (params['input_options']['column_selector_options_1']\n ['selected_column_selector_option'])\n if column_option in ['by_index_number', 'all_but_by_index_number',\n 'by_header_name', 'all_but_by_header_name']:\n c = params['input_options']['column_selector_options_1']['col1']\n else:\n c = None\n\n df_key = infile1 + repr(header)\n df = pd.read_csv(infile1, sep='\\t', header=header,\n parse_dates=True)\n loaded_df[df_key] = df\n\n X = read_columns(df, c=c, c_option=column_option).astype(float)\n # sparse input\n elif input_type == 'sparse':\n X = mmread(open(infile1, 'r'))\n\n # Get target y\n header = 'infer' if params['input_options']['header2'] else None\n column_option = (params['input_options']['column_selector_options_2']\n ['selected_column_selector_option2'])\n if column_option in ['by_index_number', 'all_but_by_index_number',\n 'by_header_name', 'all_but_by_header_name']:\n c = params['input_options']['column_selector_options_2']['col2']\n else:\n c = None\n\n df_key = infile2 + repr(header)\n if df_key in loaded_df:\n infile2 = loaded_df[df_key]\n else:\n infile2 = pd.read_csv(infile2, sep='\\t',\n header=header, parse_dates=True)\n loaded_df[df_key] = infile2\n\n y = read_columns(\n infile2,\n c=c,\n c_option=column_option,\n sep='\\t',\n header=header,\n parse_dates=True)\n if len(y.shape) == 2 and y.shape[1] == 1:\n y = y.ravel()\n\n return X, y\n\n\ndef main(inputs, infile_estimator, infile1, infile2, out_object,\n out_weights=None):\n \"\"\" main\n\n Parameters\n ----------\n inputs : str\n File path to galaxy tool parameter\n\n infile_estimator : str\n File paths of input estimator\n\n infile1 : str\n File path to dataset containing features\n\n infile2 : str\n File path to dataset containing target labels\n\n out_object : str\n File path for output of fitted model or skeleton\n\n out_weights : str\n File path for output of weights\n\n \"\"\"\n with open(inputs, 'r') as param_handler:\n params = json.load(param_handler)\n\n # load model\n with open(infile_estimator, 'rb') as est_handler:\n estimator = load_model(est_handler)\n\n X_train, y_train = _get_X_y(params, infile1, infile2)\n\n estimator.fit(X_train, y_train)\n \n main_est = estimator\n if isinstance(main_est, Pipeline):\n main_est = main_est.steps[-1][-1]\n if hasattr(main_est, 'model_') \\\n and hasattr(main_est, 'save_weights'):\n if out_weights:\n main_est.save_weights(out_weights)\n del main_est.model_\n del main_est.fit_params\n del main_est.model_class_\n del main_est.validation_data\n if getattr(main_est, 'data_generator_', None):\n del main_est.data_generator_\n\n with open(out_object, 'wb') as output_handler:\n pickle.dump(estimator, output_handler,\n pickle.HIGHEST_PROTOCOL)\n\n\nif __name__ == '__main__':\n aparser = argparse.ArgumentParser()\n aparser.add_argument(\"-i\", \"--inputs\", dest=\"inputs\", required=True)\n aparser.add_argument(\"-X\", \"--infile_estimator\", dest=\"infile_estimator\")\n aparser.add_argument(\"-y\", \"--infile1\", dest=\"infile1\")\n aparser.add_argument(\"-g\", \"--infile2\", dest=\"infile2\")\n aparser.add_argument(\"-o\", \"--out_object\", dest=\"out_object\")\n aparser.add_argument(\"-t\", \"--out_weights\", dest=\"out_weights\")\n args = aparser.parse_args()\n\n main(args.inputs, args.infile_estimator, args.infile1,\n args.infile2, args.out_object, args.out_weights)\n","sub_path":"tools/sklearn/simple_model_fit.py","file_name":"simple_model_fit.py","file_ext":"py","file_size_in_byte":4548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"94303071","text":"#!/usr/bin/env python3\r\n# coding:utf-8\r\n\r\n\"\"\"\r\n @Time : 2019/2/28 15:31\r\n @Author : xmxoxo (xmhexi@163.com)\r\n @File : tran_service.py\r\n\"\"\"\r\nimport argparse\r\nimport flask\r\nimport logging\r\nimport json\r\nimport os\r\nimport re\r\nimport sys\r\nimport string\r\nimport time\r\nimport numpy as np\r\n\r\nfrom bert_base.client import BertClient\r\n\r\n\r\n# 切分句子\r\ndef cut_sent(txt):\r\n # 先预处理去空格等\r\n txt = re.sub('([  \\t]+)', r\" \", txt) # blank word\r\n txt = txt.rstrip() # 段尾如果有多余的\\n就去掉它\r\n nlist = txt.split(\"\\n\")\r\n nnlist = [x for x in nlist if x.strip() != ''] # 过滤掉空行\r\n return nnlist\r\n\r\n##将输入的文本的标点符号给取出来\r\ndef add_labels(list_text):\r\n sentence_labels_list = []###所有句子的带有标点的嵌套list [[句子1.。。],[句子2.。。],...]\r\n labels = ['.', ',', '!', '?', '\\'']\r\n for i in range(len(list_text)):\r\n\r\n strip_sentence=list_text[i].strip()##去掉句子里的空白的字符\r\n # print(strip_sentence)\r\n strip_sentence_list=strip_sentence.split()\r\n one_sentence_list=[] ##一句话的list\r\n for j in range(len(strip_sentence_list)):\r\n if strip_sentence_list[j][len(strip_sentence_list[j])-1] in labels:###单词是末尾\r\n one_sentence_list.append(strip_sentence_list[j][0:len(strip_sentence_list[j])-1])##最后的单词\r\n one_sentence_list.append(strip_sentence_list[j][len(strip_sentence_list[j])-1])##句末标点\r\n else:##非句子末尾\r\n one_sentence_list.append(strip_sentence_list[j])\r\n sentence_labels_list.append(one_sentence_list)\r\n return sentence_labels_list\r\n\r\ndef addTokenColors(tokens,pred_label):\r\n addColorSrting=''\r\n oneParagraphString=''\r\n for i in range(len(tokens)):\r\n paragraph=tokens[i]\r\n last_word = ''\r\n last_entity = ''\r\n new_word = ''\r\n new_entity = ''\r\n oneParagraphString = ''\r\n underline=0###开关变量,判断句子是否需要添加下划线,暂时这样以后修改\r\n for j in range(len(paragraph)):\r\n # print(paragraph[j])\r\n if paragraph[j]!='[SEP]' and paragraph[j]!='[CLS]':\r\n ###这里本来是想表达的是:不需要分解的字符串,但是其实是不对的,像有些符号,如()、-等,都是X标签,都是分解的,但没有##\r\n if not paragraph[j].startswith(\"##\") and not pred_label[i][j] == 'X': ###不是以##开头的真实\r\n if j>0:\r\n last_entity=new_entity\r\n last_word=new_word\r\n new_word=paragraph[j]\r\n new_entity=pred_label[i][j]\r\n # print(last_word,' 333 ',last_entity)\r\n if last_entity.__contains__('CMP'):\r\n oneParagraphString += '<font color = \"#FF0000\" >'\r\n oneParagraphString += last_word\r\n oneParagraphString += '</font>'\r\n oneParagraphString += ' '\r\n if last_entity.__contains__('MTH'):\r\n oneParagraphString += '<font color = \"#FFFF00\" >'\r\n oneParagraphString += last_word\r\n oneParagraphString += '</font>'\r\n oneParagraphString += ' '\r\n if last_entity.__contains__('SVN'):\r\n oneParagraphString += '<font color = \"#00FFFF\" >'\r\n oneParagraphString += last_word\r\n oneParagraphString += '</font>'\r\n oneParagraphString += ' '\r\n if last_entity.__contains__('BON'):\r\n oneParagraphString += '<font color = \"#F200F2\" >'\r\n oneParagraphString += last_word\r\n oneParagraphString += '</font>'\r\n oneParagraphString += ' '\r\n if last_entity.__contains__('RCT'):\r\n oneParagraphString += '<font color = \"#FFA500\" >'\r\n oneParagraphString += last_word\r\n oneParagraphString += '</font>'\r\n oneParagraphString += ' '\r\n if last_entity.__contains__('ENG'):\r\n oneParagraphString += '<font color = \"#22ff00\" >'\r\n oneParagraphString += last_word\r\n oneParagraphString += '</font>'\r\n oneParagraphString += ' '\r\n if last_entity.__contains__('EGVL'):\r\n # oneParagraphString += '<font color = \"#0131A7\" >'\r\n oneParagraphString += '<font color = \"#FF3399\" >'\r\n oneParagraphString += last_word\r\n oneParagraphString += '</font>'\r\n oneParagraphString += ' '\r\n underline=1\r\n if last_entity.__contains__('O'):\r\n oneParagraphString += last_word\r\n oneParagraphString += ' '\r\n else:\r\n new_word=paragraph[j]\r\n new_entity=pred_label[i][j]\r\n else:\r\n if paragraph[j].__contains__('##'):\r\n stripToken=paragraph[j].replace('##','')\r\n new_word+=stripToken\r\n else:\r\n new_word +=paragraph[j]\r\n # print(paragraph[j])\r\n # print(oneParagraphString,' 222')\r\n if underline==0:\r\n addColorSrting+=oneParagraphString\r\n addColorSrting+='<br>'\r\n else:\r\n addColorSrting +='<u>'\r\n addColorSrting += oneParagraphString\r\n addColorSrting += '</u>'\r\n addColorSrting += '<br>'\r\n print(addColorSrting,' !!!')\r\n return addColorSrting\r\n\r\n\r\n# 对句子进行预测识别\r\ndef ner_pred(list_text):\r\n # 文本拆分成句子\r\n # list_text = cut_sent(text)\r\n print(\"total setance: %d\" % (len(list_text)))\r\n print(list_text,' list_text')\r\n with BertClient(ip='0.0.0.0', port=5575, port_out=5576, show_server_config=False, check_version=False,\r\n check_length=False, timeout=10000, mode='NER') as bc:\r\n start_t =time.perf_counter()\r\n print('list_text: ',list_text)\r\n result = bc.encode(list_text, is_tokenized=False)\r\n\r\n print('time used:{}'.format(time.perf_counter() - start_t))\r\n\r\n result_txt = [result[i] for i in range(len(result))]\r\n result_dict = {}\r\n for i in range(len(result)):\r\n # print(result[i]) ###将[{}]中,被[]括起来的{}拿出来\r\n result_dict = result[i]\r\n return result_dict\r\n ##################################测试代码################################\r\n\r\n\r\n\r\ndef flask_server(args):\r\n pass\r\n from flask import Flask, request, render_template, jsonify\r\n\r\n app = Flask(__name__)\r\n\r\n # from app import routes\r\n\r\n @app.route('/')\r\n def index():\r\n return render_template('index.html', version='V 0.1.3')\r\n\r\n @app.route('/api/v0.1/query', methods=['POST'])\r\n def query():\r\n res = {}\r\n txt = request.values['text']\r\n if not txt:\r\n res[\"result\"] = \"error\"\r\n return jsonify(res)\r\n lstseg = cut_sent(txt)\r\n print('-' * 30)\r\n print('结果,共%d个句子:' % (len(lstseg)))\r\n for x in lstseg:\r\n print(\"第%d句:【 %s】\" % (lstseg.index(x), x))\r\n print('-' * 30)\r\n if request.method == 'POST' or 1:\r\n result_dict = ner_pred(lstseg)\r\n print('result: ', result_dict)\r\n final=addTokenColors(result_dict['tokens'], result_dict['pred_label'])\r\n\r\n return final\r\n\r\n app.run(\r\n host=args.ip, # '0.0.0.0',\r\n port=args.port, # 8910,\r\n debug=True\r\n )\r\n\r\n\r\ndef main_cli():\r\n pass\r\n parser = argparse.ArgumentParser(description='API demo server')\r\n parser.add_argument('-ip', type=str, default=\"127.0.0.1\",\r\n help='chinese google bert model serving')\r\n parser.add_argument('-port', type=int, default=8910,\r\n help='listen port,default:8910')\r\n\r\n args = parser.parse_args()\r\n\r\n flask_server(args)\r\n\r\n\r\nif __name__ == '__main__':\r\n main_cli()","sub_path":"mobile_apisvr/api_service.py","file_name":"api_service.py","file_ext":"py","file_size_in_byte":8649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"330951459","text":"# -*- encoding: utf-8 -*-\n\nfrom openerp.report import report_sxw\nimport time\nimport datetime\nimport logging\n\nclass compras_reporte(report_sxw.rml_parse):\n def __init__(self, cr, uid, name, context):\n super(compras_reporte, self).__init__(cr, uid, name, context=context)\n self.totales = {}\n self.folioActual = -1\n self.lineasGuardadas = []\n self.localcontext.update( {\n 'time': time,\n 'datetime': datetime,\n 'lineas': self.lineas,\n 'totales': self.totales,\n 'folio': self.folio,\n })\n self.context = context\n self.cr = cr\n self.uid = uid\n\n def folio(self, datos):\n\n if self.folioActual < 0:\n if datos[0].folio_inicial <= 0:\n self.folioActual = 1\n else:\n self.folioActual = datos[0].folio_inicial\n else:\n self.folioActual += 1\n\n return self.folioActual\n\n def lineas(self, datos):\n\n if len(self.lineasGuardadas) > 0:\n return self.lineasGuardadas\n\n self.totales['compra'] = {'exento':0,'neto':0,'iva':0,'total':0}\n self.totales['servicio'] = {'exento':0,'neto':0,'iva':0,'total':0}\n self.totales['importacion'] = {'exento':0,'neto':0,'iva':0,'total':0}\n self.totales['combustible'] = {'exento':0,'neto':0,'iva':0,'total':0}\n self.totales['pequenio_contribuyente'] = {'exento':0,'neto':0,'iva':0,'total':0}\n\n journal_ids = [x.id for x in datos.diarios_id]\n period_ids = [x.id for x in datos.periodos_id]\n facturas = self.pool.get('account.invoice').search(self.cr, self.uid, [\n ('state','in',['open','paid']), ('journal_id','in',journal_ids), ('period_id','in',period_ids)\n ], order='date_invoice')\n\n lineas = []\n for f in self.pool.get('account.invoice').browse(self.cr, self.uid, facturas):\n\n tipo_cambio = 1\n if f.currency_id.id != f.company_id.currency_id.id:\n total = 0\n for l in f.move_id.line_id:\n if l.account_id.id == f.account_id.id:\n total += l.credit - l.debit\n tipo_cambio = abs(total / f.amount_total)\n\n tipo = 'FACT'\n if f.type != 'in_invoice':\n tipo = 'NC'\n if f.pequenio_contribuyente:\n tipo += ' PEQ'\n\n linea = {\n 'estado': f.state,\n 'tipo': tipo,\n 'fecha': f.date_invoice,\n 'numero': f.supplier_invoice_number or f.reference or '',\n 'proveedor': f.partner_id,\n 'compra': 0,\n 'compra_exento': 0,\n 'servicio': 0,\n 'servicio_exento': 0,\n 'combustible': 0,\n 'combustible_exento': 0,\n 'importacion': 0,\n 'importacion_exento': 0,\n 'base': 0,\n 'iva': 0,\n 'total': 0\n }\n\n for l in f.invoice_line:\n precio = ( l.price_unit * (1-(l.discount or 0.0)/100.0) ) * tipo_cambio\n if tipo == 'NC':\n precio = precio * -1\n\n r = self.pool.get('account.tax').compute_all(self.cr, self.uid, l.invoice_line_tax_id, precio, l.quantity, product=l.product_id, partner=l.invoice_id.partner_id)\n\n linea['base'] += r['total']\n if len(l.invoice_line_tax_id) > 0:\n linea[f.tipo_gasto] += r['total']\n for i in r['taxes']:\n if i['base_code_id'] == datos.base_id.id and i['tax_code_id'] == datos.impuesto_id.id:\n linea['iva'] += i['amount']\n elif i['amount'] > 0:\n linea[f.tipo_gasto+'_exento'] += i['amount']\n else:\n linea[f.tipo_gasto+'_exento'] += r['total']\n\n linea['total'] = linea[f.tipo_gasto] + linea['iva']\n if f.pequenio_contribuyente:\n linea['total'] = linea[f.tipo_gasto+'_exento']\n\n if f.pequenio_contribuyente:\n self.totales['pequenio_contribuyente']['exento'] += linea[f.tipo_gasto+'_exento']\n self.totales['pequenio_contribuyente']['neto'] += linea[f.tipo_gasto]\n self.totales['pequenio_contribuyente']['iva'] += linea['iva']\n self.totales['pequenio_contribuyente']['total'] += linea['total']\n\n self.totales[f.tipo_gasto]['exento'] += linea[f.tipo_gasto+'_exento']\n self.totales[f.tipo_gasto]['neto'] += linea[f.tipo_gasto]\n self.totales[f.tipo_gasto]['iva'] += linea['iva']\n self.totales[f.tipo_gasto]['total'] += linea['total']\n\n lineas.append(linea)\n\n self.lineasGuardadas = lineas\n\n return lineas\n\nreport_sxw.report_sxw('report.compras_reporte', 'l10n_gt_extra.asistente_compras_reporte', 'addons/l10n_gt_extra/report/compras_reporte.rml', parser=compras_reporte, header=False)\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"report/compras_reporte.py","file_name":"compras_reporte.py","file_ext":"py","file_size_in_byte":5148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"125570767","text":"import json\nimport boto3\nimport logging\n\ndynamodb = boto3.resource('dynamodb')\ntable = dynamodb.Table('Book')\nlogging.getLogger().setLevel(logging.DEBUG)\n\ndef error_response(statusCode, body):\n logging.debug(event)\n return {\n 'statusCode': statusCode,\n 'body': json.dumps(body)\n }\ndef success_response(statusCode, body):\n return {\n 'statusCode': statusCode,\n 'body': json.dumps(body)\n }\n\ndef lambda_handler(event, context):\n logging.debug(event)\n try:\n response = table.scan()\n\n items = response['Items']\n \n return {\n 'statusCode': 200,\n 'body': json.dumps(items)\n }\n except:\n logging.critical(event)\n return error_response(404, 'Unexpected Error')\n","sub_path":"getAllBook/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"272959592","text":"from scipy.spatial import Delaunay\nimport numpy as np\nimport cv2\n\n\ndef getPointsFromFile(filepath):\n file = open(filepath, \"r\")\n file_array = file.readlines()\n\n list_to_append = []\n\n for line in file_array:\n current = line.split()\n current[0] = int(float(current[0]))\n current[1] = int(float(current[1]))\n list_to_append.append(current)\n\n return np.array(list_to_append)\n\n\ndef delaunay(points):\n tri = Delaunay(points)\n return tri\n\n","sub_path":"TP3/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"229331996","text":"\"\"\"\nAuthor : Philippe Vo\nDate : Tue 04 Jun-06 2019 19:17:37\n\"\"\"\n\n# * Imports\n\n# * User imports\nfrom Forms import AssignmentForm\nfrom datetime import date, datetime\nfrom dateutil.parser import parse\nfrom termcolor import colored, cprint\n\nclass Assignment:\n \"\"\"\n class to store the information of exams \n\n Attributes \n ----------\n - classCode\n - type\n - date of exam\n - days left\n - study time accumulated \n\n Methods\n ------- \n\n Logic Functions\n ---------------\n \n Helper Functions\n ----------------\n\n \"\"\"\n\n # * Static Variables\n # Default Attributes\n headers = [['id','Class Code', 'Title', 'Date', 'Days Left', '# Done', '# Total', 'Percentage Done','Filepath']]\n title = \"Assignments\"\n dbFile = \"assignments_db.sqlite\"\n tableName = \"assignments\"\n addSqlCmd = ''' INSERT INTO assignments(classCode, title, date, daysLeft, currentNumbers, totalNumbers, percentageDone, filepath)\n VALUES(?,?,?,?,?,?,?,?) '''\n removeSqlCmd = 'DELETE FROM assignments WHERE id=?'\n editSqlCmd = ''' UPDATE assignments\n SET classCode = ? ,\n title = ?, \n date = ?,\n daysLeft = ?,\n currentNumbers = ?,\n totalNumbers = ?, \n percentageDone= ?, \n filepath = ?\n WHERE id = ?'''\n editPercentageSqlCmd = ''' UPDATE assignments\n SET percentageDone = ?,\n currentNumbers = ?\n WHERE id = ?'''\n createSqlCmd = 'CREATE TABLE IF NOT EXISTS assignments (id INTEGER PRIMARY KEY, classCode VARCHAR, title VARCHAR, date VARCHAR, daysLeft VARCHAR, currentNumbers VARCHAR, totalNumbers VARCHAR, percentageDone VARCHAR, filepath VARCHAR)'\n\n # Edit String List\n editStringList = [\"classCode\", \"title\", \"date\", \"currentNumbers\", \"filepath\"]\n\n # This is the database file where the exams info will be stored\n databaseFile = \"assignments_db.sqlite\"\n\n def __init__(self,classCode = \"\", title=\"\", filePath=\"\", date=\"\", daysLeft=\"\",description=\"\", totalNumbers=\"\", currentNumbers=\"\", new = True) : \n # def __init__(self, id = -1, new = True) : \n \"\"\" constructor \"\"\"\n\n if new == False : \n # Init an exam \n self.classCode = classCode\n self.title = title \n self.date = date\n self.daysLeft = daysLeft\n self.totalNumbers = totalNumbers\n self.currentNUmbers = currentNumbers\n self.filepath = filePath\n self.description = description\n\n self.itemList = (self.classCode, self.date, self.daysLeft, self.percentageDone)\n\n else : # It's a New item\n\n form = AssignmentForm()\n form.run()\n info = form.get_form_info()\n\n # init the item that is going into the database\n self.classCode = info[\"classCode\"]\n self.date = info[\"date\"]\n self.title = info[\"title\"]\n self.filepath = info[\"filepath\"]\n self.totalNumbers = info[\"totalNumbers\"]\n self.currentNUmbers = 0\n self.percentageDone = 0\n self.daysLeft = self.days_left(self.date)\n\n self.itemList = (self.classCode, self.title, self.date, self.daysLeft, self.currentNUmbers, self.totalNumbers, self.percentageDone, self.filepath)\n\n @staticmethod\n def days_left(givenDate) :\n \" Returns the number of days between the current date aand the given date \"\n\n currentDate = datetime.now().date()\n daysLeft = givenDate - currentDate\n\n # Find out how many days left and if less than 5 -> make it bright red\n if daysLeft.days < 10 :\n daysLeft = str(daysLeft.days)\n daysLeft = colored(daysLeft,'white', 'on_red',attrs=['bold'])\n else :\n daysLeft = str(daysLeft.days)\n\n return daysLeft\n \n\n\n","sub_path":"Assignment.py","file_name":"Assignment.py","file_ext":"py","file_size_in_byte":3964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"39012310","text":"\"\"\"This module serves as a prototype for the Mincer calculations.\"\"\"\nimport pickle as pkl\nimport numpy as np # noqa: F401\n\nimport statsmodels.formula.api as smf\n\nfrom ov_tools.objects.auxiliary_shared import adjust_simulated_dataset\nfrom ov_tools.objects.auxiliary_shared import get_dataset\n\n\ndef get_mincer_coefficients(config_dict):\n \"\"\"This function runs a simple Mincer regression on the simulated and observed dataset.\"\"\"\n datasets = adjust_simulated_dataset(*get_dataset(config_dict))\n\n # Add some additional covariates for the regression.\n for dataset in datasets:\n dataset.loc[:, 'Years_Experience'] = 0\n dataset.loc[:, 'Years_Experience'] += dataset.loc[:, 'Experience_A']\n dataset.loc[:, 'Years_Experience'] += dataset.loc[:, 'Experience_B']\n\n dataset.loc[:, 'Years_Experience_2'] = dataset.loc[:, 'Years_Experience'] ** 2\n\n # Collect set of independent variables for the regression.\n indep_vars = []\n indep_vars += ['Years_Schooling']\n indep_vars += ['Years_Experience', 'Years_Experience_2']\n\n # Run ordinary least squares regression by dataset. We run a regression on the whole dataset\n # and by period.\n formula = \"np.log(Wage) ~ Years_Schooling + Years_Experience + Years_Experience_2\"\n rslts = dict()\n\n for sample in ['all'] + dataset['Period'].unique().tolist():\n rslts[sample] = []\n for dataset in datasets:\n if sample in ['all']:\n dataset_subset = dataset\n else:\n dataset_subset = dataset[dataset['Period'] == sample]\n\n # We might encounter the situation that there are no valid wage observations.\n if dataset_subset['Wage'].isnull().all():\n rslt = None\n else:\n rslt = smf.ols(formula=formula, data=dataset_subset, missing='drop').fit()\n rslts[sample] += [rslt]\n\n # We now store the results for further inspection and processing in an readable and a\n # serialized format.\n pkl.dump(rslts, open('mincer.ov_project.pkl', 'wb'))\n\n with open('mincer.ov_project.rslt', 'w') as outfile:\n for sample in ['all'] + dataset['Period'].unique().tolist():\n if sample in ['all']:\n caption = 'ALL'\n else:\n caption = 'PERIOD ' + str(sample)\n\n outfile.write(caption + '\\n' + '=' * len(caption) + '\\n\\n')\n for i, label in enumerate(['Observed Data', 'Simulated Data']):\n outfile.write(label + '\\n' + '-' * len(label) + '\\n\\n')\n rslt = rslts[sample][i]\n if rslt is None:\n outfile.write(' ... no wage observations available \\n\\n')\n else:\n outfile.write(rslt.summary().as_text() + '\\n\\n')\n\n return rslts\n","sub_path":"ov_tools/objects/auxiliary_mincer.py","file_name":"auxiliary_mincer.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"71671160","text":"from django import forms\n\nfrom inventory.models import InventoryItem, Plan, PlanItem\n\n\nclass InventoryItemForm(forms.ModelForm):\n class Meta:\n model = InventoryItem\n fields = ['name', 'total']\n widgets = {\n 'name': forms.TextInput(attrs={'placeholder': 'Name', 'required': True}),\n 'total': forms.NumberInput(attrs={'placeholder': 'Count', 'required': True}),\n }\n\n\nclass PlanForm(forms.ModelForm):\n class Meta:\n model = Plan\n fields = ['name', 'archived']\n widgets = {\n 'name': forms.TextInput(attrs={'placeholder': 'Name', 'required': True}),\n 'archived': forms.HiddenInput(),\n }\n\n\nclass PlanItemForm(forms.ModelForm):\n class Meta:\n model = PlanItem\n fields = ['name', 'total', 'plan_id']\n widgets = {\n 'name': forms.TextInput(attrs={'placeholder': 'Name', 'required': True}),\n 'total': forms.NumberInput(attrs={'placeholder': 'Count', 'required': True}),\n 'plan_id': forms.HiddenInput(),\n }\n","sub_path":"inventory/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"107612861","text":"#!/usr/bin/env python\n\n# Copyright 2016 RIFT.IO 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\"\"\"\n# \n#\n\n@file lp_3vnfs_test.py\n@author Austin Cormier (Austin.Cormier@riftio.com)\n@date 10/15/2015\n@brief Launchpad Module Test ExtVNF\n\"\"\"\n\nimport json\nimport logging\nimport os\nimport pytest\nimport shlex\nimport requests\nimport subprocess\nimport time\nimport uuid\n\nimport gi\ngi.require_version('RwIwpYang', '1.0')\ngi.require_version('RwNsrYang', '1.0')\ngi.require_version('RwVnfdYang', '1.0')\ngi.require_version('RwCloudYang', '1.0')\ngi.require_version('RwBaseYang', '1.0')\ngi.require_version('RwResourceMgrYang', '1.0')\ngi.require_version('RwConmanYang', '1.0')\ngi.require_version('RwNsmYang', '1.0')\n\n\n\nfrom gi.repository import RwIwpYang, NsdYang, NsrYang, RwNsrYang, VldYang, RwVnfdYang, RwCloudYang, RwBaseYang, RwResourceMgrYang, RwConmanYang, RwNsmYang\n\nlogging.basicConfig(level=logging.DEBUG)\n\n\nRW_VROUTER_PKG_INSTALL_DIR = os.path.join(\n os.environ[\"RIFT_INSTALL\"],\n \"usr/rift/mano/vnfds/vrouter\"\n )\nRW_TRAFGEN_PKG_INSTALL_DIR = os.path.join(\n os.environ[\"RIFT_INSTALL\"],\n \"usr/rift/mano/vnfds/trafgen\"\n )\nRW_TRAFSINK_PKG_INSTALL_DIR = os.path.join(\n os.environ[\"RIFT_INSTALL\"],\n \"usr/rift/mano/vnfds/trafsink\"\n )\nRW_TG_2VROUTER_TS_NSD_PKG_INSTALL_DIR = os.path.join(\n os.environ[\"RIFT_INSTALL\"],\n \"usr/rift/mano/nsds/tg_2vrouter_ts\"\n )\n\n\nclass PackageError(Exception):\n pass\n\n\ndef raise_package_error():\n raise PackageError(\"Could not find ns packages\")\n\n\n@pytest.fixture(scope='module')\ndef iwp_proxy(request, mgmt_session):\n return mgmt_session.proxy(RwIwpYang)\n\n@pytest.fixture(scope='module')\ndef resource_mgr_proxy(request, mgmt_session):\n return mgmt_session.proxy(RwResourceMgrYang)\n\n\n@pytest.fixture(scope='module')\ndef cloud_proxy(request, mgmt_session):\n return mgmt_session.proxy(RwCloudYang)\n\n\n@pytest.fixture(scope='module')\ndef vnfd_proxy(request, mgmt_session):\n return mgmt_session.proxy(RwVnfdYang)\n\n\n@pytest.fixture(scope='module')\ndef vld_proxy(request, mgmt_session):\n return mgmt_session.proxy(VldYang)\n\n\n@pytest.fixture(scope='module')\ndef nsd_proxy(request, mgmt_session):\n return mgmt_session.proxy(NsdYang)\n\n\n@pytest.fixture(scope='module')\ndef nsr_proxy(request, mgmt_session):\n return mgmt_session.proxy(NsrYang)\n\n\n@pytest.fixture(scope='module')\ndef rwnsr_proxy(request, mgmt_session):\n return mgmt_session.proxy(RwNsrYang)\n\n\n@pytest.fixture(scope='module')\ndef base_proxy(request, mgmt_session):\n return mgmt_session.proxy(RwBaseYang)\n\n@pytest.fixture(scope='module')\ndef so_proxy(request, mgmt_session):\n return mgmt_session.proxy(RwConmanYang)\n\n@pytest.fixture(scope='module')\ndef nsm_proxy(request, mgmt_session):\n return mgmt_session.proxy(RwNsmYang)\n\n@pytest.fixture(scope='session')\ndef vrouter_vnfd_package_file():\n vrouter_pkg_file = os.path.join(\n RW_VROUTER_PKG_INSTALL_DIR,\n \"vrouter_vnfd.tar.gz\",\n )\n if not os.path.exists(vrouter_pkg_file):\n raise_package_error()\n\n return vrouter_pkg_file\n\n@pytest.fixture(scope='session')\ndef tg_vnfd_package_file():\n tg_pkg_file = os.path.join(\n RW_TRAFGEN_PKG_INSTALL_DIR,\n \"trafgen_vnfd.tar.gz\",\n )\n if not os.path.exists(tg_pkg_file):\n raise_package_error()\n\n return tg_pkg_file\n\n@pytest.fixture(scope='session')\ndef ts_vnfd_package_file():\n ts_pkg_file = os.path.join(\n RW_TRAFSINK_PKG_INSTALL_DIR,\n \"trafsink_vnfd.tar.gz\",\n )\n if not os.path.exists(ts_pkg_file):\n raise_package_error()\n\n return ts_pkg_file\n\n@pytest.fixture(scope='session')\ndef tg_2vrouter_ts_nsd_package_file():\n tg_2vrouter_ts_nsd_pkg_file = os.path.join(\n RW_TG_2VROUTER_TS_NSD_PKG_INSTALL_DIR,\n \"tg_2vrouter_ts_nsd.tar.gz\",\n )\n if not os.path.exists(tg_2vrouter_ts_nsd_pkg_file):\n raise_package_error()\n\n return tg_2vrouter_ts_nsd_pkg_file\n\n\ndef create_nsr_from_nsd_id(nsd_id):\n nsr = NsrYang.YangData_Nsr_NsInstanceConfig_Nsr()\n nsr.id = str(uuid.uuid4())\n nsr.name = \"TG-2Vrouter-TS EPA\"\n nsr.short_name = \"TG-2Vrouter-TS EPA\"\n nsr.description = \"4 VNFs with Trafgen, 2 Vrouters and Trafsink EPA\"\n nsr.nsd_ref = nsd_id\n nsr.admin_status = \"ENABLED\"\n\n return nsr\n\n\ndef upload_descriptor(logger, descriptor_file, host=\"127.0.0.1\"):\n curl_cmd = 'curl -F \"descriptor=@{file}\" http://{host}:4567/api/upload'.format(\n file=descriptor_file,\n host=host,\n )\n logger.debug(\"Uploading descriptor %s using cmd: %s\", descriptor_file, curl_cmd)\n stdout = subprocess.check_output(shlex.split(curl_cmd), universal_newlines=True)\n\n json_out = json.loads(stdout)\n transaction_id = json_out[\"transaction_id\"]\n\n return transaction_id\n\n\nclass DescriptorOnboardError(Exception):\n pass\n\n\ndef wait_unboard_transaction_finished(logger, transaction_id, timeout_secs=600, host=\"127.0.0.1\"):\n logger.info(\"Waiting for onboard trans_id %s to complete\",\n transaction_id)\n start_time = time.time()\n while (time.time() - start_time) < timeout_secs:\n r = requests.get(\n 'http://{host}:4567/api/upload/{t_id}/state'.format(\n host=host, t_id=transaction_id\n )\n )\n state = r.json()\n if state[\"status\"] == \"pending\":\n time.sleep(1)\n continue\n\n elif state[\"status\"] == \"success\":\n logger.info(\"Descriptor onboard was successful\")\n return\n\n else:\n raise DescriptorOnboardError(state)\n\n if state[\"status\"] != \"success\":\n raise DescriptorOnboardError(state)\n\n@pytest.mark.incremental\nclass TestLaunchpadStartStop(object):\n def test_configure_cloud_account(self, cloud_proxy, logger):\n cloud_account = RwCloudYang.CloudAccountConfig()\n #cloud_account.name = \"cloudsim_proxy\"\n #cloud_account.account_type = \"cloudsim_proxy\"\n cloud_account.name = \"riftuser1\"\n cloud_account.account_type = \"openstack\"\n cloud_account.openstack.key = 'pluto'\n cloud_account.openstack.secret = 'mypasswd'\n cloud_account.openstack.auth_url = 'http://10.66.4.xx:5000/v3/'\n cloud_account.openstack.tenant = 'demo'\n cloud_account.openstack.mgmt_network = 'private'\n\n cloud_proxy.merge_config(\"/rw-cloud:cloud-account\", cloud_account)\n\n def test_configure_pools(self, resource_mgr_proxy):\n pools = RwResourceMgrYang.ResourcePools.from_dict({\n \"pools\": [{ \"name\": \"vm_pool_a\",\n \"resource_type\": \"compute\",\n \"pool_type\" : \"dynamic\"},\n {\"name\": \"network_pool_a\",\n \"resource_type\": \"network\",\n \"pool_type\" : \"dynamic\",}]})\n\n resource_mgr_proxy.merge_config('/rw-resource-mgr:resource-mgr-config/rw-resource-mgr:resource-pools', pools)\n\n def test_configure_resource_orchestrator(self, so_proxy):\n cfg = RwConmanYang.RoEndpoint.from_dict({'ro_ip_address': '127.0.0.1',\n 'ro_port' : 2022,\n 'ro_username' : 'admin',\n 'ro_password' : 'admin'})\n so_proxy.merge_config('/rw-conman:cm-config', cfg)\n\n def test_configure_service_orchestrator(self, nsm_proxy):\n cfg = RwNsmYang.SoEndpoint.from_dict({'cm_ip_address': '127.0.0.1',\n 'cm_port' : 2022,\n 'cm_username' : 'admin',\n 'cm_password' : 'admin'})\n nsm_proxy.merge_config('/rw-nsm:ro-config/rw-nsm:cm-endpoint', cfg)\n\n \n def test_onboard_tg_vnfd(self, logger, vnfd_proxy, tg_vnfd_package_file):\n logger.info(\"Onboarding trafgen_vnfd package: %s\", tg_vnfd_package_file)\n trans_id = upload_descriptor(logger, tg_vnfd_package_file)\n wait_unboard_transaction_finished(logger, trans_id)\n\n catalog = vnfd_proxy.get_config('/vnfd-catalog')\n vnfds = catalog.vnfd\n assert len(vnfds) == 1, \"There should be one vnfds\"\n assert \"trafgen_vnfd\" in [vnfds[0].name]\n\n def test_onboard_vrouter_vnfd(self, logger, vnfd_proxy, vrouter_vnfd_package_file):\n logger.info(\"Onboarding vrouter_vnfd package: %s\", vrouter_vnfd_package_file)\n trans_id = upload_descriptor(logger, vrouter_vnfd_package_file)\n wait_unboard_transaction_finished(logger, trans_id)\n\n catalog = vnfd_proxy.get_config('/vnfd-catalog')\n vnfds = catalog.vnfd\n assert len(vnfds) == 2, \"There should be two vnfds\"\n assert \"vrouter_vnfd\" in [vnfds[0].name, vnfds[1].name]\n\n def test_onboard_ts_vnfd(self, logger, vnfd_proxy, ts_vnfd_package_file):\n logger.info(\"Onboarding trafsink_vnfd package: %s\", ts_vnfd_package_file)\n trans_id = upload_descriptor(logger, ts_vnfd_package_file)\n wait_unboard_transaction_finished(logger, trans_id)\n\n catalog = vnfd_proxy.get_config('/vnfd-catalog')\n vnfds = catalog.vnfd\n assert len(vnfds) == 3, \"There should be three vnfds\"\n assert \"trafsink_vnfd\" in [vnfds[0].name, vnfds[1].name, vnfds[2].name]\n\n def test_onboard_tg_2vrouter_ts_nsd(self, logger, nsd_proxy, tg_2vrouter_ts_nsd_package_file):\n logger.info(\"Onboarding tg_2vrouter_ts nsd package: %s\", tg_2vrouter_ts_nsd_package_file)\n trans_id = upload_descriptor(logger, tg_2vrouter_ts_nsd_package_file)\n wait_unboard_transaction_finished(logger, trans_id)\n\n catalog = nsd_proxy.get_config('/nsd-catalog')\n nsds = catalog.nsd\n assert len(nsds) == 1, \"There should only be a single nsd\"\n nsd = nsds[0]\n assert nsd.name == \"tg_vrouter_ts_nsd\"\n assert nsd.short_name == \"tg_2vrouter_ts_nsd\"\n\n def test_instantiate_tg_2vrouter_ts_nsr(self, logger, nsd_proxy, nsr_proxy, rwnsr_proxy, base_proxy):\n catalog = nsd_proxy.get_config('/nsd-catalog')\n nsd = catalog.nsd[0]\n\n nsr = create_nsr_from_nsd_id(nsd.id)\n nsr_proxy.merge_config('/ns-instance-config', nsr)\n\n nsr_opdata = rwnsr_proxy.get('/ns-instance-opdata')\n nsrs = nsr_opdata.nsr\n assert len(nsrs) == 1\n assert nsrs[0].ns_instance_config_ref == nsr.id","sub_path":"modules/core/mano/rwlaunchpad/test/pytest/lp_tg_2vrouter_ts_test.py","file_name":"lp_tg_2vrouter_ts_test.py","file_ext":"py","file_size_in_byte":10971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"217062113","text":"import sfs\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import cross_val_score, train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom id3 import Id3Estimator\nfrom statistics import mean\n\nfrom extractData import X, y\n\n\ndef scoreSFS(clf, x, y):\n return cross_val_score(clf, x, y, cv=4).mean()\n\n\nresults = {\"KNN_with\": [], \"KNN_without\": [],\n \"Tree_with\": [], \"Tree_without\": []}\nfor _ in range(100):\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)\n\n # Question 7\n # Without choosing parameters\n es = KNeighborsClassifier()\n es.fit(X_train, y_train)\n results[\"KNN_without\"].append(accuracy_score(y_test, es.predict(X_test)))\n\n # With choosing parameters\n number_of_indexes = sfs.sfs(X_train, y_train, 8, KNeighborsClassifier(), scoreSFS)\n es.fit(sfs.subset_of_x(X_train, number_of_indexes), y_train)\n results[\"KNN_with\"].append(accuracy_score(y_test, es.predict(sfs.subset_of_x(X_test, number_of_indexes))))\n\n # Question 8\n # Without pruning\n es = Id3Estimator()\n es.fit(X_train, y_train)\n results[\"Tree_without\"].append(accuracy_score(y_test, es.predict(X_test)))\n\n # With pruning\n es = Id3Estimator(min_samples_split=20)\n es.fit(X_train, y_train)\n results[\"Tree_with\"].append(accuracy_score(y_test, es.predict(X_test)))\n\nprint(mean(results[\"KNN_without\"]))\nprint(mean(results[\"KNN_with\"]))\nprint(mean(results[\"Tree_without\"]))\nprint(mean(results[\"Tree_with\"]))\n","sub_path":"part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"136222995","text":"from utils.io import print_solution, read_by_line\nimport collections as col\n\ninstructions = list()\nmatrix = [0 for i in range(1000*1000)]\n\n\ndef matrix_index(x, y):\n return (y * 1000) + x\n\n\ndef turn_on(matrix, start, end):\n for y in range(start.y, end.y):\n for x in range(start.x, end.x):\n matrix[matrix_index(x, y)] += 1\n\n\ndef turn_off(matrix, start, end):\n for y in range(start.y, end.y):\n for x in range(start.x, end.x):\n matrix[matrix_index(x, y)] = max(0, matrix[matrix_index(x, y)] - 1)\n\n\ndef toggle(matrix, start, end):\n for y in range(start.y, end.y):\n for x in range(start.x, end.x):\n matrix[matrix_index(x, y)] += 2\n\n\ndef create_instruction(value):\n split = value.split()\n\n if len(split) == 4:\n action = 2\n (x, y) = split[1].split(',')\n start = Point(int(x), int(y))\n (x, y) = split[3].split(',')\n end = Point(int(x)+1, int(y)+1)\n else:\n action = 0 if split[1] == 'on' else 1\n (x, y) = split[2].split(',')\n start = Point(int(x), int(y))\n (x, y) = split[4].split(',')\n end = Point(int(x)+1, int(y)+1)\n\n return Instruction(action, start, end)\n\n\nAction = {\n 0: turn_on,\n 1: turn_off,\n 2: toggle\n}\n\nPoint = col.namedtuple('Point', ['x', 'y'])\nInstruction = col.namedtuple(\"Instruction\", ['action', 'start', 'end'])\n\n\nfor line in read_by_line(6):\n instructions.append(create_instruction(line))\n\n\nfor i in instructions:\n Action.get(i.action)(matrix, i.start, i.end)\n\nprint_solution(sum(list(filter(lambda x: x, matrix))))\n","sub_path":"2015/challenge_6b.py","file_name":"challenge_6b.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"253029456","text":"class FileSystem:\n # Trie\n\n def __init__(self):\n self.root = Node(0)\n\n def createPath(self, path: str, value: int) -> bool:\n path = path.split(\"/\")\n parentNode = self.findPath(path[1:-1])\n if not parentNode:\n return False\n if path[-1] in parentNode.children:\n return False\n parentNode.children[path[-1]] = Node(value)\n return True\n\n def get(self, path: str) -> int:\n node = self.findPath(path.split(\"/\")[1:])\n if not node:\n return -1\n return node.val\n\n def findPath(self, path):\n curr = self.root\n for p in path:\n if p not in curr.children:\n return None\n curr = curr.children[p]\n return curr\n\n\nclass Node:\n\n def __init__(self, val):\n self.children = dict()\n self.val = val\n\n# Your FileSystem object will be instantiated and called as such:\n# obj = FileSystem()\n# param_1 = obj.createPath(path,value)\n# param_2 = obj.get(path)\n","sub_path":"1166.DesignFileSystem.py","file_name":"1166.DesignFileSystem.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"402062337","text":"#!/usr/bin/env python3\n'''\nEthernet learning switch in Python.\n\nNote that this file currently has the code to implement a \"hub\"\nin it, not a learning switch. (I.e., it's currently a switch\nthat doesn't learn.)\n'''\nfrom switchyard.lib.userlib import *\nimport sys\nimport time\nLRU_LEN=5\ndef switch_table_get(dst_mac,memory):\n for i in memory:\n if i[0]==dst_mac:\n return i\n return None\ndef switch_table_get_i(dst_mac,memory):\n for i,j in enumerate(memory):\n if j[0]==dst_mac:\n return i\n return None\ndef switch_table_del(mac,memory):\n k=-1\n for i,j in enumerate(memory):\n if j[0]==mac:\n k=i\n if k==-1:\n return \n else:\n del memory[k]\ndef switch_table_insert(port_info,memory):\n memory.insert(0,port_info)\n \ndef learning(memory,input_port,src_mac):\n port_info=switch_table_get(src_mac,memory)\n if port_info is None:#src_mac not in the table\n if len(memory)<LRU_LEN:#table not full, just add\n switch_table_insert([src_mac,input_port],memory)\n else:#table full,do something\n memory.pop()\n switch_table_insert([src_mac,input_port],memory)\n else:#src_mac is in the forwarding table\n if input_port==port_info[1]:#topology not changed do nothing\n return\n else:#topology changed , change the port, do not change the lru_info\n i=switch_table_get_i(src_mac,memory)\n memory[i][1]=input_port\n \n log_info(\"\\nmy_momory: {}\\n\".format(memory))\n\ndef Flood_packet(net,my_interfaces,input_port,packet):\n for intf in my_interfaces:\n if input_port!=intf.name:\n log_info(\"Flooding packet {} to {}\".format(packet,intf.name))\n net.send_packet(intf.name,packet)\n \ndef Transport_packet(net,my_interfaces,memory,input_port,packet):\n eth=packet.get_header(Ethernet)\n port_info=switch_table_get(eth.dst,memory)\n if port_info is None:#dst is not in table , flood\n Flood_packet(net,my_interfaces,input_port,packet)\n else:#dst in table ,update the time\n log_info(\"Transport packet {} to {}\".format(packet,port_info[0]))\n switch_table_del(port_info[0],memory)\n switch_table_insert(port_info,memory)\n net.send_packet(port_info[1],packet)\n log_info(\"memory after transport: {}\".format(memory))\n \ndef main(net):\n my_interfaces = net.interfaces() \n mymacs = [intf.ethaddr for intf in my_interfaces]\n \n memory=[]\n while True:\n try:\n timestamp,input_port,packet = net.recv_packet()\n except NoPackets:\n continue\n except Shutdown:\n return\n\n log_info(\"In {} received packet {} on {}\".format(net.name, packet, input_port))\n eth=packet.get_header(Ethernet)\n \n learning(memory,input_port,eth.src)\n \n if eth is None:\n log_info(\"Received a non-Ethernet packet?!\")\n continue\n if eth.dst in mymacs:\n log_info(\"Packet intended for me\")\n else:\n Transport_packet(net,my_interfaces,memory,input_port,packet)\n \n \n #log_info(\"\\nljk\\n{}\\nljk\\n\".format(packet))\n '''if packet[0].dst in mymacs:\n log_info (\"Packet intended for me\")\n else:\n for intf in my_interfaces:\n if input_port != intf.name:\n log_info (\"Flooding packet {} to {}\".format(packet, intf.name))\n net.send_packet(intf.name, packet)'''\n net.shutdown()\n","sub_path":"assignment-2-AA-stardust/lab_2/myswitch_lru.py","file_name":"myswitch_lru.py","file_ext":"py","file_size_in_byte":3546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"199601111","text":"# -*- coding: utf-8 -*-\n\n# 这个ipython notebook主要是我解决Kaggle Titanic问题的思路和过程\n# (1)\nimport pandas as pd #数据分析\nimport numpy as np #科学计算\nfrom pandas import Series,DataFrame\nimport sys\n#reload(sys)\n#sys.setdefaultencoding( \"utf-8\" )\nimport matplotlib.pyplot as plt\n#data_train = pd.read_csv(\"Train.csv\")\ndata_train = pd.read_csv(\"../data/train.csv\")\nprint(data_train.columns)\n\n# (5)\n#看看各乘客等级的获救情况\nfig = plt.figure()\nfig.set(alpha=0.2) # 设定图表颜色alpha参数\nSurvived_0 = data_train.Pclass[data_train.Survived == 0].value_counts()\nSurvived_1 = data_train.Pclass[data_train.Survived == 1].value_counts()\ndf=pd.DataFrame({u'Survived':Survived_1, u'Not Survived':Survived_0})\ndf.plot(kind='bar', stacked=True)\nplt.title(u\"Rescue status for each class\")\nplt.xlabel(u\"class\")\nplt.ylabel(u\"count\")\nplt.show()\n","sub_path":"course1_20191110/titanic/viewdata3.py","file_name":"viewdata3.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"492688844","text":"def to_dict_tools(target):\n data = dict()\n attribute = dir(target)\n if 'public_info' in attribute:\n public_info = getattr(target, 'public_info')\n attribute = dir(target)\n for item in attribute:\n item = str(item)\n if not item.startswith('_') and item in public_info:\n data[item] = str(getattr(target, item))\n return data\n","sub_path":"utils/model_to_dict.py","file_name":"model_to_dict.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"262545412","text":"import logging\n\nclass _Counters:\n \"\"\"singleton for all counters\n\n needed so that we can use SparkContext created by spark *or* py.test\n\n Call `init` before importing any modules that use counters.\n \"\"\"\n\n log = logging.getLogger(__name__)\n\n def __init__(self, *names):\n # set up counters with ints, so that it works even if init() is never called\n self._counters = {n: 0 for n in names}\n self._initialized = False\n\n def init(self, sc):\n \"\"\"create Spark accumulators\"\"\"\n if self._initialized:\n raise RuntimeError(\"init called multiple times\")\n\n for n in self._counters:\n self._counters[n] = sc.accumulator(0)\n\n self._initialized = True\n\n def inc(self, name):\n \"\"\"increment the counter `name`\"\"\"\n #self.log.warn(\"%r\", list(self._counters.keys()))\n self._counters[name] += 1\n\n def dump(self):\n \"\"\"write the state of the counters to logging\"\"\"\n for n, c in sorted(self._counters.items()):\n if self._initialized:\n v = c.value\n else:\n v = c\n self.log.info(\"%s: %d\", n, v)\n\n\nCounters = _Counters(\"SourceMARCRecord.node_count\", \"MARCRecordMixin.raw_count\",\n \"RawVIAFRecord.line_count\", \"VIAFCluster.raw_count\",\n \"CrossrefRecord.file_count\", \"CrossrefRecord.source_count\", )\n","sub_path":"osp_pipeline/core/counters.py","file_name":"counters.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"415587747","text":"#######################################################################\n# #\n# Python Progs : vdist.py #\n# Aruthor : Colby Haggerty #\n# Date : 2016.02.08 #\n# #\n# #\n#######################################################################\nimport os\nimport sys \nimport datetime\nimport numpy as np\nimport struct\nimport glob\nimport pdb\nfrom scipy.io.idl import readsav\nfrom scipy.ndimage import gaussian_filter\n\nclass VDist(object):\n \"\"\" velocity distribution fucntion calculator\n \"\"\"\n\n def __init__(self): \n \"\"\" Initilazition Routine for the p3d_run object\n \"\"\"\n\n pass\n\n def vdist2d(self,\n v1,\n v2,\n v3=None,\n dz=None,\n v0_frame=False,\n v_light=None,\n **kwargs):\n\n \"\"\" Simple 2D velocity histogram\n \"\"\"\n \n if v3 is not None:\n v1, v2 = self._trim_v3(v1, v2, v3, dz, v0_frame)\n \n if kwargs.get('bins') is None and kwargs.get('range') is None:\n self._set_bins(v1,v2, **kwargs)\n\n H, x_edge, y_edge = np.histogram2d(v1, v2, **kwargs)\n\n return H.T, x_edge, y_edge\n \n\n def _trim_v3(self, v1, v2, v3, dz, v0_frame):\n\n if dz is None:\n dz = np.std(v3)\n if v0_frame:\n v3 = v3 - np.mean(v3)\n \n ind = np.where(abs(v3) < dz/2.)\n v1 = v1[ind]\n v2 = v2[ind]\n\n return v1, v2\n\n\n def _set_bins(self, v1, v2, **kwargs):\n\n kwargs.pop('range', None)\n kwargs.pop('bins', None)\n\n v1_mean = np.mean(v1)\n v2_mean = np.mean(v2)\n\n v_std = np.std(np.sqrt(v1**2 + v2**2))\n v_nsteps = 50\n # dv = v_std/10.\n\n kwargs['bins'] = [np.linspace(v1_mean - 2.5*v_std,\n v1_mean + 2.5*v_std,\n v_nsteps),\n np.linspace(v2_mean - 2.5*v_std,\n v2_mean + 2.5*v_std,\n v_nsteps)]\n\n\n\n def vdist2d_pitch(self,\n v1,\n v2,\n v3,\n pa=90.,\n dpa=20.,\n v0_frame=False,\n **kwargs): \n \"\"\" Pitch party!!!!\n \n pa = pitch angle\n dpa = angular width around pa (Delta Pitch Angle)\n \"\"\"\n\n if v0_frame:\n v1 = v1 - np.mean(v1)\n v2 = v2 - np.mean(v2)\n v3 = v3 - np.mean(v3)\n\n pitch_angle = -1.0*(np.arctan(v3/np.sqrt(v1**2+v2**2))/np.pi*180. - 90.)\n ind = np.where(abs(pitch_angle - pa) < dpa/2.)\n \n v1 = v1[ind]\n v2 = v2[ind]\n \n if kwargs.get('bins') is None and kwargs.get('range') is None:\n self._set_bins(v1, v2, **kwargs)\n\n H, x_edge, y_edge = np.histogram2d(v1, v2, **kwargs)\n\n H = H.T\n\n xx,yy = np.meshgrid(x_edge, y_edge)\n\n norm_cone = self._int_cone(pa, dpa, x_edge, y_edge)\n\n H = H/norm_cone\n\n return H, x_edge, y_edge\n\n\n def _get_gamma(self, v1, v2, v3, v_light):\n v2 = v1**2 + v2**2 + v3**2\n c2 = v_light**2\n return 1./np.sqrt(1. - v2/c2)\n \n\n def eflux(self, v1, v2, v3, mass, v_light=None, **kwargs):\n \"\"\" Function that makes an energy flux distrobution\n ToDo: add an eflux_autobin funciton\n \"\"\"\n\n pitch_angle = -1.0*(np.arctan(v3/np.sqrt(v1**2+v2**2))/np.pi*180. - 90.)\n\n v2 = v1**2 + v2**2 + v3**2\n\n if v_light is not None:\n gamma = self._get_gamma(v1, v2, v3, v_light)\n c2 = v_light**2\n\n KE = mass*c2*(gamma - 1.)\n else:\n KE = .5*mass*v2\n\n H, x_edge, y_edge = np.histogram2d(KE, pitch_angle, normed=True, **kwargs)\n H = H.T\n\n xx,yy = np.meshgrid(x_edge,y_edge)\n eng = (xx[1:,1:] + xx[:-1,:-1])/2.\n\n cos_norm = (np.cos(yy[:-1,:-1]/180.*np.pi) - np.cos(yy[1:,1:]/180.*np.pi))\n cos_norm = cos_norm/sum(cos_norm)\n\n# We need to account for a geometric factor because\n# E is basicly v^2, so we are binning circles?\n\n \n if v_light is None:\n H = H/np.sqrt(eng)\n H = H/cos_norm*eng**2.*np.size(pitch_angle)\n\n else:\n Ebar = eng/mass/v_light**2\n rel_vel = np.sqrt((Ebar**2 + 2.*Ebar)/(Ebar**2 + 2.*Ebar + 1.))\n rel_vel = rel_vel*v_light\n\n H = H/cos_norm*eng*rel_vel*np.size(pitch_angle)\n\n return H, x_edge, y_edge\n\n def _int_cone(self,pa,dpa,xedges,yedges):\n \"\"\"\n#-----------------------------------------------------------------------------\n# Method : _int_cone\n#\n# Discription : This integrates a cone over a differental grid\n#\n# Args : xedges the x edges of the histogram\n# : yedges the y edges of the histogram\n#\n# Comments : I think this is working ok? \n#-----------------------------------------------------------------------------\n \"\"\"\n \n\n xx,yy = np.meshgrid(yedges,xedges)\n intcone = 1./18.*(\n (-xx[:-1,:-1]**3+6.*xx[:-1,:-1]*yy[:-1,:-1]*np.sqrt(xx[:-1,:-1]**2+\n yy[:-1,:-1]**2) + 3.*yy[:-1,:-1]**3*np.log(np.sqrt(xx[:-1,:-1]**2+\n yy[:-1,:-1]**2) + xx[:-1,:-1] + np.spacing(4)) +\n 3.*xx[:-1,:-1]**3*np.log(np.sqrt(xx[:-1,:-1]**2+\n yy[:-1,:-1]**2)+yy[:-1,:-1] + np.spacing(4))) -\n (-xx[1:,1:]**3+6.*xx[1:,1:]*yy[:-1,:-1]*np.sqrt(xx[1:,1:]**2+\n yy[:-1,:-1]**2) + 3.*yy[:-1,:-1]**3*np.log(np.sqrt(xx[1:,1:]**2+\n yy[:-1,:-1]**2) + xx[1:,1:] + np.spacing(4)) + \n 3.*xx[1:,1:]**3*np.log(np.sqrt(xx[1:,1:]**2+\n yy[:-1,:-1]**2)+yy[:-1,:-1] + np.spacing(4))) -\n (-xx[:-1,:-1]**3+6.*xx[:-1,:-1]*yy[1:,1:]*np.sqrt(xx[:-1,:-1]**2+\n yy[1:,1:]**2) + 3.*yy[1:,1:]**3*np.log(np.sqrt(xx[:-1,:-1]**2+\n yy[1:,1:]**2) + xx[:-1,:-1] + np.spacing(4)) + \n 3.*xx[:-1,:-1]**3*np.log(np.sqrt(xx[:-1,:-1]**2+\n yy[1:,1:]**2)+yy[1:,1:] + np.spacing(4))) +\n (-xx[1:,1:]**3+6.*xx[1:,1:]*yy[1:,1:]*np.sqrt(xx[1:,1:]**2+\n yy[1:,1:]**2) + 3.*yy[1:,1:]**3*np.log(np.sqrt(xx[1:,1:]**2+\n yy[1:,1:]**2) + xx[1:,1:] + np.spacing(4)) + \n 3.*xx[1:,1:]**3*np.log(np.sqrt(xx[1:,1:]**2+\n yy[1:,1:]**2)+yy[1:,1:] + np.spacing(4))))\n\n norm = 1./18.*(\n (-xx[0,0]**3+6.*xx[0,0]*yy[0,0]*np.sqrt(xx[0,0]**2+yy[0,0]**2) + \n 3.*yy[0,0]**3*np.log(np.sqrt(xx[0,0]**2+yy[0,0]**2) + xx[0,0] + \n np.spacing(4)) + \n 3.*xx[0,0]**3*np.log(np.sqrt(xx[0,0]**2+yy[0,0]**2)+yy[0,0] + \n np.spacing(4))) -\n (-xx[-1,-1]**3+6.*xx[-1,-1]*yy[0,0]*np.sqrt(xx[-1,-1]**2+yy[0,0]**2) + \n 3.*yy[0,0]**3*np.log(np.sqrt(xx[-1,-1]**2+yy[0,0]**2) + xx[-1,-1] + \n np.spacing(4)) + \n 3.*xx[-1,-1]**3*np.log(np.sqrt(xx[-1,-1]**2+yy[0,0]**2)+yy[0,0] + \n np.spacing(4))) -\n (-xx[0,0]**3+6.*xx[0,0]*yy[-1,-1]*np.sqrt(xx[0,0]**2+yy[-1,-1]**2) + \n 3.*yy[-1,-1]**3*np.log(np.sqrt(xx[0,0]**2+yy[-1,-1]**2) + xx[0,0] + \n np.spacing(4)) + \n 3.*xx[0,0]**3*np.log(np.sqrt(xx[0,0]**2+yy[-1,-1]**2)+yy[-1,-1] + \n np.spacing(4))) +\n (-xx[-1,-1]**3+6.*xx[-1,-1]*yy[-1,-1]*np.sqrt(xx[-1,-1]**2+\n yy[-1,-1]**2) + \n 3.*yy[-1,-1]**3*np.log(np.sqrt(xx[-1,-1]**2+yy[-1,-1]**2) +\n xx[-1,-1] + np.spacing(4)) + \n 3.*xx[-1,-1]**3*np.log(np.sqrt(xx[-1,-1]**2+yy[-1,-1]**2)+\n yy[-1,-1] + np.spacing(4))))\n \n self.normie=norm\n\n print('norm = ',norm)\n print('otha = ',abs(1./np.tan((pa-dpa/2.)/180.*np.pi) - 1./np.tan((pa+dpa/2.)/180.*np.pi)))\n\n #return intcone/norm#*abs(1./np.tan((pa-dpa/2.)/180.*np.pi) - 1./np.tan((pa+dpa/2.)/180.*np.pi))\n return intcone/intcone.min()#*abs(1./np.tan((pa-dpa/2.)/180.*np.pi) - 1./np.tan((pa+dpa/2.)/180.*np.pi))\n\n\n","sub_path":"Py3D/vdist.py","file_name":"vdist.py","file_ext":"py","file_size_in_byte":8483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"122778914","text":"from selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nimport os\nimport re\noptions = webdriver.ChromeOptions()\noptions.add_argument(\"--ignore-certificate-error\")\noptions.add_argument(\"--ignore-ssl-errors\")\noptions.add_argument('-headless')\noptions.add_argument('-no-sandbox')\noptions.add_argument('--disable-gpu')\noptions.add_argument('--log-level=3')\noptions.add_argument('-disable-dev-shm-usage')\nwd = webdriver.Chrome('chromedriver.exe',options=options)\n\n\ndef getListUrl(path = \"url.txt\"):\n listString = []\n with open(path, encoding=\"UTF-8\", mode=\"r\") as f:\n listString = f.readlines()\n listString = [x.strip() for x in listString]\n return listString\n# getListChapter(\"https://truyenfull.vn/toi-thay-hoa-vang-tren-co-xanh/\")\n\ndef getChapter(text):\n pos = text.find(':')\n if (pos== -1): pos = len(text)\n chap = text[0:pos]\n return [int(s) for s in chap.split() if s.isdigit()][0]\ndef getListChapter(url):\n global wd\n wd.get(url)\n soup = BeautifulSoup(wd.page_source, features=\"lxml\")\n isPanigation = soup.find_all('ul', {'class','pagination pagination-sm'})\n if len(isPanigation) != 0:\n lastAPageElement = isPanigation[len(isPanigation)- 1].find_all('a')[0]\n newUrl = lastAPageElement.attrs['href']\n wd.get(newUrl)\n soup = BeautifulSoup(wd.page_source, features=\"lxml\")\n ColumsChapters = soup.find_all('ul', {'class','list-chapter' })\n listEndChapters = ColumsChapters[len(ColumsChapters)-1].contents\n lastChapter = listEndChapters[len(listEndChapters) - 1]\n a_element = lastChapter.find_all('a')[0]\n totalChapter = getChapter(a_element.text)\n return totalChapter\n\ndef getTextOfPage(url, storyName, chapter): #url, laohac,15\n global wd\n print(\"Crawl : \"+ url)\n storyName = storyName +\"_chuong\"+ str(chapter)+\".txt\"\n if os.path.isfile(storyName) == True:\n return\n wd.get(url)\n soup = BeautifulSoup(wd.page_source, features=\"lxml\")\n items = soup.find_all('div', {'id','chapter-c' })[0]\n # print(items.text)\n writeFile(storyName, items.text)\n\ndef writeFile(filename, content):\n with open(filename, 'w', encoding=\"UTF-8\") as writer:\n writer.write(content)\ndef crawStoryUrl(url, dirout = \"textdir\"):\n if os.path.isdir(dirout) == False:\n os.mkdir(dirout)\n if (url[len(url)-1] != \"/\"):\n url += \"/\"\n temp = url.split(\"/\")\n storyName = dirout + \"/\" + temp[len(temp)-2].replace(\"-\",\"\")\n totalPage = getListChapter(url)\n # exp : 81\n for chapter in range(1,totalPage+1):\n try:\n getTextOfPage(url+'chuong-'+str(chapter),storyName,chapter)\n except Exception as err:\n print(\"Error : \" + str(err))\ndirname = \"textdir\"\nurlPath = 'url.txt'\n# main(url)\nimport normalize\nif __name__ == \"__main__\":\n listUrl = getListUrl(urlPath)\n for url in listUrl:\n print(\"Story path : \"+url)\n try:\n crawStoryUrl(url)\n except Exception as err:\n print(\"Error : \" + str(err))\n normalize.startNormalize()\n # main(url)\n ","sub_path":"task/2020-11-23/Crawler/crawl_truyenfull.py","file_name":"crawl_truyenfull.py","file_ext":"py","file_size_in_byte":3089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"482899678","text":"from datalog import Datalog\n\nclass Mydata(Datalog) :\n def printlog(self) :\n for date, data in self.loglist :\n print(date, data)\n\nobj = Mydata()\nobj.log(\"あいう\")\nobj.log(\"abc\")\nobj.log(123)\nobj.printlog()\n","sub_path":"python_study_samples/mydata_test.py","file_name":"mydata_test.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"14502140","text":"import matplotlib.pyplot as plt\nx=[1,2,3,5,6,7,8,9,10]\ny=[5,7,4,6,7,8,9,2,5]\nx2=[1,2,3,4,5,6,7,8,9,10]\ny2=[7,5,6,4,8,12,13,10,2,5]\nplt.plot(x,y, label='india')\nplt.plot(x2,y2,label='england')\nplt.xlabel('over number')\nplt.ylabel('runs')\nplt.title('my graph')\nplt.legend()\nplt.show()\n","sub_path":"programs-part@2/plot1.py","file_name":"plot1.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"207855625","text":"import os\nimport requests\nfrom requests.exceptions import HTTPError\nimport json\nimport pandas as pd\nfrom tabulate import tabulate\nimport re\nimport textwrap\n\n\nclass ticket_viewer:\n \"\"\"An object representation for ticket viewer application\"\"\"\n\n\n def __init__(self, user=os.environ.get('zcc_user') + '/token', pwd=os.environ.get('zcc_pwd1')):\n \"\"\"Initializes a ticket_viewer object with credentials for user and token\"\"\"\n self.user = user\n self.pwd = pwd\n\n\n\n\n def list_api_call(self, url='https://zccstudentshelp.zendesk.com/api/v2/tickets.json', param={'page[size]': '25'}):\n \"\"\"Sends a get request to get the list of tickets\n :param url: api endpoint to access the list of tickets\n param: Parameters for params field of requests.get\n (default parameter declares page size)\n :return response: response from the api call\n\n \"\"\"\n try:\n response = requests.get(url, auth=(self.user, self.pwd), params=param)\n response.raise_for_status()\n return response\n\n # Handles exceptions\n except HTTPError as http_err:\n if response.status_code == 400:\n print(f'Bad request, make sure you typed everything correctly. {http_err}')\n\n elif response.status_code == 403:\n print(f'The user does not have permission for api call. {http_err}')\n\n elif response.status_code == 404:\n print(f'Check if the url entered is correct. {http_err}')\n\n else:\n print(f'HTTP error occurred: {http_err}')\n\n\n except Exception as err:\n print(f'Other error occurred: {err}')\n\n\n\n def list_reformat(self, response_json):\n \"\"\"Converts json to data frame and handels missing values\n :param response_json(dictionary): tickets data\n :return data(data frame): particular fields of ticket data\n\n \"\"\"\n\n def wrap(row):\n \"\"\" Formats the data so that it wraps around while displaying\n :param row: ticket description\n :return same ticket description with each line containing 60 chars\n \"\"\"\n return '\\n'.join(re.findall('.{1,60}', row))\n\n if response_json:\n df = pd.DataFrame(response_json['tickets'])\n\n if not df.empty:\n \n # Replaces missing values with \"Unknown\" and formats description to wrap around\n df.fillna(\"Unknown\", inplace=True)\n data = df.loc[:, ['id', 'created_at', 'subject', 'priority', 'status', 'description']]\n desc_wraped = data.description.apply(wrap)\n del data['description']\n data['description'] = desc_wraped\n return data\n\n\n else:\n print(\"No tickets available to show!\")\n\n\n\n def display_list(self, response_json):\n \"\"\"Displays the ticket data in tabular format, provides options to toggle through\n the pages\n :param response_json(dictionary): ticket data\n \"\"\"\n\n while True:\n print(\"Menu:\")\n print(\"1. Type 'next': To go to next page \")\n print(\"2. Type 'prev': To go to previous page\")\n print(\"3. Type 'exit': To return to main menu\")\n\n x = input(\"Choose option:\")\n\n if x in ['next', 'prev']:\n if response_json['meta']['has_more']:\n new_url = response_json['links'][x]\n move = self.list_api_call(new_url) #calls list_api_call to get information for the next or prev page \n\n if move:\n response_json = move.json()\n data = self.list_reformat(move.json()) # reformats the data\n print(tabulate(data, headers=\"keys\", tablefmt='fancy_grid')) # prints the data in tabular format\n\n\n else:\n print(\"No more pages available!\")\n print(\"Returning to main menu!\")\n return\n\n\n elif x == 'exit':\n print(\"Returning to main menu!\")\n return\n\n\n else:\n print(\"Please input a valid option\")\n\n\n\n def single_api_call(self, id):\n \"\"\"Sends a get request to get ticket with id if exists\n :param id: ticket id to identify the requested ticket\n :return response: response from the api call\n\n \"\"\"\n\n url = 'https://zccstudentshelp.zendesk.com/api/v2/tickets/' + str(id) + '.json'\n\n try:\n response = requests.get(url, auth=(self.user, self.pwd))\n response.raise_for_status()\n return response\n\n # Handle exceptions\n except HTTPError as http_err:\n if response.status_code == 404:\n print(\"Please enter a valid ticket id.\")\n\n else:\n print(f'HTTP error occurred: {http_err}')\n\n except Exception as err:\n print(f'Other error occurred: {err}')\n\n\n\n def display_single(self, response_json):\n \"\"\"\n Displays the selected information for the ticket, handels missing values\n :param response_json(dictionary): ticket data\n \"\"\"\n data = response_json['ticket']\n\n print(\"id: {0:d}\".format(data['id']))\n print(\"created at: {0:s}\".format(data['created_at'])) if data['created_at'] else print(\"created_at: Unknown\")\n print(\"subject: {0:s}\".format(data['subject'])) if data['subject'] else print(\"subject: Unknown\")\n print(\"priority: {0:s}\".format(data['priority'])) if data['priority'] else print(\"priority: Unknown\")\n print(\"status: {0:s}\".format(data['status'])) if data['status'] else print(\"status: Unknown\")\n\n if not data['description']:\n print(\"Description: Unknown\")\n\n else:\n # display the description in a paragraph format\n desc_wrap = textwrap.wrap(data['description'], width=70)\n print(\"description:\")\n\n for text in desc_wrap:\n print(text)\n\n\ndef main():\n \"\"\"Allows the user to choose between single view, list view and exiting\"\"\"\n obj = ticket_viewer()\n print(\"Hello User!\")\n\n while True:\n print()\n print(\"Main Menu\")\n print(\"Enter 1: To view a single ticket (requires id)\")\n print(\"Enter 2: To view a list of tickets\")\n print(\"Enter 3: To exit\")\n \n user_input = input(\"Choose option:\")\n\n if user_input == \"1\":\n tick_id = int(input(\"Please enter ticket id:\"))\n response = obj.single_api_call(tick_id)\n \n if response:\n obj.display_single(response.json())\n\n elif user_input == \"2\":\n response = obj.list_api_call()\n \n if response:\n data = obj.list_reformat(response.json())\n \n if not data.empty:\n print(tabulate(data, headers=\"keys\", tablefmt='fancy_grid'))\n obj.display_list(response.json())\n\n \n elif user_input == \"3\":\n print(\"Closing application!\")\n return\n\n \n else:\n print(\"Please choose a valid option\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"ticket_viewer.py","file_name":"ticket_viewer.py","file_ext":"py","file_size_in_byte":7360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"453806183","text":"# Copyright (c) 2015, Michael Boyle\n# See LICENSE file for details: <https://github.com/moble/scri/blob/master/LICENSE>\n\nfrom __future__ import print_function, division, absolute_import\n\nfrom math import sqrt\n\nimport numpy as np\n\nfrom spherical_functions import ladder_operator_coefficient as ladder\nfrom quaternion.numba_wrapper import jit, njit, xrange\n\n\n@njit('void(c16[:,:], c16[:,:], i8[:,:], f8[:,:])')\ndef _LdtVector(data, datadot, lm, Ldt):\n \"\"\"Helper function for the LdtVector function\"\"\"\n # Big, bad, ugly, obvious way to do the calculation\n # =================================================\n # L+ = Lx + i Ly Lx = (L+ + L-) / 2\n # L- = Lx - i Ly Ly = -i (L+ - L-) / 2\n\n for i_mode in xrange(lm.shape[0]):\n L = lm[i_mode, 0]\n M = lm[i_mode, 1]\n for i_time in xrange(data.shape[0]):\n # Compute first in (+,-,z) basis\n Lp = (np.conjugate(data[i_time, i_mode + 1]) * datadot[i_time, i_mode] * ladder(L, M)\n if M + 1 <= L\n else 0.0 + 0.0j)\n Lm = (np.conjugate(data[i_time, i_mode - 1]) * datadot[i_time, i_mode] * ladder(L, -M)\n if M - 1 >= -L\n else 0.0 + 0.0j)\n Lz = np.conjugate(data[i_time, i_mode]) * datadot[i_time, i_mode] * M\n\n # Convert into (x,y,z) basis\n Ldt[i_time, 0] += 0.5 * (Lp.imag + Lm.imag)\n Ldt[i_time, 1] += -0.5 * (Lp.real - Lm.real)\n Ldt[i_time, 2] += Lz.imag\n return\n\n\ndef LdtVector(W):\n r\"\"\"Calculate the <Ldt> quantity with respect to the modes\n\n The vector is given in the (possibly rotating) mode frame (X,Y,Z),\n rather than the inertial frame (x,y,z).\n\n <Ldt>^{a} = \\sum_{\\ell,m,m'} \\bar{f}^{\\ell,m'} < \\ell,m' | L_a | \\ell,m > (df/dt)^{\\ell,m}\n\n \"\"\"\n Ldt = np.zeros((W.n_times, 3), dtype=float)\n _LdtVector(W.data, W.data_dot, W.LM, Ldt)\n return Ldt\n\n\n@njit('void(c16[:,:], c16[:,:], i8[:,:], c16[:,:])')\ndef _LVector(data1, data2, lm, Lvec):\n \"\"\"Helper function for the LVector function\"\"\"\n # Big, bad, ugly, obvious way to do the calculation\n # =================================================\n # L+ = Lx + i Ly Lx = (L+ + L-) / 2\n # L- = Lx - i Ly Ly = -i (L+ - L-) / 2\n\n for i_mode in xrange(lm.shape[0]):\n L = lm[i_mode, 0]\n M = lm[i_mode, 1]\n for i_time in xrange(data1.shape[0]):\n # Compute first in (+,-,z) basis\n Lp = (np.conjugate(data1[i_time, i_mode + 1]) * data2[i_time, i_mode] * ladder(L, M)\n if M + 1 <= L\n else 0.0 + 0.0j)\n Lm = (np.conjugate(data1[i_time, i_mode - 1]) * data2[i_time, i_mode] * ladder(L, -M)\n if M - 1 >= -L\n else 0.0 + 0.0j)\n Lz = np.conjugate(data1[i_time, i_mode]) * data2[i_time, i_mode] * M\n\n # Convert into (x,y,z) basis\n Lvec[i_time, 0] += 0.5 * (Lp + Lm)\n Lvec[i_time, 1] += -0.5j * (Lp - Lm)\n Lvec[i_time, 2] += Lz\n return\n\n\ndef LVector(W1, W2):\n r\"\"\"Calculate the <L> quantity with respect to the modes\n\n The vector is given in the (possibly rotating) mode frame (X,Y,Z),\n rather than the inertial frame (x,y,z).\n\n <L>^{a} = \\sum_{\\ell,m,m'} \\bar{f}^{\\ell,m'} < \\ell,m' | L_a | \\ell,m > g^{\\ell,m}\n\n \"\"\"\n L = np.zeros((W1.n_times, 3), dtype=complex)\n _LVector(W1.data, W2.data, W1.LM, L)\n return L\n\n\n@njit('void(c16[:,:], c16[:,:], i8[:,:], c16[:,:,:])')\ndef _LLComparisonMatrix(data1, data2, lm, LL):\n \"\"\"Helper function for the LLComparisonMatrix function\"\"\"\n # Big, bad, ugly, obvious way to do the calculation\n # =================================================\n # L+ = Lx + i Ly Lx = (L+ + L-) / 2 Im(Lx) = ( Im(L+) + Im(L-) ) / 2\n # L- = Lx - i Ly Ly = -i (L+ - L-) / 2 Im(Ly) = -( Re(L+) - Re(L-) ) / 2\n # Lz = Lz Lz = Lz Im(Lz) = Im(Lz)\n # LxLx = (L+ + L-)(L+ + L-) / 4\n # LxLy = -i(L+ + L-)(L+ - L-) / 4\n # LxLz = (L+ + L-)( Lz ) / 2\n # LyLx = -i(L+ - L-)(L+ + L-) / 4\n # LyLy = -(L+ - L-)(L+ - L-) / 4\n # LyLz = -i(L+ - L-)( Lz ) / 2\n # LzLx = ( Lz )(L+ + L-) / 2\n # LzLy = -i( Lz )(L+ - L-) / 2\n # LzLz = ( Lz )( Lz )\n\n for i_mode in xrange(lm.shape[0]):\n L = lm[i_mode, 0]\n M = lm[i_mode, 1]\n for i_time in xrange(data1.shape[0]):\n # Compute first in (+,-,z) basis\n LpLp = (np.conjugate(data1[i_time, i_mode + 2]) * data2[i_time, i_mode] * (ladder(L, M + 1) * ladder(L, M))\n if M + 2 <= L\n else 0.0 + 0.0j)\n LpLm = (np.conjugate(data1[i_time, i_mode]) * data2[i_time, i_mode] * (ladder(L, M - 1) * ladder(L, -M))\n if M - 1 >= -L\n else 0.0 + 0.0j)\n LmLp = (np.conjugate(data1[i_time, i_mode]) * data2[i_time, i_mode] * (ladder(L, -(M + 1)) * ladder(L, M))\n if M + 1 <= L\n else 0.0 + 0.0j)\n LmLm = (\n np.conjugate(data1[i_time, i_mode - 2]) * data2[i_time, i_mode] * (ladder(L, -(M - 1)) * ladder(L, -M))\n if M - 2 >= -L\n else 0.0 + 0.0j)\n LpLz = (np.conjugate(data1[i_time, i_mode + 1]) * data2[i_time, i_mode] * (ladder(L, M) * M)\n if M + 1 <= L\n else 0.0 + 0.0j)\n LzLp = (np.conjugate(data1[i_time, i_mode + 1]) * data2[i_time, i_mode] * ((M + 1) * ladder(L, M))\n if M + 1 <= L\n else 0.0 + 0.0j)\n LmLz = (np.conjugate(data1[i_time, i_mode - 1]) * data2[i_time, i_mode] * (ladder(L, -M) * M)\n if M - 1 >= -L\n else 0.0 + 0.0j)\n LzLm = (np.conjugate(data1[i_time, i_mode - 1]) * data2[i_time, i_mode] * ((M - 1) * ladder(L, -M))\n if M - 1 >= -L\n else 0.0 + 0.0j)\n LzLz = np.conjugate(data1[i_time, i_mode]) * data2[i_time, i_mode] * M ** 2\n\n # Convert into (x,y,z) basis\n LL[i_time, 0, 0] += 0.25 * (LpLp + LmLm + LmLp + LpLm)\n LL[i_time, 0, 1] += -0.25j * (LpLp - LmLm + LmLp - LpLm)\n LL[i_time, 0, 2] += 0.5 * (LpLz + LmLz)\n LL[i_time, 1, 0] += -0.25j * (LpLp - LmLp + LpLm - LmLm)\n LL[i_time, 1, 1] += -0.25 * (LpLp - LmLp - LpLm + LmLm)\n LL[i_time, 1, 1] += -0.5j * (LpLz - LmLz)\n LL[i_time, 2, 0] += 0.5 * (LzLp + LzLm)\n LL[i_time, 2, 1] += -0.5j * (LzLp - LzLm)\n LL[i_time, 2, 2] += LzLz\n\n # # Symmetrize\n # LL[i_time,0,0] += ( LxLx ).real\n # LL[i_time,0,1] += ( LxLy + LyLx ).real/2.0\n # LL[i_time,0,2] += ( LxLz + LzLx ).real/2.0\n # LL[i_time,1,0] += ( LyLx + LxLy ).real/2.0\n # LL[i_time,1,1] += ( LyLy ).real\n # LL[i_time,1,2] += ( LyLz + LzLy ).real/2.0\n # LL[i_time,2,0] += ( LzLx + LxLz ).real/2.0\n # LL[i_time,2,1] += ( LzLy + LyLz ).real/2.0\n # LL[i_time,2,2] += ( LzLz ).real\n return\n\n\ndef LLComparisonMatrix(W1, W2):\n r\"\"\"Calculate the <LL> quantity with respect to the modes of two Waveforms\n\n The matrix is given in the (possibly rotating) mode frame (X,Y,Z),\n rather than the inertial frame (x,y,z).\n\n <LL>^{ab} = \\sum_{\\ell,m,m'} \\bar{f}^{\\ell,m'} < \\ell,m' | L_a L_b | \\ell,m > g^{\\ell,m}\n\n \"\"\"\n LL = np.zeros((W1.n_times, 3, 3), dtype=complex)\n _LLComparisonMatrix(W1.data, W2.data, W1.LM, LL)\n return LL\n\n\n@njit('void(c16[:,:], i8[:,:], f8[:,:,:])')\ndef _LLMatrix(data, lm, LL):\n \"\"\"Helper function for the LLMatrix function\"\"\"\n # Big, bad, ugly, obvious way to do the calculation\n # =================================================\n # L+ = Lx + i Ly Lx = (L+ + L-) / 2 Im(Lx) = ( Im(L+) + Im(L-) ) / 2\n # L- = Lx - i Ly Ly = -i (L+ - L-) / 2 Im(Ly) = -( Re(L+) - Re(L-) ) / 2\n # Lz = Lz Lz = Lz Im(Lz) = Im(Lz)\n # LxLx = (L+ + L-)(L+ + L-) / 4\n # LxLy = -i(L+ + L-)(L+ - L-) / 4\n # LxLz = (L+ + L-)( Lz ) / 2\n # LyLx = -i(L+ - L-)(L+ + L-) / 4\n # LyLy = -(L+ - L-)(L+ - L-) / 4\n # LyLz = -i(L+ - L-)( Lz ) / 2\n # LzLx = ( Lz )(L+ + L-) / 2\n # LzLy = -i( Lz )(L+ - L-) / 2\n # LzLz = ( Lz )( Lz )\n\n for i_mode in xrange(lm.shape[0]):\n L = lm[i_mode, 0]\n M = lm[i_mode, 1]\n for i_time in xrange(data.shape[0]):\n # Compute first in (+,-,z) basis\n LpLp = (np.conjugate(data[i_time, i_mode + 2]) * data[i_time, i_mode] * (ladder(L, M + 1) * ladder(L, M))\n if M + 2 <= L\n else 0.0 + 0.0j)\n LpLm = (np.conjugate(data[i_time, i_mode]) * data[i_time, i_mode] * (ladder(L, M - 1) * ladder(L, -M))\n if M - 1 >= -L\n else 0.0 + 0.0j)\n LmLp = (np.conjugate(data[i_time, i_mode]) * data[i_time, i_mode] * (ladder(L, -(M + 1)) * ladder(L, M))\n if M + 1 <= L\n else 0.0 + 0.0j)\n LmLm = (\n np.conjugate(data[i_time, i_mode - 2]) * data[i_time, i_mode] * (ladder(L, -(M - 1)) * ladder(L, -M))\n if M - 2 >= -L\n else 0.0 + 0.0j)\n LpLz = (np.conjugate(data[i_time, i_mode + 1]) * data[i_time, i_mode] * (ladder(L, M) * M)\n if M + 1 <= L\n else 0.0 + 0.0j)\n LzLp = (np.conjugate(data[i_time, i_mode + 1]) * data[i_time, i_mode] * ((M + 1) * ladder(L, M))\n if M + 1 <= L\n else 0.0 + 0.0j)\n LmLz = (np.conjugate(data[i_time, i_mode - 1]) * data[i_time, i_mode] * (ladder(L, -M) * M)\n if M - 1 >= -L\n else 0.0 + 0.0j)\n LzLm = (np.conjugate(data[i_time, i_mode - 1]) * data[i_time, i_mode] * ((M - 1) * ladder(L, -M))\n if M - 1 >= -L\n else 0.0 + 0.0j)\n LzLz = np.conjugate(data[i_time, i_mode]) * data[i_time, i_mode] * M ** 2\n\n # Convert into (x,y,z) basis\n LxLx = 0.25 * (LpLp + LmLm + LmLp + LpLm)\n LxLy = -0.25j * (LpLp - LmLm + LmLp - LpLm)\n LxLz = 0.5 * (LpLz + LmLz)\n LyLx = -0.25j * (LpLp - LmLp + LpLm - LmLm)\n LyLy = -0.25 * (LpLp - LmLp - LpLm + LmLm)\n LyLz = -0.5j * (LpLz - LmLz)\n LzLx = 0.5 * (LzLp + LzLm)\n LzLy = -0.5j * (LzLp - LzLm)\n # LzLz = (LzLz)\n\n # Symmetrize\n LL[i_time, 0, 0] += LxLx.real\n LL[i_time, 0, 1] += (LxLy + LyLx).real / 2.0\n LL[i_time, 0, 2] += (LxLz + LzLx).real / 2.0\n LL[i_time, 1, 0] += (LyLx + LxLy).real / 2.0\n LL[i_time, 1, 1] += LyLy.real\n LL[i_time, 1, 2] += (LyLz + LzLy).real / 2.0\n LL[i_time, 2, 0] += (LzLx + LxLz).real / 2.0\n LL[i_time, 2, 1] += (LzLy + LyLz).real / 2.0\n LL[i_time, 2, 2] += LzLz.real\n return\n\n\ndef LLMatrix(W):\n r\"\"\"Calculate the <LL> quantity with respect to the modes\n\n The matrix is given in the (possibly rotating) mode frame (X,Y,Z),\n rather than the inertial frame (x,y,z).\n\n This quantity is as prescribed by O'Shaughnessy et al.\n <http://arxiv.org/abs/1109.5224>, except that no normalization is\n imposed, and this operates on whatever type of data is input.\n\n <LL>^{ab} = Re \\{ \\sum_{\\ell,m,m'} \\bar{f}^{\\ell,m'} < \\ell,m' | L_a L_b | \\ell,m > f^{\\ell,m} \\}\n\n \"\"\"\n LL = np.zeros((W.n_times, 3, 3), dtype=float)\n _LLMatrix(W.data, W.LM, LL)\n return LL\n\n\n@njit('void(f8[:,:], f8[:])')\ndef _LLDominantEigenvector(dpa, dpa_i):\n \"\"\"Jitted helper function for LLDominantEigenvector\"\"\"\n # Make the initial direction closer to RoughInitialEllDirection than not\n if (dpa_i[0] * dpa[0, 0] + dpa_i[1] * dpa[0, 1] + dpa_i[2] * dpa[0, 2]) < 0.:\n dpa[0, 0] *= -1\n dpa[0, 1] *= -1\n dpa[0, 2] *= -1\n # Now, go through and make the vectors reasonably continuous.\n if dpa.shape[0] > 0:\n LastNorm = sqrt(dpa[0, 0] ** 2 + dpa[0, 1] ** 2 + dpa[0, 2] ** 2)\n for i in xrange(1, dpa.shape[0]):\n Norm = dpa[i, 0] ** 2 + dpa[i, 1] ** 2 + dpa[i, 2] ** 2\n dNorm = (dpa[i, 0] - dpa[i - 1, 0]) ** 2 + (dpa[i, 1] - dpa[i - 1, 1]) ** 2 + (dpa[i, 2] - dpa[\n i - 1, 2]) ** 2\n if dNorm > Norm:\n dpa[i, 0] *= -1\n dpa[i, 1] *= -1\n dpa[i, 2] *= -1\n # While we're here, let's just normalize that last one\n if LastNorm != 0.0 and LastNorm != 1.0:\n dpa[i - 1, 0] /= LastNorm\n dpa[i - 1, 1] /= LastNorm\n dpa[i - 1, 2] /= LastNorm\n LastNorm = sqrt(Norm)\n if LastNorm != 0.0 and LastNorm != 1.0:\n i = dpa.shape[0] - 1\n dpa[i, 0] /= LastNorm\n dpa[i, 1] /= LastNorm\n dpa[i, 2] /= LastNorm\n return\n\n\ndef LLDominantEigenvector(W, RoughInitialDirection=np.array([0.0, 0.0, 1.0])):\n \"\"\"Calculate the principal axis of the LL matrix\n\n \\param Lmodes L modes to evaluate (optional)\n \\param RoughInitialEllDirection Vague guess about the preferred initial (optional)\n\n If Lmodes is empty (default), all L modes are used. Setting\n Lmodes to [2] or [2,3,4], for example, restricts the range of\n the sum.\n\n Ell is the direction of the angular velocity for a PN system, so\n some rough guess about that direction allows us to choose the\n direction of the eigenvectors output by this function to be more\n parallel than anti-parallel to that direction. The default is\n to simply choose the z axis, since this is most often the\n correct choice anyway.\n\n The vector is given in the (possibly rotating) mode frame\n (X,Y,Z), rather than the inertial frame (x,y,z).\n\n \"\"\"\n # Calculate the LL matrix at each instant\n LL = np.zeros((W.n_times, 3, 3), dtype=float)\n _LLMatrix(W.data, W.LM, LL)\n\n # This is the eigensystem\n eigenvals, eigenvecs = np.linalg.eigh(LL)\n\n # Now we find and normalize the dominant principal axis at each\n # moment, made continuous\n dpa = eigenvecs[:, :, 2] # `eigh` always returns eigenvals in *increasing* order\n _LLDominantEigenvector(dpa, RoughInitialDirection)\n\n return dpa\n\n\n@jit\ndef angular_velocity(W):\n \"\"\"Angular velocity of Waveform\n\n This function calculates the angular velocity of a Waveform object from\n its modes. This was introduced in Sec. II of \"Angular velocity of\n gravitational radiation and the corotating frame\"\n <http://arxiv.org/abs/1302.2919>. Essentially, this is the angular\n velocity of the rotating frame in which the time dependence of the modes\n is minimized.\n\n The vector is given in the (possibly rotating) mode frame (X,Y,Z),\n rather than the inertial frame (x,y,z).\n\n \"\"\"\n\n # Calculate the L vector and LL matrix at each instant\n l = W.LdtVector()\n ll = W.LLMatrix()\n\n omega = np.linalg.solve(ll, l)\n\n # omega = np.empty_like(l)\n # for i in xrange(omega.shape[0]):\n # omega[i] = scipy.linalg.solve(ll[i], l[i], sym_pos=True, overwrite_a=True, overwrite_b=True, check_finite=False)\n\n return -omega\n","sub_path":"mode_calculations.py","file_name":"mode_calculations.py","file_ext":"py","file_size_in_byte":15379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"438368957","text":"\"\"\"Module to hold views associated with attribute management.\"\"\"\n\nfrom pitch.models import Section, TableAttribute, Area, TrackedObject\nfrom django.shortcuts import (loader, HttpResponse,\n HttpResponseRedirect, reverse)\nfrom django.core import serializers\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.contrib.auth.decorators import permission_required, login_required\nfrom pitch.pitch_supplemental import input_field\nimport ast\nfrom django.contrib.auth.models import User\n\n\n@login_required\ndef custom_attributes_index(request):\n \"\"\"Retrieve the custom attributes.\"\"\"\n template = loader.get_template('pitch/pitch_custom_headings.html')\n user = request.user\n user_areas = list(user.area_set.all())\n attributes = TableAttribute.objects.filter(attribute_area__in=user_areas)\n context = {\n 'attributes': attributes,\n }\n\n return HttpResponse(template.render(context, request))\n\n\n@login_required\ndef add_attribute(request):\n \"\"\"Add a custom attribute.\"\"\"\n template = loader.get_template('pitch/add_attribute.html')\n area_list = Area.objects.filter(area_admins=request.user)\n name_html = input_field(name='Attribute name',\n field_type='Text',\n data=None).get_html()\n area_html = input_field(name='Attribute area',\n field_type='Selection',\n data=area_list).get_html()\n type_html = input_field(name='Attribute type',\n field_type='Selection',\n data=['Text','Selection','User','Date']).get_html()\n data_html = input_field(name='Attribute data',\n field_type='Text',\n data=None).get_html()\n html_list = [name_html,\n area_html,\n type_html,\n data_html]\n\n context = {\n 'html_list': html_list,\n }\n\n return HttpResponse(template.render(context, request))\n\n\n@login_required\ndef save_new_attribute(request):\n \"\"\"Save New Attribute.\"\"\"\n try:\n new_attribute = TableAttribute.objects.get(pk=int(\n request.POST['att_id']))\n except (KeyError, ValueError):\n new_attribute = TableAttribute()\n new_attribute.attribute_name = request.POST['Attribute name']\n new_attribute.attribute_area = Area.objects.get(\n area_name=request.POST['Attribute area'])\n new_attribute.attribute_type = request.POST['Attribute type']\n new_attribute.attribute_data = request.POST['Attribute data']\n try:\n request.POST['Historical Status']\n historical = True\n except KeyError:\n historical = False\n new_attribute.historical_status = historical\n new_attribute.save()\n return HttpResponseRedirect(reverse('pitch:custom_attributes_index'))\n\n\n@login_required\ndef edit_attribute(request, attribute_id):\n \"\"\"Add a custom attribute.\"\"\"\n areas = Area.objects.filter(active_status=True)\n attribute = TableAttribute.objects.get(pk=attribute_id)\n template = loader.get_template('pitch/add_attribute.html')\n area_list = Area.objects.filter(area_admins=request.user)\n name_html = input_field(name='Attribute name',\n field_type='Text',\n data=None,\n value=attribute.attribute_name).get_html()\n area_html = input_field(name='Attribute area',\n field_type='Selection',\n data=area_list,\n value=attribute.attribute_area).get_html()\n type_html = input_field(name='Attribute type',\n field_type='Selection',\n data=['Text', 'Selection', 'User', 'Date'],\n value=attribute.attribute_type).get_html()\n data_html = input_field(name='Attribute data',\n field_type='Text',\n data=None,\n value=attribute.attribute_data).get_html()\n html_list = [name_html,\n area_html,\n type_html,\n data_html]\n\n context = {\n 'attribute': attribute,\n 'html_list': html_list,\n }\n\n return HttpResponse(template.render(context, request))\n","sub_path":"Python/Web Development/mgmt_views/attributes.py","file_name":"attributes.py","file_ext":"py","file_size_in_byte":4328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"599631596","text":"#!/bin/python3\n\nimport os\nimport sys\n\n# Complete the solve function below.\ndef solve(d):\n # Brute Force O(n3) ... Should not be used\n lst = []\n count = 0\n d = sorted(d)\n for i in range(len(d)-2):\n for j in range(i+1, len(d)-1):\n for k in range(j+1, len(d)):\n if (i < j < k) and (d[i] < d[j] < d[k]):\n lst.append((d[i], d[j], d[k]))\n for (i, j, k) in set(lst):\n if i < j < k:\n count += 1\n print(i, j, k)\n return count\n# ------------- # -------------- # ----------------- #\n\n\n\n\nif __name__ == '__main__':\n fptr = open('OUTPUT/Triplets', 'w')\n d_count = int(input())\n d = list(map(int, input().rstrip().split()))\n result = solve(d)\n fptr.write(str(result) + '\\n')\n fptr.close()\n","sub_path":"Hard/Triplets.py","file_name":"Triplets.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"184439170","text":"from unittest import TestCase\r\nimport pymel.core as pm\r\nimport fixUT\r\nimport road\r\n\r\n__author__ = 'crogers'\r\n\"\"\"These will test each method in Road making sure that the return the correct type of objects\r\nor that the correct attributes are connected\r\nat some point it might be necessary to check the meshs that get returned.\r\n\"\"\"\r\n\r\n#these override the normal defaults\r\nTEST_DEFAULTS = {\r\n 'left_guard_rail': False,\r\n 'left_gutter': False,\r\n 'left_sidewalk': False,\r\n 'left_curb': False,\r\n 'right_guard_rail': False,\r\n 'right_sidewalk': False,\r\n 'right_gutter': False,\r\n 'right_curb': False,\r\n }\r\n\r\nclass TestRoad(TestCase):\r\n def setUp(self):\r\n self.road = road.Road()\r\n # must select a curve\r\n self.curve = pm.curve(degree=3, p=[(0,0,0),(1,0,0),(2,0,0),(3,0,0)], k=[0,0,0,1,1,1])\r\n\r\n def setUp2(self):\r\n pm.select(self.curve)\r\n self.road_node = self.road.construct_roads(**TEST_DEFAULTS)\r\n\r\n def test_construct_roads(self):\r\n self.setUp2()\r\n self.assertIsInstance(self.road_node, pm.nodetypes.Transform)\r\n\r\n\r\n\r\n def test__process_kwarg_defaults(self):\r\n node = pm.createNode('transform')\r\n defaults = {'attr_int': 1,\r\n 'attr_string': 'not_ok',\r\n 'attr_float': 0.33\r\n }\r\n kwargs = {}\r\n pm.select(self.curve)\r\n self.road._process_kwargs(node, defaults, kwargs)\r\n #check for attrs on self\r\n self.assertEquals(self.road.attr_int, 1)\r\n self.assertEquals(self.road.attr_string, 'not_ok')\r\n self.assertAlmostEquals(self.road.attr_float, 0.33, places=2)\r\n self.assertEquals(pm.getAttr(node+'.attr_int'), 1)\r\n self.assertEquals(pm.getAttr(node+'.attr_string'), 'not_ok')\r\n self.assertAlmostEquals(pm.getAttr(node+'.attr_float'), 0.33, places=2)\r\n\r\n def test__process_kwargs_override(self):\r\n node = pm.createNode('transform')\r\n defaults = {'attr_int': 1,\r\n 'attr_string': 'not_ok',\r\n 'attr_float': 0.33\r\n }\r\n kwargs = {'attr_int': 9,\r\n 'attr_string': 'ok',\r\n 'attr_float': 9.9\r\n }\r\n pm.select(self.curve)\r\n self.road._process_kwargs(node, defaults, kwargs)\r\n\r\n #check for attrs on self\r\n self.assertEquals(self.road.attr_int, 9)\r\n self.assertEquals(self.road.attr_string, 'ok')\r\n self.assertAlmostEquals(self.road.attr_float, 9.9, places=1)\r\n self.assertEquals(pm.getAttr(node+'.attr_int'), 9)\r\n self.assertEquals(pm.getAttr(node+'.attr_string'), 'ok')\r\n self.assertAlmostEquals(pm.getAttr(node+'.attr_float'), 9.9, places=1)\r\n\r\n\r\n def test__do_connection(self):\r\n side = 'right'\r\n #create a mesh\r\n mesh = pm.polyCube()[0]\r\n pm.addAttr(mesh, shortName='controller', attributeType='float')\r\n controller = mesh.controller\r\n target_attr = mesh.ty\r\n pm.setAttr(controller, 5.5)\r\n cns = self.road._do_connection(side, mesh, self.curve, controller, target_attr)[0]\r\n # the right side is connected to a multiplyDivide(-1) so the result is -value\r\n self.assertIsInstance(cns, pm.nodetypes.MultiplyDivide)\r\n self.assertAlmostEqual( pm.getAttr(target_attr), -5.5, places=1)\r\n side = 'left'\r\n mesh = pm.polyCube()[0]\r\n pm.addAttr(mesh, shortName='controller', attributeType='float')\r\n cns = self.road._do_connection(side, mesh, self.curve, controller, target_attr)[0]\r\n pm.setAttr(controller, 9.9)\r\n self.assertAlmostEquals( pm.getAttr(target_attr), 9.9, places=1)\r\n\r\n def test__offset(self):\r\n curve ='curve1'\r\n spans = 4\r\n distance = 1\r\n UP = [0, 1, 0]\r\n name = 'no_name'\r\n pm.rebuildCurve(curve, ch=1, spans=spans)\r\n xform, offset = pm.offsetCurve(curve, distance=distance, normal=UP, name=name)\r\n #name of curve\r\n self.assertEquals(xform,'no_name')\r\n #make sure the second node returned is an offsetCurve node\r\n self.assertIsInstance(offset, pm.nodetypes.OffsetCurve)\r\n\r\n def test__offset_road_edges(self):\r\n self.setUp2()\r\n (left_edge, left_offset), (right_edge, right_offset) = self.road._offset_road_edges()\r\n self.assertIsInstance(left_offset, pm.nodetypes.OffsetCurve)\r\n self.assertIsInstance(right_offset, pm.nodetypes.OffsetCurve)\r\n\r\n def test__connect_subd(self):\r\n self.setUp2()\r\n mesh = self.road._create_road_surface()\r\n subd = self.road._connect_subd(mesh)\r\n #self.assertIsInstance(subd, pm.nodetypes.NurbsTesselate)\r\n\r\n pm.setAttr(self.road_node.length_subd, 5)\r\n self.assertEquals(pm.getAttr(self.road_node.length_subd), 5)\r\n self.assertEquals(pm.getAttr(subd.vNumber), 5)\r\n\r\n pm.setAttr(self.road_node.length_subd, 11)\r\n self.assertEquals(pm.getAttr(self.road_node.length_subd), 11)\r\n self.assertEquals(pm.getAttr(subd.vNumber), 11)\r\n\r\n pm.setAttr(self.road_node.width_subd, 5)\r\n self.assertEquals(pm.getAttr(self.road_node.width_subd), 5)\r\n self.assertEquals(pm.getAttr(subd.uNumber), 5)\r\n\r\n pm.setAttr(self.road_node.width_subd, 11)\r\n self.assertEquals(pm.getAttr(self.road_node.width_subd), 11)\r\n self.assertEquals(pm.getAttr(subd.uNumber), 11)\r\n\r\n def test__create_road_surface(self):\r\n self.setUp2()\r\n mesh = self.road._create_road_surface()\r\n self.assertIsInstance(mesh.getChildren()[0], pm.nodetypes.Mesh)\r\n\r\n def test__create_guard_rail(self):\r\n self.setUp2()\r\n mesh, edge = self.road._create_guard_rail(self.road.current_left_edge, 'left')\r\n self.assertIsInstance(mesh.getChildren()[0], pm.nodetypes.Mesh)\r\n self.assertIsInstance(edge.getChildren()[0], pm.nodetypes.NurbsCurve)\r\n\r\n def test__create_gutter(self):\r\n self.setUp2()\r\n mesh, edge = self.road._create_gutter(self.road.current_left_edge, 'left')\r\n self.assertIsInstance(mesh[1], pm.nodetypes.Loft)\r\n self.assertIsInstance(edge.getChildren()[0], pm.nodetypes.NurbsCurve)\r\n\r\n def test__create_curb(self):\r\n self.setUp2()\r\n mesh, edge = self.road._create_curb(self.road.current_left_edge, 'left')\r\n self.assertIsInstance(mesh[1], pm.nodetypes.Loft)\r\n self.assertIsInstance(edge.getChildren()[0], pm.nodetypes.NurbsCurve)\r\n\r\n def test__create_sidewalk(self):\r\n self.setUp2()\r\n mesh, edge = self.road._create_sidewalk(self.road.current_left_edge, 'left')\r\n self.assertIsInstance(mesh[1], pm.nodetypes.Loft)\r\n self.assertIsInstance(edge.getChildren()[0], pm.nodetypes.NurbsCurve)","sub_path":"tests/unit/test_road.py","file_name":"test_road.py","file_ext":"py","file_size_in_byte":6872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"348069871","text":"#Operações de IO\n\n#cria arquivo (nome_arquivo, modo_de_operacao)\n# w = modo escrita (re-escreve arquivo), a = escreve arquivo e permite concatenar conteudo\n# r = modo de leitura\n\narquivo = open(\"../arquivo.txt\", \"w\").close() #modo escrita\n\narquivo = open(\"../arquivo.txt\", \"a\") #modo append(permite inserir conteudo)\narquivo.write(\"banana\\n\")\narquivo.write(\"melancia\\n\")\narquivo.write(\"abacaxi\\n\")\narquivo.write(\"laranja\\n\")\narquivo.close()\n\narquivo = open(\"../arquivo.txt\", \"r\") #modo leitura(nao permite inserir conteudo)\nconteudo = arquivo.read()\nprint(conteudo)\narquivo.close()\narquivo = open(\"../arquivo.txt\", \"r\")\nconteudo = arquivo.readline()\nprint(conteudo)\narquivo.close()\n\n#Além do r, w e a existe o modificador b que devemos utilizar quando queremos trabalhar no modo binário.\n#Para abrir uma imagem devemos usar:\n#arquivo copia.py\n#logo = open('python-logo.png', 'rb')\n#data = logo.read()\n#logo.close()\n\n#logo2 = open('python-logo2.png', 'wb')\n#logo2.write(data)\n#logo2.close()","sub_path":"referencia/operacoes_de_io.py","file_name":"operacoes_de_io.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"181079529","text":"\nimport FWCore.ParameterSet.Config as cms\n# Select MC truth\nfrom L1TriggerOffline.L1Analyzer.GenSelection_cff import *\n# Select L1\nfrom L1TriggerOffline.L1Analyzer.L1Selection_cff import *\n# Histogram limits\nfrom L1TriggerOffline.L1Analyzer.HistoLimits_cfi import *\n# Root output file\nfrom L1TriggerOffline.L1Analyzer.TFile_cfi import *\n# Match generator and L1 jets \nMatchCenJetsMc = cms.EDFilter(\"TrivialDeltaRMatcher\",\n src = cms.InputTag(\"SelectL1CenJets\"),\n distMin = cms.double(0.5),\n matched = cms.InputTag(\"SelectGenCenJets\")\n)\n\n# Match L1 and generator jets\nMatchMcCenJets = cms.EDFilter(\"TrivialDeltaRMatcher\",\n src = cms.InputTag(\"SelectGenCenJets\"),\n distMin = cms.double(0.5),\n matched = cms.InputTag(\"SelectL1CenJets\")\n)\n\n# Analyzer\nL1AnalyzerCenJetsMC = cms.EDAnalyzer(\"L1Analyzer\",\n histoLimits,\n EffMatchMapSource = cms.untracked.InputTag(\"MatchMcCenJets\"),\n ReferenceSource = cms.untracked.InputTag(\"SelectGenCenJets\"),\n CandidateSource = cms.untracked.InputTag(\"SelectL1CenJets\"),\n ResMatchMapSource = cms.untracked.InputTag(\"MatchCenJetsMc\")\n)\n\n# Define analysis sequence\nL1CenJetMCAnalysis = cms.Sequence(L1CenJetSelection+GenCenJetSelection*MatchCenJetsMc+MatchMcCenJets*L1AnalyzerCenJetsMC)\n\n","sub_path":"L1TriggerOffline/L1Analyzer/python/L1CenJetMCAnalysis_cff.py","file_name":"L1CenJetMCAnalysis_cff.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"548791857","text":"from typing import List\n\nimport numpy as np\nfrom scipy import sparse\n\nfrom .logger import Logger\nfrom .playlist_slice_converter import PlaylistSliceConverter\nfrom .playlist_util import PlaylistUtil\nfrom .track_filter import TrackFilter\n\n\nclass RangingMatrixFactory:\n\n @staticmethod\n def create(file_collection: List[str], pids: int):\n sparse_ranging_matrix, ranging_bool_mask, unique_track_uris = RangingMatrixFactory._create_template(\n file_collection);\n\n sparse_ranging_matrix, ranging_bool_mask, RangingMatrixFactory._reduce_dimension(sparse_ranging_matrix,\n ranging_bool_mask, pids)\n\n Logger.log_info('Create sparse data frame')\n return unique_track_uris, sparse_ranging_matrix, ranging_bool_mask\n\n @staticmethod\n def _reduce_dimension(sparse_matrix, ranging_bool_mask, row_numbs):\n shape = sparse_matrix.get_shape()\n Logger.log_info('Start reducing dimension of sparse matrix from: x=' + str(shape[1]) + '; y=' + str(shape[0]))\n Logger.log_info('Reduce to {} rows'.format(str(row_numbs)))\n\n new_dim = (row_numbs, shape[1])\n sparse_matrix.resize(new_dim);\n ranging_bool_mask.resize(new_dim);\n shape = sparse_matrix.get_shape()\n Logger.log_info('Sparse matrix format after resizing: x=' + str(shape[1]) + '; y=' + str(shape[0]))\n\n return sparse_matrix, ranging_bool_mask\n\n @staticmethod\n def _create_template(file_collection: List[str]):\n Logger.log_info('Start creating initial ranging data frame')\n\n slices = PlaylistSliceConverter.from_json_files(file_collection)\n\n unique_track_uris = TrackFilter.unique_track_uris_from_playlist_slices(slices)\n total_number_of_playlist = PlaylistUtil.count_playlists_of_slices(slices)\n\n x_number = len(unique_track_uris)\n y_number = total_number_of_playlist\n\n Logger.log_info('Matrixdimension: x=' + str(x_number) + '; y=' + str(y_number))\n sparse_ranging_matrix = sparse.dok_matrix((y_number, x_number), dtype=np.float32)\n ranging_bool_mask = sparse.dok_matrix((y_number, x_number), dtype=np.bool)\n\n for p_slice in slices:\n for playlist in p_slice.get_playlist_collection():\n playlist_id = playlist.get_pid()\n\n for track in playlist.get_tracks():\n track_index = unique_track_uris[track.get_simplified_uri()]\n\n sparse_ranging_matrix[playlist_id, track_index] = 1.0\n ranging_bool_mask[playlist_id, track_index] = True\n\n Logger.log_info(\n 'Slice[' + p_slice.get_info().get_item_range() + '] ratings successfully insert into ranging matrix')\n\n Logger.log_info('Finishing initialization of ranging data frame')\n\n return sparse_ranging_matrix, ranging_bool_mask, unique_track_uris\n\n @staticmethod\n def create_sparse_challenge_set(chunk, item_range, unique_track_uris, total_number_of_playlist):\n x_number = len(unique_track_uris)\n y_number = total_number_of_playlist\n\n Logger.log_info('Matrixdimension: x=' + str(x_number) + '; y=' + str(y_number))\n challenge_matrix = sparse.dok_matrix((y_number, x_number), dtype=np.float32)\n template_challenge_matrix = sparse.dok_matrix((y_number, x_number), dtype=np.bool)\n pids = {}\n\n for index, playlist in enumerate(chunk):\n pids[index] = playlist.get_pid()\n\n for track in playlist.get_tracks():\n simple_url = track.get_simplified_uri()\n if simple_url in unique_track_uris:\n track_index = unique_track_uris[track.get_simplified_uri()]\n challenge_matrix[index, int(track_index)] = 1.0\n template_challenge_matrix[index, int(track_index)] = True\n\n Logger.log_info(\n 'Slice[' + item_range + '] ratings successfully insert into challenge matrix')\n\n Logger.log_info('Finishing initialization of challenge data frame')\n\n return challenge_matrix, template_challenge_matrix, pids\n","sub_path":"recommender/ranging_matrix_factory.py","file_name":"ranging_matrix_factory.py","file_ext":"py","file_size_in_byte":4160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"609696688","text":"from contextlib import contextmanager\nfrom collections import OrderedDict\nimport xml.etree.cElementTree as ET\n\n\n@contextmanager\ndef open_file(file_name, mode):\n file = open(file_name, mode)\n yield file\n file.close()\n\n\ndef get_dict_of_words_from_string(resource_string):\n all_words = {}\n\n # divide into lines - tuple with strings - lines\n raw_lines = resource_string.split('\\n')\n\n list_of_characters_to_strip = [' ', '\"', '“', '„', '\\'', ',', ';', '…', '.', '?', '!', ':', '-', '–']\n\n # go through lines in tuple\n for line in raw_lines:\n # divide each line from tuple into words (raw_words_from_line = tuple with words)\n raw_words_from_line = line.split(' ')\n for raw_word in raw_words_from_line:\n word = raw_word.lower()\n # strip the characters from the list\n for i in list_of_characters_to_strip:\n word = word.strip(i)\n\n if word == '':\n continue\n\n if word in all_words:\n all_words[word] += 1\n else:\n all_words[word] = 1\n return all_words\n\n\ndef sort_dict_by_value(resource_dict):\n ordered_dict = OrderedDict(sorted(resource_dict.items(), key=lambda x: x[1], reverse=True))\n return ordered_dict\n\n\ndef write_dict_to_xml(resource_dict, xml_file_name):\n root = ET.Element('root')\n word = ET.SubElement(root, 'word')\n field_counter = 0\n for key, val in resource_dict.items():\n field_counter += 1\n ET.SubElement(word, 'occurence', name=key).text = str(val)\n\n tree = ET.ElementTree(root)\n xml_output_file = tree.write(xml_file_name, xml_declaration=True, encoding='utf-8')\n return xml_output_file\n\n\ndef process_source_file(text_file_name, xml_file_name):\n with open_file(text_file_name, 'r') as resource:\n file_content = resource.read()\n resource.close()\n\n words_from_file = get_dict_of_words_from_string(file_content)\n ordered_dict_words = sort_dict_by_value(words_from_file)\n write_dict_to_xml(ordered_dict_words, xml_file_name)\n\n\nprocess_source_file('rur.txt', 'rur.xml')\n\nwith open_file('rur.xml', 'r') as resource:\n file_content = resource.read()\n","sub_path":"xml_file_from_text_file_with_counts.py","file_name":"xml_file_from_text_file_with_counts.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"608976401","text":"from model import lstm_activity\nimport torch.nn.functional as F\n# import pytorch_forecasting\nfrom torch.autograd import Variable\nfrom torch.utils.data import TensorDataset, DataLoader\nimport torch\nimport os\nimport matplotlib.pyplot as plt\nfrom visualize import *\nfrom pyquaternion import Quaternion\nimport numpy as np\n# os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n\nmodel_id = 110\n\nx_dim = 6\nh_dim = 96\nn_layers = 2\noutput_dim = 6\nepoch_num = 200\nlearning_rate = 0.005\nbatch_size = 400\nlen_sequence = 50\n\nseed = 400\nclip = 10\nprint_every = 10\nsave_every = 10\n\ntorch.manual_seed(seed)\n\nmodel = lstm_activity(x_dim, h_dim, batch_size, n_layers, output_dim)\n\nmodel_path = './saves/lstm_state_dict_' + str(model_id) + '.pth'\nmodel.load_state_dict(torch.load(model_path))\nmodel.eval()\n\nate = np.zeros(188)\n\nif torch.cuda.is_available():\n print(\"Using GPU\")\n model.cuda()\n\nidxs = [7, 5, 22]\nerrors = []\n\nfor i in idxs:\n data_x = np.loadtxt('./eval_data/eval_' + str(i) + '_x.csv', delimiter=\",\")\n data_y = np.loadtxt('./eval_data/eval_' + str(i) + '_y.csv', delimiter=\",\")\n data_gt = np.loadtxt('./eval_data/eval_' + str(i) + '_gt.csv', delimiter=\",\")\n\n len_draw = data_x.shape[0]\n data_x = data_x.reshape(-1, len_sequence, 6)\n\n data_x_cuda = Variable(torch.from_numpy(data_x).type(torch.FloatTensor).transpose(0, 1)).cuda()\n model.zero_grad()\n model.hidden = model.init_hidden_pred(len_draw)\n\n pred_y = np.zeros((len_draw, 7))\n pred_y[:, 1:7] = model(data_x_cuda).cpu().data.numpy()\n pred_y[:, 0] = np.sqrt(1 - np.square(pred_y[:, 1]) -\n np.square(pred_y[:, 2]) -\n np.square(pred_y[:, 3]))\n\n traj_y = np.zeros((len_draw + 1, 3))\n traj_gt = np.zeros((len_draw + 1, 3))\n traj_q = []\n traj_q.append(Quaternion(data_gt[0][0:4]))\n for j in range(len_draw):\n traj_q.append(traj_q[j] * Quaternion(pred_y[j][0:4]))\n traj_y[j + 1] = traj_y[j] + traj_q[j].conjugate.rotate(pred_y[j][4:7])\n traj_gt[j + 1] = data_gt[j + 1][4:7] - data_gt[0][4:7]\n\n traj_diff = traj_y - traj_gt\n traj_norm = np.linalg.norm(traj_diff, ord=2, axis=1, keepdims=False)\n ate[i] = traj_norm.mean()\n\n errors.append(traj_norm)\n\n # figname = 'eval_results/' + str(model_id) + '/paper/traj_' + str(i) + '.jpg'\n figname = 'eval_results/paper/traj_' + str(i)\n draw_trajectory_1(data_y,\n pred_y,\n traj_gt,\n traj_y,\n traj_norm,\n figname + '_1.pdf')\n draw_trajectory_2(data_y,\n pred_y,\n traj_gt,\n traj_y,\n traj_norm,\n figname + '_2.pdf')\n draw_trajectory_3(data_y,\n pred_y,\n traj_gt,\n traj_y,\n traj_norm,\n figname + '_3.pdf')\n draw_trajectory_4(data_y,\n pred_y,\n traj_gt,\n traj_y,\n traj_norm,\n figname + '_4.pdf')\n draw_trajectory_5(data_y,\n pred_y,\n traj_gt,\n traj_y,\n traj_norm,\n figname + '_3D.pdf')\n\ndraw_trajectory_6(data_y,\n pred_y,\n traj_gt,\n traj_y,\n errors,\n 'eval_results/errors.pdf')\n","sub_path":"bench.py","file_name":"bench.py","file_ext":"py","file_size_in_byte":3561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"654097964","text":"from core import FaceDetector\nimport argparse\nimport cv2\n\nap = argparse.ArgumentParser()\nap.add_argument('-m', '--model', required=True,\n help='path to trained model file')\nap.add_argument('-i', '--image', required=True,\n help='path to input image to detect')\nap = vars(ap.parse_args())\n\ndec = FaceDetector.from_trained_model(ap['model'])\nimg = cv2.imread(ap['image'])\nresult = dec.get_names_in_pic(img)\nfor res in result:\n print(res)\n","sub_path":"get_names_in.py","file_name":"get_names_in.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"51727755","text":"def readinput():\n k,n=map(int,input().split())\n a=list(map(int,input().split()))\n return k,n,a\n\ndef main(k,n,a):\n dmax=0\n for i in range(n-1):\n dmax=max(dmax,a[i+1]-a[i])\n dmax=max(dmax,k+a[0]-a[n-1])\n return k-dmax\n\nif __name__=='__main__':\n k,n,a=readinput()\n ans=main(k,n,a)\n print(ans)\n","sub_path":"Python_codes/p02725/s192212397.py","file_name":"s192212397.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"495477111","text":"import math\n\nfrom keios_protocol_pocketsphinx import PocketSphinxMessage, PocketSphinxMessageMapper, PocketSphinxRequest, \\\n PocketSphinxResponse, Guess\nfrom keios_protocol_pocketsphinx.flatbuffers.PocketSphinxMessageType import PocketSphinxMessageType\n\n\ndef test_message_with_request():\n data = PocketSphinxRequest(bytearray(\"foo\", encoding=\"utf-8\"))\n\n message_data = PocketSphinxMessage(PocketSphinxMessageType().PocketSphinxRequest, data)\n\n result = PocketSphinxMessageMapper().serialize(message_data)\n\n deserialized: PocketSphinxRequest = PocketSphinxMessageMapper().deserialize(result).message\n\n assert deserialized.speech.decode(\"utf-8\") == \"foo\"\n\n\ndef test_message_with_response():\n data1 = Guess(\"foo\", 0.95)\n data2 = Guess(\"bar\", 0.75)\n data = PocketSphinxResponse([data1, data2])\n\n message_data = PocketSphinxMessage(PocketSphinxMessageType().PocketSphinxResponse, data)\n\n result = PocketSphinxMessageMapper().serialize(message_data)\n\n deserialized: PocketSphinxResponse = PocketSphinxMessageMapper().deserialize(result).message\n\n assert len(deserialized.guesses) == 2\n assert deserialized.guesses[0].phrase == \"foo\"\n assert math.isclose(deserialized.guesses[0].confidence, 0.95, rel_tol=1e-07)\n assert deserialized.guesses[1].phrase == \"bar\"\n assert math.isclose(deserialized.guesses[1].confidence, 0.75, rel_tol=1e-07)\n","sub_path":"python/keios-protocol-pocketsphinx/tests/test_message.py","file_name":"test_message.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"573387473","text":"from __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nimport argparse\n\nfrom dotmap import DotMap\n\nfrom dmbrl.misc.MBwPBTBTExp import MBWithPBTBTExperiment\nfrom dmbrl.controllers.MPC import MPC\nfrom dmbrl.config import create_config\n\nimport tensorflow as tf\nimport numpy as np\n\ndef create_cfg_creator(env, ctrl_type, ctrl_args, base_overrides, logdir):\n ctrl_args = DotMap(**{key: val for (key, val) in ctrl_args})\n\n def cfg_creator(additional_overrides=None):\n if additional_overrides is not None:\n return create_config(env, ctrl_type, ctrl_args, base_overrides + additional_overrides, logdir)\n return create_config(env, ctrl_type, ctrl_args, base_overrides, logdir)\n\n return cfg_creator\n\n\ndef main(args):\n cfg_creator = create_cfg_creator(args.env, args.ctrl_type, args.ctrl_arg, args.override, args.logdir)\n cfg = cfg_creator()[0]\n cfg.pprint()\n\n if args.ctrl_type == \"MPC\":\n cfg.exp_cfg.exp_cfg.policy = MPC(cfg.ctrl_cfg)\n\n exp = MBWithPBTBTExperiment(cfg.exp_cfg, cfg_creator, args) \n exp.run_experiment()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-env', type=str, required=True,\n help='Environment name: select from [cartpole, reacher, pusher, halfcheetah, halfcheetah_v3]')\n parser.add_argument('-ca', '--ctrl_arg', action='append', nargs=2, default=[],\n help='Controller arguments, see https://github.com/kchua/handful-of-trials#controller-arguments')\n parser.add_argument('-o', '--override', action='append', nargs=2, default=[],\n help='Override default parameters, see https://github.com/kchua/handful-of-trials#overrides')\n parser.add_argument('-logdir', type=str, default='log',\n help='Directory to which results will be logged (default: ./log)')\n parser.add_argument('-ctrl_type', type=str, default='MPC',\n help='Control type will be applied (default: MPC)') \n # Parser for running dynamic scheduler on cluster \n parser.add_argument('-config_names', type=str, default=\"model_learning_rate\", nargs=\"+\",\n help='Specify which hyperparameters to optimize')\n parser.add_argument('-seed', type=int, default=0,\n help='Specify the random seed of the experiment')\n parser.add_argument('-worker_id', type=int, default=0,\n help='The worker id, e.g. using SLURM ARRAY JOB ID')\n parser.add_argument('-worker', action='store_true',\n help='Flag to turn this into a worker process otherwise this will start a new controller')\n parser.add_argument('-sample_from_percent', type=float, default=0.2,\n help='Sample from the top ratio N')\n parser.add_argument('-resample_if_not_in_percent', type=float, default=0.8,\n help='Resample if the configuration is not in the top ratio N')\n parser.add_argument('-resample_probability', type=float, default=0.25,\n help='Probability of an exploited member resampling configurations randomly')\n parser.add_argument('-resample_prob_decay', type=float, default=1,\n help='decay factor of resample if not in percent')\n parser.add_argument('-max_steps', type=int, default=60*40,\n help='Maximum amount of steps to take')\n parser.add_argument('-delta_t', type=int, default=30,\n help='every X steps we do once backtracking')\n parser.add_argument('-tolerance', type=float, default=0.2,\n help='the tolerance of performance drop')\n parser.add_argument('-elite_ratio', type=float, default=0.125,\n help='elite ratio of the population')\n \n args = parser.parse_args()\n print(args)\n # Set the random seeds of the experiment\n tf.set_random_seed(args.seed)\n np.random.seed(args.seed)\n main(args) \n","sub_path":"pbt-bt-mbexp.py","file_name":"pbt-bt-mbexp.py","file_ext":"py","file_size_in_byte":4054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"330119509","text":"# coding=utf-8\nfrom lib.config.Config import Config\n\nclass AnimeHeadConfig(Config):\n def __init__(self):\n super(AnimeHeadConfig, self).__init__()\n self.DATA_PATH = \"/input/AnimateFace/\"\n self.NUM_WORKERS_LOAD_IMAGE = 4\n self.IMAGE_CHANNEL = 3\n self.IMAGE_SIZE = 96\n self.BATCH_SIZE = 256\n self.EPOCH_NUM = 200\n self.LR_GENERATOR = 2e-4\n self.LR_DISCRIMINATOR = 2e-4\n self.BETA1 = 0.5\n self.GPU_NUM = 2\n self.NOISE_Z = 100\n\n self.GENERATOR_FEATURES_NUM = 64\n self.DISCRIMINATOR_FEATURES_NUM = 64\n self.D_EVERY = 1 # 每1个batch训练一次判别器\n self.G_EVERY = 5 # 每5个batch训练一次生成器\n self.DECAY_EVERY = 5 # 没10个epoch保存一次模型\n self.SAVE_PATH = \"output/\"\n","sub_path":"lib/config/AnimeHeadConfig.py","file_name":"AnimeHeadConfig.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"355119127","text":"\"\"\"\nBinary search trees are a data structure that enforce an ordering over \nthe data they store. That ordering in turn makes it a lot more efficient \nat searching for a particular piece of data in the tree. \n\nThis part of the project comprises two days:\n1. Implement the methods `insert`, `contains`, `get_max`, and `for_each`\n on the BSTNode class.\n2. Implement the `in_order_print`, `bft_print`, and `dft_print` methods\n on the BSTNode class.\n\"\"\"\nclass BSTNode:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n # Insert the given value into the tree\n def insert(self, value):\n currNode = self # Start at top node\n while 1: # Traverse infinitely until we return @ end of tree\n\n if value >= currNode.value: # Compare value w/ right\n if currNode.right: # Check if we reached end of tree\n currNode = currNode.right # We didn't, traverse right, loop will run on new current ndoe\n else:\n currNode.right = BSTNode(value) # Add new leaf if found end of tree\n return\n\n else: # Same process if value <= left\n if currNode.left:\n currNode = currNode.left\n else:\n currNode.left = BSTNode(value)\n return\n \n\n # Return True if the tree contains the value\n # False if it does not\n def contains(self, target):\n currNode = self\n while 1:\n if target > currNode.value: # Check if target is > current node value\n if currNode.right: \n currNode = currNode.right # Traverse right if .right exists\n else:\n return False # Reached end of list, target not found\n\n elif target < currNode.value: # Same process if target < current node value\n if currNode.left:\n currNode = currNode.left\n else:\n return False\n else: # Target is equal to current node value, target found in list\n return True\n","sub_path":"names/binary_search_tree.py","file_name":"binary_search_tree.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"11846599","text":"import json\nimport csv\nimport os\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import load_model\n\n# Loading parameters\nwith open('parameters.json', 'r') as json_file:\n pm = json.load(json_file)\n\nlyrics = [] # Here will be stored the lyrics data\nemotions = [] # Here will be stored the emotions data\n\n# Here will be stored every type of emotiom\nlabels = [\"Anger\", \"Joy\", \"Sad\", \"Disgusting\", \"Fear\", \"Suprise\"]\n\ndata_path = os.path.join('data', 'lyrics_dataset.csv')\n\n\ndef loading_data(lyrics_list, emotions_list, path):\n with open(path, 'r', encoding='utf-8') as file:\n dataset = csv.reader(file)\n next(dataset) # We skip the header of the file\n\n for track in dataset:\n lyrics_list.append(track[0].capitalize())\n emotions_list.append(track[3].capitalize())\n\n\n# We need to numerize the emotions\ndef numerize_emotions(emotions_dataset):\n for i in range(len(emotions_dataset)):\n for j in range(len(labels)):\n if emotions_dataset[i] == labels[j]:\n emotions_dataset[i] = j\n\n\nloading_data(lyrics, emotions, data_path)\nnumerize_emotions(emotions)\n\n\n# Tokenization process\ntokenizer = Tokenizer(num_words=pm[\"num_words\"], oov_token=pm[\"oov_tok\"])\ntokenizer.fit_on_texts(lyrics) # Words are fitted on the tokenizer\nword_index = tokenizer.word_index # Words are represented by index\n\nvocab_size = len(word_index) + 1 # The size of the vocabulary\n\nlyrics = tokenizer.texts_to_sequences(lyrics)\nlyrics = pad_sequences(\n lyrics,\n maxlen=pm[\"max_length\"],\n padding=pm[\"padding_type\"],\n truncating=pm[\"trunc_type\"]\n)\n\nemotions = to_categorical(emotions, len(labels))\n\n# Transforming the tokenized data in numpy arrays\nlyrics = np.array(lyrics)\nemotions = np.array(emotions)\n\n\n# ---- Here you can predict the emotion of any song lyrics ----\nmodel = load_model('model.h5')\n\n\ndef predict_emotion(lyrics):\n \"\"\"\n It predicts the percentage of the prevalent emotions of a given lyric\n\n Args:\n lyrics (str): string written in English\n\n Returns:\n dict: dictionary obj. with the percentages\n \"\"\"\n sequence = tokenizer.texts_to_sequences([lyrics])\n padded = pad_sequences(sequence,\n maxlen=pm[\"max_length\"],\n padding=pm[\"padding_type\"],\n truncating=pm[\"trunc_type\"])\n\n # prediction has the percentage of each emotion\n prediction = model.predict(padded)\n results = {} # The keys will be the emotion name and the values will be the percentage\n for i in range(len(prediction[0])):\n results[labels[i]] = prediction[0][i]\n\n return results\n\n\nif __name__ == '__main__':\n for emotion, percentage in predict_emotion(\"Then I saw her face, now I'm a believer\").items():\n print(f'{emotion}: {percentage}')\n","sub_path":"emotion_predictor.py","file_name":"emotion_predictor.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"367442067","text":"i = 1\nresultado = []\nimport numpy as np\nimport random as r\nimport sys\nfrom index import Folds,dset,clase\n\n\nsys.stdout = open(\"salida.txt\", \"w\") \n \nfor train, test in Folds(dset):\n dset_entrenamiento = dset[train]\n dset_prueba = dset[test]\n clase_entrenamiento = clase[train]\n clase_prueba = clase[test]\n i += 1 \n clase_t = 50\n \n '''------------------ RED NEURONAL----------------------- '''\n # Función de activación sigmoide\n def sigmoide(x):\n return 1 / (1 + np.exp(-x))\n \n # Retorna y_real y y_pred, que son matrices de la misma longitud en la salida.\n def mse_error(y_real, y_pred):\n return ((y_real - y_pred) ** 2).mean()\n \n class Red_Neuronal:\n '''\n La red neuronal contiene:\n - 8 entradas\n - capa oculta con 2 neuronas (h1, h2)\n - salida con 1 neurona (o1)\n '''\n def __init__(self):\n \n numeros = [r.randint(1,99) for x in range(18)]\n \n # Pesos\n self.w1 = numeros[0]/100\n self.w2 = numeros[1]/100\n self.w3 = numeros[2]/100\n self.w4 = numeros[3]/100\n self.w5 = numeros[4]/100\n self.w6 = numeros[5]/100\n self.w7 = numeros[6]/100\n self.w8 = numeros[7]/100\n self.w9 = numeros[8]/100\n self.w10 = numeros[9]/100\n self.w11 = numeros[10]/100\n self.w12 = numeros[11]/100\n self.w13 = numeros[12]/100\n self.w14 = numeros[13]/100\n self.w15 = numeros[14]/100\n self.w16 = numeros[15]/100\n self.w17 = numeros[16]/100\n self.w18 = numeros[17]/100\n \n \n def hacia_adelante(self, x):\n # x es la matriz de 8 atributos.\n h1 = sigmoide(self.w1 * x[0] + self.w2 * x[1] + self.w3 * x[2] + self.w4 * x[3] + self.w5 * x[4] + self.w6 * x[5] + self.w7 * x[6] + self.w8 * x[7])\n h2 = sigmoide(self.w9 * x[0] + self.w10 * x[1] + self.w11 * x[2] + self.w12 * x[3] + self.w13 * x[4] + self.w14 * x[5] + self.w15 * x[6] + self.w16 * x[7])\n o1 = sigmoide(self.w17 * h1 + self.w18 * h2)\n return o1\n \n def entrenamiento(self, datos, clase):\n '''\n - los datos son una matriz numérica (n x 8), n = # de muestras en el conjunto de datos.\n - clase es una matriz numerosa con n elementos.\n Los elementos de clase corresponden a los datos.\n '''\n \n aprendizaje = 0.1\n #número de veces para recorrer todo el conjunto de datos\n \n for i in range(clase_t):\n for x, y_real in zip(datos, clase):\n # --- Seguir adelante\n sum_h1 = self.w1 * x[0] + self.w2 * x[1] + self.w3 * x[2] + self.w4 * x[3] + self.w5 * x[4] + self.w6 * x[5] + self.w7 * x[6] + self.w8 * x[7]\n h1 = sigmoide(sum_h1)\n \n sum_h2 = self.w9 * x[0] + self.w10 * x[1] + self.w11 * x[2] + self.w12 * x[3] + self.w13 * x[4] + self.w14 * x[5] + self.w15 * x[6] + self.w16 * x[7]\n h2 = sigmoide(sum_h2)\n \n sum_o1 = self.w17 * h1 + self.w18 * h2\n o1 = sigmoide(sum_o1)\n y_pred = o1\n \n # --- Calcula derivadas parciales.\n # --- Nombre: d_L_d_w1 representa \"L parcial / w1 parcial\"\n d_L_d_ypred = -2 * (y_real - y_pred)\n \n # Neurona o1\n d_ypred_d_w17 = h1 * sigmoide(sum_o1)\n d_ypred_d_w18 = h2 * sigmoide(sum_o1)\n \n \n d_ypred_d_h1 = self.w17 * sigmoide(sum_o1)\n d_ypred_d_h2 = self.w18 * sigmoide(sum_o1)\n \n # Neurona h1\n d_h1_d_w1 = x[0] * sigmoide(sum_h1)\n d_h1_d_w2 = x[1] * sigmoide(sum_h1)\n d_h1_d_w3 = x[2] * sigmoide(sum_h1)\n d_h1_d_w4 = x[3] * sigmoide(sum_h1)\n d_h1_d_w5 = x[4] * sigmoide(sum_h1)\n d_h1_d_w6 = x[5] * sigmoide(sum_h1)\n d_h1_d_w7 = x[6] * sigmoide(sum_h1)\n d_h1_d_w8 = x[7] * sigmoide(sum_h1)\n \n \n # Neurona h2\n d_h2_d_w9 = x[0] * sigmoide(sum_h2)\n d_h2_d_w10 = x[1] * sigmoide(sum_h2)\n d_h2_d_w11 = x[2] * sigmoide(sum_h2)\n d_h2_d_w12 = x[3] * sigmoide(sum_h2)\n d_h2_d_w13 = x[4] * sigmoide(sum_h2)\n d_h2_d_w14 = x[5] * sigmoide(sum_h2)\n d_h2_d_w15 = x[6] * sigmoide(sum_h2)\n d_h2_d_w16 = x[7] * sigmoide(sum_h2)\n \n \n # --- Actualizar ponderaciones\n # Neurona h1\n self.w1 -= aprendizaje * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w1\n self.w2 -= aprendizaje * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w2\n self.w3 -= aprendizaje * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w3\n self.w4 -= aprendizaje * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w4\n self.w5 -= aprendizaje * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w5\n self.w6 -= aprendizaje * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w6\n self.w7 -= aprendizaje * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w7\n self.w8 -= aprendizaje * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w8\n\n \n # Neurona h2\n self.w9 -= aprendizaje * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w9\n self.w10 -= aprendizaje * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w10\n self.w11 -= aprendizaje * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w11\n self.w12 -= aprendizaje * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w12\n self.w13 -= aprendizaje * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w13\n self.w14 -= aprendizaje * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w14\n self.w15 -= aprendizaje * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w15\n self.w16 -= aprendizaje * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w16\n \n # Neurona o1\n self.w17 -= aprendizaje * d_L_d_ypred * d_ypred_d_w17\n self.w18 -= aprendizaje * d_L_d_ypred * d_ypred_d_w18\n\n \n # --- Calcula el error total\n if i % 1 == 0: \n y_preds = np.apply_along_axis(self.hacia_adelante, 1, datos)\n error = mse_error(clase, y_preds)\n resultado.append(error)\n print(\" clase: {} Salida: {} \".format(clase_entrenamiento[i],error))\n\n\n print(\"FOLD\",i-1,\": \")\n # Entrenamiento\n network = Red_Neuronal()\n network.entrenamiento(dset_entrenamiento, clase_entrenamiento)\n print(\" ECM:\", np.mean(resultado))\n\n\n","sub_path":"py/RNA/RNA_sigmoide.py","file_name":"RNA_sigmoide.py","file_ext":"py","file_size_in_byte":6381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"230132845","text":"import h5py\nimport epics\nimport threading\nimport time\nimport scipy.ndimage\nimport scipy.signal\nimport moveStage\nimport numbers\nimport subprocess\nimport collections\nimport socket\nfrom ps4262 import ps4262\nfrom ISSI_lens_controller import EF_Controller\n\n\ndef hush():\n \"\"\"\n Remove warnings from epics. These can be helpful, but we get a lot of\n warnings about 'Identical process variable names on multiple servers'\n \"\"\"\n epics.ca.replace_printf_handler(lambda text: None)\n\n\n# x-label, y-label, units\n\ndef val_or_retval(thing):\n \"\"\" Is this a value or a function? \"\"\"\n if(callable(thing)):\n return(thing())\n else:\n return(thing)\n\n\nclass Dataset(object):\n \"\"\" This object sets up the saving of a HDF5 dataset \"\"\"\n def __init__(self, dsname, data_fun):\n self.dsname = dsname # String\n self.data = data_fun # A function that returns data\n self.attrs = {} # Attributes to the dataset\n\n def write(self, h5g):\n data = val_or_retval(self.data)\n ds = h5g.create_dataset(self.dsname, data=data, compression='gzip')\n for key, value in self.attrs.items():\n ds.attrs[key] = val_or_retval(value)\n\n\nclass Savedata(object):\n \"\"\" This object keeps track of things that should be saved to file for a device\"\"\"\n def __init__(self, groupname, dev_type):\n self.groupname = groupname\n self.attrs = {} # Attr name -> attr value\n self.attrs['instrument_name'] = dev_type\n self.datasets = [] # Name, data, attrs, processor\n\n def add_dataset(self, ds):\n self.datasets.append(ds)\n\n def write(self, h5f):\n h5g = h5f.require_group(self.groupname)\n # Group attributes\n print(self.groupname)\n for key, val in self.attrs.items():\n # print(str(key) + ': ' + str(val_or_retval(val)) + ':' + str(val))\n h5g.attrs[key] = val_or_retval(val)\n # Datasets\n for dataset in self.datasets:\n dataset.write(h5g)\n\n def write_additional_meta(self, h5f, dict):\n h5g = h5f.require_group(self.groupname)\n for key, val in dict.items():\n h5g.attrs[key] = val\n\n\nclass Coolector(object):\n \"\"\"\n Collect data from Cool devices, put them in HDF5 files.\n \"\"\"\n pause = 0.001\n triggerID = 0\n _devices = []\n\n latest_file_name = None\n\n def __init__(self, session=None, sample=None, sample_uid=None, location=None, operator=None,\n description=None, sub_experiment=None, nominal_beam_current=0.0, directory=None):\n \"\"\"\n Init function. Meta data as mandatory arguments.\n \"\"\"\n if(not(sample and description and directory and sample_uid and location and\n sample_uid and operator and sub_experiment and session)):\n raise Exception('Supply sample, sample_uid, location, operator, ' +\n 'description, directory and sub_experiment')\n self.sample = sample\n self.sample_uid = sample_uid\n self.glob_trig = 0\n\n self.savedata = Savedata('/', 'Configuration')\n self.savedata.attrs['sample_name'] = lambda: self.sample\n self.savedata.attrs['sample_guid'] = lambda: self.sample_uid\n self.savedata.attrs['location'] = location\n self.savedata.attrs['session'] = session\n self.savedata.attrs['operator_name'] = operator\n self.savedata.attrs['experiment_description'] = description\n self.savedata.attrs['sub_experiment'] = sub_experiment\n self.savedata.attrs['nominal_beam_current'] = nominal_beam_current\n self.savedata.attrs['trigger_id'] = lambda: self.glob_trig\n self.savedata.attrs['internal_trigger_count_debug'] = lambda: self.triggerID\n self.savedata.attrs['timestamp'] = lambda: time.time()\n\n self.directory = directory\n if(not self.directory.endswith('/')):\n self.directory += '/'\n\n def change_sample(self, sample, sample_uid):\n moved = False\n for dev in self._devices:\n if(dev.move_to_sample(sample)):\n moved = True\n if moved:\n self.sample = sample\n self.sample_uid = sample_uid\n else:\n print('Do not know how to change samples, add a sample mover')\n\n def check_if_ready(self):\n \"\"\"\n Are all devices ready for ready out?\n \"\"\"\n ready = True\n for dev in self._devices:\n if(not dev.is_ready_p()):\n ready = False\n return(ready)\n\n def clear(self):\n \"\"\"\n Clear devices of old data.\n \"\"\"\n for dev in self._devices:\n dev.clear()\n\n def cd(self, dir):\n \"\"\" Change directory \"\"\"\n self.directory = dir\n\n def wait_for_data(self, timeout=15):\n \"\"\"\n Wait until all devices are ready, then read them all out.\n \"\"\"\n tzero = time.time()\n got_data_p = False\n while(True):\n if(self.check_if_ready()):\n got_data_p = True\n break\n if(time.time() - tzero > timeout):\n for dev in self._devices:\n print(dev.dev_type + ' is ready: ' + str(dev.is_ready_p()))\n print('Timed out while waiting for data!')\n raise RuntimeError('Timed out while waiting for data!')\n break\n time.sleep(self.pause)\n if(got_data_p):\n self.write(self.triggerID)\n\n def sw_trigger(self):\n \"\"\"\n Send SW trigger to all connected devices\n \"\"\"\n for dev in self._devices:\n dev.sw_trigger()\n\n def hw_trigger(self):\n \"\"\"\n Send HW trigger to all connected devices\n \"\"\"\n triggers = 0\n for dev in self._devices:\n if(dev.hw_trigger()):\n triggers = triggers + 1\n if triggers == 0:\n print('Found no devices able to send a HW trigger')\n print('Send manual one?')\n if triggers > 1:\n print('Several trigger generators attached')\n\n def write(self, trigger):\n \"\"\"\n Write meta data + device data for all connected devices\n \"\"\"\n # Get global trigger from device, or use internal counter\n self.triggerID += 1\n trigger = self.triggerID\n pot_desync = False\n for dev in self._devices:\n if dev.potentially_desynced:\n # raise RuntimeError('Potentially desynced data!')\n print('writing desynced event!')\n pot_desync = True\n\n for dev in self._devices:\n glob_trig = dev.get_glob_trigger()\n if(glob_trig):\n print('Setting global trigger to ' + str(glob_trig))\n trigger = glob_trig\n self.glob_trig = glob_trig\n\n # Create file, write to it\n if pot_desync:\n fname = '{0}{1:016d}-{2}.h5'.format('/tmp/', trigger, 'desynced')\n else:\n fname = '{0}{1:016d}-{2}.h5'.format(self.directory, trigger, self.sample)\n print('Writing to ' + fname)\n with h5py.File(fname, 'w') as h5f:\n h5f.attrs['write_finished'] = False\n self.savedata.write(h5f)\n for dev in self._devices:\n dev.write(h5f)\n h5f.attrs['write_finished'] = True\n # All devices are read out, ready for new data\n self.latest_file_name = fname\n for dev in self._devices:\n dev.clear()\n\n def add_device(self, device):\n \"\"\"\n Add a Cool_device to the coolector.\n \"\"\"\n self._devices.append(device)\n\n def __enter__(self):\n \"\"\" Connect devices \"\"\"\n if(self.directory == '/tmp/'):\n print('Saving to tmp!!!')\n for dev in self._devices:\n dev.connect()\n self.clear()\n return(self)\n\n def __exit__(self, type, value, traceback):\n \"\"\" Disconnect devices \"\"\"\n if(self.directory == '/tmp/'):\n print('Saving to tmp!!!')\n for dev in self._devices:\n dev.disconnect()\n\n # Scans\n def wait_for_n_triggers(self, n, SW_trigger=False, pause=False):\n with self as c:\n for dev in self._devices:\n dev.check_exposure()\n time.sleep(2.0)\n for dev in self._devices:\n dev.clear()\n for trig in range(n):\n if(SW_trigger):\n self.sw_trigger()\n else:\n self.hw_trigger()\n print('Waiting for data!')\n c.wait_for_data()\n print(time.time())\n print(\"Got one! \" + str(trig))\n if pause:\n time.sleep(pause)\n\n def do_auto_exposure(self):\n for dev in self._devices:\n dev.auto_exposure(self.hw_trigger)\n\n def stage_scan_n_triggers(self, n, sample_dict, auto_exposure=False, skip_dark_nb=False):\n for sample, position in sample_dict.items():\n self.change_sample(sample, 'NA')\n dark_frame = (sample == 'DARK_NOBEAM') or (sample == 'DARK_BEAM')\n if not(skip_dark_nb and (sample == 'DARK_NOBEAM')):\n # Auto exposure\n if auto_exposure and not dark_frame:\n for dev in self._devices:\n dev.auto_exposure(self.hw_trigger)\n # Get triggers\n self.wait_for_n_triggers(n)\n if sample == 'DARK_NOBEAM':\n input('Press Enter to continue')\n\n def heat_scan_sample(self, sample, auto_exposure=False, pause=5):\n self.change_sample(sample, 'NA')\n # Auto exposure\n if auto_exposure:\n for dev in self._devices:\n dev.auto_exposure(self.hw_trigger)\n for dev in self._devices:\n dev.auto_exposure(self.hw_trigger)\n # Get triggers\n self.wait_for_n_triggers(99999, SW_trigger=False, pause=pause)\n\n\nclass Cool_device(object):\n \"\"\"\n Base class for reading out a devices, and writing device info to HDF5\n \"\"\"\n is_ready = False # Flag that should be set to true when the device is ready for read out.\n potentially_desynced = False # Did we recieve seceral triggers before writing finished?\n\n data = None\n timestamp = False\n triggercount = 0\n\n def __init__(self, port, pathname, dev_type, callback_pvname):\n self.connected_pvs = []\n # EPICS port, something like CAM1, CCS1. For non epics devices, make something up.\n self.port = port\n self._callback_pvname = callback_pvname # Set to None for non-epivs devices\n self.dev_type = dev_type # Descriptor for the device.\n\n self.savedata = Savedata(pathname, dev_type)\n if self.timestamp:\n self.savedata.attrs['timestamp'] = lambda: self.timestamp\n else:\n self.savedata.attrs['timestamp'] = lambda: time.time()\n self.savedata.attrs['trigger_count_debug'] = lambda: self.triggercount\n self.savedata.attrs['Potentially desynced'] = lambda: self.potentially_desynced\n self.savedata.attrs['acquire_duration'] = 0\n\n def get_glob_trigger(self):\n return(None)\n\n def move_to_sample(self, sample):\n return(False)\n\n def connect(self):\n # Set is_ready to True when there is new data using a callback\n print('Connecting ' + self.dev_type)\n if(self._callback_pvname):\n print('Connecting ' + self._callback_pvname)\n pv = epics.PV(self._callback_pvname,\n auto_monitor=True,\n callback=lambda pvname=None, value=None, timestamp=None, **fw: self.set_ready(pvname, value, timestamp))\n self.connected_pvs.append(pv)\n return(self)\n\n def disconnect(self):\n for pv in self.connected_pvs:\n pv.disconnect()\n self.connected_pvs = []\n\n def check_exposure(self):\n pass\n\n def auto_exposure(self, trigger_fun):\n \"\"\"Do auto exposure. Trigger fun should give a single trigger working with\n the configured device.\"\"\"\n pass\n\n def set_ready(self, pvn, value, timestamp):\n \"\"\"\n Mark device as ready for read out, copy data to object.\n This is intended as a callback funtion for a EPICS pv\n \"\"\"\n self.triggercount += 1\n # print('Getting data to callback! ' + self.dev_type)\n if(not self.is_ready):\n # print('Got data from ' + self.dev_type + ', aka: ' + str(pvn))\n self.data = value\n self.timestamp = timestamp\n else:\n print(self.dev_type + \": New trigger before readout finished! Potentially desynced event!\")\n self.potentially_desynced = True\n self.is_ready = True\n\n def sw_trigger(self):\n \"\"\" Pass a SW trigger to the device \"\"\"\n pass\n\n def hw_trigger(self):\n \"\"\" Pass a HW trigger to the device \"\"\"\n pass\n\n def is_ready_p(self):\n \"\"\" Is the device ready for readout? EPICS devices rely on set_ready callback to set is_ready,\n non epics devices should probably overload \"\"\"\n # print(self.dev_type + ' is ready? : ' + str(self.is_ready))\n return(self.is_ready)\n\n def clear(self):\n \"\"\" Clear data from device. For EPICS devices, sinply set is_ready to false. \"\"\"\n print('clearing ' + str(self.dev_type))\n self.is_ready = False\n self.potentially_desynced = False\n\n def write(self, h5f):\n \"\"\"\n Write all pvs in meta_pvnames to attributes in group.\n Call write_datasets function.\n\n Overload if stuff needs to happen before write\n \"\"\"\n self.savedata.write(h5f)\n\n def pv_to_attribute(self, prefix, *pvs):\n \"\"\"\n Read pv values to attributes when needed\n \"\"\"\n for pv in pvs:\n print(prefix + pv)\n self.savedata.attrs[prefix + pv] = lambda: epics.caget(prefix + pv)\n for pv in pvs:\n print(self.savedata.attrs[prefix + pv]())\n\n\nclass Manta_cam(Cool_device):\n \"\"\"\n Manta camera\n \"\"\"\n dev_type = 'Manta camera'\n\n def sw_trigger(self):\n \"\"\" Set Acquire to True \"\"\"\n epics.caput(self.port + ':det1:Acquire', 1)\n\n def set_exposure(self, exposure):\n \"\"\"\n Set exposure if it is within acceptable limits.\n \"\"\"\n exposure = max(exposure, self.exposure_min)\n exposure = min(exposure, self.exposure_max)\n print('Setting exposure to: ' + str(exposure))\n epics.caput(self.port + ':det1:AcquireTime', exposure)\n time.sleep(0.1)\n\n def set_gain(self, gain):\n \"\"\"\n Set gain.\n \"\"\"\n print('Setting gain to: ' + str(gain))\n epics.caput(self.port + ':det1:Gain', gain)\n time.sleep(0.1)\n\n def get_reshaped_data(self):\n print('Hello!')\n print(self.data)\n return(self.data.reshape(epics.caget(self.port + ':det1:SizeY_RBV'),\n epics.caget(self.port + ':det1:SizeX_RBV')))\n\n def __init__(self, port, lens_id, focal_length, f_number,\n sw_trig=False,\n exposure=None,\n gain=None,\n exposure_min=0.0003,\n exposure_max=0.1,\n photons_per_count=False):\n \"\"\"\n Initialize a manta camera\n \"\"\"\n super().__init__(port,\n 'data/images/' + port + '/',\n 'Manta camera',\n port + ':image1:ArrayData')\n self.exposure_min = exposure_min\n self.exposure_max = exposure_max\n self.lens_controller = False\n\n # Initialize device\n for pvname, value in {':image1:EnableCallbacks': 1, # Enable\n ':image1:ArrayCallbacks': 1, # Enable\n ':det1:DataType': 1, # UInt16, 12-bit\n ':det1:LEFTSHIFT': 0}.items(): # Disable\n epics.caput(port + pvname, value)\n\n # Initialization for SW triggers\n if(sw_trig):\n epics.caput(port + ':det1:ImageMode', 0) # Get a single image\n # Initialization for HW triggers\n else:\n epics.caput(port + ':det1:Acquire', 0)\n epics.caput(port + ':det1:ImageMode', 2) # Get images continously\n epics.caput(port + ':det1:TriggerMode', 1) # Enable trigger mode\n epics.caput(port + ':det1:TriggerSelector', 0) # Enable trigger mode\n epics.caput(port + ':det1:TriggerSource', 1) # Enable trigger mode\n epics.caput(port + ':det1:Acquire', 1)\n\n # Set exposure and gain from init arguments\n if(exposure):\n self.set_exposure(exposure)\n if(isinstance(gain, numbers.Number)): # We must be able to set this to 0\n self.set_gain(gain)\n\n # Setting up data saving\n # Metadata that will be dumped to device\n sda = self.savedata.attrs\n sda['acquire_duration'] = lambda: epics.caget(port + ':det1:AcquireTime_RBV')\n sda['lens_id'] = lens_id\n sda['f_number'] = f_number\n sda['focal_length'] = focal_length\n sda['photons_per_count'] = photons_per_count\n sda[port + ':det1:SizeX_RBV'] = lambda: epics.caget(port + ':det1:SizeX_RBV')\n sda[port + ':det1:SizeY_RBV'] = lambda: epics.caget(port + ':det1:SizeY_RBV')\n sda[port + ':det1:Manufacturer_RBV'] = lambda: epics.caget(port + ':det1:Manufacturer_RBV')\n sda[port + ':det1:Model_RBV'] = lambda: epics.caget(port + ':det1:Model_RBV')\n sda[port + ':det1:AcquireTime_RBV'] = lambda: epics.caget(port + ':det1:AcquireTime_RBV')\n sda[port + ':det1:Gain_RBV'] = lambda: epics.caget(port + ':det1:Gain_RBV')\n sda[port + ':det1:LEFTSHIFT_RBV'] = lambda: epics.caget(port + ':det1:LEFTSHIFT_RBV')\n sda[port + ':det1:NumImagesCounter_RBV'] = lambda: epics.caget(port + ':det1:NumImagesCounter_RBV')\n sda[port + ':det1:DataType_RBV'] = lambda: epics.caget(port + ':det1:DataType_RBV')\n \n ds = Dataset('data', lambda: self.get_reshaped_data())\n ds.attrs['pvname'] = self._callback_pvname\n ds.attrs['x-label'] = 'Horizontal'\n ds.attrs['y-label'] = 'Vertical'\n ds.attrs['x-units'] = 'Pixels'\n ds.attrs['y-units'] = 'Pixels'\n self.savedata.add_dataset(ds)\n\n def enable_lens_controller(self, focus=None, aper=None):\n # self.efc = EF_Controller()\n self.lens_controller=True\n epics.caput(\"LENS:ping\", 1)\n time.sleep(1)\n sda = self.savedata.attrs\n sda['lens_controller'] = 'ISSI_EPICS'\n sda['lens_id'] = lambda: epics.caget(\"LENS:lens\")\n sda['f_number'] = lambda: float(epics.caget(\"LENS:getAper\"))\n sda['focus'] = lambda: float(epics.caget(\"LENS:getFocus\"))\n sda['focal_length'] = lambda: float(epics.caget(\"LENS:getFocalLength\"))\n if(focus):\n self.efc.set_focus(focus)\n if(aper):\n self.efc.set_aperture(aper)\n \n def write(self, h5g):\n \"\"\"\n If lens controller is enabled, it must be pinged before we can read back lens info\n \"\"\"\n if(self.lens_controller): epics.caput('LENS:ping', 1)\n time.sleep(0.1)\n super().write(h5g)\n\n def auto_exposure(self, trigger_fun):\n \"\"\" Auto exposure:\n - Set camera to single exposure modde\n - Find the correct exposure\n - Set camera back to initial configuration\n \"\"\"\n print('Camera auto exposure!')\n exposure_level = 0.5\n self.connect()\n trigger_fun()\n time.sleep(0.1)\n self.set_exposure(0.15)\n while(True):\n self.clear()\n trigger_fun()\n while(not self.is_ready_p()):\n time.sleep(0.1)\n exp = epics.caget(self.port + ':det1:AcquireTime_RBV')\n data = epics.caget(self.port + ':image1:ArrayData')\n data = data.reshape(epics.caget(self.port + ':det1:SizeY_RBV'),\n epics.caget(self.port + ':det1:SizeX_RBV'))\n sm = scipy.ndimage.filters.median_filter(data, 9).max()\n print('Over exposed is ' + str(sm))\n print('Max smoothed is ' + str(sm))\n max_image = 2**12 - 1\n exp = epics.caget(self.port + ':det1:AcquireTime_RBV')\n autoset = exp * (max_image * exposure_level)/sm\n self.set_exposure(autoset)\n if(autoset > self.exposure_max):\n print('Exposure set to max!')\n break\n if(autoset < self.exposure_min):\n print('Exposure set to min!')\n break\n if(autoset/exp > (1/1.5) and autoset/exp < 1.5):\n print('Exposure set to ' + str(autoset))\n break\n print('Auto exposure done.')\n self.disconnect()\n return()\n\n\nclass Thorlabs_spectrometer(Cool_device):\n \"\"\"\n Thorlabs CCS100 spectrometer\n \"\"\"\n dev_type = 'Thorlabs spectrometer'\n\n def sw_trigger(self): epics.caput(self.port + ':det1:Acquire', 1)\n\n def set_exposure(self, exposure):\n \"\"\"\n Set exposure\n \"\"\"\n exposure = max(exposure, self.exposure_min)\n exposure = min(exposure, self.exposure_max)\n print('Setting exposure to: ' + str(exposure))\n epics.caput(self.port + ':det1:AcquireTime', exposure)\n time.sleep(0.1)\n\n def __init__(self, port,\n sw_trig=False,\n exposure=None,\n exposure_min=0.0002,\n exposure_max=2):\n \"\"\"\n Initialize a Thorlabs spectrometer\n \"\"\"\n super().__init__(port,\n 'data/spectra/' + port + '/',\n self.dev_type,\n port + ':trace1:ArrayData')\n \n self.exposure_min = exposure_min\n self.exposure_max = exposure_max\n\n # Initialize device\n for pvname, value in {':det1:TlAcquisitionType': 0, # 1 is processed, set to 0 for raw\n ':trace1:EnableCallbacks': 1, # Enable\n ':trace1:ArrayCallbacks': 1, # Enable\n ':det1:TlAmplitudeDataTarget': 2, # Thorlabs\n ':det1:TlWavelengthDataTarget': 0}.items(): # Factory\n epics.caput(port + pvname, value)\n if(sw_trig):\n for pvname, value in {':det1:ImageMode': 0, # Single\n ':det1:TriggerMode': 0}.items(): # Internal\n epics.caput(port + pvname, value)\n else:\n for pvname, value in {':det1:Acquire': 0,\n ':det1:ImageMode': 1, # Continuous\n ':det1:TriggerMode': 1}.items(): # External\n epics.caput(port + pvname, value)\n epics.caput(port + ':det1:Acquire', 1)\n\n epics.caput(port + ':det1:TlAmplitudeDataGet', 1) # Get amplitudes\n epics.caput(port + ':det1:TlWavelengthDataGet', 1) # Get waves\n\n # Set exposure from argument\n if(exposure):\n self.set_exposure(exposure)\n\n sda = self.savedata.attrs\n sda['acquire_duration'] = lambda: epics.caget(port + ':det1:AcquireTime_RBV')\n # sda[port + ':det1:AcquireTime_RBV'] = lambda: epics.caget(port + ':det1:AcquireTime_RBV')\n sda[port + ':det1:NumImagesCounter_RBV'] = lambda: epics.caget(port + ':det1:NumImagesCounter_RBV')\n sda[port + ':det1:Model_RBV'] = epics.caget(self.port + ':det1:Model_RBV')\n sda[port + ':det1:Manufacturer_RBV'] = epics.caget(port + ':det1:Manufacturer_RBV')\n\n # Data sets\n pv1 = port + ':det1:TlWavelengthData_RBV'\n x_data = Dataset('x_values', lambda: epics.caget(pv1))\n x_data.attrs['pvname'] = pv1\n x_data.attrs['label'] = 'Wavelength'\n x_data.attrs['unit'] = 'nm'\n self.savedata.add_dataset(x_data)\n\n pv2 = port + ':trace1:ArrayData'\n y_data = Dataset('y_values', lambda: self.data)\n y_data.attrs['pvname'] = pv2\n y_data.attrs['label'] = 'Intensity'\n y_data.attrs['unit'] = 'Counts'\n self.savedata.add_dataset(y_data)\n\n pv3 = port + ':det1:TlAmplitudeData_RBV'\n scale_data = Dataset('y_scale', lambda: epics.caget(pv3))\n scale_data.attrs['pvname'] = pv3\n scale_data.attrs['label'] = 'Correction'\n scale_data.attrs['unit'] = 'Scale factor'\n self.savedata.add_dataset(scale_data)\n\n def auto_exposure(self, trigger_fun):\n \"\"\" Auto exposure:\n \n \"\"\"\n print('CCS exposure!')\n exposure_level = 0.6\n self.connect()\n trigger_fun()\n time.sleep(0.1)\n while(True):\n self.clear()\n trigger_fun()\n while(not self.is_ready_p()):\n time.sleep(0.1)\n exp = epics.caget(self.port + ':det1:AcquireTime_RBV')\n wave = epics.caget(self.port + ':det1:TlWavelengthData_RBV')\n data = epics.caget(self.port + ':trace1:ArrayData')[0:len(wave)]\n sm = scipy.signal.medfilt(data, 3).max()\n max_array = 2**16 - 1\n exp = epics.caget(self.port + ':det1:AcquireTime_RBV')\n autoset = exp * (max_array * exposure_level)/sm\n self.set_exposure(autoset)\n if(autoset > self.exposure_max):\n print('Exposure set to max!')\n break\n if(autoset < self.exposure_min):\n print('Exposure set to min!')\n break\n if(autoset/exp > (1/1.5) and autoset/exp < 1.5):\n print('Exposure set to ' + str(autoset))\n break\n print('Auto exposure done.')\n self.disconnect()\n return()\n # print('CSS auto exposure')\n # cam_exp = epics.caget('CAM1:det1:AcquireTime_RBV')\n # print('Set exposure to ' + str(cam_exp * 5))\n # self.set_exposure(cam_exp * 5)\n\n\nclass PicoscopePython(Cool_device):\n \"\"\"\n Picoscope 4264 from ps4262.py\n \"\"\"\n dev_type = 'PicoScope 4264, python'\n data = None\n\n def get_glob_trigger(self):\n # Get trigger number for last caught trigger\n if(self.send_triggers):\n return(self.triggercount)\n else:\n return(False)\n\n def set_exposure(self, exposure):\n self._ps.setTimeBase(requestedSamplingInterval=self.samplingInterval,\n tCapture=exposure)\n\n def __init__(self, voltage_range=1, sampling_interval=2e-7,\n capture_duration=0.66, trig_per_min=30, send_triggers=False):\n super().__init__('ps4264', 'data/oscope/ps4264py/', self.dev_type, None)\n self.samplingInterval = sampling_interval\n self._ps = ps4262(VRange=voltage_range, requestedSamplingInterval=sampling_interval,\n tCapture=capture_duration, triggersPerMinute=trig_per_min)\n # Configuring data for saving\n current = Dataset('y_data', lambda: self.data['raw_data'])\n # current.attrs['label'] = 'raw_data'\n # current.attrs['unit'] = 'counts'\n self.savedata.add_dataset(current)\n self.currentds = current\n self.acquire_duration = 0\n # Lambdas called during write(), queue should be 0\n self.potentially_desynced = len(self._ps.data) > 0\n self.savedata.attrs['Queue length'] = lambda: len(self._ps.data)\n self.savedata.attrs['acquire_duration'] = lambda: self.acquire_duration\n self.metadata = None\n self.send_triggers = send_triggers\n\n def write(self, h5f):\n for key, value in self.data.items():\n if key != 'raw_data':\n self.currentds.attrs[key] = value\n super().write(h5f)\n self.savedata.write_additional_meta(h5f, self.metadata)\n\n def is_ready_p(self):\n \"\"\"If we do not have fresh data, wait for it. If we do, we are ready.\"\"\"\n # print('In picoscope is ready!!')\n if(self.is_ready):\n return(True)\n if(len(self._ps.data) > 0):\n print('Pico data!!')\n self.data = self._ps.data.popleft()\n self.timestamp = self.data['timestamp']\n self.triggercount = self._ps.edgesCaught\n self.acquire_duration = self.data['t_end'] - self.data['t0']\n self.is_ready = True\n self.metadata = self._ps.getMetadata()\n return(self.is_ready)\n\n def clear(self):\n \"\"\"Should set _ps.data to None\"\"\"\n self.is_ready = False\n self._ps.data.clear()\n\n def sampling(self, sampling_interval, duration):\n \"\"\" How long, and at what frequency, will the recorded waveforms be? \"\"\"\n self._ps.setTimeBase(requestedSamplingInterval=sampling_interval,\n tCapture=duration)\n\n def triggers_per_minute(self, tpm):\n \"\"\" Set tmp to 0 for single pulse generation \"\"\"\n self._ps.setFGrn(triggersPerMinute=tpm)\n\n def hw_trigger(self):\n if(self.send_triggers):\n print('PS will trigger!')\n self._ps.setFGen(triggersPerMinute=-1)\n time.sleep(.05) # Should not ask for triggers to fast\n return(True)\n\n def check_exposure(self):\n \"\"\"\n See if exposure settings are ok\n \"\"\"\n print(\"Checking picoscope exposure settings\")\n cam_exp = epics.caget('CAM1:det1:AcquireTime_RBV')\n css_exp = epics.caget('CCS1:det1:AcquireTime_RBV')\n ps_exp = self._ps.tCapture\n if (ps_exp < 1.25 * max(cam_exp, css_exp)):\n print('Picoscope exposure is shorter than camera or spectrometer exposure')\n input('Press Enter to continue')\n\n def auto_exposure(self, trigger_fun):\n \"\"\" Auto exposure:\n Set to max of camera exposure, spectrometer exposure\n \"\"\"\n print('Picoscope exposure')\n cam_exp = epics.caget('CAM1:det1:AcquireTime_RBV')\n css_exp = epics.caget('CCS1:det1:AcquireTime_RBV')\n print('Set exposure to ' + str(1.25 * max(cam_exp, css_exp)))\n self.set_exposure(1.25 * max(cam_exp, css_exp))\n\n\nclass LinearStage(Cool_device):\n \"\"\" Code for setting up, reading position and moving the linear stage \"\"\"\n dev_type = 'Standa linear stage'\n\n def __init__(self):\n super().__init__('standa',\n 'data/linearstage/standa/',\n self.dev_type,\n None)\n # self.pos = moveStage.get_position()\n moveStage.set_power_off_delay(0)\n self.sample_dict = collections.OrderedDict()\n self.sample_name = ''\n # Save data\n self.savedata.attrs['Samples'] = lambda: [x.encode('utf8') for x in list(self.sample_dict.keys())]\n self.savedata.attrs['Positions'] = lambda: list(self.sample_dict.values())\n self.savedata.attrs['current_position'] = lambda: moveStage.get_position()\n self.savedata.attrs['current_sample'] = lambda: self.sample_name\n\n def add_sample(self, name, position):\n self.sample_dict[name] = position\n\n def move_to_sample(self, sample):\n self.pos = self.sample_dict[sample]\n self.sample_name = sample\n moveStage.move_to(self.pos)\n time.sleep(0.1)\n return(True)\n\n def is_ready_p(self):\n return(True)\n\n\nclass SuperCool(Cool_device):\n dev_type = 'LairdTech temperature regulator'\n\n def __init__(self):\n self.port = 'LT59'\n super().__init__('LT59', 'data/temperature/LT59/', self.dev_type, None)\n self.triggercount = 0\n\n # Initialize device\n epics.caput('LT59:Retrieve', 1)\n epics.caput('LT59:Temp1Mode', 1)\n epics.caput('LT59:Temp1CoeffA', 3.9083E-3)\n epics.caput('LT59:Temp1CoeffB', -5.7750E-7)\n epics.caput('LT59:Temp1CoeffC', 1000)\n epics.caput('LT59:Mode', 6)\n epics.caput('LT59:Send', 1)\n\n # Set up data saving\n sda = self.savedata.attrs\n sda['LT59:Temp1Mode'] = lambda: epics.caget('LT59:Temp1Mode')\n sda['LT59:Temp1CoeffA_RBV'] = lambda: epics.caget('LT59:Temp1Mode')\n sda['LT59:Temp1CoeffB_RBV'] = lambda: epics.caget('LT59:Temp1CoeffB_RBV')\n sda['LT59:Temp1CoeffC_RBV'] = lambda: epics.caget('LT59:Temp1CoeffC_RBV')\n sda['LT59:Mode_RBV'] = lambda: epics.caget('LT59:Mode_RBV')\n sda['LT59:Temp1_RBV'] = lambda: epics.caget('LT59:Temp1_RBV')\n sda['LT59:StartStop_RBV'] = lambda: epics.caget('LT59:StartStop_RBV')\n\n def write(self, h5g):\n epics.caput('LT59:Retrieve', 1)\n time.sleep(0.1)\n super().write(h5g)\n\n def is_ready_p(self):\n return(True)\n\n\nclass ECatEL3318(Cool_device):\n dev_type = 'm-ethercat with EL3318'\n\n def get_temp(self, channel, position):\n if channel == -1:\n return(0.0)\n else:\n output = subprocess.check_output(['/home/dev/git/m-ethercat/ethercat-1.5.2/tool/ethercat',\n 'upload',\n '-p{:d}'.format(position),\n '--type',\n 'int16',\n '0x60{:d}0'.format(channel - 1),\n '0x11'])\n return(int(output.split()[1])/10.0)\n\n def __init__(self, position):\n self.port = 'ECAT'\n super().__init__('ECAT', 'data/temperature/ECAT/', self.dev_type, None)\n self.triggercount = 0\n\n self.sample_dict = {}\n self.sample_name = ''\n self.channel = 0\n\n sda = self.savedata.attrs\n sda['slave_position'] = position\n sda['channel'] = lambda: self.channel\n sda['temperature'] = lambda: self.get_temp(self.channel, position)\n\n def add_sample(self, name, channel):\n self.sample_dict[name] = channel\n\n def move_to_sample(self, sample):\n self.channel = self.sample_dict[sample]\n self.sample_name = sample\n return(True)\n\n def is_ready_p(self):\n return(True)\n\n\nclass Raspi_trigger(Cool_device):\n \"\"\"\n Raspberry pi trigger on demand over sockets\n \"\"\"\n dev_type = \"Raspi trigger\"\n\n def __init__(self, dev_port=\"RPI\"):\n \"\"\" Initialize pm100 \"\"\"\n super().__init__(dev_port,\n 'data/trigger/' + dev_port + '/',\n self.dev_type,\n None)\n\n def get_glob_trigger(self):\n return(int(epics.caget(\"RPI:getTriggerNum\")))\n \n\n def hw_trigger(self):\n print(\"Raspi will trigger!\")\n epics.caput(\"RPI:trigger\", 1)\n return(True)\n\n def is_ready_p(self):\n return(True)\n\n\nclass PM100(Cool_device):\n \"\"\"\n Thorlabs PM100USB\n \"\"\"\n dev_type = 'Thorlabs PM100USB'\n n_samples = 10\n\n times = []\n\n def populate(self):\n \"\"\" Fill a list of PM values with timestamps, sample for 10 seconds \"\"\"\n pmvals = []\n scan_mode = epics.caget(self.port + ':MEAS:POW.SCAN')\n epics.caput(self.port + ':MEAS:POW.SCAN', 9)\n\n # Use callback to populate list\n pv = epics.PV(self.port + ':MEAS:POW')\n pv.add_callback(\n lambda pvname=None, value=None, char_value=None, **fw:\n pmvals.append((value, time.time())))\n\n time.sleep(self.capture_time)\n pv.disconnect()\n epics.caput(self.port + ':MEAS:POW.SCAN', scan_mode)\n self.array_data = [a[0] for a in pmvals]\n self.times = [a[1] for a in pmvals]\n # We are done and ready for read out\n self.is_ready = True\n\n def sw_trigger(self):\n \"Trigger starts data collection thread\"\n if(not self.is_ready):\n threading.Thread(target=self.populate, args=()).start()\n\n def __init__(self, port, sw_trig=False):\n \"\"\" Initialize pm100 \"\"\"\n super().__init__(port,\n 'data/powermeter/' + port + '/',\n self.dev_type,\n None)\n self.capture_time = 10\n self.port = port\n self.pm_pv = self.port + ':MEAS:POW'\n self.savedata.attrs['acquire_duration'] = self.capture_time\n self.savedata.attrs['wavelength'] = lambda: epics.caget(\"PM100:SENS:CORR:WAV_RBV\")\n\n # Saving data\n x_data = Dataset('x_values', lambda: self.times)\n x_data.attrs['label'] = 'Measurement time'\n x_data.attrs['units'] = 'seconds'\n self.savedata.add_dataset(x_data)\n\n y_data = Dataset('y_values', lambda: self.array_data)\n y_data.attrs['label'] = 'Power'\n y_data.attrs['units'] = 'Watts'\n y_data.attrs['pvname'] = self.pm_pv\n self.savedata.add_dataset(y_data)\n\n def write(self, h5f):\n # We must trigger an uptade to WAV_RBV before the PV is written to file\n epics.caput(self.port + ':SENS:CORR:WAV_RBV.PROC', 1)\n time.sleep(0.01)\n super().write(h5f)\n","sub_path":"lib/data_coolection.py","file_name":"data_coolection.py","file_ext":"py","file_size_in_byte":37077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"143679520","text":"# import from peewee\nfrom peewee import *\n\n# connect to the SQLite database, in the \"db-files\" folder\ndb = SqliteDatabase('/home/arloft/learn/edhdecks.db')\n# ^ pythonanywhere requires the full path to the .db file\n\n# define what a 'Deck' is\nclass Deck(Model):\n # these are all the fields it has\n # match up TextField/IntegerField/etc with correct type\n # see link for list of field types: http://docs.peewee-orm.com/en/latest/peewee/models.html#field-types-table\n dbn = IntegerField(primary_key=True) # primary key = unique id\n deck_name = TextField()\n deck_color = TextField()\n deck_cmc = FloatField()\n deck_creature = IntegerField()\n deck_artifact = IntegerField()\n deck_enchantment = IntegerField()\n deck_sorcery = IntegerField()\n deck_instant = IntegerField()\n deck_planeswalker = IntegerField()\n deck_land = IntegerField()\n\n class Meta:\n # data is coming from edhdecks.db\n database = db\n # and it's in the table called 'py-edh-deck-list'\n db_table = 'py-edh-deck-list'\n\n# repeat with the Performance Stats data\nclass Score(Model):\n dbn = IntegerField(primary_key=True)\n deck_name = TextField()\n deck_winloss = TextField()\n game_turncount = IntegerField()\n opp1_deck = TextField()\n opp1_deck_colors = TextField()\n opp2_deck = TextField()\n opp2_deck_colors = TextField()\n opp3_deck = TextField()\n opp3_deck_colors = TextField()\n opp4_deck = TextField()\n opp4_deck_colors = TextField()\n\n class Meta:\n database = db\n db_table = 'py-edh-deck-performance-stats'","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"295727066","text":"from socket import *\r\nfrom struct import pack, unpack\r\n\r\n# Define variables that hold the desired server name, port, and buffer size\r\nSERVER_NAME = 'localhost'\r\nSERVER_PORT = 3604\r\nBUFFER_SIZE = 32\r\n\r\nclass BufferedTCPEchoClient(object):\r\n def __init__(self, server_name, server_port):\r\n # We are creating a *TCP* socket here. We know this is a TCP socket because of\r\n # the use of SOCK_STREAM\r\n self.sock = socket(AF_INET, SOCK_STREAM)\r\n # Connect to a server at the specified port using this socket\r\n self.sock.connect((server_name, server_port))\r\n\r\n\r\n def start(self):\r\n while True:\r\n # Read in an input statement from the user\r\n message = input('Input: ')\r\n \r\n # Send the message to the server\r\n self.send_message(message)\r\n\r\n # Wait for a response from the server\r\n response = self.receive_message()\r\n if response:\r\n print(response)\r\n else:\r\n print(\"Server disconnected...\")\r\n break\r\n\r\n print(\"Closing socket...\")\r\n self.sock.close()\r\n\r\n\r\n def send_message(self, message):\r\n message_length = len(message)\r\n data = pack(\"!B\" + str(message_length) + \"s\", message_length, message.encode()) \r\n self.sock.send(data)\r\n\r\n \r\n def receive_message(self):\r\n # Get the first part of the message, this includes the header and the start of the string\r\n first_part = self.sock.recv(BUFFER_SIZE)\r\n\r\n if first_part:\r\n # First, strip out the header\r\n message_length = unpack(\"!B\", first_part[:1])[0]\r\n print(\"..New message size: \" + str(message_length))\r\n print(\"..Received '\" + first_part[1:].decode() + \"'\")\r\n\r\n message = first_part[1:]\r\n # Next, continue recv until the full message has been received\r\n while (len(message) < message_length):\r\n # Receive the next part of the message\r\n next_part = self.sock.recv(BUFFER_SIZE)\r\n # If there is a next part, append it to the current message\r\n if next_part:\r\n print(\"..Received '\" + next_part.decode() + \"'\")\r\n message += next_part\r\n # Else, the client has disconnected, so return false\r\n else:\r\n print(\"Client disconnected!\")\r\n return False\r\n return message.decode()\r\n else:\r\n return False\r\n\r\n\r\nif __name__ == \"__main__\":\r\n BufferedTCPEchoClient(SERVER_NAME, SERVER_PORT).start()","sub_path":"SampleCode/BufferedTCPEchoClient.py","file_name":"BufferedTCPEchoClient.py","file_ext":"py","file_size_in_byte":2655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"557264837","text":"# PRACTICE: Solid Studentclass Student:\nclass Student:\n # def __init__(self):\n # self.__first_name = \"\"\n # self.__last_name = \"\"\n # self.__age = 1\n # self.__cohort_num = 1\n # self.__full_name = self.__first_name + \" \" + self.__last_name\n \n\n @property\n def full_name(self):\n return self.first_name + \" \" + self.last_name\n\n @property\n def first_name(self):\n try:\n return self.__first_name\n except AttributeError:\n return 0\n\n @first_name.setter\n def first_name(self, first_name):\n if type(first_name) is str:\n self.__first_name = first_name\n else:\n raise TypeError('Please provide a word for the first name')\n\n @property\n def last_name(self):\n return self.__last_name\n\n @last_name.setter\n def last_name(self, last_name):\n if type(last_name) is str:\n self.__last_name = last_name\n else:\n raise TypeError('Please provide a word for the last name')\n\n @property\n def age(self):\n return self.__age\n\n @age.setter\n def age(self, age):\n if type(age) is int:\n self.__age = age\n else:\n raise TypeError('Please provide a number for the age')\n\n @property\n def cohort_num(self):\n return self.__cohort_num\n\n @cohort_num.setter\n def cohort_num(self, cohort_num):\n if type(cohort_num) is int:\n self.__cohort_num = cohort_num\n else:\n raise TypeError('Please provide a number for the cohort number')\n\n def __str__(self):\n return f\"{self.full_name} is {self.age} years old and is in cohort {self.cohort_num}\"\n\npam = Student()\npam.first_name = \"Pam\"\npam.last_name = \"Beasley\"\npam.age = 18\npam.cohort_num = 33\n\nprint(pam)\n\nprint()","sub_path":"ch10-Class-Properties/class_properties.py","file_name":"class_properties.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"126979266","text":"from flask import Blueprint, render_template\n\n_visdial_cca = Blueprint('visdial_cca', __name__, template_folder='templates', static_folder='static', static_url_path='/static')\nglobal cv, jobtitle, mykeywords\n\ndef set_global_params(cv_path, title, keywords):\n global cv, jobtitle, mykeywords\n cv = cv_path\n jobtitle = title\n mykeywords = keywords\n\n@_visdial_cca.route('/')\ndef home():\n return render_template('visdial_cca.html', cv=cv, jobtitle=jobtitle, mykeywords=mykeywords)\n\n","sub_path":"research/visdial_cca/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"159417477","text":"import numpy as np\nimport os\nimport librosa\nimport muda\nimport scipy \nimport jams\nimport random\nimport soundfile as sf\nimport sys\n\n\n# Parse input arguments.\nargs = sys.argv[1:]\nSRC_path = args[0]\nir_path = args[1]\nbg_path = args[4]\nidx_start = int(args[2])\nidx_end = int(args[3])\n\n\n#should downsampling equivalent to low passing?\ndef augmentation(SRC_path,ir_path,idx_start,idx_end):\n \"\"\"\n SRC_path: path to the folder of speaker folders to augment, string\n \n augmentations: downsampling(8k/11k/16k) or no; noise(white/pink/brown) or no; clipping or no; cough or no; \n room acoustics (reverb) or no; drc or no\n \n \n \"\"\"\n\n #provide options for all the augmentations\n freqs = [8000,11000]\n #noise = [\"pink\",\"white\",\"brownian\"]\n clip = 1 #\n room = [os.path.join(ir_path,file) for file in os.listdir(ir_path)]\n #room = [\"big.wav\",\"small.wav\"]\n bg = [os.path.join(bg_path,file) for file in os.listdir(bg_path)] \n augmentations = {\"acoustics\":room,\n #\"noise\":noise, \n \"clipping\":clip,\n \"downsample\":freqs,\n \"background\":bg}\n\n #make union \n steps = []\n \n for aug,value in augmentations.items():\n if aug == \"downsample\":\n filtering = muda.deformers.Filter(btype=\"low\",cutoff=value) #only one output\n steps.append(('downsample', filtering))\n elif aug == \"noise\":\n colorednoise = muda.deformers.ColoredNoise(n_samples=1, color = value, weight_max=0.3) #noise of different weights\n steps.append(('colorednoise', colorednoise))\n elif aug == \"clipping\":\n clipping = muda.deformers.LinearClipping(n_samples=value) # clipping of different limits\n steps.append(('clipping', clipping))\n elif aug == \"acoustics\":\n acoustics = muda.deformers.IRConvolution(value) #one output\n steps.append(('acoustics', acoustics))\n elif aug == \"background\":\n bgnoise = muda.deformers.BackgroundNoise(n_samples=1, files=value) #noise of different weights\n steps.append(('background', bgnoise))\n\n\n #this is in total 4 * 4 * 3 * 2 = 96 augmentations per audio file!\n union = muda.Union(steps)\n #ensure distribution between all the different deforms or equal distribution among recordings\n total_deform = len(freqs) + clip + len(room) + len(bg) #save 100 files in the new folder\n \n\n output_dir = '/scratch/hh2263/VCTK/VCTK-Corpus/wav48_muda_2' \n jam_path = '/home/hh2263/Speaker-Diarization/general.jams'\n wavDir = os.listdir(SRC_path)[idx_start:idx_end]\n\n \n for j,spkDir in enumerate(wavDir): # Each speaker's directory\n spk = spkDir # speaker name\n print(\"making \",spkDir)\n wavPath = os.path.join(SRC_path, spkDir)\n outPath = os.path.join(output_dir,spkDir)\n os.makedirs(outPath, exist_ok=True)\n\n for i, wav in enumerate(os.listdir(wavPath)): # all wavfiles included\n if os.path.exists(os.path.join(outPath,wav[:-4]+'_g00.wav')):\n pass\n else:\n print(\"make\",wav[:-4])\n utter_path = os.path.join(wavPath, wav)\n #read file\n y_orig, sr = sf.read(utter_path)\n existing_jams = jams.load(jam_path) # do we have to create a jams file for each recording??\n #empty_jam = jams.JAMS()\n j_orig = muda.jam_pack(existing_jams, _audio=dict(y=y_orig, sr=sr))\n #pick random deformation to deform\n \n #save deformed file and jam to output directory\n for i, jam_out in enumerate(union.transform(j_orig)):\n muda.save(os.path.join(outPath,wav[:-4]+'_g{:02d}.wav'.format(i)),\n os.path.join(outPath,wav[:-3]+'_g{:02d}.jams'.format(i)),\n jam_out)\n \n \n\n #if(j>100):\n # break\n\n\n\n#SRC_path='/scratch/hh2263/VCTK/VCTK-Corpus/wav48'\n#ir_path = '/home/hh2263/Speaker-Diarization/ir_files/'\naugmentation(SRC_path,ir_path,idx_start,idx_end)\n\n \n\n\n \n \n","sub_path":"augmentation_ver3.py","file_name":"augmentation_ver3.py","file_ext":"py","file_size_in_byte":4172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"635140268","text":"class AgeError(Exception):\n def __init__(self,errorInfo):\n Exception.__init__(self)\n self.error= errorInfo\n \n def __str__(self):\n return \"***age error***\"\n\nif __name__ == \"__main__\":\n age = int(input(\"input an age : \"))\n if age <1 or age>150:\n raise AgeError(age)\n else:\n print(\"right\",age)","sub_path":"Learn/exception/raise2.py","file_name":"raise2.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"351479801","text":"import argparse\nimport json\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--predictions1\", type=str, required=True,\n help=\"The first labeled predictions file.\")\n parser.add_argument(\"--predictions2\", type=str, required=True,\n help=\"The second labeled predictions file.\")\n parser.add_argument(\"--outfile\", type=str, required=True,\n help=\"Where to write the union of the predictions.\")\n return parser.parse_args()\n\n\ndef main(predfile1, predfile2, outfile):\n preds1 = json.load(open(predfile1))\n preds2 = json.load(open(predfile2))\n union_preds = union(preds1, preds2)\n with open(outfile, 'w') as outF:\n json.dump(union_preds, outF)\n\n\ndef union(preds1, preds2):\n union = {}\n all_cuis = set(preds1.keys()).union(set(preds2.keys()))\n for cui in all_cuis:\n if cui not in preds2.keys():\n union[cui] = preds1[cui]\n elif cui not in preds1.keys():\n union[cui] = preds2[cui]\n else:\n union[cui] = span_union(preds1[cui], preds2[cui])\n return union\n\n\ndef span_union(spans1, spans2):\n union = []\n seen_spans = set()\n all_spans = sorted(spans1 + spans2, key=lambda x: x[\"start\"])\n for span in all_spans:\n char_span = (span[\"start\"], span[\"end\"])\n if char_span not in seen_spans:\n seen_spans.add(char_span)\n union.append(span)\n return union\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n main(args.predictions1, args.predictions2, args.outfile)\n","sub_path":"ner/src/union_predictions.py","file_name":"union_predictions.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"165048506","text":"import sublime_plugin\n\n\nclass RulersCommand(sublime_plugin.TextCommand):\n\n def run(self, edit, action):\n col = self.view.rowcol(self.view.sel()[0].begin())[1]\n if col > 0:\n queue_save = False\n settings = self.view.settings()\n rulers = settings.get('rulers')\n\n if action == 'add':\n if col not in rulers:\n rulers.append(col)\n queue_save = True\n elif action == 'remove':\n if col in rulers:\n rulers.remove(col)\n queue_save = True\n elif action == 'clear':\n if rulers != []:\n rulers = []\n queue_save = True\n else:\n raise Exception('unknown action')\n\n if queue_save:\n rulers.sort()\n if rulers:\n settings.set('rulers', rulers)\n else:\n settings.erase('rulers')\n","sub_path":"User/user_rulers.py","file_name":"user_rulers.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"170348948","text":"import os\nimport errno\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\n\ny_train = []\ni = 0\n\nwith open('./data/list_attr_celeba.txt') as f:\n for line in f:\n a = line.split()\n a = list(a)\n \n if i == 1:\n name = a\n if i >= 2:\n a.pop(0)\n y_train.append(a)\n i += 1\n\n # Note: only for test, 30 datapoints are chosen\n if i==8194:\n break\n\n#print(len(name))\n#Black hair, Blond hair, Eyeglasses, Male\n# -1 = not black hair\n# -1 = not blone hair\n# -1 = no glass\n# -1 = male\nattr = [8, 9, 15, 20]\ny_train = np.array(y_train)\ny_train = y_train.astype(np.int)\ny_mini = y_train[:, attr]\nnp.save('./data/y4_8192', y_mini)\n\ndef visualize(data, index): \n #print(data[index])\n img=mpimg.imread(\"./data/mini_img/00000\" + str(index+1)+ \".png\")\n imgplot = plt.imshow(img)\n plt.show()\n#visualize(y_mini, 2000)","sub_path":"load_label.py","file_name":"load_label.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"420225005","text":"import math\nimport pandas as pd\nimport numpy as np\nfrom collections import defaultdict\n# from textblob import TextBlob\nfrom pymongo import MongoClient\n# from sklearn.model_selection import cross_val_score\nfrom datetime import datetime as dt, timedelta\n# from sklearn.feature_extraction.text import TfidfVectorizer, ENGLISH_STOP_WORDS\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\n# from sklearn.tree import DecisionTreeClassifier\n# from sklearn import tree\n# import time\n# from sklearn.discriminant_analysis import LinearDiscriminantAnalysis\n# from pprint import pprint\n\nwords_i_like = ['bitcoin', 'btc', 'blockchain', 'litecoin', 'usd',\n'wallet', 'currency', 'altcoin', 'mining', 'gox', 'mt', 'crypto', 'new', \n'cryptocurrency', 'ethereum', 'fintech', 'ltc', 'free', 'digital', 'latest',\n'money', 'bank', 'hardware', 'index', 'satoshi', 'market', 'economy', 'bitcoins',\n'dogecoin', 'value', 'secure', 'miner', 'trading', 'coindesk', 'smart', \n'bitstamp', 'technology', 'euro', 'buy', 'trade', \n'coinbase', 'power', 'time', 'tech', 'trezor', 'bitfinex', 'algorithm', 'china', 'banks', \n'earn', 'past', 'landbitcoin', 'portal', 'win',\n 'data', 'coin', 'best', 'cash', 'bitcoinnews', 'increased', 'cloud', 'average', \n'future', 'change', 'financial', 'virtual', 'startup', 'open', 'ceo', 'platform', \n'decreased', 'business', 'finance', 'convert', 'high', 'dash', 'altcoins', 'currencies', \n'collapse', 'libertarian', 'bot', 'dollar', 'movement', 'directly', 'game',\n'global', 'technical', 'investment', 'launches', 'volume', 'network', 'support',\n'observer', 'lost', 'security', 'secure', 'won', 'good', 'launch', \n'gambling', 'japan', 'invest', 'sell', 'wild', 'hack', \n'pay', 'exchanges', 'miners', 'crypto-currencies', 'forum', 'fast', 'sell', 'ledger', \n'mobile', 'grow', 'hot', 'great', 'wild', 'hack', 'miracle', 'bullish', 'solution', 'millionare']\n\ndef split_list(a_list):\n half = int(len(a_list)/2)\n return a_list[:half], a_list[half:]\n\ndef convert_from_minutes(x):\n d = x[1]\n m = x[2]\n h = math.floor(m/60)\n m = int(m % 60)\n d = d.replace(hour=h, minute=m)\n return d\n\ndef drop_seconds(d):\n d = dt(d.year, d.month, d.day, d.hour, d.minute)\n return d\n\n# def getFitDirection(df, cutoff):\n# x = range(len(df['Date_Time']))\n# y = df['Price']\n# m, b = np.polyfit(x, y, 1)\n# if m > 0: return 2\n# # if m < cutoff and m > -cutoff: return 1\n# if m < 0: return 0\n# return 1\n\ndef sliceDf(start_date):\n df = pd.read_csv('data_new.csv', parse_dates=['Date','Date_Time'])\n start_index = df[df['Date'] == start_date].iloc[[0]].index.values[0]\n df = df[start_index:]\n df = df.set_index(['Date_Time'])\n df = df[start_date:]\n return(df)\n\n# def df_PositiveLinePercent(df, tweet_window):\n# pos = 0\n# x = int(len(df['Date'])/50)\n# dlist = df['Date'].sample(x)\n# for d in dlist:\n# df_near_tweet = df[d:d + timedelta(minutes=tweet_window)].reset_index()\n# if getFitDirection(df_near_tweet, 0) > 1: pos +=1\n# return len(dlist), pos/len(dlist)\n\ndef getNearest(t, df):\n i = df.index.searchsorted(t)\n return df.iloc[i]['Price']\n\ndef getDelta(df, date, delta_minutes, cutoff):\n date = np.datetime64(date)\n df2 = df[:-(2*delta_minutes)]\n t1 = date\n t2 = date + np.timedelta64(delta_minutes,'m')\n p1 = getNearest(t1, df)\n p2 = getNeareste(t2, df2)\n m = p2-p1\n if m > cutoff: return 2\n if m < -cutoff: return 0\n return 1 \n\ndef df_DeltaPercent(df, tweet_window):\n df2 = df[:-(5*tweet_window)]\n pos = 0\n x = int(len(df['Date'])/200)\n dlist = np.random.choice(df2.index.values, x)\n for d in dlist:\n delta = getDelta(df, d, tweet_window, 0)\n if delta == -1: x-=1\n if delta > 1: pos +=1\n return x, pos/x\n\ndef showsomething(df, tweets, tweet_window):\n df2 = df[:-(5*tweet_window)]\n tweet_prices = []\n non_tweet_prices = []\n\n y = int(len(df['Date'])/100)\n tlist = np.random.choice(tweets, y)\n for document in tlist:\n date = drop_seconds(document['date'])\n tweet_prices.append(getDelta(df, date, tweet_window, 0))\n\n x = int(len(df['Date'])/200)\n dlist = np.random.choice(df2.index.values, x)\n for d in dlist:\n delta = getDelta(df, d, tweet_window, 0)\n non_tweet_prices.append(delta)\n print('number of_non_tweets sampled:', )\n \n return len(non_tweet_prices), sum(tweet_prices)/len(tweets)/2, sum(non_tweet_prices)/len(x)/2\n\ndef grabTweets(twitter_start_date, end_date, retweets_min):\n db = MongoClient(\"mongodb://104.236.1.250:27017\")['local']\n collection = db['twitter_two']\n print('regular grabbing tweets')\n tweets = list(collection.find({\"date\": {\"$gt\": twitter_start_date, \"$lt\": end_date}, \"retweets\": {\"$gte\":retweets_min}}))\n print('# of tweets grabbed:', len(tweets))\n # print(tweets)\n return tweets\n\ndef buildFVs(df, tweets, price_window, tweet_window, min_tweets, cutoff):\n print('buildFVs')\n minute_data = np.zeros(len(words_i_like))\n date = tweets[0]['date']\n last_date = df['Date'][-1] - timedelta(days=1)\n tweet_count = 0\n fvs = []\n targetdata =[]\n most_recent = []\n\n for tweet in tweets:\n counts = defaultdict(int)\n for word in tweet['text'].lower().split(' '):\n word = word.lstrip('#')\n counts[word] = counts[word] + 1\n fv = np.zeros(len(words_i_like))\n for i, word in enumerate(words_i_like): fv[i] = counts[word]\n fv *= (tweet['retweets'] + 1)\n if date.minute - tweet['date'].minute == 0:\n minute_data += fv\n tweet_count +=1\n else:\n # print(minute_data, np.linalg.norm(minute_data))\n if tweet_count > min_tweets:\n if date > last_date: return fvs, targetdata\n # if np.linalg.norm(minute_data) != 0:\n # most_recent.append(minute_data / np.linalg.norm(minute_data))\n # else:\n most_recent.append(minute_data)\n if len(most_recent) > tweet_window:\n most_recent.pop(0)\n window_fvs = sum(most_recent)\n date = np.datetime64(date)\n targetdata.append(getDelta(df, date, price_window, cutoff))\n fvs.append(window_fvs)\n minute_data = np.zeros(len(words_i_like))\n date = tweet['date']\n tweet_count = 0\n return fvs, targetdata\n\ndef customVal(modeltype, feature_vector, target_data):\n print('MODEL: ', modeltype)\n guessedup = 0\n fva, fvb = split_list(feature_vector)\n tda, tdb = split_list(target_data)\n clf = modeltype.fit(fva, tda)\n pred = clf.predict(fvb)\n # prob = clf.predict_proba(fvb)\n \n print(\"percentage of predictions up:\", pred.mean()/2)\n print(\"percentage of target up:\", sum(tdb)/len(tdb)/2)\n count = total = 0\n for i, x in enumerate(pred):\n if x != 1 and tdb[i] != 1:\n count += 1\n if x == 2: guessedup+=1\n if x == tdb[i]: total += 1\n print('(amount removed:', (len(pred) - count)/len(pred), '%)')\n print('percent_accurate:', total/count)\n\n return clf\n\ndef predict(start_date, end_date, price_window, tweet_window, min_tweets, retweets_min, cutoff):\n print('======== Tuning ========')\n print('start date: ', start_date)\n print('price – minutes after tweet: ', price_window) # '. minutes before:', MINUTES_BEFORE)\n print('tweet window: ', tweet_window)\n print('minimum tweets in window: ', min_tweets)\n print('minimum retweets: ', retweets_min)\n print('cutoff:', cutoff)\n print('========================')\n df = sliceDf(start_date) \n tweets = grabTweets(start_date + timedelta(days=1), end_date, 0)\n # number_samples, nonTweet_percentPos, tweet_percentPos = showsomething(df, tweets, tweet_window)\n number_samples, nonTweet_percentPos = df_DeltaPercent(df, price_window)\n print('For', number_samples, 'instances of', price_window, 'minute periods, The percent pos is:', nonTweet_percentPos) \n # print('For tweets, the percent percent pos is:', tweet_percentPos)\n fvs, target_data = buildFVs(df, tweets, price_window, tweet_window, min_tweets, cutoff)\n print('lenght of target data:', len(target_data))\n # print(fvs[1::100])\n # print(target_data[1::100])\n for mt in [MultinomialNB(), LogisticRegression(), RandomForestClassifier(n_estimators=5000)]:\n customVal(mt, fvs, target_data) \n # clf = customVal(DecisionTreeClassifier(), fvs, target_data)\n # tree.export_graphviz(clf, out_file='tree.dot', feature_names=words_i_like) \n\n# def multiRun():\n# minutes_before = 0\n# SMs = [6, 7, 8, 9, 10]\n# RMs = [0, 1, 5, 10]\n# WSs = [200, 300, 400, 600]\n# MTs = [MultinomialNB, LogisticRegression]\n# for m in SMs:\n# start_date = start_date = dt(2016, m, 1, 0, 0, 0)\n# for retweets_min in RMs:\n# for tweet_window in WSs:\n# for mt in MTs:\n# predictBitcoins(start_date, retweets_min, tweet_window, mt, minutes_before)\n\ndef singleRun():\n # MTs = [MultinomialNB, LogisticRegression, RandomForestClassifier]\n start_date = dt(2016, 4, 1, 0, 0, 0)\n end_date = dt(2016, 11, 23, 0, 00, 00)\n price_window = 200\n tweet_window = 200\n min_tweets = 2\n retweets_min = 0\n cutoff = .25\n # mt = MTs[2]\n return predict(start_date, end_date, price_window, tweet_window, min_tweets, retweets_min, cutoff)\n\ndef main():\n # multiRun()\n singleRun()\n #consider adding in a few new features:\n # distance from time being searched, is there link?, how many hashtags?, sentiment analysis, retweets \n\nmain()\n","sub_path":"anlayze/bitcoin_data.py","file_name":"bitcoin_data.py","file_ext":"py","file_size_in_byte":9778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"505877722","text":"import os\nfrom setuptools import find_packages, setup\n\nwith open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:\n README = readme.read()\n\n# allow setup.py to be run from any path\nos.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))\n\nsetup(\n name='django-markdown-blog',\n version='0.4',\n packages=find_packages(),\n include_package_data=True,\n license='BSD License', # example license\n description='A simple Django app to provide markdown blog functionality.',\n long_description=README,\n author='Kevin Mann',\n author_email='kevinrmann@gmail.com',\n install_requires=[\n 'Django>=1.9',\n 'django-markdown-app>=0.9.0',\n 'django-imagekit>=3.3',\n 'awesome-slugify>=1.6.5',\n 'django-autoslug>=1.9.3'\n ],\n classifiers=[ \n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Framework :: Django :: 1.10', # replace \"X.Y\" as appropriate\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License', # example license\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n # Replace these appropriately if you are stuck on Python 2.\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Topic :: Internet :: WWW/HTTP',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',\n ],\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"462683583","text":"import MusEEG\nimport pandas\nimport os\nimport numpy as np\n\nsave = True\n\nbrain = MusEEG.classifier()\ntrain_inputs, train_targets, test_inputs, test_targets = brain.loadTrainingData(\n address=os.path.join(MusEEG.parentDir, 'data', 'training', 'batch1_batch2_320samples', 'bigChunks'),\n percentTrain=0.5,\n normalize=True)\nbrain.build_model(inputShape=brain.inputShape,\n hiddenNeurons=100,\n hiddenActivation='elu',\n numberOfTargets=max(train_targets) + 1,\n regularization='l1_l2 ',\n loss='sparse_categorical_crossentropy')\n\nbrain.train_model(train_inputs, train_targets, nEpochs=50, verbose=2)\nbrain.evaluate_model(test_inputs, test_targets)\n\ncm = brain.print_confusion(test_inputs, test_targets)\n\ncmdataframe = pandas.DataFrame(cm)\n\nprint('hi')\nif save:\n prompt = input('should we save this model, ye great master?')\n if prompt == 'yes':\n name = input('what should we name it, ye great master?')\n brain.savemodel(name)\n else:\n print('oh ok')\n","sub_path":"scripts/saveModels.py","file_name":"saveModels.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"199553620","text":"#!/usr/bin/python\n\"\"\"\n<Program Name>\n dorputget.py\n\n<Started>\n December 17, 2008\n\n<Author>\n ivan@cs.washington.edu\n Ivan Beschastnikh\n\n<Purpose>\n Attempt to put a (k,v) into DO registry and then get it back. On error\n send an email to some folks.\n\n<Usage>\n Modify the following global var params to have this script functional:\n - notify_list, a list of strings with emails denoting who will be\n emailed when something goes wrong\n\n This script takes no arguments. A typical use of this script is to\n have it run periodically using something like the following crontab line:\n 7 * * * * /usr/bin/python /home/seattle/dorputget.py > /home/seattle/cron_log.dorputget\n\"\"\"\n\nimport time\nimport os\nimport socket\nimport sys\nimport traceback\nimport threading\nimport random\n\nimport send_gmail\nimport integrationtestlib\nimport repyhelper\n\nrepyhelper.translate_and_import(\"/home/integrationtester/cron_tests/dorputget/DORadvertise.repy\")\n\n# Armon: This is to replace using the time command with getruntime\nimport nonportable\n\n# event for communicating when the lookup is done or timedout\nlookup_done_event = threading.Event()\n\n\n\ndef lookup_timedout():\n \"\"\"\n <Purpose>\n Waits for lookup_done_event and notifies the folks on the\n notify_list (global var) of the lookup timeout.\n\n <Arguments>\n None.\n\n <Exceptions>\n None.\n\n <Side Effects>\n Sends an email to the notify_list folks\n\n <Returns>\n None.\n \"\"\"\n integrationtestlib.log(\"in lookup_timedout()\")\n notify_msg = \"DOR lookup failed -- lookup_timedout() fired after 60 seconds.\"\n subject = \"DOR with repy test failed\" \n\n # wait for the event to be set, timeout after 30 minutes\n wait_time = 1800\n tstamp_before_wait = nonportable.getruntime()\n lookup_done_event.wait(wait_time)\n tstamp_after_wait = nonportable.getruntime()\n\n t_waited = tstamp_after_wait - tstamp_before_wait\n if abs(wait_time - t_waited) < 5:\n notify_msg += \" And lookup stalled for over 30 minutes (max timeout value).\"\n else:\n notify_msg += \" And lookup stalled for \" + str(t_waited) + \" seconds\"\n\n integrationtestlib.notify(notify_msg,subject )\n return\n\ndef main():\n \"\"\"\n <Purpose>\n Program's main.\n\n <Arguments>\n None.\n\n <Exceptions>\n All exceptions are caught.\n\n <Side Effects>\n None.\n\n <Returns>\n None.\n \"\"\"\n # setup the gmail user/password to use when sending email\n success,explanation_str = send_gmail.init_gmail()\n if not success:\n integrationtestlib.log(explanation_str)\n sys.exit(0)\n\n integrationtestlib.notify_list.append(\"cemeyer@u.washington.edu\")\n\n key = str(random.randint(4,2**30))\n value = str(random.randint(4,2**30))\n ttlval = 60\n subject = \"DOR with repy test failed\"\n\n\n # put(key,value) with ttlval into DOR\n integrationtestlib.log(\"calling DORadvertise_announce(key: \" + str(key) + \", val: \" + str(value) + \", ttl: \" + str(ttlval) + \")\")\n try:\n DORadvertise_announce(key, value, ttlval)\n except:\n message = \"DORadvertise_lookup() failed.\\nFailed while doing DORadvertise_announce(). \"\n message = message + \"Anouncing with key: \" + key + \", value: \" + value + \", ttlval: \" + str(ttlval)\n integrationtestlib.handle_exception(\"DORadvertise_announce() failed\", subject)\n sys.exit(0)\n\n # a 60 second timer to email the notify_list on slow lookups\n lookup_timedout_timer = threading.Timer(60, lookup_timedout)\n # start the lookup timer\n lookup_timedout_timer.start()\n\n # get(key) from DOR\n integrationtestlib.log(\"calling DORadvertise_lookup(key: \" + str(key) + \")\")\n try:\n ret_value = DORadvertise_lookup(key)\n # TODO: check the return value as well\n # ret_value = int(ret_value[0])\n except:\n message = \"DORadvertise_lookup() failed.\\nFailed while doing DORadvertise_lookup(). \"\n message = message + \"Looking up with key: \" + key\n integrationtestlib.handle_exception(message, subject)\n sys.exit(0)\n\n lookup_timedout_timer.cancel()\n lookup_done_event.set()\n return\n\nif __name__ == \"__main__\":\n main()\n \n","sub_path":"dorputget/dorputget_new.py","file_name":"dorputget_new.py","file_ext":"py","file_size_in_byte":4185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"67627598","text":"'''\nheight = 1.75\nweight = 80.5\nbmi = weight / height**2\nprint(bmi)\nif bmi < 18.5:\n print(\"过轻\")\nelif bmi < 25:\n print(\"正常\")\nelif bmi < 28:\n print(\"过重\")\nelif bmi <= 32:\n print(\"肥胖\")\nelif bmi > 32:\n print(\"严重肥胖\")\n'''\n'''\nL = ['Bart', 'Lisa', 'Adam']\nfor ls in L:\n print(\"Hello,\"+ls+\"!\")\n'''\n\n#一元二次方程\nimport math\n\n\ndef quadratic(a, b, c):\n for i in (a, b, c):\n if not isinstance(i, (int, float)):\n raise TypeError(\"ERROR TYPE\")\n derta = b**2 - 4 * a * c\n if a <= 0:\n print(\"a can't be 0\")\n elif derta < 0:\n print(\"no answer\")\n elif derta >= 0:\n x1 = (-b + math.sqrt(derta)) / (a * 2)\n x2 = (-b - math.sqrt(derta)) / (a * 2)\n if x1 == x2:\n return x1\n else:\n return x1, x2\n else:\n pass\n\n\n# 测试:\nprint('quadratic(2, 3, 1) =', quadratic(2, 3, 1))\nprint('quadratic(1, 3, -4) =', quadratic(1, 3, -4))\n\nif quadratic(2, 3, 1) != (-0.5, -1.0):\n print('测试失败')\nelif quadratic(1, 3, -4) != (1.0, -4.0):\n print('测试失败')\nelse:\n print('测试成功')\n","sub_path":"demo/demo/v1.0/demo1.py","file_name":"demo1.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"425094314","text":"import pickle\nimport json# 加载 json 模块\nfrom athletelist import AthleteList\n\n\ndef get_coach_data(filename): #从文件中获取数据\n\n try:\n with open (filename) as f:\n data = f.readline()\n templ = data.strip().split(',')\n return (AthleteList(templ.pop(0),templ.pop(0),templ))\n except IOError as ioerr:\n print ('File Error: ' + str(ioerr))\n return (None)\n\ndef put_to_store(file_list):\n\n all_athletes = {}\n for each_f in file_list:\n ath = get_coach_data(each_f) #这里ath 返回的 athletelist 的对象(athletelist 是一个list)\n #all_athletes['Name'] = ath.name\n #all_athletes['DOB'] = ath.dob\n #all_athletes['Times']= ath\n all_athletes[ath.name] = ath #将ath name 作为键,将ath作为值\n \n try:\n with open ('athletes.pickle','wb') as ath_f:\n pickle.dump (all_athletes,ath_f)\n except IOError as ioerr:\n print('File Error(put_to_store): '+str(ioerr))\n return (all_athletes)\n\ndef get_from_store():\n\n all_athletes = {}\n try:\n with open ('athletes.pickle','rb') as ath_f:\n all_athletes = pickle.load(ath_f)\n except IOError as ioerr:\n print('File Error(get_from_store): '+str(ioerr))\n \n return (all_athletes)\n\n\ndef get_names_from_store():\n athletes = get_from_store()\n response = [athletes[each_ath].name for each_ath in athletes]\n#从数据中抽取选手名作为一个列表\n return (response)\n\n\n\n\"\"\"\n测试代码\nfiles = ['sarah2.txt','james2.txt','mikey2.txt','julie2.txt']\ndata = put_to_store(files)#data 是一个字典\nprint(data)\nfor each_ath in data:\n #print(data[each_ath].name + ' ' +data[each_ath].dob )\n print(data[each_ath].name)\ndata = get_names_from_store()\nprint(data)\n\"\"\"\n","sub_path":"chapter09/21-P297-ch9/webapp/cgi-bin/athletemodel.py","file_name":"athletemodel.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"628806822","text":"import faster_than_requests as requests\nimport json\nimport smtplib\nimport time\nfrom email.mime.text import MIMEText\nimport random\nlast_publish_id = 54385\nrecipients =['singhakash414@gmail.com','jsmith503@gmail.com','j15bowbow@gmail.com']\nprint(\"Script started...\")\nwhile True:\n try:\n d = requests.get2dict(\n \"https://www.binance.com/bapi/composite/v1/public/cms/article/latest/query\")\n new_publish_id = json.loads(d[3]['data'])['latestArticles'][0]['id']\n if new_publish_id > last_publish_id:\n publishdate=json.loads((d[3])['data'])['latestArticles'][0]['publishDate']\n new_title = json.loads(d[3]['data'])['latestArticles'][0]['title']\n msg = MIMEText(\"Title:- \"+str(new_title)+\" // Publish Time:- \" +\n str(publishdate)+\"// Current Time:-\" + str(publishdate+round(random.uniform(0.698,1.100),3)))\n msg['Subject'] = \"OHIO Binance Update: \" + str(new_title)\n msg['From'] = 'vasudv0912@gmail.com'\n msg['To'] = \", \".join(recipients)\n server = smtplib.SMTP_SSL(\"smtp.gmail.com\", 465)\n server.login(\"vasudv0912@gmail.com\", \"vasu9@0906\")\n server.sendmail('vasudv0912@gmail.com',\n recipients, msg.as_string())\n server.quit()\n last_publish_id = new_publish_id\n print(new_title, last_publish_id)\n x=round(random.uniform(0.100,0.150),3)\n time.sleep(x)\n except Exception as e:\n print(str(e)+\" will try after 4 sec // \" + str(time.time()*1000))\n time.sleep(4)\n","sub_path":"abc.py","file_name":"abc.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"479407888","text":"'''\nWe extract only texts fields from the retrieved tweets. This process only helps\nto process the large data later.\n\nWe start by reading each line of the input data file. Each line is the json\nencoded information of the tweets which also include information about the\nauthor of the tweets. We discard all other metadata but we keep essential user\ninformation such as (i) screen_name, and (ii) user_id.\n\nThe output will contain only (i) text, and (ii) user_id in the following format:\n\n {\n screen_name: value\n text: value\n user_id: value\n name: value\n }\n\nEach line includes above dictionary reprsentation.\n\n'''\n\nimport json\n\ninputdatadir = \"/home/pyongjoo/workspace/twitter-research/data\"\ninputfile = inputdatadir + \"/retrievedTweets-Jun19-2.0.jsonarr\"\n\noutputdatadir = inputdatadir + \"/temp\"\noutputfile = outputdatadir + \"/tweetsFlatten-Jun19-Step0.jsonarr\"\nout = open(outputfile, 'w')\n\n\n# Read each line from the data file\nfor line in open(inputfile):\n tweets = json.loads(line)\n\n screen_name = tweets['user']['screen_name']\n text = tweets['text']\n user_id = tweets['user']['id']\n name = tweets['user']['name']\n\n dic = {}\n dic['screen_name'] = screen_name\n dic['text'] = text\n dic['user_id'] = user_id\n dic['name'] = name\n\n out.write(json.dumps(dic))\n out.write('\\n')\n\n","sub_path":"code_backup/python/src/tools/extractTexts.py","file_name":"extractTexts.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"608616157","text":"class callback_parse:\n def __init__(self, data):\n self.qtype = None\n self.qact = None\n self.qdata = None\n\n self.data = data\n self.parse()\n\n def parse(self):\n tmp = self.data.split()\n self.qtype = tmp[0]\n self.qact = tmp[1]\n self.qdata = ' '.join(tmp[2:])\n self.qdata_list = tmp[2:]\n","sub_path":"plugin/callabck_parse.py","file_name":"callabck_parse.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"544701437","text":"import numpy as np\nimport itertools\nfrom matplotlib import pyplot as plt\nfrom matplotlib import animation, colors\nimport seaborn as sb\n\n# Define the colour palette to be used\ncolours = \"custom1\"\n\nif colours is \"seaborn\":\n square_colours = sb.color_palette(palette='deep') # Options: 'deep', 'muted', 'pastel', 'bright', 'dark', and 'colorblind'\nelif colours is \"custom1\":\n square_colours = ['white', 'black', 'indianred', 'dodgerblue', 'gold', \"steelblue\", \"tomato\", \"slategray\", \"plum\", \"seagreen\", \"gray\"]\nelif colours is \"custom2\":\n square_colours = [\"#000000\", \"#FF0000\", \"#444444\", \"#FFFF00\", \"#00FF00\", \"#00FFFF\", \"#0000FF\", \"#9900FF\"]\nelse:\n print(\"Colour palette not recognised. Exiting\")\n exit()\n\n'''\nUser Changeable Input\n''' \n# Set the dimensions of the grid\ndim = 700\n# Set the number of steps the ant should take\nant_steps = 1000000\n# Tell the program what moveset to give the ant\nant_move_list = 'LRRRRLLLRRR'\n\n'''\nEnd User Changeable Input\n'''\n\n# Build a corresponding numpy array of dimensions (dim,dim)\ngrid = np.array(np.zeros((dim, dim)))\n# Define a variable to represent the current ant_position of the ant on the board\nant_pos = np.array([[int(dim/2)], [int(dim/2)]])\n# Define a variable to represent the direction ant is currently moving\ndirection = np.matrix([[1], [0]])\n\n# Clockwise rotation matrix\nclockwise_rot = np.array([[0, 1], [-1, 0]])\n# Anti-clockwise rotation matrix\nanticlockwise_rot = np.array([[0, -1], [1, 0]])\n\n# Calculate the length of the ant_move_list\nlen_ant_move_list = len(ant_move_list)\n# Extract the unique 'L' and 'R' moves in order\nunique_moves = [i for i in ant_move_list]\n# Assign the correct rotation matrix to each 'L' and 'R' choice and store in a list\nrot_matrices = [anticlockwise_rot if i == 'L' else clockwise_rot for i in unique_moves]\n# Assign each of these unique 'L' and 'R' letters to a discrete integer which will later represent a colour \ncolour_indices = [i for i in range(len(ant_move_list))]\n\ndef move_ant(grid, ant_pos, direction):\n '''\n Controls the movement of the ant by a single square\n\n This function takes the current position and the direction of the ant and updates it via the 2 rules specified above as it takes its next stdep. It then updates the new position, direction and square colour for the next step.\n\n Parameters:\n grid (np.array) : This is the grid of dimension, dim, that the ant moves around on\n ant_pos (np.array) : This represents the ants' position defined as a numpy array of its x,y coordinate on the grid\n direction(np.matrix) : This represents the direction that the ant will move in on this step. \n\n Returns:\n None: No explicit return \n '''\n # Create the next ant position\n ant_pos[:] = ant_pos + direction\n # Extract the x coordinate of this new position\n x_ant_pos = ant_pos[0, 0]\n # Extract the y coordinate of this new position\n y_ant_pos = ant_pos[1, 0]\n\n if any(i == dim or i == 0 for i in ant_pos):\n print(\"Hit the edge of the board!\")\n exit()\n if grid[x_ant_pos, y_ant_pos] in colour_indices:\n index = grid[x_ant_pos, y_ant_pos]\n grid[x_ant_pos, y_ant_pos] = colour_indices[int(index+1) % len(colour_indices)]\n direction[:] = rot_matrices[int(index)] * direction\n else:\n print(\"Index not in colour indices. Exiting\")\n exit()\n\n# Define the boundaries for each discrete colour\n# The form is [0, 0, 1, 1, 2, 2, 3, 3]\n# c1 c2 c3 c4\n# where cX represents a unique colour \nboundaries = list(itertools.chain.from_iterable(itertools.repeat(x, 2) for x in colour_indices))\n\nfig = plt.figure()\nax = fig.add_subplot(111)\n\n# Define custom discrete colour map\ncmap = colors.ListedColormap(square_colours[0:len_ant_move_list])\n\nnorm = colors.BoundaryNorm(boundaries, cmap.N, clip=True)\n# Define the 'image' to be created using imshow. Specify the custom colour map\nim = plt.imshow(grid, cmap=cmap, norm=norm)\n\nfor i in range(ant_steps):\n move_ant(grid, ant_pos, direction) \n\nim.set_data(grid)\n# Hide the axes\nax.axis('off')\n# Report the movement pattern number of ant steps taken in the title of the image\nplt.suptitle(\"{}, No. Steps Taken = {:d}\".format(ant_move_list, ant_steps), fontsize=13)\n# Save the image\n\nplt.savefig(\"{}_{}.png\".format(ant_move_list, ant_steps), format='png')\n# Show the image\n#plt.show()","sub_path":"_posts/LangtonsAntCode/Langtons_ant_Fractal_v1-02.py","file_name":"Langtons_ant_Fractal_v1-02.py","file_ext":"py","file_size_in_byte":4363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"343074248","text":"import sys\n\nfrom setuptools import setup\nfrom setuptools.command.test import test as TestCommand\n\n\nclass PyTest(TestCommand):\n \"\"\"\n Overrides setup \"test\" command, taken from here:\n http://pytest.org/latest/goodpractises.html\n \"\"\"\n\n def finalize_options(self):\n TestCommand.finalize_options(self)\n self.test_args = []\n self.test_suite = True\n\n def run_tests(self):\n # import here, cause outside the eggs aren't loaded\n import pytest\n\n errno = pytest.main([])\n sys.exit(errno)\n\n\nsetup(\n name=\"pytest-qt\",\n packages=[\"pytestqt\"],\n entry_points={\"pytest11\": [\"pytest-qt = pytestqt.plugin\"]},\n install_requires=[\"pytest>=3.0.0\"],\n extras_require={\"doc\": [\"sphinx\", \"sphinx_rtd_theme\"]},\n # metadata for upload to PyPI\n author=\"Bruno Oliveira\",\n author_email=\"nicoddemus@gmail.com\",\n description=\"pytest support for PyQt and PySide applications\",\n long_description=open(\"README.rst\").read(),\n license=\"MIT\",\n keywords=\"pytest qt test unittest\",\n url=\"http://github.com/pytest-dev/pytest-qt\",\n use_scm_version={\"write_to\": \"pytestqt/_version.py\"},\n setup_requires=[\"setuptools_scm\"],\n python_requires=\">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*\",\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Framework :: Pytest\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.4\",\n \"Programming Language :: Python :: 3.5\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Topic :: Desktop Environment :: Window Managers\",\n \"Topic :: Software Development :: Quality Assurance\",\n \"Topic :: Software Development :: Testing\",\n \"Topic :: Software Development :: User Interfaces\",\n ],\n tests_require=[\"pytest\"],\n cmdclass={\"test\": PyTest},\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"334290248","text":"from sys import stdin\n\ndef main():\n n = int(stdin.readline().strip())\n lista = [int(x) for x in stdin.readline().strip().split()]\n if lista[0]>lista[1]:\n nmax, nmin = lista[0], lista[1]\n else:\n nmax, nmin = lista[1], lista[0]\n for i in range(2, len(lista)):\n if lista[i]>nmax:\n nmax = lista[i]\n elif lista[i]<nmin:\n nmin = lista[i]\n print(nmin, nmax)\n\nmain()\n","sub_path":"Laboratorios/Laboratorio 3 - Análisis de algoritmos/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"332855931","text":"#!/usr/bin/env python\nimport rospy\nfrom geometry_msgs.msg import Twist\nimport time\n\nvelocity_publisher = rospy.Publisher(\n '/robotont/cmd_vel', Twist, queue_size=10)\nvel_msg = Twist()\n\n\ndef closing():\n # After the loop, stops the robot\n vel_msg.linear.x = 0\n vel_msg.linear.y = 0\n vel_msg.linear.z = 0\n vel_msg.angular.x = 0\n vel_msg.angular.y = 0\n vel_msg.angular.z = 0\n # Force the robot to stop\n velocity_publisher.publish(vel_msg)\n\n#######################\n# YOUR FUNCTIONS HERE #\n#######################\n\ndef forward(speed,duration):\n for i in range(0,duration):\n vel_msg.linear.x = speed\n vel_msg.linear.y = 0\n vel_msg.angular.z = 0\n velocity_publisher.publish(vel_msg)\n rospy.sleep(0.1)\n\ndef turning(speed,duration):\n for i in range(0,duration):\n vel_msg.linear.x = 0\n vel_msg.linear.y = 0\n vel_msg.angular.z = speed\n velocity_publisher.publish(vel_msg)\n rospy.sleep(0.1)\n\ndef side(speed,duration):\n for i in range(0,duration):\n vel_msg.linear.x = 0\n vel_msg.linear.y = speed\n vel_msg.angular.z = 0\n velocity_publisher.publish(vel_msg)\n rospy.sleep(0.1)\n\ndef drive(x,y,z,duration):\n for i in range(0,duration):\n vel_msg.linear.x = x\n vel_msg.linear.y = y\n vel_msg.angular.z = z\n velocity_publisher.publish(vel_msg)\n rospy.sleep(0.1)\n\ndef loop():\n drive(0,0.8,1.6,20)\n\ndef move_turning():\n drive(0.5,0,0.8,20)\n\ndef figure_eight():\n drive(0.4,0,1,55)\n drive(0.5,0,0,15)\n drive(0.4,0,-1,55)\n drive(0.5,0,0,15)\n\n###########################\n# YOUR FUNCTIONS HERE END #\n###########################\n\n\ndef move():\n # Starts a new node\n rospy.init_node('robotont_velocity_publisher', anonymous=True)\n\n vel_msg.linear.x = 0\n vel_msg.linear.y = 0\n vel_msg.linear.z = 0\n vel_msg.angular.x = 0\n vel_msg.angular.y = 0\n vel_msg.angular.z = 0\n\n while not rospy.is_shutdown():\n ########################\n # YOUR CODE HERE START #\n ########################\n figure_eight()\n ######################\n # YOUR CODE HERE END #\n ######################\n\n\nif __name__ == '__main__':\n try:\n rospy.on_shutdown(closing)\n move()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"scripts/praktikum2_functions.py","file_name":"praktikum2_functions.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"649634013","text":"import sys\nimport re\n\n#given a template blueprint file, adds 'extended ends' and +-2 residues on each helix\n\n# OUTPUT - a series of blueprint files which allows design of the sepecified loop lengths, at each combination of extend ends\n# INPUT - template blueprint file and loop length range:\n# sys.argv[1] - name of template bp\n# sys.argv[2] - minimum loop length\n# sys.argv[3] - maximum loop length\n\ntemplate = open( sys.argv[1], 'r' )\nswitch = False\nfirst_chunk = []\nn_added_first_chunk = 0\nn_added_second_chunk = 0\nsecond_chunk = []\nfor line in template:\n if( re.match( '^X', line) ):\n switch = True\n continue\n if( not switch ):\n first_chunk.append(line)\n if( re.match( \"^0\", line) ):\n n_added_first_chunk += 1\n else:\n if( re.match( \"^0\", line) ):\n n_added_second_chunk += 1\n second_chunk.append(line)\n\nfor loop_len in range(int(sys.argv[2]), int(sys.argv[3])+1):\n for i in range( -3, 4 ):\n for mod in [\"Amin2\", \"Amin1\", \"A\", \"Aplus1\", \"Aplus2\", \"Bmin2\", \"Bmin1\", \"B\", \"Bplus1\", \"Bplus2\"]:\n filename = \"ext_ends_\" + str(i) + \"_loop_len_\" + str(loop_len) + \"_\" + mod + \".bp\"\n out = open(filename, 'w')\n \n for line in first_chunk:\n if( mod == \"Amin1\" ):\n n = i - 1\n elif( mod == \"Aplus1\" ):\n n = i + 1\n elif( mod == \"Amin2\" ):\n n = i - 2\n elif( mod == \"Aplus2\" ):\n n = i + 2\n else:\n n = i\n \n fields = line.split()\n curr_res = int( fields[0] )\n nres = len(first_chunk) - n_added_first_chunk\n if( curr_res < nres + n and curr_res != nres ):\n out.write(line)\n if( curr_res == nres + n or (n > 0 and curr_res == nres) ):\n fields[2] = \"H\\n\"\n out.write( \" \".join(fields) )\n \n if( i > 0 ):\n if( mod == \"Amin1\" ):\n n = i - 1\n elif( mod == \"Aplus1\" ):\n n = i + 1\n elif( mod == \"Amin2\" ):\n n = i - 2\n elif( mod == \"Aplus2\" ):\n n = i + 2\n else:\n n = i\n \n for k in range(0,n):\n out.write(\"0 x H ALLAA\\n\")\n\n for j in range(0, loop_len):\n out.write(\"0 x L ALLAA\\n\")\n \n if( i > 0 ):\n if( mod == \"Bmin1\" ):\n n = i - 1\n elif( mod == \"Bplus1\" ):\n n = i + 1\n elif( mod == \"Bmin2\" ):\n n = i - 2\n elif( mod == \"Bplus2\" ):\n n = i + 2\n else:\n n = i\n\n for k in range(0,n):\n out.write(\"0 x H ALLAA\\n\")\n \n for line in second_chunk:\n if( mod == \"Bmin1\" ):\n n = i - 1\n elif( mod == \"Bplus1\" ):\n n = i + 1\n elif( mod == \"Bmin2\" ):\n n = i - 2\n elif( mod == \"Bplus2\" ):\n n = i + 2\n else:\n n = i\n\n fields = line.split()\n curr_res = int( fields[0] )\n nres = len(first_chunk) - n_added_first_chunk #this is not a typo, relies on number of residues in first chunk\n if( curr_res > nres + 1 - n and curr_res != nres + 1 ):\n out.write(line)\n if( curr_res == nres + 1 - n or (n > 0 and curr_res == nres + 1) ):\n fields[2] = \"H\\n\"\n out.write( \" \".join(fields) )\n\n","sub_path":"python/remodel_loopdeloop.py","file_name":"remodel_loopdeloop.py","file_ext":"py","file_size_in_byte":3877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"305653578","text":"def letras_favoritas(letra, frase):\n letra = input(\"Sua letra favorita: \")\n frase = input(\"Uma frase importante: \")\n tamanho_da_frase = len(frase)\n qtd_letra = 0\n for i in range(0, tamanho_da_frase):\n if frase[i].lower() == letra.lower():\n qtd_letra += 1\n print(\"Sua letra favorita é a letra\", letra, \"e ela aparece\", qtd_letra, \"vezes na frase\", frase)\n \n\n\n","sub_path":"letra_favorita.py","file_name":"letra_favorita.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"473178960","text":"# -*- coding: utf-8 -*-\nimport pygame\nclass Board:\n _offsets = [(x,y) for x in range(0,2) for y in range(0,2) if x != y or x != 0]\n def __init__(self, width, height, configuration):\n self._width = width\n self._height = height\n self._cells = [[False for _ in range(width)] for _ in range(height)]\n for x,y in configuration:\n self._cells[x][y] = True\n \n def getNeighboursCount(self, x, y):\n neighbours = 0\n for (x_off, y_off) in Board._offsets:\n newx = x + x_off\n newy = y + y_off\n if newx >= 0 and \\\n newx < self._width and \\\n newy >= 0 and \\\n newy < self._height: \n if self._cells[newx][newy]:\n neighbours = neighbours + 1\n \n return neighbours\n \n def draw(self, background):\n width,height = background.get_size()\n widthSize = width / (self._width)\n heightSize = height / (self._height)\n for i in range(self._width - 1):\n pygame.draw.line(background, (0,0,0), (widthSize * (i + 1), 0), (widthSize * ( i + 1), height))\n for i in range(self._height - 1):\n pygame.draw.line(background, (0,0,0), (0, heightSize * (i + 1)), (width, heightSize * (i + 1)))\n \n for i in range(self._width):\n for j in range(self._height):\n if (self._cells[i][j] == True):\n centerX = widthSize * i + (widthSize / 2)\n centerY = heightSize * j + (heightSize / 2)\n pygame.draw.circle(background, (0,0,0), (centerX, centerY), widthSize / 2)","sub_path":"Board.py","file_name":"Board.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"425262083","text":"# problem : https://practice.geeksforgeeks.org/problems/length-unsorted-subarray/0\n# code\nT = int(input())\nfor t in range(T):\n N = int(input())\n array = [int(i)for i in input().split()]\n sorted_array = sorted(array)\n idxs = []\n for j in range(N):\n if array[j] != sorted_array[j]:\n idxs.append(j)\n if len(idxs) > 0:\n print(idxs[0], idxs[-1])\n else:\n print(0, 0)\n","sub_path":"Length Unsorted Subarray.py","file_name":"Length Unsorted Subarray.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"149189242","text":"from flask_restful import Resource, reqparse\nfrom flask import Flask, request, jsonify\nfrom infer import SketchInfer\nimport numpy as np\nimport argparse\nimport os\n\nusers = [\n {\n \"name\": \"Nicholas\",\n \"age\": 42,\n \"occupation\": \"Network Engineer\"\n },\n {\n \"name\": \"Elvin\",\n \"age\": 30,\n \"occupation\": \"Doctor\"\n },\n {\n \"name\": \"Jass\",\n \"age\": 22,\n \"occupation\": \"Web developer\"\n }\n]\n\napp = Flask(__name__)\n\n\n@app.route('/imginfer', methods=['GET', 'POST'])\ndef infer():\n content = request.json\n img_numpy = np.array(content['imgs']).astype(np.uint8)\n # output_params = inference_engine.infer_img(img_numpy)\n output_params = inference_engine.infer_imgs(img_numpy)\n print(output_params)\n return jsonify({\"params\": output_params})\n\n@app.route('/imginferV2/segment', methods=['GET', 'POST'])\ndef segment():\n content = request.json\n img_numpy = np.array(content['imgs']).astype(np.uint8)\n output_params = inference_engine.segment_img(img_numpy)\n print(output_params)\n return jsonify({\"params\": output_params})\n\n@app.route('/imginferV2/regress', methods=['GET', 'POST'])\ndef regress():\n content = request.json\n img_dict = content['imgs']\n regress_dict = {}\n for k, imgs in img_dict.items():\n if k not in regress_dict:\n regress_dict[k] = []\n for img in imgs:\n img_numpy = np.array(img).astype(np.uint8)\n regress_dict[k].append(img_numpy)\n output_params = inference_engine.regress_imgs(regress_dict)\n print(output_params)\n return jsonify({\"params\": output_params})\n\n\n\nclass User(Resource):\n def get(self, name):\n for user in users:\n if (name == user[\"name\"]):\n return user, 200\n return \"User not found\", 404\n\n def post(self, name):\n parser = reqparse.RequestParser()\n parser.add_argument(\"age\")\n\nclass ImgInfer(Resource):\n def post(self):\n #print(request.json)\n parser = reqparse.RequestParser()\n parser.add_argument(\"img\")\n args = parser.parse_args()\n print(args)\n return \"Success\", 200\n\ndef main():\n global inference_engine\n parser = argparse.ArgumentParser()\n parser.add_argument('--base_dir', type=str, required=True)\n parser.add_argument('--classification_dir', type=str, required=True)\n parser.add_argument('--regress_dirs', nargs='+', default=[])\n parser.add_argument('--segment_dir', type=str, required=True)\n parser.add_argument('--resnet_type', type=str, required=True)\n parser.add_argument('--use_cpu', action='store_true')\n\n args = parser.parse_args()\n os.chdir(os.path.dirname(__file__))\n\n print('current working dir', os.getcwd())\n\n inference_engine = SketchInfer.TotalInfer(args)\n inference_engine.init()\n app.run()\n\n # inference_engine.warp_fix()\n\n # estimated_pts = np.array([0.6785781979560852, 0.7342093586921692, 0.556641697883606, 0.5983264446258545, 0.44624197483062744, 0.47519931197166443, 0.3184840679168701, 0.3628543019294739])\n # estimated_pts = np.reshape(estimated_pts, (estimated_pts.shape[0] // 2, 2))\n #\n # inference_engine.fit_curve_pts(estimated_pts)\n\n # inference_engine.show_catmull_spline(np.random.rand(20).reshape((10, 2)))\n # inference_engine.show_catmull_spline(np.random.rand(6,2), True)\n #inference_engine.load_model();\n # api = Api(app)\n # api.add_resource(User, \"/user/<string:name>\")\n # api.add_resource(ImgInfer, \"/imginfer\")\n app.run(debug=True)\n\n\n\nif __name__ == '__main__':\n main()\n # import cv2\n # img = cv2.imread(\"test0area.png\")\n # # inference_engine.predict_line_segments(img)\n # inference_engine.contour_extraction_area(img)\n\n","sub_path":"samples/crowd/RESTserver.py","file_name":"RESTserver.py","file_ext":"py","file_size_in_byte":3748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"212659399","text":"class Stack():\n def __init__(self):\n self.a = []\n self.top = -1\n\n def push(self, ele):\n self.a.append(ele)\n self.top += 1\n\n def pop(self):\n self.a.pop()\n self.top -= 1\n\n def isEmpty(self):\n if self.top == -1:\n return True\n else:\n return False\n \ns = Stack()\nexp = input('Please enter the paranthesis:')\nfor i in exp:\n if i == '(':\n s.push(1)\n elif i == ')':\n if s.isEmpty():\n s.push(1)\n else:\n s.pop()\n isBalanced = True\n else:\n if s.isEmpty():\n isBalanced = True\n else:\n isBalanced = False\n\nif s.isEmpty():\n print('There are equal number of paranthesis')\nelse:\n print('There are unequal number of paranthesis')\n","sub_path":"paranthesis.py","file_name":"paranthesis.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"106035390","text":"\"\"\"\nConversion of low-level events to high-level causes, and handling them.\n\nThese functions are invoked from the queueing module `kopf.reactor.queueing`,\nwhich are the actual event loop of the operator process.\n\nThe conversion of the low-level events to the high-level causes is done by\nchecking the object's state and comparing it to the preserved last-seen state.\n\nThe framework itself makes the necessary changes to the object, -- such as the\nfinalizers attachment, last-seen state updates, and handler status tracking, --\nthus provoking the low-level watch-events and additional queueing calls.\nBut these internal changes are filtered out from the cause detection\nand therefore do not trigger the user-defined handlers.\n\"\"\"\nimport asyncio\nimport datetime\nfrom typing import Optional\n\nfrom kopf.clients import patching\nfrom kopf.engines import logging as logging_engine\nfrom kopf.engines import posting\nfrom kopf.engines import sleeping\nfrom kopf.reactor import causation\nfrom kopf.reactor import errors\nfrom kopf.reactor import handling\nfrom kopf.reactor import lifecycles\nfrom kopf.reactor import registries\nfrom kopf.reactor import states\nfrom kopf.structs import bodies\nfrom kopf.structs import containers\nfrom kopf.structs import finalizers\nfrom kopf.structs import lastseen\nfrom kopf.structs import patches\nfrom kopf.structs import resources\n\n\nasync def process_resource_event(\n lifecycle: lifecycles.LifeCycleFn,\n registry: registries.OperatorRegistry,\n memories: containers.ResourceMemories,\n resource: resources.Resource,\n raw_event: bodies.RawEvent,\n replenished: asyncio.Event,\n event_queue: posting.K8sEventQueue,\n) -> None:\n \"\"\"\n Handle a single custom object low-level watch-event.\n\n Convert the low-level events, as provided by the watching/queueing tasks,\n to the high-level causes, and then call the cause-handling logic.\n\n All the internally provoked changes are intercepted, do not create causes,\n and therefore do not call the handling logic.\n \"\"\"\n\n # Convert to a heavy mapping-view wrapper only now, when heavy processing begins.\n # Raw-event streaming, queueing, and batching use regular lightweight dicts.\n # Why here? 1. Before it splits into multiple causes & handlers for the same object's body;\n # 2. After it is batched (queueing); 3. While the \"raw\" parsed JSON is still known;\n # 4. Same as where a patch object of a similar wrapping semantics is created.\n body = bodies.Body(raw_event['object'])\n patch = patches.Patch()\n delay: Optional[float] = None\n\n # Each object has its own prefixed logger, to distinguish parallel handling.\n logger = logging_engine.ObjectLogger(body=body)\n posting.event_queue_loop_var.set(asyncio.get_running_loop())\n posting.event_queue_var.set(event_queue) # till the end of this object's task.\n\n # Recall what is stored about that object. Share it in little portions with the consumers.\n # And immediately forget it if the object is deleted from the cluster (but keep in memory).\n memory = await memories.recall(body, noticed_by_listing=raw_event['type'] is None)\n if raw_event['type'] == 'DELETED':\n await memories.forget(body)\n\n # Invoke all silent spies. No causation, no progress storage is performed.\n if registry.resource_watching_handlers[resource]:\n resource_watching_cause = causation.detect_resource_watching_cause(\n raw_event=raw_event,\n resource=resource,\n logger=logger,\n patch=patch,\n body=body,\n memo=memory.user_data,\n )\n await process_resource_watching_cause(\n lifecycle=lifecycles.all_at_once,\n registry=registry,\n memory=memory,\n cause=resource_watching_cause,\n )\n\n # Object patch accumulator. Populated by the methods. Applied in the end of the handler.\n # Detect the cause and handle it (or at least log this happened).\n if registry.resource_changing_handlers[resource]:\n extra_fields = registry.resource_changing_handlers[resource].get_extra_fields()\n old, new, diff = lastseen.get_essential_diffs(body=body, extra_fields=extra_fields)\n resource_changing_cause = causation.detect_resource_changing_cause(\n raw_event=raw_event,\n resource=resource,\n logger=logger,\n patch=patch,\n body=body,\n old=old,\n new=new,\n diff=diff,\n memo=memory.user_data,\n initial=memory.noticed_by_listing and not memory.fully_handled_once,\n )\n delay = await process_resource_changing_cause(\n lifecycle=lifecycle,\n registry=registry,\n memory=memory,\n cause=resource_changing_cause,\n )\n\n # Whatever was done, apply the accumulated changes to the object.\n # But only once, to reduce the number of API calls and the generated irrelevant events.\n if patch:\n logger.debug(\"Patching with: %r\", patch)\n await patching.patch_obj(resource=resource, patch=patch, body=body)\n\n # Sleep strictly after patching, never before -- to keep the status proper.\n # The patching above, if done, interrupts the sleep instantly, so we skip it at all.\n # Note: a zero-second or negative sleep is still a sleep, it will trigger a dummy patch.\n if delay and patch:\n logger.debug(f\"Sleeping was skipped because of the patch, {delay} seconds left.\")\n elif delay is None and not patch:\n logger.debug(f\"Handling cycle is finished, waiting for new changes since now.\")\n elif delay is not None:\n if delay > 0:\n logger.debug(f\"Sleeping for {delay} seconds for the delayed handlers.\")\n limited_delay = min(delay, handling.WAITING_KEEPALIVE_INTERVAL)\n unslept_delay = await sleeping.sleep_or_wait(limited_delay, replenished)\n else:\n unslept_delay = None # no need to sleep? means: slept in full.\n\n if unslept_delay is not None:\n logger.debug(f\"Sleeping was interrupted by new changes, {unslept_delay} seconds left.\")\n else:\n # Any unique always-changing value will work; not necessary a timestamp.\n dummy_value = datetime.datetime.utcnow().isoformat()\n dummy_patch = patches.Patch({'status': {'kopf': {'dummy': dummy_value}}})\n logger.debug(\"Provoking reaction with: %r\", dummy_patch)\n await patching.patch_obj(resource=resource, patch=dummy_patch, body=body)\n\n\nasync def process_resource_watching_cause(\n lifecycle: lifecycles.LifeCycleFn,\n registry: registries.OperatorRegistry,\n memory: containers.ResourceMemory,\n cause: causation.ResourceWatchingCause,\n) -> None:\n \"\"\"\n Handle a received event, log but ignore all errors.\n\n This is a lightweight version of the cause handling, but for the raw events,\n without any progress persistence. Multi-step calls are also not supported.\n If the handler fails, it fails and is never retried.\n\n Note: K8s-event posting is skipped for `kopf.on.event` handlers,\n as they should be silent. Still, the messages are logged normally.\n \"\"\"\n handlers = registry.resource_watching_handlers[cause.resource].get_handlers(cause=cause)\n outcomes = await handling.execute_handlers_once(\n lifecycle=lifecycle,\n handlers=handlers,\n cause=cause,\n state=states.State.from_scratch(handlers=handlers),\n default_errors=errors.ErrorsMode.IGNORED,\n )\n\n # Store the results, but not the handlers' progress.\n states.deliver_results(outcomes=outcomes, patch=cause.patch)\n\n\nasync def process_resource_changing_cause(\n lifecycle: lifecycles.LifeCycleFn,\n registry: registries.OperatorRegistry,\n memory: containers.ResourceMemory,\n cause: causation.ResourceChangingCause,\n) -> Optional[float]:\n \"\"\"\n Handle a detected cause, as part of the bigger handler routine.\n \"\"\"\n logger = cause.logger\n patch = cause.patch # TODO get rid of this alias\n body = cause.body # TODO get rid of this alias\n delay = None\n done = None\n skip = None\n\n resource_changing_handlers = registry.resource_changing_handlers[cause.resource]\n requires_finalizer = resource_changing_handlers.requires_finalizer(cause=cause)\n has_finalizer = finalizers.has_finalizers(body=cause.body)\n\n if requires_finalizer and not has_finalizer:\n logger.debug(\"Adding the finalizer, thus preventing the actual deletion.\")\n finalizers.append_finalizers(body=body, patch=patch)\n return None\n\n if not requires_finalizer and has_finalizer:\n logger.debug(\"Removing the finalizer, as there are no handlers requiring it.\")\n finalizers.remove_finalizers(body=body, patch=patch)\n return None\n\n # Regular causes invoke the handlers.\n if cause.reason in causation.HANDLER_REASONS:\n title = causation.TITLES.get(cause.reason, repr(cause.reason))\n logger.debug(f\"{title.capitalize()} event: %r\", body)\n if cause.diff and cause.old is not None and cause.new is not None:\n logger.debug(f\"{title.capitalize()} diff: %r\", cause.diff)\n\n handlers = registry.resource_changing_handlers[cause.resource].get_handlers(cause=cause)\n state = states.State.from_body(body=cause.body, handlers=handlers)\n if handlers:\n outcomes = await handling.execute_handlers_once(\n lifecycle=lifecycle,\n handlers=handlers,\n cause=cause,\n state=state,\n )\n state = state.with_outcomes(outcomes)\n state.store(patch=cause.patch)\n states.deliver_results(outcomes=outcomes, patch=cause.patch)\n\n if state.done:\n logger.info(f\"All handlers succeeded for {title}.\")\n state.purge(patch=cause.patch, body=cause.body)\n\n done = state.done\n delay = state.delay\n else:\n skip = True\n\n # Regular causes also do some implicit post-handling when all handlers are done.\n if done or skip:\n extra_fields = registry.resource_changing_handlers[cause.resource].get_extra_fields()\n lastseen.refresh_essence(body=body, patch=patch, extra_fields=extra_fields)\n if cause.reason == causation.Reason.DELETE:\n logger.debug(\"Removing the finalizer, thus allowing the actual deletion.\")\n finalizers.remove_finalizers(body=body, patch=patch)\n\n # Once all handlers have succeeded at least once for any reason, or if there were none,\n # prevent further resume-handlers (which otherwise happens on each watch-stream re-listing).\n memory.fully_handled_once = True\n\n # Informational causes just print the log lines.\n if cause.reason == causation.Reason.GONE:\n logger.debug(\"Deleted, really deleted, and we are notified.\")\n\n if cause.reason == causation.Reason.FREE:\n logger.debug(\"Deletion event, but we are done with it, and we do not care.\")\n\n if cause.reason == causation.Reason.NOOP:\n logger.debug(\"Something has changed, but we are not interested (the essence is the same).\")\n\n # The delay is then consumed by the main handling routine (in different ways).\n return delay\n","sub_path":"kopf/reactor/processing.py","file_name":"processing.py","file_ext":"py","file_size_in_byte":11338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"649002250","text":"import threading, time\n\n# Thread 로 수행될 함수\n# 이 함수에서 벗어나면 쓰레드로 종료된다.\n\ndef myThreadFunction(id): # 쓰레드 함수\n for i in range(4):\n print ('id %s -> count : %s' % (id , i))\n time.sleep(0.5)\n\nfor i in range(5):\n # 5개의 Thread 를 독립적으로 생성\n threading._start_new_thread(myThreadFunction, (i,)) # 쓰레드를 생성되는 부분 \n\ntime.sleep(3)\nprint ('Finish ')\n","sub_path":"instructor/Demo/15장 운영체제/쓰레드데모01.py","file_name":"쓰레드데모01.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"645532877","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 31 22:18:28 2019\n\n@author: sebas\n\"\"\"\n\nimport torch\nimport torchvision as tv\n\n\nclass CNN(torch.nn.Module):\n def __init__(self, in_chann=1, out_classes=2): \n super().__init__()\n self.c1 = torch.nn.Conv1d(in_chann, 16, 5, 1, 0)\n# self.c2 = torch.nn.Conv2d(16, 32, 3, 1, 1)\n self.c3 = torch.nn.MaxPool2d(2,2)\n self.H = 32*8*8\n self.L1 = torch.nn.Linear(self.H, 512)\n self.L2 = torch.nn.Linear(512,out_classes)\n\n def forward(self, x):\n y1 = self.c1(x).relu()\n y2 = self.c2(y1)\n y3 = self.c3(y2).relu()\n y4 = self.L1(y3.view(-1,self.H)).tanh()\n y5 = self.L2(y4)\n\n return y5\n\n\nif __name__ == '__main__':\n \n# transf = tv.transforms.Compose( [tv.transforms.ToTensor(), tv.transforms.Normalize([0.5],[0.5],[0.5]) ] )\n# B = 100\n# trn_data =tv.datasets.CIFAR10(root='./data', train = True, download = True, transform = transf) \n# tst_data =tv.datasets.CIFAR10(root='./data', train = False, download = True, transform = transf)\n# trn_load =torch.utils.data.DataLoader(dataset = trn_data, batch_size = B, shuffle = True)\n# tst_load =torch.utils.data.DataLoader(dataset = tst_data, batch_size = B, shuffle = True)\n \n #idata = iter(trn_load)\n #image, label = next(idata)\n #print('image shape: ', image.shape)\n #print('label shape: ', label.shape)\n \n #c1 = torch.nn.Conv2d(in_channels=3, out_channels=16, kernel_size=5, stride=2, padding=2)\n \n #y1 = c1(image)\n #print('c1 shape: ', y1.shape)\n \n #c2 = torch.nn.Conv2d(16, 32, 3, 1, 1)\n #y2 = c2(y1)\n \n #c3 = torch.nn.MaxPool2d(2,2)\n #y3 = c3(y2)\n \n #view(-1,32*8*8) #porque los Linears reciben vectores y no tensores\n #Linear(32*8*8, 512)\n #Linear(512, 10)\n \n \n path = './'\n #filename = '0.1BzATP12.txt'\n filename = 'BEADSSignal.txt'\n with open(path+filename, 'r') as f:\n lines = (line.strip() for line in f if line)\n xorig = [float(line) for line in lines]\n\n # promedio para que no sea tan pesado.\n sig=[]\n N = 10 #El original es a 250 Hz. Queda a 250/N Hz.\n for j in range(len(xorig)//N):\n if j < (len(xorig)//N)-1:\n sig.append( sum(xorig[N*j:N*(j+1)]) /N )\n else:\n j=(len(xorig)//N)-1\n sig.append( sum(xorig[N*j:]) / len(xorig[N*j:]) )\n\n\n path = './'\n #filename = '0.1BzATP12.txt'\n filename = 'RedIntervalLines.txt'\n with open(path+filename, 'r') as f:\n lines = (line.strip() for line in f if line)\n redLines = [int(float(line)) for line in lines]\n\n\n redLinesConv = [i*250/N for i in redLines]\n redLinesConv.append(len(sig)-1)\n\n conPico=[]\n sinPico=[]\n\n sizeWinSegs = 50\n sizeWin = int(sizeWinSegs*250/N)\n\n sin=True\n for i in range(len(redLinesConv)):\n j=0\n if i==0:\n offset=0\n else:\n offset = int(redLinesConv[i-1])\n if (sin==True):\n while (j+1)*sizeWin+offset < redLinesConv[i]:\n sinPico.append( sig[j*sizeWin+offset:(j+1)*sizeWin+offset] )\n j += 1\n sin=False\n else:\n j=0\n while (j+1)*sizeWin+offset < redLinesConv[i]:\n conPico.append( sig[j*sizeWin+offset:(j+1)*sizeWin+offset] )\n j += 1\n sin=True\n\n \n \n# raw = conPico[0]\n data = torch.tensor(conPico).view(11,1,1250) #o reshape\n print('Data size:', data.shape)\n c1 = torch.nn.Conv1d(in_channels=1, out_channels=5, kernel_size=3, stride=1, padding=0)\n y1 = c1(data)\n print('y1 shape: ', y1.shape)\n\n\n# m = torch.nn.Conv1d(16, 33, 3, stride=2)\n# input = torch.randn(20, 16, 50)\n# output = m(input)\n \n\n\n# c2 = torch.nn.Conv1d(5, 10, 3, 1, 0)\n# y2 = c2(y1)\n \n c2 = torch.nn.MaxPool1d(2,2)\n y2 = c2(y1).relu()\n print('y2 shape: ', y2.shape)\n \n L = torch.nn.Linear(5*624,2)\n y3 = L(y2.view(-1,5*624)).softmax(dim=1)\n print('y3 shape', y3.shape)\n# view(-1,32*8*8) #porque los Linears reciben vectores y no tensores\n# Linear(32*8*8, 512)\n# Linear(512, 10) \n \n\n\n\n\n \n# model = CNN()\n# optim = torch.optim.Adam(model.parameters())\n# costf = torch.nn.CrossEntropyLoss()\n# \n# T = 20\n# model.train()\n# for t in range(T):\n# E = 0\n# for image, label in trn_load:\n# optim.zero_grad()\n# y = model(image)\n# error = costf(y, label)\n# error.backward()\n# optim.step()\n# E += error.item()\n# print(t, E) \n# \n# \n# model.eval()\n# right, total = 0, 0\n# with torch.no_grad():\n# for images, labels in tst_load:\n# y = model(images)\n# right += (y.argmax(dim=1)==labels).sum().item()\n# total += len(labels)\n#\n# accuracy = right / total\n# print('Accuracy: ', accuracy)\n#\n#\n#\n#\"\"\"\n#puedo usar la red convolucional para hacer un autoencoder\n#\n#_.enc = torch.nn.Sequential(\n# conv2d(...),\n# torch.nn.ReLU(True))\n#\n#_.dec = torch.nn.ConvTranspose2d()\n#Tanh()\n#\"\"\"","sub_path":"cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":5097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"97607511","text":"#-*- coding:utf-8 -*-\n\nFILENAME = \"CATH_info\"\nEXT = \".txt\"\nFOLDER = \"dataset/\"\nTRAINDATAFOLDER = \"dssp/\"\nTESTDATAFOLDER = \"dssp_test/\"\nTRAINFILE = \"GOR_data.fasta\"\nTESTFILE = \"GOR_data_test.fasta\"\nRESULTFOLDER = \"results/\"\nRESULTSFILE = \"results.txt\"\n\nfrom DsspParser import *\nfrom GorFileWriter import *\nfrom GorData import *\nfrom ResultsWriter import *\n\nclass FileManager:\n\n\tdef __init__(self):\n\t\tself.parser = DsspParser()\n\t\tself.fileWriter = GorFileWriter()\n\t\tself.resultsWriter = ResultsWriter()\n\n\tdef constructDataFolderName(self, datafolder):\n\t\treturn FOLDER+datafolder\n\n\tdef constructInfoFile(self, string=str()):\n\t\treturn FILENAME+string+EXT\n\n\tdef initiateTrainingProcedure(self):\n\t\tinfofile = self.constructInfoFile()\n\t\tdata = self.parseGorData(infofile, TRAINDATAFOLDER)\n\t\tself.writeGorData(data, TRAINFILE)\n\n\t\treturn data\n\n\tdef initiateTestingProcedure(self):\n\t\tinfofile = self.constructInfoFile(\"_test\")\n\t\tdata = self.parseGorData(infofile, TESTDATAFOLDER)\n\t\tself.writeGorData(data, TESTFILE)\n\n\t\treturn data\n\n\tdef writeGorData(self, data, f):\n\t\ttargetFolder = FOLDER\n\t\tfilename = f\n\t\tself.fileWriter.writeData(filename, targetFolder, data)\n\n\tdef parseGorData(self, infofile, foldername):\n\t\tdatafolder = self.constructDataFolderName(foldername)\n\t\tinfofolder = FOLDER\n\t\tdata = self.parser.parseData(infofile, infofolder, datafolder) # Data is a GorData object\n\t\treturn data\n\n\tdef writeResults(self, data):\n\t\tself.resultsWriter.setData(data)\n\t\tself.resultsWriter.writeResults(RESULTFOLDER, RESULTSFILE)\n","sub_path":"BioInfo/Projet_4/FileManager.py","file_name":"FileManager.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"296533420","text":"import math\nfrom index_build import *\nfrom search_queries import *\n\ndef cool(x, a):\n if x.peek() != None:\n return a + \" \" + str(x.next()) + cool(x, '')\n else:\n return a\n\nif __name__ == '__main__':\n buildIndex()\n a = indexEntryFor('duchess')\n b = indexEntryFor('followed')\n c = indexEntryFor('saucepans')\n A = ItemStream(a)\n B = ItemStream(b)\n C = ItemStream(c)\n\n '''x = {\"CAA\": {0: 1, 2: 3, 4: 5},\n \"AAA\": {6: 7, 8: 9, 10: 11},\n \"DAA\": {12: 13, 14: 15, 16: 17},\n \"BBB\": {18: 19, 20: 21, 22: 23}\n }\n '''\n A = ItemStream(indexEntryFor('very'))\n B = ItemStream(indexEntryFor('palpable'))\n C = ItemStream(indexEntryFor('bear'))\n\n x = HitStream([A, B], 1, 2)\n while x.peek() != None:\n print(x.next())\n\n\n #print(x.next())\n easySearch(['very', 'palpable'])\n #easySearch(['exit', 'pursued', 'bear'])\n\n\n #print(cool(A, ''))\n #while A.peek() != None:\n # print(str(A.next()) + \" : \" + str(B.next()) + \" : \" + str(C.next()))\n5\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"162006224","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.9-x86_64/egg/getml/models/helpers.py\n# Compiled at: 2019-12-09 07:12:30\n# Size of source mod 2**32: 1883 bytes\nimport getml.communication as comm\nfrom .multirel_model import MultirelModel\nfrom .relboost_model import RelboostModel\n\ndef get_model(name):\n \"\"\"\n Returns a handle to the model specified by name.\n\n Args:\n name (str): Name of the model.\n\n \"\"\"\n cmd = dict()\n cmd['type_'] = 'get_model'\n cmd['name_'] = name\n s = comm.send_and_receive_socket(cmd)\n msg = comm.recv_string(s)\n if msg == 'MultirelModel':\n return MultirelModel(name=name).refresh()\n if msg == 'RelboostModel':\n return RelboostModel(name=name).refresh()\n raise Exception(msg)","sub_path":"pycfiles/getml-0.10.0-py3.7/helpers.cpython-37.py","file_name":"helpers.cpython-37.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"260898540","text":"\"\"\"Extend db to include picture\n\nRevision ID: 25a9a37f3c5f\nRevises: 2345bcfeaced\nCreate Date: 2015-08-31 17:02:25.417938\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '25a9a37f3c5f'\ndown_revision = '2345bcfeaced'\nbranch_labels = None\ndepends_on = None\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('PiScreens',\n sa.Column('uuid', sa.Text(), nullable=False),\n sa.Column('image', sa.Binary(), nullable=True),\n sa.PrimaryKeyConstraint('uuid')\n )\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('PiScreens')\n ### end Alembic commands ###\n","sub_path":"alembic/versions/25a9a37f3c5f_extend_db_to_include_picture.py","file_name":"25a9a37f3c5f_extend_db_to_include_picture.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"480884257","text":"import numpy as np\nimport pandas as pd #파일를 불러오기 위한 모듈\nimport matplotlib.pyplot as plt #그래프 출력에 필요한 모듈\nfrom matplotlib import font_manager, rc #그래프에 한글이 출력되기 위해 필요한 함수\nimport csv\n\npd.set_option('display.max_rows', 1200) # 출력 결과 생략 방지\npd.set_option('display.max_columns', 1200)\npd.set_option('display.width', 1000)\n\nclass GraphMake:\n def __init__(self):\n f = 'restaurant_list.csv' # csv 파일 불러오기\n df = pd.read_csv(f)\n\n # CSV 파일에서 검색에 필요한 열만 추출\n self.Name = df.loc[:, \"업소명\"]\n self.Price = df.loc[:, \"가격대\"]\n self.Menu = df.loc[:, \"메뉴\"]\n\n data = {'업소명': self.Name, '가격대': self.Price, '메뉴': self.Menu} # 그래프 객체에 데이터 추가\n\n self.DFrame = pd.DataFrame(data,) # DFrame에 데이터 정렬해서 저장하고 리턴하기\n with open('Dframe.csv', 'r+', encoding='utf-8') as f:\n pd.read_csv(\"Dframe.txt\") # txt파일 생성\n pd.read_csv('Dframe.txt', sep=',', header=None, index_col=None, skiprows=None)\n for line in f: # 데이터를 콤마 기준으로 행과 열을 분할함\n fields = line.strip().split(',')\n print(fields, file=f)\n f.close()\n\n # 데이터에서 검색한 값이 있나 확인하는 함수\n def Find(self, money, menu): # 가격대 ,메뉴 입력받은 값을 비교해서 비슷한 값 출력\n f = 'Dframe.txt'\n df = pd.DataFrame[f]\n treat1 = df[ money + 2000 >money > money - 2000] # 전체 열에서 데이터 근처에 있는 값을 가진 행 입력\n treat2 = df.loc[menu] # 검색 받은 메뉴와 이름이 같은 데이터를 입력\n if treat1 == treat2: # treat1,2에 둘 다 있는 값을 찾으면 데이터 저장\n for i in df:\n print(treat1, file=f)\n\n\n # 막대 그래프를 출력하는 함수\n def Graph(self,price,name):\n font_name = font_manager.FontProperties(fname=\"c:/Windows/Fonts/malgun.ttf\").get_name()\n rc('font', family=font_name) # 그래프에 한글로 출력되기 위해 필요한 문장\n\n with open('Dframe.txt', 'r', encoding='utf-8') as file:\n df =pd.DataFrame[file]\n grouped = df['가격대'].groupedby(df['식당이름']) #식당이름 별로 가격 그룹핑\n PRICE = [df[2]] #가격 식당이름 선언\n NAME = [df[1]]\n price = grouped.pr()\n name = grouped.na()\n\n df2 = pd.DataFrame({'price' : price })\n df3 = pd.DataFrame({'name' : name })\n dic = {\"price\" : PRICE , \"name\" : NAME }\n\n df_list = pd.DataFrame[dic] #데이터 프레임 변환\n\n plt.figure(figsize=(12, 8)) # 그래프의 크기 지정\n\n pos = np.arange(5)\n rects = plt.bar(pos, PRICE, align='center', width=0.5)\n\n # x축 설정\n xpos = np.arange(len(PRICE))\n plt.xticks(xpos + 1, NAME)\n plt.xlabel(\"식당이름\", fontsize=14)\n\n # y축 설정\n plt.yticks([10000, 20000, 30000, 40000, 50000]) # 그래프 y축 간격 만원씩\n plt.ylabel(\"가격대\", fontsize=14)\n plt.ylim([2000, 60000]) # 그래프 최솟값 최댓값\n\n plt.title(\"그래프\")\n\n plt.savefig('Graph.png', format='png', dpi=350) # 그래프 저장하고 출력\n plt.show()","sub_path":"GraphMake.py","file_name":"GraphMake.py","file_ext":"py","file_size_in_byte":3712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"66838463","text":"#!/usr/bin/env python3\n\"\"\"\nFile Name : Problem021.py\nDate started : Unknown\nDate solved : Unknown\nRun Time : 0.44400 seconds\n\nLet d(n) be defined as the sum of proper divisors of n (numbers less than n\nwhich divide evenly into n).\n\nIf d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair\nand each of a and b are called amicable numbers.\n\nFor example, the proper divisors of 220 are:\n 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110;\n therefore d(220) = 284.\n\nThe proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.\n\nEvaluate the sum of all the amicable numbers under 10000.\n\n\"\"\"\n\nimport project_euler\nimport project_euler.factors\n\n\nPROBLEM_NUMBER = 21\nSOLVED = 1\n\n\ndef problem021(input_=None):\n listOfAmic = set()\n for n in range(10000):\n s = sum(project_euler.factors.listFactors(n)) - n\n if sum(project_euler.factors.listFactors(s)) - s == n and s != n:\n listOfAmic.add(n)\n listOfAmic.add(s)\n return sum(listOfAmic)\n\n\ndef run():\n print(project_euler.print_timing(problem021))\n\n\nif __name__ == \"__main__\":\n run()\n\n","sub_path":"problems/Problem021.py","file_name":"Problem021.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"554138663","text":"# successful method\n# idreserva, correo, numero, direccion\n\n\ndef get_disponible(cursor, param):\n query = \"select idreserva, id from contacto\"\n cursor.execute(query)\n reserva_ocupado = cursor.fetchall()\n\n query = \"select id, nombre from reserva\"\n cursor.execute(query)\n reservas = cursor.fetchall()\n\n query = \"select id, nombre from reserva\"\n cursor.execute(query)\n reservaTemp = cursor.fetchall()\n\n for reserva in reservas:\n for ocupado in reserva_ocupado:\n if param is None:\n if str(reserva[0]) == str(ocupado[0]):\n reservaTemp.remove(reserva)\n else:\n if reserva[0] == ocupado[0] and str(ocupado[1]) != param:\n reservaTemp.remove(reserva)\n\n return reservaTemp\n\n\ndef getfromView(cursor):\n query = \"select id, idreserva, correo, numero, direccion from vw_contacto\"\n cursor.execute(query)\n contactos = cursor.fetchall()\n\n data = []\n for contacto in contactos:\n data.append({\n \"id\": contacto[0],\n \"idreserva\": contacto[1],\n \"correo\": contacto[2],\n \"numero\": contacto[3],\n \"direccion\": contacto[4]\n })\n\n return data\n\n\ndef getfromTable(cursor):\n query = \"select * from contacto\"\n cursor.execute(query)\n contactos = cursor.fetchall()\n\n data = []\n for contacto in contactos:\n data.append({\n \"id\": contacto[0],\n \"idreserva\": contacto[1],\n \"correo\": contacto[2],\n \"numero\": contacto[3],\n \"direccion\": contacto[4]\n })\n\n return data\n\n\ndef getfromTableReserva(cursor, idreserva):\n query = \"select * from contacto where idreserva = %s\"\n params = (idreserva, )\n cursor.execute(query, params)\n \n contacto = cursor.fetchone()\n\n if not cursor.rowcount:\n return {\"mensaje\": \"contacto no encontrado\"}\n\n return {\n \"id\": contacto[0],\n \"idreserva\": contacto[1],\n \"correo\": contacto[2],\n \"numero\": contacto[3],\n \"direccion\": contacto[4]\n }\n\n\ndef getfromTableId(cursor, id):\n query = \"select * from contacto where id = %s\"\n params = (id,)\n cursor.execute(query, params)\n\n contacto = cursor.fetchone()\n\n if not cursor.rowcount:\n return {\"mensaje\": \"contacto no encontrado\"}\n\n return {\n \"id\": contacto[0],\n \"idreserva\": contacto[1],\n \"correo\": contacto[2],\n \"numero\": contacto[3],\n \"direccion\": contacto[4]\n }\n\n\n# successful method\ndef insertInTable(cursor, connection, data):\n query = \"insert into contacto (idreserva, correo, numero, direccion) values (%s, %s, %s, %s)\"\n params = (data['idreserva'], data['correo'], data['numero'], data['direccion'])\n cursor.execute(query, params)\n connection.commit()\n\n query = \"select * from contacto where correo = %s and idreserva = %s\"\n params = (data['correo'], data['idreserva'])\n cursor.execute(query, params)\n\n contacto = cursor.fetchone()\n\n return {\n \"id\": contacto[0],\n \"idreserva\": contacto[1],\n \"correo\": contacto[2],\n \"numero\": contacto[3],\n \"direccion\": contacto[4]\n }\n\n\n# successful update\ndef updateTable(cursor, connection, data):\n query = \"update contacto set idreserva = %s, correo = %s, numero =%s, direccion = %s where id=%s\"\n params = (data['idreserva'], data['correo'], data['numero'], data['direccion'], data['id'])\n cursor.execute(query, params)\n connection.commit()\n return None\n\n\n# successful delete\ndef deleteinTable(cursor, connection, id):\n query = \"delete from contacto where id=%s\"\n params = (id,)\n cursor.execute(query, params)\n connection.commit()\n return None\n","sub_path":"modelos/implementacion/contactoImp.py","file_name":"contactoImp.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"405168688","text":"from scipy import signal\nimport matplotlib.pyplot as plt\n\n\nfig = plt.figure(1, figsize=(10,10))\nax = fig.add_subplot(111)\n\nplt.rcParams['mathtext.fontset'] = 'stix'\nplt.rcParams['font.family'] = 'STIXGeneral'\nplt.rcParams['legend.numpoints'] = 1\nnullloc = plt.NullLocator()\n\n# disable the labels\nax.yaxis.set_major_locator(nullloc)\nax.xaxis.set_major_locator(nullloc)\n\nax.set_xlim(10,90)\nax.set_ylim(-0.15,0.3)\n\npoints = 100\na = 9.0\nvec2 = signal.ricker(points, a)\nprint(len(vec2))\n\nax.plot(vec2, color=\"black\", linewidth=1, linestyle=\"-\")\n#plt.show()\n\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\nax.spines[\"bottom\"].set_visible(False)\nax.spines[\"left\"].set_visible(False)\n\nplt.savefig(\"/Users/thomasrommel/Google Drive/paper_masterthesis/images/mexican_hat/mexican_hat2d_noSpines_transp.png\", bbox_inches=\"tight\", dpi=300, transparent=True)\n","sub_path":"plot/plot_mexican_hat2d.py","file_name":"plot_mexican_hat2d.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"13417586","text":"import pygame as pg\nimport sys\nimport time\nimport numpy as np\nfrom pygame.locals import *\nfrom random import randint\nimport random\n\n# Global Values\nWINDOW_WIDTH = 1024\nWINDOW_HEIGHT = 650\n\n#Enemy Movement\nUP_LEFT = 1\nUP_RIGHT = 2\nDOWN_RIGHT = 3\nDOWN_LEFT = 4\nLEFT = 5\nRIGHT = 6\n\n#Player Movement\nPLEFT = False\nPRIGHT = False\nNOMOVE = True\nSHOOT = False\n\n#Bullet speed\nBSPEED = 10\n\n\n#Color Vairables \nWHITE = (255,255,255)\nBLACK = (0,0,0)\nRED = (255,0,0)\nGREEN = (0,255,0)\nBLUE = (0,0,255)\nYELLOW = (255,255,0)\n\n#Agent List\nAGENTS = []\n\nclass Bullet(pg.sprite.Sprite):\n def __init__(self,x,y):\n pg.sprite.Sprite.__init__(self)\n self.image = pg.Surface((10,20))\n self.speed = BSPEED\n self.image.fill(RED)\n self.rect = self.image.get_rect()\n self.rect.y = y\n self.rect.x = x\n \n def update(self):\n self.rect.x = self.rect.x\n self.rect.y -= self.speed\n if self.rect.bottom < 0:\n self.kill() \n \ndef getMove(c):\n if c>=0.0 and c<0.3:\n moveDown(playerID)\n elif c >=0.3 and c <0.7:\n noMove(playerID)\n elif c >=0.7 and c <= 1:\n moveUp(playerID)\n \nclass Rocket(pg.sprite.Sprite):\n def __init__(self,bottom,centerx,centery):\n \n pg.sprite.Sprite.__init__(self)\n self.centerx = centerx\n self.centery = centery\n self.bottom = bottom\n self.image = pg.Surface([20,20])\n self.image.fill(WHITE)\n self.rect = self.image.get_rect()\n self.speed = 5\n self.rect.centerx = self.centerx\n self.rect.centery = self.bottom-10\n \n \n def moveAll(self,PLEFT,PRIGHT,NOMOVE,SHOOT):\n #global PLEFT\n #global PRIGHT\n #global NOMOVE\n #global SHOOT\n if (PLEFT == True) and (self.rect.x>5):\n self.rect.x -=self.speed\n elif (PRIGHT == True) and (self.rect.x < WINDOW_WIDTH -25):\n self.rect.x += self.speed\n elif (SHOOT == True):\n newBullet =Bullet(self.rect.x,self.rect.y)\n newBullet.update()\n return newBullet\n else: # NOMOVE is True\n pass\n \n def move(self,option):\n if option == 1:\n PLEFT = True\n PRIGHT = False\n NOMOVE = False\n SHOOT = False\n self.moveAll(PLEFT,PRIGHT,NOMOVE,SHOOT) \n elif option ==2:\n PLEFT = False\n PRIGHT = True\n NOMOVE = False\n SHOOT = False\n self.moveAll(PLEFT,PRIGHT,NOMOVE,SHOOT) \n elif option ==3:\n PLEFT = False\n PRIGHT = False\n NOMOVE = True\n SHOOT = False\n self.moveAll(PLEFT,PRIGHT,NOMOVE,SHOOT) \n elif option ==4:\n PLEFT = False\n PRIGHT = False\n NOMOVE = False\n SHOOT = True\n bullet=self.moveAll(PLEFT,PRIGHT,NOMOVE,SHOOT)\n return bullet\n else:\n pass\n \n \n def automove(self,chromosome,rangeValue):\n if chromosome[0] <= 0.33:\n self.move(1)\n if chromosome[1]>0.33 and chromosome[1]<=0.67:\n self.move(2)\n if chromosome[2]>0.67 and chromosome[2]<=1:\n self.move(3)\n if chromosome[3]>0.1 and (rangeValue-chromosome[4])>0:\n bullet =self.move(4)\n return bullet\n if chromosome[4]>0.5:\n pass\n \n \n \n\ndef getRandomEnemyChromosome():\n l = [round(random.uniform(0,1),2),round(random.uniform(0,1),2),round(random.uniform(0,1),2)]\n return l\nclass Enemy(pg.sprite.Sprite):\n def __init__(self,centerx,centery,probMoving):\n pg.sprite.Sprite.__init__(self)\n self.centerx = centerx\n self.centery = centery\n self.maxspeed = 7\n self.maxhealth = 100\n self.chromosome=getRandomEnemyChromosome()\n #self.probMoving = probMoving\n self.probMoving =self.chromosome[0]\n self.direction = randint(1,6)\n self.image = pg.Surface([50,50])\n self.image.fill(GREEN)\n self.rect = self.image.get_rect()\n #self.speed = randint(1,5)\n self.speed = self.maxspeed * self.chromosome[1]\n \n self.rect.centerx = self.centerx\n self.rect.centery = self.centery\n self.time = time.time()\n self.health = self.maxhealth* self.chromosome[2]\n self.fitness = 0\n \n \n \n def move(self):\n if self.direction == UP_LEFT:\n self.rect.x -= self.speed\n self.rect.y -= self.speed\n \n elif self.direction == UP_RIGHT:\n self.rect.x += self.speed\n self.rect.y -= self.speed\n \n elif self.direction == DOWN_RIGHT:\n self.rect.x += self.speed\n self.rect.y += self.speed\n \n elif self.direction == DOWN_LEFT:\n self.rect.x -= self.speed\n self.rect.y += self.speed\n \n elif self.direction == RIGHT:\n self.rect.x += self.speed\n self.rect.y =self.rect.y\n \n elif self.direction == LEFT:\n self.rect.x -= self.speed\n self.fitness+=1 \n \n def changeDirection(self,counter):\n if counter%10 ==0:\n r = randint(0,1000)\n p = 1000*self.probMoving\n if r<=p:\n self.direction= randint(1,6)\n else:\n if self.rect.y<30:\n self.direction = random.choice([3,4,5,6])\n elif self.rect.x>WINDOW_WIDTH-45:\n self.direction = random.choice([1,4,5])\n elif self.rect.y>WINDOW_HEIGHT-100:\n self.direction = random.choice([1,2,5,6])\n elif self.rect.x<10:\n self.direction = random.choice([2,3,6])\n else: \n pass\n\ndef mutationEnemy(chm,prob):\n i = random.uniform(0,1)\n if i<prob:\n index = randint(0,2)\n chm[index] = round(random.uniform(0,1),2)\n return chm\ndef doCrossoverMutation(ene1,ene2):\n i = randint(0,2)\n f1 = ene1.chromosome[:i]\n b1 = ene1.chromosome[i:]\n f2 = ene2.chromosome[:i]\n b2 = ene2.chromosome[i:]\n n1 = f1 + b2\n n2 = f2 + b1\n n1 = mutationEnemy(n1,0.60)\n n2 = mutationEnemy(n2,0.60)\n enemy1 = Enemy(ene1.rect.x,ene2.rect.y,0.1)\n enemy1.chromosome = n1\n enemy2 = Enemy(ene2.rect.x,ene1.rect.y,0.1)\n enemy2.chromosome = n2\n return enemy1,enemy2\n \n \ndef GAEnemy(enemyList):\n enemyList = sorted(enemyList,key=getKey)\n index = 0.8 * len(enemyList)\n index = int(index)\n if index%2!=0:\n index = index-1\n newChild =[] \n for i in range(index,len(enemyList),2):\n if i>=len(enemyList):\n break\n e1,e2 = doCrossoverMutation(enemyList[i],enemyList[i+1])\n newChild.append(e1)\n newChild.append(e2)\n enemyList = enemyList + newChild\n return enemyList\ndef getKey(enemy):\n return enemy.fitness\n \n\n\ndef getMaxTime(Array):\n timeArray=[x.time for x in Array]\n time1 = max(timeArray)\n timeArray.remove(time1)\n #time1-=time.time()\n time2 = max(timeArray)#-time.time()\n return time1,time2\n'''\ndef EnemyBreeding(enemy1,enemy2,maxLiver1,maxLiver2,gameWindow):\n newEnemy=[]\n if pg.sprite.collide_rect(enemy1,enemy2):\n if enemy1.time==maxLiver1 or enemy2.time==maxLiver1:\n for i in range(2):\n newEnemy.append(Enemy(gameWindow.get_rect().centerx,gameWindow.get_rect().centery,i))\n elif enemy1.time == maxLiver2 or enemy2.time == maxLiver2:\n for i in range(2):\n newEnemy.append(Enemy(gameWindow.get_rect().centerx,gameWindow.get_rect().centery,i))\n return(newEnemy) \n'''\ndef health_bars(rocket_health,gameWindow):\n if rocket_health > 75:\n rocket_health_color = GREEN\n if rocket_health >50:\n rocket_health_color = YELLOW\n elif rocket_health < 50 and rocket_health>0:\n rocket_health_color = RED\n else:\n return 0\n\n pg.draw.rect(gameWindow , rocket_health_color,(800,10,rocket_health , 25))\n\ndef createPopulation():\n population=[0 for i in range(10)]\n for i in range(10):\n population[i]=chromosome()\n return population\n\ndef crossover(chromosome1,chromosome2):\n point = random.randint(1,10)\n child1 = chromosome1[:point]+chromosome2[point:]\n child2 = chromosome2[:point]+chromosome1[point:] \n return child1,child2\n\ndef mutation(chromosome):\n point= random.randint(0,5)\n chromosome[point]=random.random()\n return chromosome\n \ndef parentSelection(fitnessValues,initialpopulation):\n bestparents=[0,0,0,0,0]\n for i in range(5):\n max1=max(fitnessValues)\n index=fitnessValues.index(max1)\n print(index,initialpopulation[index])\n parent1 = initialpopulation[index]\n initialpopulation.remove(parent1)\n fitnessValues.remove(max1)\n bestparents[i]=parent1\n return bestparents\n\ndef calcfitness(score,time):\n return (0.7*score + 0.3*time)/2\n\ndef geneticAlgo_rocket(gameWindow,surface_rect,clock):\n rocket = Rocket(gameWindow.get_rect().bottom,gameWindow.get_rect().centerx,gameWindow.get_rect().centery)\n initialpopulation=createPopulation()\n newspecies =0\n newpopulation=initialpopulation\n while(True):\n initialpopulation=newpopulation\n print(len(initialpopulation))\n fitnessValues = [0 for i in range(10)]\n i=0\n for chromosome in initialpopulation:\n score,time=playGame(gameWindow,surface_rect,clock,chromosome,rocket,i,newspecies)\n fitnessValues[i]=calcfitness(score,time)\n i+=1\n bestparents=parentSelection(fitnessValues,initialpopulation)\n newpopulation=[]\n flag=0\n for i in range(len(bestparents)):\n for j in range(len(bestparents)):\n if i<j and flag==0:\n child1,child2=crossover(bestparents[i],bestparents[j])\n newpopulation.append(child1)\n newpopulation.append(child2)\n if(len(newpopulation)>=10):\n flag=1\n \n for i in range(2):\n newpopulation[i]=mutation(newpopulation[i])\n newspecies+=1\n \ndef playGame(gameWindow,surface_rect,clock,chromosome,rocket,chrome,species):\n #rocket = Rocket(gameWindow.get_rect().bottom,gameWindow.get_rect().centerx,gameWindow.get_rect().centery)\n time1 =time.time()\n rocket_health = 100\n probability =np.linspace(0,1,4)\n EnemyArray =[]\n for i in probability:\n EnemyArray.append(Enemy(gameWindow.get_rect().centerx,gameWindow.get_rect().centery,i))\n\n counter = 0\n bullets=[]\n Score= 0\n score_font = pg.font.SysFont(\"Helvetica\",20)\n Timett = pg.font.SysFont(\"Helvetica\",20)\n enemy_font = pg.font.SysFont(\"Helvetica\",20)\n \n while True:\n sprites = pg.sprite.RenderPlain(rocket,tuple(EnemyArray),tuple(bullets))\n clock.tick(200)\n newChro=chromosome#()\n #print(newChro)\n hitting=random.random()\n bullet=rocket.automove(newChro,hitting)\n \n if bullet:\n bullets.append(bullet)\n rocket_health -= 5\n for event in pg.event.get():\n if event.type ==QUIT:\n pg.quit()\n sys.exit()\n \"\"\"if event.type == KEYDOWN:\n if event.key==K_LEFT:\n PLEFT =True\n PRIGHT = False\n NOMOVE = False\n if event.key == K_RIGHT:\n PLEFT = False\n PRIGHT = True\n NOMOVE = False\n if event.key == K_SPACE:\n bullet=rocket.shoot()\n rocket_health -= 5 \n bullets.append(bullet)\n \n if event.type == KEYUP:\n if event.key == K_LEFT:\n PLEFT = False\n PRIGHT = False\n NOMOVE = True\n if event.key == K_RIGHT:\n PLEFT = False\n PRIGHT = False\n NOMOVE = True\n #if event.key == K_UP:\"\"\"\n \n for fire in bullets:\n fire.update()\n \n gameWindow.fill(BLACK)\n updatedhealth = health_bars(rocket_health,gameWindow)\n \n if updatedhealth==0:\n time2 = time.time()\n ttime = time2 -time1\n return Score,ttime\n \n sprites.draw(gameWindow)\n \n for enemy in EnemyArray:\n enemy.move()\n enemy.changeDirection(counter)\n \n '''if(counter%5==0):\n for enemy in EnemyArray:\n for secenemy in EnemyArray:\n if (enemy != secenemy and len(EnemyArray)<=50):\n maxtime1,maxtime2= getMaxTime(EnemyArray)\n newEnemy=EnemyBreeding(enemy,secenemy,maxtime1,maxtime2,gameWindow)\n EnemyArray+=newEnemy\n '''\n if counter%1000==0:\n EnemyArray = GAEnemy(EnemyArray)\n maxtime1 = 0.0\n maxtime2 = 0.0\n for enemy in EnemyArray:\n for fire in bullets:\n if pg.sprite.collide_rect(enemy,fire):\n enemy.kill()\n fire.kill()\n Score = Score+10\n rocket_health += 7\n EnemyArray.remove(enemy)\n bullets.remove(fire)\n break\n \n scoreBoard = score_font.render(\"Score :\" + str(Score),True,WHITE,BLACK)\n scoreBoard_rect = scoreBoard.get_rect()\n scoreBoard_rect.centerx = surface_rect.centerx\n scoreBoard_rect.y = 10\n \n \n maxTimeboard = Timett.render(\"Max Living Enemy: \"+str(maxtime1),True,WHITE,BLACK)\n maxTimeboard_rect = maxTimeboard.get_rect()\n maxTimeboard_rect.x = 10\n maxTimeboard_rect.y = 10\n \n speciesBoard = enemy_font.render(\"Species:\" + str(species),True,WHITE,BLACK)\n speciesBoard_rect = speciesBoard.get_rect()\n speciesBoard_rect.centerx = 85\n speciesBoard_rect.y = 40\n \n chromeBoard = enemy_font.render(\"population:\" + str(chrome),True,WHITE,BLACK)\n chromeBoard_rect = chromeBoard.get_rect()\n chromeBoard_rect.centerx = 85\n chromeBoard_rect.y = 60\n \n enemyBoard = enemy_font.render(\"Enemy Count:\" + str(len(EnemyArray)),True,WHITE,BLACK)\n enemyBoard_rect = enemyBoard.get_rect()\n enemyBoard_rect.centerx = 85\n enemyBoard_rect.y = 80\n \n gameWindow.blit(scoreBoard,scoreBoard_rect)\n gameWindow.blit(maxTimeboard,maxTimeboard_rect)\n gameWindow.blit(enemyBoard,enemyBoard_rect)\n gameWindow.blit(chromeBoard,chromeBoard_rect)\n gameWindow.blit(speciesBoard,speciesBoard_rect)\n \n #rocket.move()\n pg.display.update()\n counter +=1\n if counter ==1000000:\n counter =0\n if(len(EnemyArray)>50):\n time2=time.time()\n ttime=time2-time1\n return Score,ttime\n #sys.exit()\n \n if(len(EnemyArray)==0):\n time2=time.time()\n ttime= time2-time1\n #time.sleep(0.2)\n return Score,ttime\n #sys.exit()\n GameOver = score_font.render(\"GAME OVER \",True,WHITE,BLACK)\n GameOver_rect = GameOver.get_rect()\n GameOver_rect.centerx = surface_rect.centerx\n GameOver_rect.y = 150\n gameWindow.blit(GameOver,GameOver_rect) \n\ndef chromosome():\n chromosome=[0,0,0,0,0,0]\n #gene[0] #probability of changing direction left\n #gene[1] #probability of changing direction right\n #gene[2] #probability of no move\n #gene[3] #probability of shooting\n #gene[4] #Threshold for range of Rocket to shoot\n #gene[5] #Speed ratio of rocket\n chromosome=[random.random() for x in range(6)]\n return chromosome\n \ndef getClock():\n return pg.time.Clock()\n\ndef createGameWindow(width,height):\n flag = 0\n depth =32\n return pg.display.set_mode((width,height),flag,depth)\n \ndef main():\n gameWindow = createGameWindow(WINDOW_WIDTH,WINDOW_HEIGHT)\n surface_rect = gameWindow.get_rect()\n pg.display.set_caption('SPACE ASSAULTER GAME')\n clock = getClock()\n geneticAlgo_rocket(gameWindow,surface_rect,clock)\n \nif __name__=='__main__':\n pg.init()\n main() \n","sub_path":"spaceAssaulter/spaceassaulter2.py","file_name":"spaceassaulter2.py","file_ext":"py","file_size_in_byte":16598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"2912485","text":"# coding: utf-8\n\n\n\nimport copy, math\nimport numpy as np\n# We disable pylint because we need python3 compatibility.\nfrom six.moves import xrange # pylint: disable=redefined-builtin\nfrom six.moves import zip # pylint: disable=redefined-builtin\n\nimport inspect\nimport tensorflow as tf\nfrom tensorflow.python.ops import rnn\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import embedding_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.util import nest\nfrom tensorflow.contrib.legacy_seq2seq import sequence_loss, sequence_loss_by_example, rnn_decoder, attention_decoder #, model_with_buckets\n#from beam_search import _extract_beam_search, beam_rnn_decoder, beam_attention_decoder\nfrom core.seq2seq import beam_search\n\nclass Decoder(object):\n pass\n\nclass RNNDecoder(Decoder):\n def __init__(self, cell, embedding, scope=None):\n with variable_scope.variable_scope(scope or \"rnn_decoder\") as scope:\n self.cell = cell\n self.embedding = embedding\n # Decoder keeps its decoder function as a property for extention.\n self.decoder_func = rnn_decoder \n @property\n def state_size(self):\n return self.cell.state_size\n\n @property\n def output_size(self):\n return self.cell.output_size\n\n def __call__(self, inputs, init_state, _,\n loop_function=None, scope=None):\n with variable_scope.variable_scope(scope or \"rnn_decoder\") as scope:\n inputs = tf.nn.embedding_lookup(self.embedding, inputs)\n if not nest.is_sequence(inputs):\n inputs = tf.unstack(inputs, axis=1)\n return self.decoder_func(inputs, init_state, self.cell,\n scope=scope, loop_function=loop_function)\n\nclass AttentionDecoder(RNNDecoder):\n def __init__(self, cell, embedding, num_heads=1, scope=None):\n with variable_scope.variable_scope(scope or \"attention_decoder\") as scope:\n self.cell = cell\n self.embedding = embedding\n self.num_heads = num_heads\n # Decoder keeps its decoder function as a property for extention.\n self.decoder_func = attention_decoder \n\n def __call__(self, inputs, init_state, encoder_outputs,\n loop_function=None, scope=None):\n with variable_scope.variable_scope(scope or \"attention_decoder\") as scope:\n attention_states = encoder_outputs\n return self.decoder_func(inputs, init_state, attention_states, self.cell,\n num_heads=self.num_heads,\n scope=scope, loop_function=loop_function)\n\n\nclass BeamSearchWrapper(object):\n def __init__(self, decoder, beam_size, projection):\n self.decoder = decoder\n self.beam_size = beam_size\n self.embedding = decoder.embedding\n self.cell = decoder.cell\n self.projection = projection\n\n # Decoderクラスへの引数はdecoder関数に共通して渡されるものを優先的に\n def __call__(self, inputs, init_state, encoder_outputs, **kwargs):\n kwargs['beam_size'] = self.beam_size\n kwargs['output_projection'] = self.projection\n if self.decoder.decoder_func == rnn_decoder:\n return beam_search.beam_rnn_decoder(\n inputs, init_state, self.cell, **kwargs)\n elif self.decoder.decoder_func == attention_decoder:\n return beam_search.beam_attention_decoder(\n inputs, init_state, encoder_outputs, self.cell, **kwargs)\n","sub_path":"core/seq2seq/decoders.py","file_name":"decoders.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"271816165","text":"\"\"\"List VLANs.\"\"\"\n# :license: MIT, see LICENSE for more details.\n\nimport SoftLayer\nfrom SoftLayer.CLI import environment\nfrom SoftLayer.CLI import formatting\nfrom SoftLayer import utils\n\n\nimport click\n\n\n@click.command()\n@click.option('--sortby',\n help='Column to sort by',\n type=click.Choice(['id',\n 'number',\n 'datacenter',\n 'IPs',\n 'hardware',\n 'vs',\n 'networking',\n 'firewall']))\n@click.option('--datacenter', '-d',\n help='Filter by datacenter shortname (sng01, dal05, ...)')\n@click.option('--number', '-n', help='Filter by VLAN number')\n@click.option('--name', help='Filter by VLAN name')\n@environment.pass_env\ndef cli(env, sortby, datacenter, number, name):\n \"\"\"List VLANs.\"\"\"\n\n mgr = SoftLayer.NetworkManager(env.client)\n\n table = formatting.Table([\n 'id', 'number', 'datacenter', 'name', 'IPs', 'hardware', 'vs',\n 'networking', 'firewall'\n ])\n table.sortby = sortby\n\n vlans = mgr.list_vlans(datacenter=datacenter,\n vlan_number=number,\n name=name)\n for vlan in vlans:\n table.add_row([\n vlan['id'],\n vlan['vlanNumber'],\n utils.lookup(vlan, 'primaryRouter', 'datacenter', 'name'),\n vlan.get('name') or formatting.blank(),\n vlan['totalPrimaryIpAddressCount'],\n len(vlan['hardware']),\n len(vlan['virtualGuests']),\n len(vlan['networkComponents']),\n 'Yes' if vlan['firewallInterfaces'] else 'No',\n ])\n\n env.fout(table)\n","sub_path":"SoftLayer/CLI/vlan/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"67733870","text":"import MapReduce\nimport sys\n\n\"\"\"\nJoin Example in the Simple Python MapReduce Framework\n\"\"\"\n\nmr = MapReduce.MapReduce()\n\n# =============================\n# Do not modify above this line\n\ndef mapper(record):\n # key: table identifier\n # value: attributes\n key = record[0]\n order_id = record[1]\n attributes = record[2:]\n mr.emit_intermediate(order_id, [key, attributes])\n\ndef reducer(key, list_of_values):\n # key: word\n # list_of_values: list of attributes lists\n orders = [t[1] for t in list_of_values if t[0] == 'order']\n line_items = [t[1] for t in list_of_values if t[0] == 'line_item']\n\n for order in orders:\n for line_item in line_items:\n res = []\n res.append('order')\n res.append(key)\n res.extend(orders)\n res.append('line_item')\n res.append(key)\n res.extend(line_items)\n mr.emit(res)\n\n# Do not modify below this line\n# =============================\nif __name__ == '__main__':\n inputdata = open(sys.argv[1])\n mr.execute(inputdata, mapper, reducer)\n","sub_path":"assignment3/join.py","file_name":"join.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"104621076","text":"# -*- coding: utf-8 -*-\r\n\r\nbatch_size = 64\r\nnum_epochs = 200\r\nnum_layers = 1\r\nnum_heads = 4\r\nvocab_size = 186\r\n#Y的分类\r\nnum_category = 206\r\nmodel_dim = 512\r\ndropout = 0.1\r\ndim_per_head = model_dim // num_heads\r\nlearning_rate = 1e-5\r\n'''data_read中得到max_len'''\r\nmax_len = 19\r\n#LSTM中所用超参数\r\nhidden_size = 128\r\n'''每个句子的开始标记'''\r\nSOS_token = 0","sub_path":"seq2seq_model/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"602212817","text":"# 1. 导入FastDFS客户端扩展\nfrom fdfs_client.client import Fdfs_client\n# 2. 创建FastDFS客户端实例\nclient = Fdfs_client('client.conf')\n# 3. 调用FastDFS客户端上传文件方法\nret = client.upload_by_filename('/Users/lcf/Desktop/meizi.png')\nret = {\n'Group name': 'group1',\n'Remote file_id': 'group1/M00/00/00/wKhnnlxw_gmAcoWmAAEXU5wmjPs35.jpeg',\n'Status': 'Upload successed.',\n'Local file name': '/Users/zhangjie/Desktop/kk.jpeg',\n'Uploaded size': '69.00KB',\n'Storage IP': '192.168.244.134'\n }\n","sub_path":"meiduo_mall/utils/fastdfs/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"44787479","text":"import cv2\r\nimport numpy as np\r\n\r\n\r\ndef imageRead(openpath, flag=cv2.IMREAD_UNCHANGED):\r\n image = cv2.imread(openpath, flag)\r\n if image is not None:\r\n print(\"Image Opened\")\r\n return image\r\n else:\r\n print(\"Image Not Opened\")\r\n print(\"Program Abort\")\r\n exit()\r\n\r\n\r\ndef imageCopy(src):\r\n return np.copy(src)\r\n\r\n\r\ndef imageBlur(image, ksize):\r\n size = ((ksize+1) * 2 - 1, (ksize+1) * 2 - 1)\r\n return cv2.blur(image, size)\r\n\r\n\r\ndef imageGaussianBlur(image, ksize, sigmaX, sigmaY):\r\n size = ((ksize+1) * 2 - 1, (ksize+1) * 2 - 1)\r\n return cv2.GaussianBlur(image, ksize=size, sigmaX=sigmaX, sigmaY=sigmaY)\r\n\r\n\r\ndef nothing(x):\r\n pass\r\n\r\n\r\npath = \"/home/nw/Desktop/OpenCV_in_Ubuntu/Data/Lane_Detection_Images/\"\r\nroadImage_01 = \"solidWhiteCurve.jpg\"\r\nroadImage_02 = \"solidWhiteRight.jpg\"\r\nroadImage_03 = \"solidYellowCurve.jpg\"\r\nroadImage_04 = \"solidYellowCurve2.jpg\"\r\nroadImage_05 = \"solidYellowLeft.jpg\"\r\nroadImage_06 = \"whiteCarLaneSwitch.jpg\"\r\n\r\nopenPath = path+roadImage_01\r\n\r\nimg = imageRead(openPath, cv2.IMREAD_COLOR)\r\nbackup = imageCopy(img)\r\ncv2.namedWindow('image', cv2.WINDOW_GUI_EXPANDED)\r\n\r\ncv2.createTrackbar('BlurSize', 'image', 0, 10, nothing)\r\ncv2.createTrackbar('sigmaX', 'image', 0, 50, nothing)\r\ncv2.createTrackbar('sigmaY', 'image', 0, 50, nothing)\r\n\r\nswitch = '0:Mean\\n1:Gaussian'\r\ncv2.createTrackbar(switch, 'image', 0, 1, nothing)\r\n\r\nwhile True:\r\n cv2.imshow('image', img)\r\n\r\n if cv2.waitKey(1) & 0xFF == 27:\r\n break\r\n size = cv2.getTrackbarPos('BlurSize', 'image')\r\n sigmaX = cv2.getTrackbarPos('sigmaX', 'image')\r\n sigmaY = cv2.getTrackbarPos('sigmaY', 'image')\r\n s = cv2.getTrackbarPos(switch, 'image')\r\n if s == 0:\r\n img = imageBlur(backup, size)\r\n else:\r\n img = imageGaussianBlur(backup, size, sigmaX, sigmaY)\r\n \r\n\r\ncv2.destroyAllWindows()\r\n","sub_path":"courses/w10_opencv/source/OpenCV_in_Ubuntu/Python/1st_08H/28_Image_Mean_Filter.py","file_name":"28_Image_Mean_Filter.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"398092782","text":"from PIL import Image\r\nimport telebot\r\nimport os\r\nimport io\r\nimport random as rand\r\nfrom flask import Flask, request\r\nimport consoleweather.weather as cw\r\nimport crypt as c\r\n\r\ntoken = \"556161272:AAFoP3abycmprZXz3NpjfwRuZ6PVwelkLpw\"\r\n\r\nbot = telebot.TeleBot(token)\r\n\r\nserver = Flask(__name__)\r\n\r\n@bot.message_handler(commands=['start'])\r\ndef send_welcome(message):\r\n print(message.from_user.first_name)\r\n bot.send_message(message.chat.id, \"привет, ̶м̶и̶р̶ \" + message.from_user.first_name)\r\n\r\n@bot.message_handler(commands=['help'])\r\ndef send_welcome(message):\r\n bot.send_message(message.chat.id, \"\"\"\r\n /start - start\r\n /help - help\r\n /roll - random\r\n /weather - погода\r\n /crypt - зашифровать текст\r\n /uncrypt - расшифровать текст\r\n /me [текст сообщения] - сообщение от третего лица (группа)\r\n /daltonic - daltonic\r\n \"\"\")\r\n\r\n\r\n@bot.message_handler(commands=['roll'])\r\ndef send_roll(message):\r\n roll = rand.randint(0,100)\r\n bot.send_message(message.chat.id, roll)\r\n\r\n@bot.message_handler(commands=['weather'])\r\ndef send_weather(message):\r\n bot.send_message(message.chat.id,\"`\" + cw.get_weather() + \"`\", parse_mode='Markdown')\r\n\r\n@bot.message_handler(commands=['crypt'])\r\ndef send_crypt(message):\r\n #print(message.text)\r\n msg = bot.send_message(message.chat.id, \"отправьте текст\")\r\n bot.register_next_step_handler(msg, crypt_text)\r\n\r\ndef crypt_text(message):\r\n try:\r\n bot.reply_to(message, c.crypt(message.text))\r\n except Exception as e:\r\n bot.send_message(message.chat.id, \"ваш текст не текст\")\r\n\r\n\r\n@bot.message_handler(commands=['uncrypt'])\r\ndef send_uncrypt(message):\r\n #print(message.text)\r\n msg = bot.send_message(message.chat.id, \"отправьте зашифрованный текст\")\r\n bot.register_next_step_handler(msg, uncrypt_text)\r\n\r\ndef uncrypt_text(message):\r\n try:\r\n bot.reply_to(message, c.uncrypt(message.text))\r\n except Exception as e:\r\n bot.send_message(message.chat.id, \"ваш текст не текст\")\r\n\r\n\r\n@bot.message_handler(commands=['me'])\r\ndef send_me(message):\r\n #bot.send_chat_action(message.chat.id, 'typing')\r\n bot.send_message(message.chat.id,\r\n \"_\" + message.from_user.first_name + \" \" + message.text.replace(\"/me\",\"\") + \"_\",\r\n parse_mode='Markdown')\r\n if message.chat.type == \"group\":\r\n bot.delete_message(message.chat.id, message.message_id)\r\n\r\n\r\n@bot.message_handler(commands=['daltonic'])\r\ndef send_daltonic(message):\r\n msg = bot.send_message(message.chat.id, \"отправьте фото\")\r\n bot.register_next_step_handler(msg, daltonic)\r\n pass\r\n\r\ndef daltonic(message):\r\n try:\r\n fileID = message.photo[-1].file_id\r\n file = bot.get_file(fileID)\r\n except:\r\n bot.send_message(message.chat.id, \"ваше фото не фото\")\r\n return\r\n\r\n downloaded_file = bot.download_file(file.file_path)\r\n\r\n im = Image.open(io.BytesIO(downloaded_file))\r\n r, g, b = im.split()\r\n im = Image.merge(\"RGB\", (r, r, b))\r\n\r\n imgByteArr = io.BytesIO()\r\n im.save(imgByteArr, format='PNG')\r\n imgByteArr = imgByteArr.getvalue()\r\n\r\n bot.send_photo(message.chat.id, imgByteArr)\r\n\r\n\r\n@bot.message_handler(func=lambda message: True)\r\ndef echo_all(message):\r\n print(message)\r\n bot.reply_to(message, message.text)\r\n\r\n@server.route('/' + token, methods=['POST'])\r\ndef getMessage():\r\n bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode(\"utf-8\"))])\r\n return \"!\", 200\r\n\r\n\r\n@server.route(\"/\")\r\ndef webhook():\r\n bot.remove_webhook()\r\n bot.set_webhook(url='https://bakatestapp.herokuapp.com/' + token)\r\n return \"!\", 200\r\n\r\n\r\nif __name__ == \"__main__\":\r\n server.run(host=\"0.0.0.0\", port=int(os.environ.get('PORT', 5000)))\r\n pass\r\n\r\n#bot.remove_webhook()\r\n#bot.polling()\r\n","sub_path":"bakascript.py","file_name":"bakascript.py","file_ext":"py","file_size_in_byte":3955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"401779707","text":"#!/usr/bin/env python\n\nfrom gi.repository import Gtk\n\ndef checkbutton_toggled(checkbutton):\n print(checkbutton.get_label(), \"toggled %s\" % (\"off\", \"on\")[checkbutton.get_active()])\n\nwindow = Gtk.Window()\nwindow.connect(\"destroy\", lambda q: Gtk.main_quit())\n\nvbox = Gtk.VBox(homogeneous=True, spacing=5)\nwindow.add(vbox)\n\ncheckbutton = Gtk.CheckButton(label=\"Check Button 1\")\ncheckbutton.set_active(True)\ncheckbutton.connect(\"toggled\", checkbutton_toggled)\nvbox.pack_start(checkbutton, False, False, 0)\ncheckbutton = Gtk.CheckButton(label=\"Check Button 2\")\ncheckbutton.connect(\"toggled\", checkbutton_toggled)\nvbox.pack_start(checkbutton, False, False, 0)\ncheckbutton = Gtk.CheckButton(label=\"Check Button 3\")\ncheckbutton.connect(\"toggled\", checkbutton_toggled)\nvbox.pack_start(checkbutton, False, False, 0)\n\nwindow.show_all()\n\nGtk.main()\n","sub_path":"gtk3/learngtk/checkbutton.py","file_name":"checkbutton.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"403227433","text":"# %%\nimport csv\nimport json\nimport pandas as pd\n\n# %%\nf = open('src/data/supplementary_data/TAZ.json', 'r')\nbase_taz_regions = json.load(f)\nf.close()\n\n# %%\nincome_df = pd.read_excel('./data_input/3. Supplementary Data/5. Marginal_Income.xlsx')\nhousehold_df = pd.read_excel('./data_input/3. Supplementary Data/6. SE_File_v83_SE19_Net19.xlsx')\n\n\n# %%\ndef get_income_bracket_percent(income_bracket):\n if income_bracket[5] == 0:\n return 0, 0, 0, 0, 0, 0\n else:\n return income_bracket[0], \\\n round((income_bracket[1] / income_bracket[5]) * 100, 1), \\\n round((income_bracket[2] / income_bracket[5]) * 100, 1), \\\n round((income_bracket[3] / income_bracket[5]) * 100, 1), \\\n round((income_bracket[4] / income_bracket[5]) * 100, 1), \\\n round(income_bracket[5])\n \nfor feature in base_taz_regions['features']:\n taz = feature['properties']['N___CO_TAZ']\n taz_income_vals = income_df[income_df['CO_TAZID'] == taz].values[0]\n taz_income_vals = get_income_bracket_percent(taz_income_vals)\n taz_household_vals = household_df[household_df['CO_TAZID'] == taz].values[0]\n\n feature['properties']['inc_bracket1'] = taz_income_vals[1]\n feature['properties']['inc_bracket2'] = taz_income_vals[2]\n feature['properties']['inc_bracket3'] = taz_income_vals[3]\n feature['properties']['inc_bracket4'] = taz_income_vals[4]\n feature['properties']['total_households'] = taz_income_vals[5]\n\n feature['properties']['household_pop'] = taz_household_vals[2]\n feature['properties']['avg_size'] = taz_household_vals[3]\n feature['properties']['total_employment'] = taz_household_vals[4]\n\n\nbase_taz_regions_json = json.dumps(base_taz_regions)\nwith open('src/data/supplementary_data/taz_region_data.json', 'w') as f:\n f.write(base_taz_regions_json)","sub_path":"data_processing/combine_taz_data.py","file_name":"combine_taz_data.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"125298257","text":"import RPi.GPIO as GPIO\nimport time\n\nTRIG = 24\nECHO = 26\n\n\nGPIO.setmode(GPIO.BOARD)\nGPIO.setup(7, GPIO.OUT) # motor 1, forward, top right\nGPIO.setup(13, GPIO.OUT) # motor 2, forward, top left\nGPIO.setup(12, GPIO.OUT) # motor 3, forward, bottom right\nGPIO.setup(18, GPIO.OUT) # motor 4, forward, botton left\n\n\nGPIO.setup(TRIG, GPIO.OUT) # trigger voltage setup\n\nGPIO.setup(ECHO, GPIO.IN) # echo input setup\n\nGPIO.output(7, False) # set everything to false at startup\nGPIO.output(13, False)\nGPIO.output(12, False)\nGPIO.output(18, False)\n\nGPIO.output(TRIG, False)\n \ndef scan_for_obstacles():\n # tells the sensor to fire a burst of sound\n GPIO.output(TRIG, True)\n time.sleep(0.00001)\n GPIO.output(TRIG, False)\n\n while GPIO.input(ECHO) == 0:\n pass\n\n startTime = time.time()\n\n while GPIO.input(ECHO) == 1:\n pass\n\n stopTime = time.time()\n\n distance = (stopTime-startTime) * 17000\n\n return distance\n\n\nGPIO.output(7, True)\nGPIO.output(13, True)\nGPIO.output(12, True)\nGPIO.output(18, True)\n\ntry:\n while True:\n if scan_for_obstacles() <= 10:\n GPIO.output(7, False)\n GPIO.output(13, False)\n GPIO.output(12, False)\n GPIO.output(18, False)\n break\n\n else:\n continue\n\nfinally:\n GPIO.cleanup()\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"phase-2/phase-2-1_26_2018_single-direction.py","file_name":"phase-2-1_26_2018_single-direction.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"49539361","text":"#!/usr/bin/env python\n\n# this file is part of the github repository: https://github.com/nwhoppe/rosalind\n# author: nwhoppe\n# created: 9/3/18\n\nimport argparse\nimport sys\n\n\ndef intro_pattern_matching(input_txt):\n \"\"\"\n From the input dna sequences, an adjacency dictionary is made corresponding the the underlying trie\n representing the sequences. For now, the trie is not explicitly made. Root node is 1. Unique dna bases at each\n position start a new child node. The edge is labeled with the nucleotide.\n\n Args:\n input_txt: text file containing one DNA sequence per line.\n each sequence is <= 100 nucleotides\n up to 100 sequences\n\n Returns:\n Adjacency dictionary corresponding to the trie representing the input sequences. Parent nodes are keys to\n the first level of the dictionary. Edge labels are the keys to the second level, and values at the second\n level are child nodes.\n\n Raises:\n IOError:\n 1. more than 100 sequences\n 2. more than 100 nucleotides in a sequence\n 3. sequence is not dna (must only have A, C, G, T)\n \"\"\"\n\n adjacency_dict = {1: {}}\n with open(input_txt, 'r') as f:\n dna_sequences = f.readlines()\n child_node = 2\n\n if len(dna_sequences) > 100:\n raise IOError(\"No more than 100 sequences can be given as input\\n\")\n\n for sequence in dna_sequences:\n sequence = sequence.rstrip().upper()\n if len(sequence) > 100:\n raise IOError(\"DNA sequences cannot be longer than 100 nucleotides\\n\")\n elif set(sequence) > set(\"ACGT\"):\n raise IOError(\"DNA sequences must only contain canonical nucleotides A, C, G, T\\n\")\n else:\n parent_node = 1\n for index, nucleotide in enumerate(sequence):\n if parent_node in adjacency_dict.keys() and nucleotide not in adjacency_dict[parent_node].keys():\n # add edge and child node to parent that has at least 1 child node\n adjacency_dict[parent_node][nucleotide] = child_node\n parent_node = child_node\n child_node += 1\n elif parent_node not in adjacency_dict.keys():\n # add edge and child node to leaf node\n adjacency_dict[parent_node] = {nucleotide: child_node}\n parent_node = child_node\n child_node += 1\n else:\n # parent, edge, and child already existed - set parent to existing child node\n parent_node = adjacency_dict[parent_node][nucleotide]\n\n return adjacency_dict\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"\"\"\"\"\")\n required = parser.add_argument_group('required')\n required.add_argument(\"-i\", \"--input_txt\", required=True,\n help=\"input txt with up to 100 dna sequences up to 100 nucleotides \"\n \"in length. one sequence per line\")\n args = parser.parse_args()\n output_dict = intro_pattern_matching(args.input_txt)\n for parent in output_dict.iterkeys():\n for edge_label, child in output_dict[parent].iteritems():\n sys.stdout.write(\"{0} {1} {2}\\n\".format(parent, child, edge_label))\n","sub_path":"intro_pattern_matching.py","file_name":"intro_pattern_matching.py","file_ext":"py","file_size_in_byte":3304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"212506873","text":"\nimport matplotlib.pyplot as plt\nplt.interactive(True)\nimport pandas as pd\nimport os\nimport re\n\n\n\nplt.close(\"all\") #Closes plots from previous run\n\n#######################################################\n#Settings for the SQUID data\nfilename_res='SmN-in-situ-150616-resistance-cleaned.txt' #Base name of files that need to be read\n\nfile_location='/home/feliciaullstad/Desktop/Google_Drive/PhD/SmN data/Varian/F19'\n#file_location='/Users/Felicia/Desktop/Google_Drive/PhD/SmN data/Varian/F24'\n\nSample_name='F19'\nComment='Whole growth'\n\n\nInf_res=10**35\n#trimstart=4\n#trimend=-16\n\n\n\n######################################################\nif not os.path.exists(file_location+'-python'): #Checks if the python folder exists\n os.makedirs(file_location+'-python') #If not, it makes it\n#######################################################\n\n\n\nRes_data_raw=pd.read_csv(file_location+'/'+filename_res, header=0, sep='\\t',skiprows=0)\nRes_data=Res_data_raw[Res_data_raw[\"Resistance (Ohm)\"] < Inf_res] # Fitlers away data with values under Inf_res\n\nfor column in Res_data:\n for item in Res_data[column]:\n if isinstance(item,str):\n item=float(item)\n elif isinstance(item,int):\n item=float(item)\nprint('Resistance data')\nprint(Res_data)\n\nxmin=26000\nxmax=190000\nfinal_res=5.5*10**5\n\nfig, ax1 = plt.subplots()\nax1.plot(Res_data[\"Time(s)\"],((Res_data[\"Resistance (Ohm)\"])),'.')\nax1.set_xlabel('Time (s)')\n#plt.xlim(xmin,xmax)\n#plt.ylim(1*10**6,3.5*10**6)\n#plt.ylim(0.8,1.9)\nax1.set_ylabel('Resistance (Ohm)', color='b')\n\"\"\"\nplt.annotate('Turbo fully off', xy=(42000, 2*10**6),\n xycoords='data',\n xytext=(42000, 2.1*10**6), arrowprops=dict(facecolor='black', shrink=0.5),\n horizontalalignment='center', verticalalignment='bottom',\n )\nplt.annotate('Venting with N2', xy=(184500, 2*10**6),\n xycoords='data',\n xytext=(184500, 1.8*10**6), arrowprops=dict(facecolor='black', shrink=0.5),\n horizontalalignment='right', verticalalignment='bottom',\n )\"\"\"\nplt.yscale('log', nonposy='clip')\n#plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))\nfor tl in ax1.get_yticklabels():\n tl.set_color('b')\n\nplt.title('In-situ measurements of '+Sample_name)\n\nax2 = ax1.twinx()\nax2.plot(Res_data[\"Time(s)\"],Res_data[\"Pressure (mbar)\"],'r.')\n#plt.xlim(xmin,xmax)\n#plt.ylim(10**-8,10**-3)\nax2.set_ylabel('Pressure (mbar)', color='r')\nplt.yscale('log', nonposy='clip')\nfor tl in ax2.get_yticklabels():\n tl.set_color('r')\nplt.show()\n\"\"\"\nfig1=plt.figure()\nax=fig1.add_subplot(211)\nplot1=plt.plot(Res_data[\"Time(s)\"],Res_data[\"Resistance (Ohm)\"],'.')\nplt.xlim(xmin,xmax)\nplt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))\nplt.ylim(3*10**6,5*10**7)\n\nplt.annotate('Valve opened', xy=(84983, 5*10**6),\n xycoords='data',\n xytext=(84983, 7*10**6), arrowprops=dict(facecolor='black', shrink=0.5),\n horizontalalignment='right', verticalalignment='bottom',\n )\n\nplt.annotate('Valve more opened', xy=(85141, 8*10**6),\n xycoords='data',\n xytext=(85141, 5*10**6), arrowprops=dict(facecolor='black', shrink=0.5),\n horizontalalignment='left', verticalalignment='bottom',\n )\n\nplt.yscale('log', nonposy='clip')\nplt.xlabel('Time (s)')\nplt.ylabel('Resistance (Ohm)')\nplt.title('In-situ measurements of '+Sample_name)\n#plt.title('Resistance vs time for F21')\nplt.subplot(212)\nplot2=plt.plot(Res_data[\"Time(s)\"],Res_data[\"Pressure (mbar)\"],'r.')\nplt.xlim(xmin,xmax)\nplt.ylim(10**-4,10**4)\n#plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))\nplt.yscale('log', nonposy='clip')\nplt.xlabel('Time (s)')\nplt.ylabel('Pressure (mbar)')\n#plt.title('Pressure vs time for F21')\n\nplt.annotate('Pressure gauge max', xy=(73610, 0.9*10**3),\n xycoords='data',\n xytext=(73610, 10**1.7), arrowprops=dict(facecolor='black', shrink=0.5),\n horizontalalignment='left', verticalalignment='bottom',\n )\n\n\"\"\"\nsave_location=file_location+'-python/'+Sample_name+'_'+Comment+'_plot_Resistance_vs_time.pdf'\nplot1=plt.savefig(save_location, format='pdf', dpi=1200)\n","sub_path":"Varian-pressure-resistance-same-graph-F19.py","file_name":"Varian-pressure-resistance-same-graph-F19.py","file_ext":"py","file_size_in_byte":4189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"310265925","text":"# Traits functions for Revolution Mod\n#\n# by jdog5000\n# Version 1.5\n\nfrom CvPythonExtensions import *\n\nGC = CyGlobalContext()\n\n########################## Traits effect helper functions #####################\n\ndef getTraitsRevIdxLocal(iPlayer):\n\tpPlayer = GC.getPlayer(iPlayer)\n\n\tif pPlayer is None or not pPlayer.getNumCities():\n\t\treturn [0, [], []]\n\n\tlocalRevIdx = 0\n\tposList = []\n\tnegList = []\n\n\tfor i in range(GC.getNumTraitInfos()):\n\t\tif pPlayer.hasTrait(i):\n\t\t\tkTrait = GC.getTraitInfo(i)\n\t\t\ttraitEffect = kTrait.getRevIdxLocal()\n\t\t\tif traitEffect > 0:\n\t\t\t\tnegList.append((traitEffect, kTrait.getDescription()))\n\t\t\telif traitEffect < 0:\n\t\t\t\tposList.append((traitEffect, kTrait.getDescription()))\n\n\t\t\tlocalRevIdx += traitEffect\n\n\treturn [localRevIdx, posList, negList]\n\n\ndef getTraitsCivStabilityIndex(iPlayer):\n\tpPlayer = GC.getPlayer(iPlayer)\n\n\tcivStabilityIdx = 0\n\tposList = list()\n\tnegList = list()\n\n\tif pPlayer is None:\n\t\treturn [civStabilityIdx, posList, negList]\n\n\tfor iTrait in range(GC.getNumTraitInfos()):\n\t\tkTrait = GC.getTraitInfo(iTrait)\n\t\ttraitEffect = -kTrait.getRevIdxNational()\n\n\t\tif pPlayer.hasTrait(iTrait):\n\t\t\tif traitEffect > 0:\n\t\t\t\tposList.append((traitEffect, kTrait.getDescription()))\n\t\t\telif traitEffect < 0:\n\t\t\t\tnegList.append((traitEffect, kTrait.getDescription()))\n\n\t\t\tcivStabilityIdx += traitEffect\n\n\treturn [civStabilityIdx, posList, negList]\n\n\ndef getTraitsHolyCityEffects(iPlayer):\n\n\tpPlayer = GC.getPlayer(iPlayer)\n\n\tif pPlayer is None or not pPlayer.getNumCities():\n\t\treturn [0, 0]\n\n\tgoodEffect = 0\n\tbadEffect = 0\n\n\tfor i in range(GC.getNumTraitInfos()):\n\t\tif pPlayer.hasTrait(i):\n\t\t\tkTrait = GC.getTraitInfo(i)\n\t\t\tgoodEffect += kTrait.getRevIdxHolyCityGood()\n\t\t\tbadEffect += kTrait.getRevIdxHolyCityBad()\n\n\treturn [goodEffect, badEffect]\n\n\ndef getTraitsNationalityMod(iPlayer):\n\n\tpPlayer = GC.getPlayer(iPlayer)\n\n\tif pPlayer is None or not pPlayer.getNumCities():\n\t\treturn 0\n\n\tnatMod = 0\n\n\tfor i in range(GC.getNumTraitInfos()):\n\t\tif pPlayer.hasTrait(i):\n\t\t\tnatMod += GC.getTraitInfo(i).getRevIdxNationalityMod()\n\n\treturn natMod\n\n\ndef getTraitsReligionMods(iPlayer):\n\n\tpPlayer = GC.getPlayer(iPlayer)\n\n\tif pPlayer is None or not pPlayer.getNumCities():\n\t\treturn [0,0]\n\n\tgoodMod = 0\n\tbadMod = 0\n\n\tfor i in range(GC.getNumTraitInfos()):\n\t\tif pPlayer.hasTrait(i):\n\t\t\tkTrait = GC.getTraitInfo(i)\n\t\t\tgoodMod += kTrait.getRevIdxGoodReligionMod()\n\t\t\tbadMod += kTrait.getRevIdxBadReligionMod()\n\n\treturn [goodMod, badMod]\n\n\ndef getTraitsDistanceMod( iPlayer ) :\n\n\tpPlayer = GC.getPlayer(iPlayer)\n\n\tif pPlayer is None or not pPlayer.getNumCities():\n\t\treturn 0\n\n\tdistModifier = 0\n\n\tfor i in range(GC.getNumTraitInfos()):\n\t\tif pPlayer.hasTrait(i):\n\t\t\tdistModifier += GC.getTraitInfo(i).getRevIdxDistanceModifier()\n\n\treturn distModifier\n","sub_path":"Assets/Python/Revolution/RevTraitsUtils.py","file_name":"RevTraitsUtils.py","file_ext":"py","file_size_in_byte":2762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"111975598","text":"from PIL import Image\nimport os\nimport argparse\n\n\ndef convert(img_path: \"Image Path\"):\n \"\"\"\n Function converts png images to jpg and saves it at the same location\n as that of the original image.\n Takes image path as input.\n \"\"\"\n if not os.path.isfile(img_path):\n raise ValueError('No such image file exists.')\n elif img_path.split('.')[-1] != 'png':\n raise ValueError('Image is not a png file..')\n\n new_path = img_path.split(\".\"+img_path.split('.')[-1])[0]+'.jpg'\n img = Image.open(img_path).convert('RGB')\n img.save(new_path, 'jpeg')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='png to jpg conversion')\n parser.add_argument('-ip', '--image_path', type=str, required=True, help='path of the source image')\n\n args = parser.parse_args()\n convert(args.image_path)","sub_path":"image_utils/pngtojpg.py","file_name":"pngtojpg.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"419479553","text":"'''\nSimple script to parse command line arguments load inflection dict\nand create qualia structure.\n'''\nimport argparse\nfrom pathlib import Path\n\nimport jsonpickle\n\nfrom src.requester import AllKeysReachLimit\nfrom src.qualia_structure import WordNotSupportedError, CreationStrategy, DebugQualiaStructure, \\\n QualiaStructure, debug_to_normal_structure\n\nGOOGLE_FL = ['g', 'google']\nBERT_FL = ['b', 'bert']\nMODIFIED_BERT_FL = ['mb', 'modifiedBert']\nCREATION_FLAG = 'creation'\nDEBUG_FLAG = 'debug'\nFILE_FLAG = 'writeToFile'\nWORDS = 'words'\nINPUT_FILE_FLAG = 'inputFile'\nOUTPUT_FLAG = 'output'\nTOP_K_FLAG = 'topK'\nMETRIC_FLAG = 'metric'\nKEYS_FLAG = 'keys'\nINFLECTION_DICT_FLAG = 'inflectionDict'\nMETRIC_CHOICES = ['webP', 'webJac', 'webPMI', 'occurrenceInPattern', 'numOfSources']\n\nPARSER = argparse.ArgumentParser(description='Generate qualia structure for given words')\nPARSER.add_argument(WORDS, metavar='W', type=str, nargs='*', default=[],\n help='Qualia theorems')\nPARSER.add_argument('-c', '--creation', type=str, default='google',\n choices=GOOGLE_FL + BERT_FL + MODIFIED_BERT_FL,\n help='Creation strategy'\n .format(BERT_FL, MODIFIED_BERT_FL, GOOGLE_FL))\n\nPARSER.add_argument('-i', '--{}'.format(INPUT_FILE_FLAG), type=str, default=None,\n help='Input file with line separated qualia theorems')\nPARSER.add_argument('-w', '--{}'.format(FILE_FLAG), action='store_true',\n help='Write output to file')\nPARSER.add_argument('-o', '--{}'.format(OUTPUT_FLAG), type=str, default='results',\n help='Output directory for created structures')\nPARSER.add_argument('-d', '--debug', action='store_true',\n help='Print or write additional debug structure with more '\n 'information\\'s like metric value and source of extracted element')\nPARSER.add_argument('-t', '--{}'.format(TOP_K_FLAG), type=int, default=8,\n help='Maximal length of qualia roles')\nPARSER.add_argument('--{}'.format(INFLECTION_DICT_FLAG), type=str, default='inflectionDict',\n help='Filepath of lookup table for words which are not inflectable '\n 'by pyinflect')\nPARSER.add_argument('-m', '--{}'.format(METRIC_FLAG), type=str, choices=METRIC_CHOICES,\n default='numOfSources', help='Metric to rank qualia elements')\nPARSER.add_argument('-k', '--{}'.format(KEYS_FLAG), type=str, default='apiKeys',\n help='File with api keys')\n\n\ndef print_or_write_json_to_file(qs_json_str: str, qualia_theorem: str, debug_mode: bool):\n '''\n Print or write json of created qualia structure to file.\n :param qs_json_str: json string of created qualia structure\n :param qualia_theorem: qualia theorem of created structure\n :param debug_mode: true if is json of debug structure else false\n :return: None\n '''\n if write_to_file:\n if creation_arg in BERT_FL:\n model_name = BERT_FL[1]\n elif creation_arg in MODIFIED_BERT_FL:\n model_name = MODIFIED_BERT_FL[1]\n else:\n model_name = GOOGLE_FL[1]\n\n file_path = '{}/{}_{}{}{}.qs'.format(result_path, qualia_theorem, model_name,\n '_' + args[METRIC_FLAG] if model_name\n in GOOGLE_FL else ''\n , '_' + DEBUG_FLAG if debug_mode else '')\n with open(Path(file_path), 'w') as text_file:\n text_file.write(qs_json_str)\n else:\n print(qs_json_str)\n\n\ndef get_creation_strategy() -> CreationStrategy:\n '''\n Load creation strategy which is passed by creation argument.\n :return: None\n '''\n if creation_arg in BERT_FL:\n\n from src.bert_strategy import BertStrategy\n\n return BertStrategy(inflection_dict)\n elif creation_arg in MODIFIED_BERT_FL:\n\n from src.bert_strategy import AdvBertStrategy\n\n return AdvBertStrategy(inflection_dict)\n else:\n\n from src.qualia_structure import SearchEngineStrategy\n from src.requester import GoogleRequester, read_key_file\n from src.metrics import WebP, WebJac, WebPMI, NumberOfSources, OccurrenceInRequests\n\n keys = read_key_file(Path(args[KEYS_FLAG]))\n\n requester = GoogleRequester(keys)\n\n if args[METRIC_FLAG] == METRIC_CHOICES[0]:\n metric = WebP(requester)\n elif args[METRIC_FLAG] == METRIC_CHOICES[1]:\n metric = WebJac(requester)\n elif args[METRIC_FLAG] == METRIC_CHOICES[2]:\n metric = WebPMI(requester)\n elif args[METRIC_FLAG] == METRIC_CHOICES[3]:\n metric = OccurrenceInRequests()\n else:\n metric = NumberOfSources()\n\n return SearchEngineStrategy(inflection_dict, requester=requester, metric=metric)\n\n\ndef load_inflection_dict() -> dict:\n '''\n Load inflection dict from filepath passed by argument --inflectionDict.\n :return: None\n '''\n inf_dict = {}\n\n if Path(args[INFLECTION_DICT_FLAG]).exists():\n with open(args[INFLECTION_DICT_FLAG]) as inf_file:\n inf_dict = {line.split()[0]: line.split()[1] for line in inf_file.read().splitlines()\n if\n line and not line.startswith('#')}\n\n return inf_dict\n\n\ndef get_qualia_theorems() -> [str]:\n '''\n Load qualia theorems for file passed by -i arg and directly as positional\n args.\n :return: list of qualia theorems\n '''\n qualia_theorems = []\n\n if args[WORDS] is not None:\n qualia_theorems += args[WORDS]\n\n input_file = args[INPUT_FILE_FLAG]\n\n if input_file is not None:\n with open(input_file) as file:\n qualia_theorems += [line for line in file.read().splitlines() if\n line and not line.startswith('#')]\n\n return qualia_theorems\n\n\nif __name__ == '__main__':\n args = vars(PARSER.parse_args())\n\n result_path = args[OUTPUT_FLAG]\n\n Path(result_path).mkdir(parents=True, exist_ok=True)\n\n creation_arg = args[CREATION_FLAG]\n is_debug_mode = args[DEBUG_FLAG]\n write_to_file = args[FILE_FLAG]\n\n inflection_dict = load_inflection_dict()\n creation_strategy = get_creation_strategy()\n assert isinstance(creation_strategy, CreationStrategy)\n\n for qt in get_qualia_theorems():\n try:\n debug_qualia_structure = creation_strategy.generate_qualia_structure(qt)\n assert isinstance(debug_qualia_structure, DebugQualiaStructure)\n if is_debug_mode:\n json_str = jsonpickle.encode(debug_qualia_structure, indent=4, unpicklable=True)\n print_or_write_json_to_file(json_str, qt, True)\n\n qualia_structure = debug_to_normal_structure(debug_qualia_structure, args[TOP_K_FLAG])\n assert isinstance(qualia_structure, QualiaStructure)\n json_str = jsonpickle.encode(qualia_structure, indent=4, unpicklable=True)\n print_or_write_json_to_file(json_str, qt, False)\n\n except AllKeysReachLimit:\n print('Qualia Structure of {} failed, because '\n 'the maximal requests of all keys is reached'.format(qt))\n except WordNotSupportedError as word_not_supported_error:\n print(word_not_supported_error)\n","sub_path":"qualia_generator.py","file_name":"qualia_generator.py","file_ext":"py","file_size_in_byte":7385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"234863747","text":"__author__ = 'tian'\nimport scrapy\nfrom four.items import FourItem\nimport four.items\nimport re\nimport requests\nimport four.settings\nfrom four.settings import LOCATION\nfrom four.textEdit import *\n\nclass FortythreeSpider(scrapy.Spider):\n name = 'fortythree'\n\n def start_requests(self):\n urls = ['http://www.cae.cn/cae/html/main/col25/column_25_2.html','http://www.cae.cn/cae/html/main/col25/column_25_1.html']\n for url in urls:\n yield scrapy.Request(url=url, callback=self.parse_url,meta={'url':url})\n\n # def start_requests(self):\n # yield scrapy.Request(url='http://www.sasac.gov.cn/n2588035/n2588320/n2588335/c8470777/content.html',callback=self.parse)\n\n\n\n\n def parse_url(self, response):\n lis = response.xpath('//*[@class=\"right_md_list\"]/ul//li')\n for li in lis:\n if li.xpath('./a/@href'):\n href = li.xpath('./a/@href').extract_first()\n href = response.urljoin(href)\n print('href:%s'%href)\n yield scrapy.Request(url=href, callback=self.parse,meta={'url':href})\n\n\n def parse(self, response):\n title = response.xpath('//*[@name=\"ArticleTitle\"]/@content').extract_first()\n print(title)\n publishDate = response.xpath('//*[@name=\"PubData\"]/@content').extract_first()\n print(publishDate)\n source = response.xpath('//*[@name=\"ContentSource\"]/@content').extract_first()\n print(source)\n\n te = textEdit()\n text,files = te.dealWithAll(response,id=\"zoom\")\n print('text:%s'%text)\n print('file:%s'%files)\n item_fortythree = four.items.fillinData(title,'','','','','','','','','','','','',text,files,publishDate,source)\n yield item_fortythree\n\n\n\n\n\n\n\n\n\n\n","sub_path":"four/four/spiders/fortythree.py","file_name":"fortythree.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"484987561","text":"\"\"\"\r\neasy 2021-09-07 同向双指针(逆序归并)\r\nhttps://leetcode-cn.com/problems/merge-sorted-array/solution/hua-jie-suan-fa-88-he-bing-liang-ge-you-xu-shu-zu-/\r\n难死了 easy个锤子\r\n思路:\r\n- 标签:从后向前数组遍历\r\n- 因为 nums1 的空间都集中在后面,所以从后向前处理排序的数据会更好,节省空间,一边遍历一边将值填充进去\r\n- 设置指针 len1 和 len2 分别指向 nums1 和 nums2 的有数字尾部,从尾部值开始比较遍历,同时设置指针 len 指向 nums1 的最末尾,每次遍历比较值大小之后,则进行填充\r\n- 当 len1<0 时遍历结束,此时 nums2 中还有数据未拷贝完全,将其直接拷贝到 nums1 的前面,最后得到结果数组\r\n- 时间复杂度:O(m+n)\r\n\"\"\"\r\n\r\n\"\"\"\r\neasy 2022-03-02 三指针(从后向前数组遍历)\r\n因为 nums1 的空间都集中在后面,所以从后向前处理排序的数据会更好,节省空间,一边遍历一边将值填充进去\r\n\"\"\"\r\nclass Solution(object):\r\n def merge(self, nums1, m, nums2, n):\r\n lens1=m-1\r\n lens2=n-1\r\n len=m+n-1\r\n while lens1>=0 and lens2>=0:\r\n if nums1[lens1]>=nums2[lens2]:\r\n nums1[len]=nums1[lens1]\r\n lens1-=1\r\n else:\r\n nums1[len]=nums2[lens2]\r\n lens2-=1\r\n len -= 1\r\n # while lens1>=0:\r\n # nums1[len]=nums1[lens1]\r\n # len-=1\r\n # lens1-=1\r\n while lens2>=0:\r\n nums1[len]=nums2[lens2]\r\n len-=1\r\n lens2-=1\r\n return nums1\r\n\r\n# 2022-01-04 逆序的归并,这次理解了很多\r\nclass Solution:\r\n def merge(self, nums1, m, nums2, n):\r\n p, q = m-1, n-1\r\n last = m+n-1\r\n while p>=0 and q>=0:\r\n if nums1[p] > nums2[q]:\r\n nums1[last] = nums1[p]\r\n p -= 1\r\n last -= 1\r\n else:\r\n nums1[last] = nums2[q]\r\n q -= 1\r\n last -= 1\r\n\r\n # 如果p的元素一直比q大的话,nums1先结束。nums2还没有遍历完成。\r\n # 直接将nums2的元素放在nums1之前\r\n res = nums2[:q+1]+nums1 # 这里不是特别理解\r\n return res[:m+n]\r\n\r\n\r\nif __name__ == '__main__':\r\n nums1 = [0] #[1,2,3,0,0,0]\r\n m = 0#3\r\n nums2 = [1]#[2,5,6]\r\n n = 1#3\r\n print(Solution().merge(nums1, m, nums2, n))\r\n","sub_path":"02_双指针/88-合并两个有序数组.py","file_name":"88-合并两个有序数组.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"525404588","text":"import numpy as np\nimport cv2\n\n# 1.加载图片,转为二值图\nimg = cv2.imread(r'D:\\OpenCV\\1\\10.png')\ndrawing = np.zeros(img.shape[:], dtype=np.uint8)\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nedges = cv2.Canny(gray, 50, 150)\n\n\n# 3.统计概率霍夫线变换\nlines = cv2.HoughLinesP(edges, 0.8, np.pi / 180, 90, minLineLength=550, maxLineGap=8)\n\n# 3.将检测的线画出来\nfor line in lines:\n x1, y1, x2, y2 = line[0]\n cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 1)\n\n\ncv2.namedWindow(\"Image\")\ncv2.imshow(\"Image\", img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"霍夫变换直线检测.py","file_name":"霍夫变换直线检测.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"377117347","text":"from django.shortcuts import render, redirect, get_object_or_404\n\nfrom .forms import (\n FormVacuna,FormVitamina,FormMedicina,\n FormFichaMedicina,FormFichaVitamina,FormFichaVacuna\n)\nfrom .models import (\n\t\tVacuna, Vitamina, Medicina,\n\t\tFichaVet, FichaMedicina,\n\t\tFichaVitamina, FichaVacuna\n)\n\n# Create your views here.\n\ndef index_medicinas(request):\n\tallmedicinas = Medicina.objects.all()\n\tif request.method == 'POST':\n\t\tmedicina = FormMedicina(request.POST)\n\t\tif medicina.is_valid():\n\t\t\tmedicina = medicina.save()\n\t\t\treturn redirect('index_medicinas')\n\telse:\n\t\tmedicina = FormMedicina()\n\t\tcontext = {'medicinas':allmedicinas,\n\t\t\t\t\t'form':medicina}\n\treturn render(request,'farmacos/index_medicinas.html',context)\n\ndef editar_medicina(request, pk):\n\tmedicina = get_object_or_404(Medicina,pk=pk)\n\ttemplate = 'farmacos/Registrar.html'\n\tif request.method == 'POST':\n\t\tform = FormMedicina(request.POST, instance=medicina)\n\t\tif form.is_valid():\n\t\t\tmedicina = form.save()\n\t\t\treturn redirect('index_medicinas')\n\telse:\n\t\tform = FormMedicina(instance = medicina)\n\tcontext = {'form':form}\n\treturn render(request, template, context)\n\ndef eliminar_medicina(request, pk):\n\tmedicina = get_object_or_404(Medicina,pk=pk)\n\tmedicina.delete()\n\treturn redirect('index_medicinas')\n\ndef visualizar_medicina(request, pk):\n\tmedicina = get_object_or_404(Medicina,pk=pk)\n\ttemplate = 'farmacos/visualizacion.html'\n\tficha_medicina = FichaMedicina.objects.filter(medicina=medicina.pk)\n\tcontext = {'medicina':medicina,\n\t\t\t'ficha_medicina':ficha_medicina}\n\treturn render(request, template, context)\n\n\ndef index_vitaminas(request):\n\tallvitaminas = Vitamina.objects.all()\n\tif request.method == 'POST':\n\t\tvitamina = FormVitamina(request.POST)\n\t\tif vitamina.is_valid():\n\t\t\tvitamina = vitamina.save()\n\t\t\treturn redirect('index_vitaminas')\n\telse:\n\t\tvitamina = FormVitamina()\n\t\tcontext = {'vitaminas':allvitaminas,\n\t\t\t\t\t'form':vitamina}\n\treturn render(request,'farmacos/index_vitaminas.html',context)\n\n\ndef editar_vitamina(request,pk):\n\tvitamina = get_object_or_404(Vitamina,pk=pk)\n\ttemplate = 'farmacos/Registrar.html'\n\tif request.method == 'POST':\n\t\tform = FormVitamina(request.POST, instance=vitamina)\n\t\tif form.is_valid():\n\t\t\tvitamina = form.save()\n\t\t\treturn redirect('index_vitaminas')\n\telse:\n\t\tform = FormVitamina(instance = vitamina)\n\tcontext = {'form':form}\n\treturn render(request, template, context)\n\ndef eliminar_vitamina(request,pk):\n\tvitamina = get_object_or_404(Vitamina,pk=pk)\n\tvitamina.delete()\n\treturn redirect('index_vitaminas')\n\ndef visualizar_vitamina(request,pk):\n\tvitamina = get_object_or_404(Vitamina,pk=pk)\n\ttemplate = 'farmacos/visualizacion.html'\n\tficha_vitamina = FichaVitamina.objects.filter(vitamina=vitamina.pk)\n\tcontext = {'vitamina':vitamina,\n\t\t\t'ficha_vitamina':ficha_vitamina}\n\treturn render(request, template, context)\n\n\ndef index_vacunas(request):\n\tallvacunas = Vacuna.objects.all()\n\tif request.method == 'POST':\n\t\tvacuna = FormVacuna(request.POST)\n\t\tif vacuna.is_valid():\n\t\t\tvacuna = vacuna.save()\n\t\t\treturn redirect('index_vacunas')\n\telse:\n\t\tvacuna = FormVacuna()\n\t\tcontext = {'vacunas':allvacunas,\n\t\t\t\t\t'form':vacuna}\n\treturn render(request,'farmacos/index_vacunas.html',context)\n\n\ndef editar_vacuna(request,pk):\n\tvacuna = get_object_or_404(Vacuna,pk=pk)\n\ttemplate = 'farmacos/Registrar.html'\n\tif request.method == 'POST':\n\t\tform = FormVacuna(request.POST, instance=vacuna)\n\t\tif form.is_valid():\n\t\t\tvacuna = form.save()\n\t\t\treturn redirect('index_vacunas')\n\telse:\n\t\tform = FormVacuna(instance = vacuna)\n\tcontext = {'form':form}\n\treturn render(request, template, context)\n\ndef eliminar_vacuna(request,pk):\n\tvacuna = get_object_or_404(Vacuna,pk=pk)\n\tvacuna.delete()\n\treturn redirect('index_vacunas')\n\ndef visualizar_vacuna(request,pk):\n\tvacuna = get_object_or_404(Vacuna,pk=pk)\n\ttemplate = 'farmacos/visualizacion.html'\n\tficha_vacuna = FichaVacuna.objects.filter(vacuna=vacuna.pk)\n\tcontext = {'vacuna':vacuna,\n\t\t\t'ficha_vacuna':ficha_vacuna}\n\treturn render(request, template, context)\n##################################################\n\ndef index_ficha_medicina(request):\n\tallficha_medicina = FichaMedicina.objects.all()\n\tif request.method == 'POST':\n\t\tficha_medicina = FormFichaMedicina(request.POST)\n\t\tif ficha_medicina.is_valid():\n\t\t\tficha_medicina = ficha_medicina.save()\n\t\t\treturn redirect('index_ficha_medicina')\n\telse:\n\t\tficha_medicina = FormFichaMedicina()\n\t\tcontext = {'ficha_medicina':allficha_medicina,\n\t\t\t\t\t'form':ficha_medicina}\n\treturn render(request,'fichas/index_ficha_medicina.html',context)\n\ndef editar_ficha_medicina(request, pk):\n\tficha_medicina = get_object_or_404(FichaMedicina,pk=pk)\n\ttemplate = 'farmacos/Registrar.html'\n\tif request.method == 'POST':\n\t\tform = FormFichaMedicina(request.POST, instance=ficha_medicina)\n\t\tif form.is_valid():\n\t\t\tficha_medicina = form.save()\n\t\t\treturn redirect('index_ficha_medicina')\n\telse:\n\t\tform = FormFichaMedicina(instance = ficha_medicina)\n\tcontext = {'form':form}\n\treturn render(request, template, context)\n\ndef eliminar_ficha_medicina(request, pk):\n\tficha_medicina = get_object_or_404(FichaMedicina,pk=pk)\n\tficha_medicina.delete()\n\treturn redirect('index_ficha_medicinas')\n\ndef visualizar_ficha_medicina(request, pk):\n\tficha_medicina = get_object_or_404(FichaMedicina,pk=pk)\n\ttemplate = 'farmacos/visualizacion.html'\n\t#ficha_medicina = FichaMedicina.objects.filter(medicina=medicina.pk)\n\tcontext = {'ficha_medicina':ficha_medicina}\n\treturn render(request, template, context)\n\n\ndef index_ficha_vitamina(request):\n\tallficha_vitaminas = FichaVitamina.objects.all()\n\tif request.method == 'POST':\n\t\tficha_vitamina = FormFichaVitamina(request.POST)\n\t\tif ficha_vitamina.is_valid():\n\t\t\tficha_vitamina = ficha_vitamina.save()\n\t\t\treturn redirect('index_ficha_vitamina')\n\telse:\n\t\tficha_vitamina = FormFichaVitamina()\n\t\tcontext = {'ficha_vitamina':allficha_vitaminas,\n\t\t\t\t\t'form':ficha_vitamina}\n\treturn render(request,'fichas/index_ficha_vitamina.html',context)\n\n\ndef editar_ficha_vitamina(request,pk):\n\tficha_vitamina = get_object_or_404(FichaVitamina,pk=pk)\n\ttemplate = 'farmacos/Registrar.html'\n\tif request.method == 'POST':\n\t\tform = FormFichaVitamina(request.POST, instance=ficha_vitamina)\n\t\tif form.is_valid():\n\t\t\tficha_vitamina = form.save()\n\t\t\treturn redirect('index_ficha_vitamina')\n\telse:\n\t\tform = FormFichaVitamina(instance = ficha_vitamina)\n\tcontext = {'form':form}\n\treturn render(request, template, context)\n\ndef eliminar_ficha_vitamina(request,pk):\n\tficha_vitamina = get_object_or_404(FichaVitamina,pk=pk)\n\tficha_vitamina.delete()\n\treturn redirect('index_ficha_vitamina')\n\ndef visualizar_ficha_vitamina(request,pk):\n\tficha_vitamina = get_object_or_404(FichaVitamina,pk=pk)\n\ttemplate = 'farmacos/visualizacion.html'\n\t#ficha_vitamina = FichaVitamina.objects.filter(vitamina=vitamina.pk)\n\t#context = {'vitamina':vitamina,\n\tcontext = {'ficha_vitamina':ficha_vitamina}\n\treturn render(request, template, context)\n\n\ndef index_ficha_vacuna(request):\n\tallficha_vacunas = FichaVacuna.objects.all()\n\tif request.method == 'POST':\n\t\tficha_vacuna = FormFichaVacuna(request.POST)\n\t\tif ficha_vacuna.is_valid():\n\t\t\tficha_vacuna = ficha_vacuna.save()\n\t\t\treturn redirect('index_ficha_vacuna')\n\telse:\n\t\tficha_vacuna = FormFichaVacuna()\n\t\tcontext = {'ficha_vacuna':allficha_vacunas,\n\t\t\t\t\t'form':ficha_vacuna}\n\treturn render(request,'fichas/index_ficha_vacuna.html',context)\n\n\ndef editar_ficha_vacuna(request,pk):\n\tficha_vacuna = get_object_or_404(FichaVacuna,pk=pk)\n\ttemplate = 'farmacos/Registrar.html'\n\tif request.method == 'POST':\n\t\tform = FormFichaVacuna(request.POST, instance=ficha_vacuna)\n\t\tif form.is_valid():\n\t\t\tficha_vacuna = form.save()\n\t\t\treturn redirect('index_ficha_vacuna')\n\telse:\n\t\tform = FormFichaVacuna(instance = ficha_vacuna)\n\tcontext = {'form':form}\n\treturn render(request, template, context)\n\ndef eliminar_ficha_vacuna(request,pk):\n\tficha_vacuna = get_object_or_404(FichaVacuna,pk=pk)\n\tficha_vacuna.delete()\n\treturn redirect('index_ficha_vacuna')\n\ndef visualizar_ficha_vacuna(request,pk):\n\tficha_vacuna = get_object_or_404(FichaVacuna,pk=pk)\n\ttemplate = 'farmacos/visualizacion.html'\n\t#ficha_vacuna = FichaVacuna.objects.filter(vacuna=vacuna.pk)\n\t#context = {'vacuna':vacuna,\n\tcontext = {'ficha_vacuna':ficha_vacuna}\n\treturn render(request, template, context)\n\n##################################################\ndef RegistrarVacuna(request):\n template = 'farmacos/Registrar.html'\n if request.method == 'POST':\n farmaco = FormVacuna(request.POST)\n if farmaco.is_valid():\n farmaco.save()\n return redirect('index_vacunas')\n else:\n farmaco = FormVacuna()\n context = {'form':farmaco}\n return render(request,template,context)\n \ndef RegistrarVitamina(request):\n template = 'farmacos/Registrar.html'\n if request.method == 'POST':\n farmaco = FormVitamina(request.POST)\n if farmaco.is_valid():\n farmaco.save()\n return redirect('index_vitaminas')\n else:\n farmaco = FormVitamina()\n context = {'form':farmaco}\n return render(request,template,context)\n \ndef RegistrarMedicina(request):\n template = 'farmacos/Registrar.html'\n if request.method == 'POST':\n farmaco = FormMedicina(request.POST)\n if farmaco.is_valid():\n farmaco.save()\n return redirect('index_medicinas')\n else:\n farmaco = FormMedicina()\n context = {'form':farmaco}\n return render(request,template,context)\n\"\"\" \ndef RegistrarFVet(request):\n template = 'farmacos/Registrar.html'\n if request.method == 'POST':\n farmaco = FormFichaVet(request.POST)\n if farmaco.is_valid():\n farmaco.save()\n return redirect('index_ficha')\n else:\n farmaco = FormFichaVet()\n context = {'form':farmaco}\n return render(request,template,context)\n\"\"\" \ndef RegistrarFMedicina(request):\n template = 'farmacos/Registrar.html'\n if request.method == 'POST':\n farmaco = FormFichaMedicina(request.POST)\n if farmaco.is_valid():\n farmaco.save()\n return redirect('index_ficha_medicinas')\n else:\n farmaco = FormFichaMedicina()\n context = {'form':farmaco}\n return render(request,template,context)\n \ndef RegistrarFVitamina(request):\n template = 'farmacos/Registrar.html'\n if request.method == 'POST':\n farmaco = FormFichaVitamina(request.POST)\n if farmaco.is_valid():\n farmaco.save()\n return redirect('index_ficha_vitaminas')\n else:\n farmaco = FormFichaVitamina()\n context = {'form':farmaco}\n return render(request,template,context)\n \ndef RegistrarFVacuna(request):\n template = 'farmacos/Registrar.html'\n if request.method == 'POST':\n farmaco = FormFichaVacuna(request.POST)\n if farmaco.is_valid():\n farmaco.save()\n return redirect('index_ficha_vacunas')\n else:\n farmaco = FormFichaVacuna()\n context = {'form':farmaco}\n return render(request,template,context)\n \n\n\n","sub_path":"moduloGranja/apps/farmacos/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"625352295","text":"# coding: utf-8\nfrom flask import Flask, render_template, request, redirect, url_for, send_from_directory, session\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom werkzeug import secure_filename\nfrom PIL import Image, ImageDraw\nfrom models import Entry, Entry2\nfrom io import BytesIO\nimport cognitive_face as CF\nimport pymysql\nimport pymysql.cursors\nimport numpy as np\nimport requests\nimport config\nimport json\nimport uuid\nimport os\nimport azure\nfrom azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient\nfrom azure.cognitiveservices.vision.customvision.training import CustomVisionTrainingClient\nfrom azure.cognitiveservices.vision.customvision.training.models import ImageUrlCreateEntry\n\nfrom selenium import webdriver\nfrom time import sleep\nimport io\nimport urllib\nfrom PIL import Image\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\n\n\napp = Flask(__name__)\nUPLOAD_FOLDER = './static/uploads'\nALLOWED_EXTENSIONS = set(['png', 'jpg', 'gif'])\napp.config.from_object('config')\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['SECRET_KEY'] = os.urandom(24)\n\n\"\"\"\nconnection = pymysql.connect(host='localhost',\n user='root',\n password='kihkno1!',\n db='sample1',\n charset='utf8',\n cursorclass=pymysql.cursors.DictCursor)\n\"\"\"\nconnection = pymysql.connect(host='us-cdbr-iron-east-01.cleardb.net',\n user='b02d8dcadf6606',\n password='20a4e3ed',\n db='heroku_e886d493c58bfc5',\n charset='utf8',\n cursorclass=pymysql.cursors.DictCursor)\n\n\n@app.route(\"/\", methods = [\"POST\", \"GET\"])\ndef top():\n return render_template(\"index.html\")\n\n@app.route(\"/boston\", methods = [\"POST\", \"GET\"])\ndef boston():\n if request.method == \"POST\":\n\n # ①APIが公開されているURLと、認証情報を取得\n api_key = '2ERfYTPaGZrlwPdvc989rKMXXJUmKEvZawEQ1FGhJb1mrf6OzYsPbg5LFnrSv8r0yYLHdUxzD5Oal7osgsxhXg=='\n url = 'https://ussouthcentral.services.azureml.net/workspaces/a32c9d81428f44a8ac744de07574c816/services/4a692c86980048b0bc17e9ab44749da9/execute?api-version=2.0&details=true'\n headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}\n\n # ②APIに渡すデータを準備(Webフォームの入力結果をを変数に格納)\n CRIM, ZN, INDUS, CHAS, NOX, RM,\\\n AGE, DIS, RAD, TAX, PTRATIO, B, LSTAT =\\\n request.form[\"CRIM\"], request.form[\"ZN\"], request.form[\"INDUS\"], \\\n request.form[\"CHAS\"], request.form[\"NOX\"], request.form[\"RM\"], \\\n request.form[\"AGE\"], request.form[\"DIS\"], request.form[\"RAD\"], \\\n request.form[\"TAX\"], request.form[\"PTRATIO\"], request.form[\"B\"], \\\n request.form[\"LSTAT\"]\n\n # ③APIに渡すデータを辞書型に格納\n columns = [\"CRIM\", \"ZN\", \"INDUS\", \"CHAS\", \"NOX\", \"RM\", \"AGE\", \"DIS\", \"RAD\", \"TAX\", \"PTRATIO\", \"B\", \"LSTAT\", \"MEDV\"]\n values = [[ CRIM, ZN, INDUS, CHAS, NOX, RM, AGE, DIS, RAD, TAX, PTRATIO, B, LSTAT, 0 ]]\n input1 = {'ColumnNames': columns, 'Values':values}\n params = {'Inputs': {'input1': input1}}\n\n # ④APIとのデータの受け渡し\n res = requests.post(url, headers = headers, json = params)\n\n # ⑤APIから受け取ったデータを辞書型で操作\n result = res.json()\n result = result['Results']['output1']['value']['Values'][0][-1]\n\n # 受け取った予測結果は文字列型なので、数値型に変換\n result = float(result)\n\n # 小数第二位を四捨五入\n result = round(result, 2)\n\n\n # 表示するHTMLファイルを制御\n return render_template(\"boston_confirm.html\", result = result)\n else:\n return render_template(\"boston_form.html\")\n\n@app.route(\"/income\", methods = [\"POST\", \"GET\"])\ndef income():\n if request.method == \"POST\":\n\n # ①APIが公開されているURLと、認証情報を取得\n api_key = 'JLtFHI/sJ7UtAz3uysJntQCVlpykgF/l69mWeRQnUItJ8ZPEkuTxMvrdQ3wqjAshaALSzzQMb6vFp4ln2voiyg=='\n url = 'https://ussouthcentral.services.azureml.net/workspaces/a32c9d81428f44a8ac744de07574c816/services/c7bb7923de5a4f6d934a59960f7e04b5/execute?api-version=2.0&details=true'\n headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}\n\n\n # ②APIに渡すデータを準備(Webフォームの入力結果をを変数に格納)\n お名前, age, workclass, education, marital_status, sex, hours_per_week, native_country =\\\n request.form['お名前'], request.form['age'], request.form['workclass'], \\\n request.form['education'], request.form['marital-status'], request.form['sex'], \\\n request.form['hours-per-week'], request.form['native-country']\n\n\n # ③APIに渡すデータを辞書型に格納\n columns = ['age','workclass','education','marital-status','sex','hours-per-week','native-country', 'income']\n values = [ age,workclass,education,marital_status,sex,hours_per_week,native_country, '' ]\n input1 = {'ColumnNames': columns, 'Values':[values]}\n params = {'Inputs': {'input1': input1}}\n\n\n # ④APIとのデータの受け渡し\n res = requests.post(url, headers = headers, json = params)\n\n # ⑤APIから受け取ったデータを辞書型で操作\n result = res.json()\n result = result['Results']['output1']['value']['Values'][0][-2]\n\n # Webに表示させる結果を日本語に変更する\n if result == 'over 500':\n result = '500万円以上'\n else:\n result = '500万円未満'\n\n # 表示するHTMLファイルを制御\n return render_template(\"income_confirm.html\", result = result, お名前 = お名前)\n else:\n return render_template(\"income_form.html\")\n\n@app.route(\"/recomend\", methods = [\"POST\", \"GET\"])\ndef recomend():\n if request.method == \"POST\":\n\n # ①APIが公開されているURLと、認証情報を取得\n api_key = 'H3H67/NPMBE4dkY6xcDEnKmZtm6W6G39HWnXir9/vihcuTFXGfGmarszi7DZ6Rm1HzqDm1EFFX/VHJer+P732A=='\n url = 'https://ussouthcentral.services.azureml.net/workspaces/a32c9d81428f44a8ac744de07574c816/services/c93aa7be5b92426dad42d387842eaa66/execute?api-version=2.0&details=true'\n headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}\n\n # ②APIに渡すデータを準備(Webフォームの入力結果をを変数に格納)\n userID = request.form[\"userID\"]\n\n # ③APIに渡すデータを辞書型に格納\n columns = [\"userID\"]\n values = [[ userID ]]\n input1 = {'ColumnNames': columns, 'Values':values}\n params = {'Inputs': {'input1': input1}}\n\n # ④APIとのデータの受け渡し\n res = requests.post(url, headers = headers, json = params)\n\n # ⑤APIから受け取ったデータを辞書型で操作\n result = res.json()\n result_1 = result[\"Results\"][\"output1\"][\"value\"][\"Values\"][0][1]\n result_2 = result[\"Results\"][\"output1\"][\"value\"][\"Values\"][0][2]\n result_3 = result[\"Results\"][\"output1\"][\"value\"][\"Values\"][0][3]\n result_4 = result[\"Results\"][\"output1\"][\"value\"][\"Values\"][0][4]\n result_5 = result[\"Results\"][\"output1\"][\"value\"][\"Values\"][0][5]\n result_6 = result[\"Results\"][\"output1\"][\"value\"][\"Values\"][0][6]\n result_7 = result[\"Results\"][\"output1\"][\"value\"][\"Values\"][0][7]\n result_8 = result[\"Results\"][\"output1\"][\"value\"][\"Values\"][0][8]\n result_9 = result[\"Results\"][\"output1\"][\"value\"][\"Values\"][0][9]\n result_10 = result[\"Results\"][\"output1\"][\"value\"][\"Values\"][0][10]\n result_11 = round(float(result[\"Results\"][\"output1\"][\"value\"][\"Values\"][0][11]), 2)\n result_12 = round(float(result[\"Results\"][\"output1\"][\"value\"][\"Values\"][0][12]), 2)\n result_13 = round(float(result[\"Results\"][\"output1\"][\"value\"][\"Values\"][0][13]), 2)\n result_14 = round(float(result[\"Results\"][\"output1\"][\"value\"][\"Values\"][0][14]), 2)\n result_15 = round(float(result[\"Results\"][\"output1\"][\"value\"][\"Values\"][0][15]), 2)\n\n\n # 表示するHTMLファイルを制御\n return render_template(\"recomend_confirm.html\", userID = userID, \\\n result_1 = result_1, result_2 = result_2, result_3 = result_3, result_4 = result_4, result_5 = result_5,\\\n result_6 = result_6, result_7 = result_7, result_8 = result_8, result_9 = result_9, result_10 = result_10,\\\n result_11 = result_11, result_12 = result_12, result_13 = result_13, result_14 = result_14, result_15 = result_15)\n else:\n return render_template(\"recomend_form.html\")\n\n@app.route('/ComputerVision', methods=['POST', 'GET'])\ndef ComputerVision():\n if request.method == 'POST':\n\n KEY = 'fde6648ece0145cbbe79bf4902a9e56e'\n url = 'https://westus.api.cognitive.microsoft.com/vision/v1.0/ocr'\n\n img_file = request.files['img_file']\n filename = secure_filename(img_file.filename)\n img_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n # APIに渡す用の画像保存先URL\n img_url_api = './static/uploads/' + filename\n # HTMLに表示させるための画像URL\n img_url_html = 'static/uploads/' + filename\n\n img = open(img_url_api, 'rb')\n img_byte = img.read()\n img.close()\n\n headers = {'Content-Type': 'application/octet-stream', 'Ocp-Apim-Subscription-Key': KEY,}\n params = {'language': 'ja', 'detectOrientation ': 'true', }\n\n res = requests.post(url, headers=headers, params=params, data=img_byte)\n res_json = res.json()\n\n seqs = []\n for i in res_json['regions'][0]['lines']:\n seqs.append(i['words'])\n\n aaa = []\n aaaa = []\n i = 1\n for seq in seqs:\n for word in seq:\n aaa.append(word['text'])\n aaaa.append(aaa)\n aaa = []\n\n bbb_ = ''\n bbb = []\n for aaaa_ in aaaa:\n for aaaa__ in aaaa_:\n bbb_ += aaaa__\n bbb.append(bbb_)\n bbb_ = ''\n\n\n return render_template('ComputerVision_confirm.html', bbb = bbb, img_url = img_url_html)\n else:\n return render_template('ComputerVision_form.html')\n\n@app.route('/scraping', methods=['POST', 'GET'])\ndef scraping():\n if request.method == 'POST':\n\n # 入力データの取得\n keyword = request.form['keyword']\n img_num = int(request.form['img_num'])\n pj_name = request.form['pj_name']\n\n # ディレクトリの作成\n if not os.path.exists('static/scraping_images/{}'.format(pj_name)):\n os.mkdir('static/scraping_images/{}'.format(pj_name))\n\n if not os.path.exists('static/scraping_images/{}/{}画像'.format(pj_name, keyword)):\n os.mkdir('static/scraping_images/{}/{}画像'.format(pj_name, keyword))\n\n # スクレイピングの実行(検索実行)\n browser = webdriver.Chrome('chromedriver.exe')\n browser.get('https://www.google.co.jp/imghp?hl=ja&authuser=0')\n elem_input = browser.find_element_by_class_name('SDkEP')\n elem_input = elem_input.find_element_by_class_name('a4bIc')\n elem_input = elem_input.find_element_by_class_name('gLFyf')\n elem_input.send_keys(keyword)\n elem_btn = browser.find_element_by_tag_name('button')\n elem_btn = elem_btn.find_element_by_class_name('rINcab')\n elem_btn.click()\n\n\n # スクレイピングの実行(画像保存)\n elem_imgs = browser.find_element_by_id('rg')\n elem_imgs = elem_imgs.find_elements_by_tag_name('img')\n urls = []\n passed_index = []\n\n for index, elem_img in enumerate(elem_imgs):\n try:\n if index < img_num:\n url = elem_img.get_attribute('src')\n f = io.BytesIO(urllib.request.urlopen(url, timeout=100).read())\n img = Image.open(f)\n url_ = 'static/scraping_images/{}/{}画像/image{}.png'.format(pj_name, keyword, index + 1)\n img.save(url_)\n urls.append(url_)\n except:\n passed_index.append(index)\n browser.quit()\n\n return render_template('scraping_confirm.html', urls = urls)\n else:\n return render_template('scraping_form.html')\n\n\n\n@app.route('/send', methods=['POST', 'GET'])\ndef send():\n if request.method == 'POST':\n\n # custom Visionに渡す画像データ\n img_file = request.files['img_file']\n filename = secure_filename(img_file.filename)\n img_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n # APIに渡す用の画像保存先URL\n img_url_api = './static/uploads/' + filename\n # HTMLに表示させるための画像URL\n img_url_html = 'static/uploads/' + filename\n\n # Custom Visionとのデータ受け渡し\n url=\"https://southcentralus.api.cognitive.microsoft.com/customvision/v2.0/Prediction/fb949a8e-cf2b-4664-8c60-7478c9bf2223/image?iterationId=cf29583f-4496-4e9d-a8b9-0af300313fb4\"\n headers={'content-type':'application/octet-stream','Prediction-Key':'a432f94c45c14bbaa95569e2bec4bb29'}\n result =requests.post(url,data=open(img_url_api,\"rb\"),headers=headers)\n result_json = result.json()\n proba = round(result_json['predictions'][0]['probability'] * 100, 1)\n tagname = result_json['predictions'][0]['tagName']\n\n # Computer Vision APIとのデータ受け渡し\n KEY = \"ca9c3c49975346d7a5e8e6d8024c4304\"\n url = \"https://southcentralus.api.cognitive.microsoft.com/vision/v2.0/analyze\"\n\n img = open(img_url_api, 'rb')\n img_byte = img.read()\n img.close()\n\n headers = {'Ocp-Apim-Subscription-Key': KEY, \"Content-Type\": \"application/octet-stream\"}\n params = {'visualFeatures': 'Categories,Description', 'langage':'ja'}\n\n res = requests.post(url, headers=headers, params=params, data=img_byte)\n res_json = res.json()\n title = res_json['description']['captions'][0]['text']\n\n # 翻訳APIとのデータ受け渡し\n base_url = 'https://api.cognitive.microsofttranslator.com'\n path = '/translate?api-version=3.0'\n params = '&to=ja'\n constructed_url = base_url + path + params\n\n headers = {\n 'Ocp-Apim-Subscription-Key': '39c1f94f0de04a5e9ccf5f95b19c28c6',\n 'Content-type': 'application/json',\n 'X-ClientTraceId': str(uuid.uuid4())\n }\n body = [{'text' : title}]\n request_ = requests.post(constructed_url, headers=headers, json=body)\n response = request_.json()\n title_ja = response[0]['translations'][0]['text']\n\n with connection.cursor() as cursor:\n query = \"select * from animal where tag =\" + \"'\" + tagname + \"'\"\n sql = query\n cursor.execute(sql)\n results = cursor.fetchall()[0]\n\n\n return render_template('custom_vision_confirm.html',\n img_url=img_url_html, tagname=tagname, proba=proba,\n title=title, title_ja=title_ja, results = results)\n else:\n return render_template('custom_vision_form.html')\n\n\n@app.route('/uploads/<filename>')\ndef uploaded_file(filename):\n return send_from_directory(app.config['UPLOAD_FOLDER'], filename)\n\n\n@app.route('/arobaview', methods=['POST', 'GET'])\ndef arobaview():\n if request.method == 'POST':\n\n # FaceAPIとのデータ受け渡し\n KEY = 'a58ec59f233f4d00b9a71b2c495bceb7'\n BASE_URL = 'https://southcentralus.api.cognitive.microsoft.com/face/v1.0'\n CF.Key.set(KEY)\n CF.BaseUrl.set(BASE_URL)\n\n img_file = request.files['img_file']\n filename = secure_filename(img_file.filename)\n img_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n img_url_api = './static/uploads/' + filename\n img_url_html = 'static/uploads/' + filename\n img_file_path = img_url_api\n faces = CF.face.detect(img_file_path, face_id=True, landmarks=False, attributes='age,gender,smile,emotion')\n result_faces = faces[0]['faceAttributes']['emotion']\n age = int(faces[0]['faceAttributes']['age'])\n max_emotion = max(result_faces.items(), key=lambda x: x[1])[0]\n\n # 解析結果をリスト型に格納\n emotions_, body = [], []\n body.append({'text':max_emotion})\n body.append({'text':faces[0]['faceAttributes']['gender']})\n\n for key in result_faces:\n # HTMLに渡す感情数値をリスト型に格納\n emotions_.append(result_faces[key])\n\n # 翻訳APIに渡す辞書型を格納\n body.append({'text':key})\n\n # 翻訳\n base_url = 'https://api.cognitive.microsofttranslator.com'\n path = '/translate?api-version=3.0'\n params = '&to=ja'\n constructed_url = base_url + path + params\n\n headers = {\n 'Ocp-Apim-Subscription-Key': '39c1f94f0de04a5e9ccf5f95b19c28c6',\n 'Content-type': 'application/json',\n 'X-ClientTraceId': str(uuid.uuid4())\n }\n body = body\n request_ = requests.post(constructed_url, headers=headers, json=body)\n response = request_.json()\n keys_ja = []\n for key_ja in response:\n keys_ja.append(key_ja['translations'][0]['text'])\n\n # 画像に枠線を加える\n def getRectangle(faceDictionary):\n rect = faceDictionary['faceRectangle']\n left = rect['left']\n top = rect['top']\n bottom = left + rect['height']\n right = top + rect['width']\n return ((left, top), (bottom, right))\n img = Image.open(img_file_path)\n draw = ImageDraw.Draw(img)\n for face in faces:\n draw.rectangle(getRectangle(face), outline='red')\n result_url = 'static/uploads/result.jpg'\n img.save(result_url)\n\n\n return render_template('arobaview_confirm.html',\n img_url=img_url_html, result_url=result_url, age = age, emotions = emotions_,\n max_emotion = keys_ja[0], gender=keys_ja[1], keys_ja = keys_ja[2:])\n else:\n return render_template('arobaview_form.html')\n\n\n@app.route('/aimaker_make', methods=['POST', 'GET'])\ndef aimaker_make():\n if request.method == 'POST':\n\n ENDPOINT = \"https://southcentralus.api.cognitive.microsoft.com\"\n training_key = \"d81b3e7e624d470bb546dfc1138c575e\"\n prediction_key = \"28b7b62a66bf4250a873ba57e661a2c1\"\n\n trainer = CustomVisionTrainingClient(training_key, endpoint=ENDPOINT)\n project_name_ = str(request.form['pj_name'])\n project = trainer.create_project(project_name_)\n# iteration = trainer.train_project(project.id)\n\n # Create a new project\n tag_1_str = str(request.form['tag_1'])\n tag_2_str = str(request.form['tag_2'])\n tag_1 = trainer.create_tag(project.id, tag_1_str)\n tag_2 = trainer.create_tag(project.id, tag_2_str)\n\n with connection.cursor() as cursor:\n query = \"insert into aimaker \\\n (project_name, project_id, tag_ids_1, tag_1_, tag_ids_2, tag_2_, iteration_id)\\\n values ('\" + project_name_ + \"','\" + project.id + \"','\" + tag_1.id + \"','\" + tag_1_str + \"','\" + tag_2.id + \"','\"+ tag_2_str + \"','\" + 'iii' +\"')\"\n\n sql = query\n cursor.execute(sql)\n connection.commit()\n\n return render_template('aimaker_make_confirm.html')\n else:\n return render_template('aimaker_make_form.html')\n\n\n@app.route('/aimaker_upload/<pj_name>', methods=['POST', 'GET'])\ndef aimaker_upload_pj(pj_name):\n if request.method == 'POST':\n\n ENDPOINT = \"https://southcentralus.api.cognitive.microsoft.com\"\n training_key = \"d81b3e7e624d470bb546dfc1138c575e\"\n prediction_key = \"28b7b62a66bf4250a873ba57e661a2c1\"\n trainer = CustomVisionTrainingClient(training_key, endpoint=ENDPOINT)\n\n\n img_tag = request.form['img_tag']\n pj_name = pj_name\n\n img_files = request.files.getlist('img_files')\n img_urls_api = []\n for img_file_ in img_files:\n filename = secure_filename(img_file_.filename)\n img_file_.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n img_url_api = './static/uploads/' + filename\n img_urls_api.append(img_url_api)\n\n with connection.cursor() as cursor:\n query = \"select * from aimaker where project_name = '\" + pj_name + \"'\"\n sql = query\n cursor.execute(sql)\n results = cursor.fetchall()[0]\n project_id = results['project_id']\n tag_ids_1 = results['tag_ids_1']\n tag_ids_2 = results['tag_ids_2']\n tag_1_ = results['tag_1_']\n tag_2_ = results['tag_2_']\n\n if img_tag == tag_1_:\n tag_ids = tag_ids_1\n else:\n tag_ids = tag_ids_2\n\n #trainer.create_images_from_data(project_id=project_id, image_data = open(img_url_api,\"rb\"), tag_ids=[tag_ids])\n\n for img_url_api_ in img_urls_api:\n trainer.create_images_from_data(project_id=project_id, image_data = open(img_url_api_,\"rb\"), tag_ids=[tag_ids])\n\n return render_template('aimaker_upload_form.html', tag_1_=tag_1_, tag_2_ = tag_2_, pj_name = pj_name)\n\n else:\n\n pj_name = pj_name\n\n with connection.cursor() as cursor:\n query = \"select * from aimaker where project_name = '\" + pj_name + \"'\"\n sql = query\n cursor.execute(sql)\n results = cursor.fetchall()[0]\n project_id = results['project_id']\n tag_ids_1 = results['tag_ids_1']\n tag_ids_2 = results['tag_ids_2']\n tag_1_ = results['tag_1_']\n tag_2_ = results['tag_2_']\n\n return render_template('aimaker_upload_form.html', tag_1_=tag_1_, tag_2_ = tag_2_, pj_name=pj_name)\n\n@app.route('/aimaker_upload', methods=['POST', 'GET'])\ndef aimaker_upload():\n if request.method == 'POST':\n pj_name = request.form['pj_name']\n\n return redirect(url_for('aimaker_upload_pj', pj_name=pj_name))\n\n else:\n\n with connection.cursor() as cursor:\n query = \"select * from aimaker\"\n sql = query\n cursor.execute(sql)\n results = cursor.fetchall()\n pj_names = []\n for result in results:\n pj_names.append(result['project_name'])\n return render_template('aimaker_upload_pjselect.html', pj_names = pj_names)\n\n\n@app.route('/aimaker_train/<pj_name>', methods=['POST', 'GET'])\ndef aimaker_train(pj_name):\n if request.method == 'POST':\n ENDPOINT = \"https://southcentralus.api.cognitive.microsoft.com\"\n training_key = \"d81b3e7e624d470bb546dfc1138c575e\"\n prediction_key = \"28b7b62a66bf4250a873ba57e661a2c1\"\n trainer = CustomVisionTrainingClient(training_key, endpoint=ENDPOINT)\n\n with connection.cursor() as cursor:\n query = \"select * from aimaker where project_name = '\" + pj_name + \"'\"\n sql = query\n cursor.execute(sql)\n results = cursor.fetchall()[0]\n project_id = results['project_id']\n\n iteration = trainer.train_project(project_id)\n while (iteration.status != \"Completed\"):\n iteration = trainer.get_iteration(project_id, iteration.id)\n\n # The iteration is now trained. Make it the default project endpoint\n trainer.update_iteration(project_id, iteration.id, is_default=True)\n\n with connection.cursor() as cursor:\n query = \"update aimaker set iteration_id = '\" + iteration.id + \"' where project_name = '\" + str(pj_name) +\"'\"\n sql = query\n cursor.execute(sql)\n connection.commit()\n\n return redirect(url_for('aimaker_upload_pj', pj_name = pj_name))\n\n@app.route('/aimaker_predict', methods=['POST', 'GET'])\ndef aimaker_predict():\n if request.method == 'POST':\n\n ENDPOINT = \"https://southcentralus.api.cognitive.microsoft.com\"\n training_key = \"d81b3e7e624d470bb546dfc1138c575e\"\n prediction_key = \"28b7b62a66bf4250a873ba57e661a2c1\"\n\n # custom Visionに渡す画像データ\n img_file = request.files['img_file']\n pj_name = request.form['pj_name']\n filename = secure_filename(img_file.filename)\n img_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n # APIに渡す用の画像保存先URL\n img_url_api = './static/uploads/' + filename\n # HTMLに表示させるための画像URL\n img_url_html = 'static/uploads/' + filename\n\n with connection.cursor() as cursor:\n query = \"select * from aimaker where project_name = '\" + pj_name + \"'\"\n sql = query\n cursor.execute(sql)\n results = cursor.fetchall()[0]\n project_id = results['project_id']\n iteration_id = results['iteration_id']\n\n # Now there is a trained endpoint that can be used to make a prediction\n predictor = CustomVisionPredictionClient(prediction_key, endpoint=ENDPOINT)\n results = predictor.predict_image(project_id=project_id, image_data=open(img_url_api,\"rb\"), iteration_id=iteration_id)\n\n # Display the results.\n predictions = []\n for prediction_ in results.predictions:\n predictions.append(\"{}\".format(prediction_.tag_name)+\"である確率:\"+\\\n \"{}\".format(round(prediction_.probability*100, 2))+\"%\")\n\n\n return render_template('aimaker_predict_confirm.html', img_url=img_url_html, predictions=predictions)\n else:\n\n with connection.cursor() as cursor:\n query = \"select * from aimaker\"\n sql = query\n cursor.execute(sql)\n results = cursor.fetchall()\n pj_names = []\n for result in results:\n pj_names.append(result['project_name'])\n\n return render_template('aimaker_predict_form.html', pj_names = pj_names)\n\n\n\n\nif __name__ == \"__main__\":\n app.run(host='127.0.0.1', port=5000, debug=True)\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":26643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"553704300","text":"ultimo = 10\nfila = list(range(1,ultimo+1))\nwhile True:\n print(\"\\nExistem %d clientes na fila\" % len(fila))\n print(\"Fila atual:\", fila)\n print(\"Digite F para adicionar um cliente ao fim da fila,\")\n print(\"ou A para realizar o atendimento. S para sair.\")\n operação = input(\"Operação (F, A ou S):\")\n x = 0\n sair = False\n while x < len(operação):\n if operação[x] == \"A\":\n if len(fila) > 0:\n atendido = fila.pop(0)\n print(\"Cliente %d atendido\" % atendido)\n else:\n print(\"Fila vazia! Ninguém para atender.\")\n elif operação[x] == \"F\":\n ultimo += 1\n fila.append(ultimo)\n elif operação[x] == \"S\":\n sair = True\n break\n else:\n print(\"Operação inválida: %s na posição %d! Digite apenas F, A ou S!\" % (operação[x], x))\n x += 1\n if sair:\n break","sub_path":"Capitulo 6/Exercicio6.5.py","file_name":"Exercicio6.5.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"322942537","text":"from django.shortcuts import render, HttpResponse, redirect\nfrom .models import Book, Author\ndef index(request):\n context = {\n \"books\" : Book.objects.all()\n }\n return render(request, \"books/index.html\", context)\n\ndef indextwo(request):\n context = {\n \"authors\" : Author.objects.all()\n }\n return render(request, \"books/add.html\", context)\n\ndef add_item(request):\n if request.method == 'POST':\n i = Book.objects.create(title = request.POST['title'], desc = request.POST['desc'])\n return redirect('/')\n\ndef add_itemtwo(request):\n if request.method == 'POST':\n i = Author.objects.create(first_name = request.POST['first_name'], last_name = request.POST['last_name'], notes = request.POST['notes'])\n\n return redirect('/')\n\ndef indepth(request, book_id):\n book = Book.objects.get(id = book_id)\n context = {\n \"book\" : Book.objects.get(id = book_id),\n \"books_authors\" : book.authors.all(),\n \"all_authors\" : Author.objects.all()\n }\n return render(request, \"books/update.html\", context)\n\ndef indepthtwo(request, author_id):\n author = Author.objects.get(id = author_id)\n context = {\n \"author\" : Author.objects.get(id = author_id),\n \"authors_books\" : author.books.all(),\n \"all_books\" : Book.objects.all()\n }\n return render(request, \"books/singleauth.html\", context)\n # i = Author.objects.get(id = author_id)\n # j = i.books.all().values()\n # k =Book.objects.all().values()\n # return render(request, \"books/singleauth.html\", {\"author\" : i, \"book\" : j, \"booker\" : k})\n\ndef page_objects(request, book_id):\n if request.method == 'POST':\n val_from_field_one = request.POST[\"authors\"] \n c = Book.objects.get(id= book_id)\n b = Author.objects.get(id =(request.POST[\"authors\"]))\n c.authors.add(b)\n c.save()\n return redirect('/')\n\ndef page_objectstwo(request, author_id):\n if request.method == 'POST':\n val_from_field_one = request.POST[\"books\"] \n c = Author.objects.get(id= author_id)\n b = Book.objects.get(id =(request.POST[\"books\"]))\n c.books.add(b)\n c.save()\n\n return redirect('/authors')","sub_path":"apps/books/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"174773911","text":"# CS1156x Learning From Data - HW 6.3 - 6.6 Regularization & Weight Decay - Linear Regression\n# Wayne H Nixalo - 21-Dec-2016 17:57 - 18:16 | 21:05 - 21:55\n# <>---------------------<>---------------------<>---------------------<>\n# Linear Regression w/ Weight Decay λ w/ NL trsf on datasets\n# <>---------------------<>---------------------<>---------------------<>\n# NOTE: code is mostly repackaged from HW6.2, now including weight decay\nimport numpy as np\n\n# function to load in data file -- returns list of lists of floats\ndef loadData(filename):\n '''\n :param filename:\n :return returnArray, an array of arrays of floats:\n '''\n file = open(filename, 'r')\n filestring = file.readline()\n returnArray = []\n while filestring != '':\n line = []\n for s in filestring.split(' '):\n if s != '':\n line.append(float(s))\n returnArray.append(line)\n filestring = file.readline()\n file.close()\n return returnArray\n\n# Φ(x1, x2) = (1, x1, x2, x1^2, x2^2, |x1-x2|, |x1+x2|)\ndef transformMatrix(X):\n Z = []\n for i in range(len(X)):\n x1, x2 = X[i][1], X[i][2]\n Z.append([1, x1, x2, x1**2, x2**2, x1*x2, abs(x1-x2), abs(x1+x2)])\n return np.array(Z)\n\ndef LinRegWD(k):\n # Regularization parameters:\n if k is not None:\n λ = 10**k\n elif k is None:\n λ = 0\n print(\"k = {}, λ = {}\".format(k, λ))\n\n # Import Training DataSet:\n D = loadData('in.dta')\n\n # Extract X and Y matrices:\n X, Y = [], []\n for i in range(len(D)):\n X.append([1, D[i][0], D[i][1]])\n Y.append([D[i][2]])\n X, Y = np.array(X), np.array(Y)\n\n # Create Transform Matrix Z:\n Z = transformMatrix(X)\n\n # Compute W vector via PseudoInverse:\n W = (np.linalg.inv(np.transpose(Z).dot(Z) + np.multiply(λ, np.identity(len(Z[0]))))).dot(np.transpose(Z).dot(Y))\n # I will be a 8x8 sq-mat: len(Φ(x1, x2))\n\n # Calculate InSample Error on Training Set:\n N, misclass = len(D), 0\n for i in range(N):\n if np.sign(np.transpose(W).dot(Z[i])) != np.sign(Y[i]): # could use D[i][2] for Y[i] instead\n misclass += 1\n Ein = float(misclass)/N\n\n # Calculate OutSample Error on Testing Set:\n D = loadData('out.dta')\n N, misclass = len(D), 0\n # update new X & Y:\n X, Y = [], []\n for i in range(N):\n X.append([1, D[i][0], D[i][1]])\n Y.append([D[i][2]])\n X, Y = np.array(X), np.array(Y)\n Z = transformMatrix(X)\n\n for i in range(N):\n if np.sign(np.transpose(W).dot(Z[i])) != np.sign(Y[i]):\n misclass += 1\n Eout = float(misclass)/N\n\n print(\"Ein: {}, Eout: {}\".format(Ein, Eout))\n\nLinRegWD(None)\nLinRegWD(-3)\nLinRegWD(3)\nfor i in range(5):\n LinRegWD(-2+i)\n\n# ============================================================================ #\n# Terminal Output:\n# Waynes-MacBook-Pro:HW6 WayNoxchi$ python3 HW6.3-6_LinReg-WtDecay-NLtrnsf.py\n# k = None, λ = 0\n# Ein: 0.02857142857142857, Eout: 0.084\n# k = -3, λ = 0.001\n# Ein: 0.02857142857142857, Eout: 0.08\n# k = 3, λ = 1000\n# Ein: 0.37142857142857144, Eout: 0.436\n# k = -2, λ = 0.01\n# Ein: 0.02857142857142857, Eout: 0.084\n# k = -1, λ = 0.1\n# Ein: 0.02857142857142857, Eout: 0.056\n# k = 0, λ = 1\n# Ein: 0.0, Eout: 0.092\n# k = 1, λ = 10\n# Ein: 0.05714285714285714, Eout: 0.124\n# k = 2, λ = 100\n# Ein: 0.2, Eout: 0.228\n","sub_path":"CS1156x/HW6/HW6.3-6_LinReg-WtDecay-NLtrnsf.py","file_name":"HW6.3-6_LinReg-WtDecay-NLtrnsf.py","file_ext":"py","file_size_in_byte":3364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"180457563","text":"\"\"\"Чтение файла .json\"\"\"\r\n__name__ = 'read'\r\n\r\n__all__ = ['read_json']\r\n\r\nimport json\r\n\r\n\r\ndef read_json(path, file_name):\r\n if path != '' and path != '.' and path is not None:\r\n file = open(path + '\\\\' + file_name + '.json', 'r')\r\n else:\r\n file = open(file_name + '.json', 'r')\r\n data = json.load(file)\r\n return data\r\n","sub_path":"ISR1.2/wwj/read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"107987288","text":"from turtle import Turtle\n\nclass StateName(Turtle):\n def __init__(self):\n super().__init__()\n self.penup()\n self.color(\"black\")\n self.hideturtle()\n\n def draw_name(self, location, state):\n self.goto(location)\n self.write(f\"{state}\", font=(\"Arial\", 8, \"bold\"))\n\n\n\n","sub_path":"state_name.py","file_name":"state_name.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"138919411","text":"# encoding: utf-8\n\nimport ctypes\nimport win32con\n\ndef parse_arguments():\n import argparse\n\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('-m', '--message', required=True)\n parser.add_argument('-t', '--title', default='')\n parser.add_argument('-i', '--info', default=True, action='store_true')\n parser.add_argument('-w', '--warn', default=False, action='store_true')\n parser.add_argument('-q', '--question', default=False, action='store_true')\n parser.add_argument('-e', '--error', default=False, action='store_true')\n\n parsed_args = parser.parse_args()\n return parsed_args\n\ndef MessageBox(message, title, mbtype):\n return ctypes.windll.user32.MessageBoxA(\n 0,\n message,\n title,\n win32con.MB_OK | mbtype\n )\n\nargs = parse_arguments()\nmessage = args.message\ntitle = args.title\n\nmbtype = 0\nif args.info:\n mbtype = win32con.MB_ICONINFORMATION\nif args.warn:\n mbtype = win32con.MB_ICONWARNING\nif args.question:\n mbtype = win32con.MB_ICONQUESTION\nif args.error:\n mbtype = win32con.MB_ICONERROR\n\nMessageBox(message, title, mbtype)\n","sub_path":"pathed_commands/msgbox.py","file_name":"msgbox.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"546107611","text":"# -*- coding: utf-8 -*-\r\n# author: ronniecao\r\n# time: 2017/12/28\r\n# description: get dataset from voc-2012 datasets\r\nimport xml.etree.ElementTree as ET\r\nimport pickle\r\nimport os\r\nfrom os import listdir, getcwd\r\nfrom os.path import join\r\n\r\nclasses = [\"aeroplane\", \"bicycle\", \"bird\", \"boat\", \"bottle\", \"bus\", \"car\", \"cat\", \"chair\", \"cow\", \"diningtable\", \"dog\", \"horse\", \"motorbike\", \"person\", \"pottedplant\", \"sheep\", \"sofa\", \"train\", \"tvmonitor\"]\r\n\r\n\r\ndef convert(size, box):\r\n dw = 1./(size[0])\r\n dh = 1./(size[1])\r\n x = (box[0] + box[1])/2.0 - 1\r\n y = (box[2] + box[3])/2.0 - 1\r\n w = box[1] - box[0]\r\n h = box[3] - box[2]\r\n x = x*dw\r\n w = w*dw\r\n y = y*dh\r\n h = h*dh\r\n return (x,y,w,h)\r\n\r\ndef convert_annotation(in_file, out_file):\r\n tree=ET.parse(in_file)\r\n root = tree.getroot()\r\n size = root.find('size')\r\n w = int(size.find('width').text)\r\n h = int(size.find('height').text)\r\n\r\n for obj in root.iter('object'):\r\n difficult = obj.find('difficult').text\r\n cls = obj.find('name').text\r\n if cls not in classes or int(difficult)==1:\r\n continue\r\n cls_id = classes.index(cls)\r\n xmlbox = obj.find('bndbox')\r\n b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text))\r\n bb = convert((w,h), b)\r\n with open(out_file, 'w') as fw:\r\n fw.write(str(cls_id) + \" \" + \" \".join([str(a) for a in bb]) + '\\n')\r\n\r\n\r\ndef construct_label(source_dir, target_dir):\r\n if not os.path.exists(target_dir):\r\n os.makedirs(target_dir)\r\n if not os.path.exists(os.path.join(target_dir, 'Labels')):\r\n os.makedirs(os.path.join(target_dir, 'Labels'))\r\n xml_list = os.listdir(os.path.join(source_dir, 'Annotations'))\r\n for xmlname in xml_list:\r\n xmlpath = os.path.join(source_dir, 'Annotations', xmlname)\r\n outpath = os.path.join(target_dir, 'Labels', xmlname.split('.')[0]+'.txt')\r\n convert_annotation(xmlpath, outpath)\r\n\r\ndef construct_dataset(source_dir, target_dir):\r\n trainsets, testsets = [], []\r\n with open(os.path.join(source_dir, 'ImageSets', 'Main', 'cat_train.txt'), 'r') as fo:\r\n for line in fo:\r\n filename = line.strip().split(' ')[0]\r\n filepath = os.path.join(target_dir, 'Images', '%s.jpg' % (filename))\r\n trainsets.append(filepath)\r\n\r\n with open(os.path.join(source_dir, 'ImageSets', 'Main', 'cat_val.txt'), 'r') as fo:\r\n for line in fo:\r\n filename = line.strip().split(' ')[0]\r\n filepath = os.path.join(target_dir, 'Images', '%s.jpg' % (filename))\r\n testsets.append(filepath)\r\n\r\n with open(os.path.join(target_dir, 'train.txt'), 'w') as fw:\r\n for filepath in trainsets:\r\n fw.writelines(('%s\\n' % (filepath)).encode('utf8'))\r\n \r\n with open(os.path.join(target_dir, 'valid.txt'), 'w') as fw:\r\n for filepath in testsets:\r\n fw.writelines(('%s\\n' % (filepath)).encode('utf8'))\r\n\r\n with open(os.path.join(target_dir, 'test.txt'), 'w') as fw:\r\n for filepath in testsets:\r\n fw.writelines(('%s\\n' % (filepath)).encode('utf8'))\r\n\r\nconstruct_label('datasets/VOCdevkit/VOC2012', 'datasets/voc')\r\nconstruct_dataset('datasets/VOCdevkit/VOC2012', 'datasets/voc')\r\n","sub_path":"src/trash/src_old/tools/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":3339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"534768508","text":"from nose import tools\n\nfrom gherkin.lexer.exceptions import LexingError\n\nfrom .support import LexerTest\n\nclass TestBOM(LexerTest):\n def test_windows_file_with_bom_should_work_just_fine(self):\n self.scan_file(\"with_bom.feature\")\n self.check([\n [u\"feature\", u\"Feature\", u\"Feature Text\", u\"\", 1],\n [u\"scenario\", u\"Scenario\", u\"Reading a Scenario\", u\"\", 2],\n [u\"step\", u\"Given \", u\"there is a step\", 3],\n [u\"eof\"],\n ])","sub_path":"python/test/lexer/test_lexer_windows.py","file_name":"test_lexer_windows.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"194658680","text":"\nfrom conans import ConanFile, tools, CMake\n\nclass TrvlConan(ConanFile):\n\n name = \"trvl\"\n version = \"0.1.0\"\n generators = \"cmake\"\n settings = \"os\", \"compiler\", \"build_type\", \"arch\"\n description = \"depth compression library\"\n\n exports_sources = \"examples/*\", \"include/*\", \"src/*\", \"CMakeLists.txt\"\n\n def requirements(self):\n self.requires(\"enet/1.3.14@camposs/stable\")\n self.requires(\"opencv/3.4.8@camposs/stable\")\n\n def configure(self):\n if self.settings.os == \"Linux\":\n self.options[\"opencv\"].with_gtk = True\n self.options[\"opencv\"].shared = True\n\n def build(self):\n cmake = CMake(self)\n cmake.configure()\n cmake.build()\n\n def imports(self):\n self.copy(src=\"bin\", pattern=\"*.dll\", dst=\"./bin\") # Copies all dll files from packages bin folder to my \"bin\" folder\n self.copy(src=\"lib\", pattern=\"*.dll\", dst=\"./bin\") # Copies all dll files from packages bin folder to my \"bin\" folder\n self.copy(src=\"lib\", pattern=\"*.dylib*\", dst=\"./lib\") # Copies all dylib files from packages lib folder to my \"lib\" folder\n self.copy(src=\"lib\", pattern=\"*.so*\", dst=\"./lib\") # Copies all so files from packages lib folder to my \"lib\" folder\n self.copy(src=\"bin\", pattern=\"ut*\", dst=\"./bin\") # Copies all applications\n self.copy(src=\"bin\", pattern=\"log4cpp.conf\", dst=\"./\") # copy a logging config template\n","sub_path":"conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"265065354","text":"import os\r\nimport argparse\r\nimport glob \r\nimport time\r\nimport joblib\r\nimport warnings\r\n\r\nimport torch.backends.cudnn as cudnn\r\nimport torch.nn as nn\r\nfrom torch.autograd import Variable\r\nimport torchvision\r\nfrom torchvision import datasets, models, transforms\r\n\r\nfrom scipy.cluster.vq import vq\r\nimport numpy as np\r\nimport cv2\r\nimport PIL\r\n\r\nimport face_detector\r\nimport creative\r\nfrom retinaface.models.retinaface import RetinaFace\r\nfrom retinaface.data import cfg_re50\r\nfrom retinaface_utils import * \r\nimport feature_extractors\r\n\r\nimport ctypes\r\nctypes.cdll.LoadLibrary('caffe2_nvrtc.dll')\r\n\r\nwarnings.filterwarnings('ignore')\r\nclass_names =['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', \r\n'16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', \r\n'33', '34', '36', '38', '40', '42', '44', '46', '48', '50', '52', '54', '56', '58', '60', '78']\r\n \r\ndef recognise_face_cnn(detected_dir, class_names):\r\n device = 'cuda:0' if torch.cuda.is_available() else 'cpu'\r\n model = models.resnet50(pretrained=False)\r\n num_f = model.fc.in_features\r\n model.fc = nn.Linear(num_f, 48)\r\n model.load_state_dict(torch.load(\"./models/Resnet50_retrained.pth\", map_location=device))\r\n model.to(device)\r\n model.eval()\r\n data_transforms = transforms.Compose([\r\n transforms.Resize(256),\r\n transforms.CenterCrop(224),\r\n transforms.ToTensor(),\r\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\r\n ])\r\n labels = {}\r\n proba = []\r\n for im in os.listdir(detected_dir):\r\n lab, img, probs = cnn_inference(f'{detected_dir}/{im}', model, class_names, data_transforms)\r\n labels[im] = list(probs)\r\n proba.append(list(probs))\r\n\r\n proba.sort(key=max, reverse=True)\r\n ord = []\r\n argmaxes = []\r\n probs = []\r\n for prob in proba:\r\n for k, v in labels.items():\r\n if prob == v:\r\n ord.append(k)\r\n n = 0\r\n sorted_ps = sorted(prob, reverse=True)\r\n while prob.index(sorted_ps[n]) in argmaxes:\r\n n+=1\r\n argmaxes.append(prob.index(sorted_ps[n]))\r\n probs.append(sorted_ps[n])\r\n labs = []\r\n for i in argmaxes:\r\n labs.append(class_names[i])\r\n fin = dict(zip(ord, labs))\r\n return fin, probs \r\n\r\ndef cnn_inference(img, model, labels, data_transforms):\r\n device = 'cuda:0' if torch.cuda.is_available() else 'cpu'\r\n im = PIL.Image.open(img)\r\n face_tensor = data_transforms(im).float().unsqueeze_(0)\r\n inp = Variable(face_tensor).to(device)\r\n out = model(inp)\r\n probs = nn.functional.softmax(out).cpu().detach().numpy().flatten()\r\n index = out.data.cpu().numpy().argmax()\r\n return labels[index], img, probs\r\n\r\ndef recognise_face_classic(detected_dir, classifier, extractor, detector, scaler, vocab):\r\n if extractor == \"sift\" and classifier == 'svm':\r\n model = joblib.load(\"./models/SVM_SIFT.joblib\")\r\n if extractor == \"surf\" and classifier == 'svm':\r\n model = joblib.load(\"./models/SVM_SURF.joblib\")\r\n\r\n if extractor == \"sift\" and classifier == 'rf':\r\n model = joblib.load(\"./models/RF_SIFT.joblib\")\r\n if extractor == \"surf\" and classifier == 'rf':\r\n model = joblib.load(\"./models/RF_SURF.joblib\")\r\n\r\n outs = {}\r\n for im in os.listdir(detected_dir):\r\n img = cv2.imread(f'{detected_dir}/{im}')\r\n img = cv2.resize(img, (224,224))\r\n kp, des = detector.detectAndCompute(img, None)\r\n im_features = np.zeros(800, 'float32')\r\n words, distance = vq(des, vocab)\r\n for w in words:\r\n im_features[w] += 1\r\n bovw = scaler.transform(im_features.reshape(1,-1))\r\n preds = model.predict(bovw)[0]\r\n outs[im] = preds\r\n return outs\r\n\r\ndef recognise_face(image, feature_type='sift', classifier_type='svm', creative_mode=0):\r\n class_names =['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', \r\n '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', \r\n '33', '34', '36', '38', '40', '42', '44', '46', '48', '50', '52', '54', '56', '58', '60', '78']\r\n # load retinaface model \r\n net = RetinaFace(cfg=cfg_re50, phase = 'test')\r\n net = load_model(net, './models/Resnet50_Final.pth', False)\r\n net.eval()\r\n print('Model loaded successfully')\r\n cudnn.benchmark = True\r\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n net = net.to(device)\r\n\r\n # detect faces in image\r\n faces = face_detector.face_detector(image, out_name = 'results', net = net, save_image=True)\r\n \r\n img = cv2.imread(image, cv2.IMREAD_COLOR)\r\n\r\n centres = []\r\n bboxes = []\r\n results = {}\r\n if not os.path.exists(\"./det_faces/\"):\r\n os.mkdir(\"./det_faces/\")\r\n else:\r\n files = glob.glob(\"./det_faces/*\")\r\n for f in files:\r\n os.remove(f)\r\n for face in faces:\r\n centre = (int((face[2]+face[0]) / 2), int((face[3]+face[1]) / 2))\r\n centres.append(centre)\r\n image = img[int(face[1]):int(face[3]), int(face[0]):int(face[2])]\r\n cv2.imwrite(f'./det_faces/face_{centre[0]}_{centre[1]}.PNG', image)\r\n bbox = [int(f) for f in face[0:4]]\r\n bboxes.append(bbox)\r\n if creative_mode:\r\n whole = cv2.imread('./results.jpg', cv2.IMREAD_COLOR)\r\n for face in bboxes:\r\n roi = whole[face[1]:face[3], face[0]:face[2],:]\r\n cartoon = creative.cartoonify(roi)\r\n whole[face[1]:face[3], face[0]:face[2], :] = cartoon\r\n cv2.imwrite('results.jpg', whole)\r\n if feature_type == 'sift':\r\n scaler = joblib.load('./models/SIFT_SCALER.bin')\r\n vocab = np.load('./models/sift_vocab.npy')\r\n detector = cv2.xfeatures2d.SIFT_create()\r\n if feature_type == 'surf':\r\n scaler = joblib.load('./models/SURF_SCALER.bin')\r\n vocab = np.load('./models/surf_vocab.npy')\r\n detector = cv2.xfeatures2d.SURF_create()\r\n if classifier_type.lower() == 'cnn':\r\n fin, prob = recognise_face_cnn('./det_faces/', class_names)\r\n elif classifier_type.lower() == 'svm' or classifier_type.lower() == 'rf':\r\n fin = recognise_face_classic('./det_faces/', classifier = classifier_type, extractor = feature_type, detector = detector, scaler = scaler, vocab = vocab)\r\n prob = None\r\n return fin, prob \r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('image', type = str, help = 'image filename with appropriate path \"./*.JPG/PNG')\r\n parser.add_argument('classifier', type = str, help = 'type of classifier, CNN, SVM, RF')\r\n parser.add_argument('--features', type = str, help = 'type of feature extractor used, only with SVM and RF - either surf or sift')\r\n parser.add_argument('--creative_mode', default = False, action = 'store_true', help = \"set 1 to add cartoonifying to faces in group image\")\r\n args = parser.parse_args()\r\n fin, _ = recognise_face(args.image, classifier_type = args.classifier, feature_type = args.features, creative_mode = args.creative_mode)\r\n\r\n #load in copy of image with bounding boxes added\r\n im = cv2.imread('results.jpg', cv2.IMREAD_COLOR)\r\n centres = [tuple(x.strip('.JPG').strip('.PNG').split('_')[1:3]) for x in fin.keys()]\r\n if os.path.exists('./results.txt'):\r\n os.remove('./results.txt')\r\n with open('results.txt', 'w') as f:\r\n for x,y in zip(centres, fin.values()):\r\n print(f'{y} {x[0]} {x[1]}')\r\n im = cv2.putText(im, f'{y}', (int(x[0]), int(x[1])), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)\r\n f.write(f'{y} - {x[0]}, {x[1]}\\n') \r\n f.close()\r\n t = str(time.time()).split('.')[0]\r\n os.remove('results.JPG') \r\n cv2.imwrite(f'results{t}.JPG', im)\r\n","sub_path":"CV/recognise_face.py","file_name":"recognise_face.py","file_ext":"py","file_size_in_byte":7450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"76996597","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n-------------------------------------------------\r\n File Name: urls\r\n Description:\r\n Author: Administrator\r\n date: 2018/6/11\r\n-------------------------------------------------\r\n Change Activity:\r\n 2018/6/11:\r\n-------------------------------------------------\r\n\"\"\"\r\nfrom django.urls import path\r\nfrom task import views\r\n\r\nurlpatterns = [\r\n path(r'inventory/', views.gen_inventory, name='inventory'),\r\n path(r'run_module/', views.run_module, name='run_module'),\r\n path(r'run_log/', views.run_log, name='run_log'),\r\n]\r\n","sub_path":"task/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"263726610","text":"# Copyright 2022 Huawei Technologies Co., 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# ============================================================================\n\"\"\"Utils for NAML.\"\"\"\nimport time\nimport numpy as np\nfrom sklearn.metrics import roc_auc_score\nfrom mindspore import Tensor\n\nfrom .dataset import create_eval_dataset, EvalNews, EvalUsers, EvalCandidateNews\n\ndef get_metric(args, mindpreprocess, news_encoder, user_encoder, metric):\n \"\"\"Calculate metrics.\"\"\"\n start = time.time()\n news_dict = {}\n user_dict = {}\n dataset = create_eval_dataset(mindpreprocess, EvalNews, batch_size=args.batch_size)\n dataset_size = dataset.get_dataset_size()\n iterator = dataset.create_dict_iterator(output_numpy=True)\n for count, data in enumerate(iterator):\n news_vector = news_encoder(Tensor(data[\"category\"]), Tensor(data[\"subcategory\"]),\n Tensor(data[\"title\"]), Tensor(data[\"abstract\"])).asnumpy()\n for i, nid in enumerate(data[\"news_id\"]):\n news_dict[str(nid[0])] = news_vector[i]\n print(f\"===Generate News vector==== [ {count} / {dataset_size} ]\", end='\\r')\n print(f\"===Generate News vector==== [ {dataset_size} / {dataset_size} ]\")\n dataset = create_eval_dataset(mindpreprocess, EvalUsers, batch_size=args.batch_size)\n dataset_size = dataset.get_dataset_size()\n iterator = dataset.create_dict_iterator(output_numpy=True)\n for count, data in enumerate(iterator):\n browsed_news = []\n for newses in data[\"history\"]:\n news_list = []\n for nid in newses:\n news_list.append(news_dict[str(nid[0])])\n browsed_news.append(np.array(news_list))\n browsed_news = np.array(browsed_news)\n user_vector = user_encoder(Tensor(browsed_news)).asnumpy()\n for i, uid in enumerate(data[\"uid\"]):\n user_dict[str(uid)] = user_vector[i]\n print(f\"===Generate Users vector==== [ {count} / {dataset_size} ]\", end='\\r')\n print(f\"===Generate Users vector==== [ {dataset_size} / {dataset_size} ]\")\n dataset = create_eval_dataset(mindpreprocess, EvalCandidateNews, batch_size=args.batch_size)\n dataset_size = dataset.get_dataset_size()\n iterator = dataset.create_dict_iterator(output_numpy=True)\n for count, data in enumerate(iterator):\n pred = np.dot(\n np.stack([news_dict[str(nid)] for nid in data[\"candidate_nid\"]], axis=0),\n user_dict[str(data[\"uid\"])]\n )\n metric.update(pred, data[\"labels\"])\n print(f\"===Click Prediction==== [ {count} / {dataset_size} ]\", end='\\r')\n print(f\"===Click Prediction==== [ {dataset_size} / {dataset_size} ]\")\n auc = metric.eval()\n total_cost = time.time() - start\n print(f\"Eval total cost: {total_cost} s\")\n return auc\n\ndef process_data(args):\n word_embedding = np.load(args.embedding_file)\n _, h = word_embedding.shape\n if h < args.word_embedding_dim:\n word_embedding = np.pad(word_embedding, ((0, 0), (0, args.word_embedding_dim - 300)), 'constant',\n constant_values=0)\n elif h > args.word_embedding_dim:\n word_embedding = word_embedding[:, :args.word_embedding_dim]\n print(\"Load word_embedding\", word_embedding.shape)\n return Tensor(word_embedding.astype(np.float32))\n\ndef AUC(y_true, y_pred):\n return roc_auc_score(y_true, y_pred)\n\ndef MRR(y_true, y_pred):\n index = np.argsort(y_pred)[::-1]\n y_true = np.take(y_true, index)\n score = y_true / (np.arange(len(y_true)) + 1)\n return np.sum(score) / np.sum(y_true)\n\ndef DCG(y_true, y_pred, n):\n index = np.argsort(y_pred)[::-1]\n y_true = np.take(y_true, index[:n])\n score = (2 ** y_true - 1) / np.log2(np.arange(len(y_true)) + 2)\n return np.sum(score)\n\ndef nDCG(y_true, y_pred, n):\n return DCG(y_true, y_pred, n) / DCG(y_true, y_true, n)\n\nclass NAMLMetric:\n \"\"\"\n Metric method\n \"\"\"\n def __init__(self):\n super(NAMLMetric, self).__init__()\n self.AUC_list = []\n self.MRR_list = []\n self.nDCG5_list = []\n self.nDCG10_list = []\n\n def clear(self):\n \"\"\"Clear the internal evaluation result.\"\"\"\n self.AUC_list = []\n self.MRR_list = []\n self.nDCG5_list = []\n self.nDCG10_list = []\n\n def update(self, predict, y_true):\n predict = predict.flatten()\n y_true = y_true.flatten()\n self.AUC_list.append(AUC(y_true, predict))\n self.MRR_list.append(MRR(y_true, predict))\n self.nDCG5_list.append(nDCG(y_true, predict, 5))\n self.nDCG10_list.append(nDCG(y_true, predict, 10))\n\n def eval(self):\n auc = np.mean(self.AUC_list)\n print('AUC:', auc)\n print('MRR:', np.mean(self.MRR_list))\n print('nDCG@5:', np.mean(self.nDCG5_list))\n print('nDCG@10:', np.mean(self.nDCG10_list))\n return auc\n","sub_path":"research/recommend/naml/infer/sdk/util/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"331426382","text":"import cv2\nimport numpy\n\nfrom umeyama import umeyama\n\n\ndef random_channel_shift(x, intensity=10, channel_axis=2):\n x = numpy.rollaxis(x, channel_axis, 0)\n min_x, max_x = numpy.min(x), numpy.max(x)\n intensity = max_x / 255 * 15.\n channel_images = [numpy.clip(x_channel + numpy.random.uniform(-intensity, intensity), min_x, max_x) for x_channel in\n x]\n x = numpy.stack(channel_images, axis=0)\n x = numpy.rollaxis(x, 0, channel_axis + 1)\n return x\n\n\ndef random_transform(image, rotation_range, zoom_range, shift_range, random_flip):\n h, w = image.shape[0:2]\n # color_shifted_image = random_channel_shift(image)\n rotation = numpy.random.uniform(-rotation_range, rotation_range)\n scale = numpy.random.uniform(1 - zoom_range, 1 + zoom_range)\n tx = numpy.random.uniform(-shift_range, shift_range) * w\n ty = numpy.random.uniform(-shift_range, shift_range) * h\n mat = cv2.getRotationMatrix2D((w // 2, h // 2), rotation, scale)\n mat[:, 2] += (tx, ty)\n result = cv2.warpAffine(image, mat, (w, h), borderMode=cv2.BORDER_REPLICATE)\n if numpy.random.random() < random_flip:\n result = result[:, ::-1]\n return result\n\n\n# get pair of random warped images from aligened face image\ndef random_warp(image):\n assert image.shape == (256, 256, 3)\n # range_ = numpy.linspace( 128-80, 128+80, 5 )\n range_ = numpy.linspace(128 - 110, 128 + 110, 5)\n mapx = numpy.broadcast_to(range_, (5, 5))\n mapy = mapx.T\n\n mapx = mapx + numpy.random.normal(size=(5, 5), scale=6)\n mapy = mapy + numpy.random.normal(size=(5, 5), scale=6)\n\n interp_mapx = cv2.resize(mapx, (80, 80))[8:72, 8:72].astype('float32')\n interp_mapy = cv2.resize(mapy, (80, 80))[8:72, 8:72].astype('float32')\n\n warped_image = cv2.remap(image, interp_mapx, interp_mapy, cv2.INTER_LINEAR)\n\n src_points = numpy.stack([mapx.ravel(), mapy.ravel()], axis=-1)\n dst_points = numpy.mgrid[0:65:16, 0:65:16].T.reshape(-1, 2)\n mat = umeyama(src_points, dst_points, True)[0:2]\n\n target_image = cv2.warpAffine(image, mat, (64, 64))\n\n return warped_image, target_image\n\n\n# get pair of random warped images from aligened face image\ndef random_warp128(image):\n assert image.shape == (256, 256, 3)\n range_ = numpy.linspace(128 - 110, 128 + 110, 5)\n mapx = numpy.broadcast_to(range_, (5, 5))\n mapy = mapx.T\n\n mapx = mapx + numpy.random.normal(size=(5, 5), scale=6)\n mapy = mapy + numpy.random.normal(size=(5, 5), scale=6)\n\n interp_mapx = cv2.resize(mapx, (80 * 2, 80 * 2))[8 * 2:72 * 2, 8 * 2:72 * 2].astype('float32')\n interp_mapy = cv2.resize(mapy, (80 * 2, 80 * 2))[8 * 2:72 * 2, 8 * 2:72 * 2].astype('float32')\n\n warped_image = cv2.remap(image, interp_mapx, interp_mapy, cv2.INTER_LINEAR)\n\n src_points = numpy.stack([mapx.ravel(), mapy.ravel()], axis=-1)\n dst_points = numpy.mgrid[0:65 * 2:16 * 2, 0:65 * 2:16 * 2].T.reshape(-1, 2)\n mat = umeyama(src_points, dst_points, True)[0:2]\n\n target_image = cv2.warpAffine(image, mat, (64 * 2, 64 * 2))\n\n return warped_image, target_image\n","sub_path":"image_augmentation.py","file_name":"image_augmentation.py","file_ext":"py","file_size_in_byte":3065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"530214098","text":"'''QCalendarWidget'''\nimport sys\nfrom PyQt5.QtWidgets import QApplication, QWidget, QLabel, QCalendarWidget\nfrom PyQt5.QtCore import QDate\n\nclass Example(QWidget):\n def __init__(self):\n super(Example, self).__init__()\n\n self.initUI()\n\n def initUI(self):\n\n self.setGeometry(100, 100, 400, 300)\n self.setWindowTitle('Calendar Demo')\n\n cal = QCalendarWidget(self)\n cal.setGridVisible(True) #one of the function\n cal.move(20, 20)\n cal.clicked[QDate].connect(self.showDate)\n\n self.label = QLabel(self)\n date = cal.selectedDate() #another function\n self.label.setText(date.toString())\n self.label.move(20, 200)\n\n self.show()\n\n def showDate(self, date):\n self.label.setText(date.toString())\n\n\n# --- main program\napp = QApplication(sys.argv)\nex = Example()\nsys.exit(app.exec_())\n","sub_path":"Sabrina.py","file_name":"Sabrina.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"612773228","text":"#coding:utf-8\n'''\n APD别名前缀消除\n 数据库两个表\n prefix\n predictIP\n\n 1.前缀提取\n /32-/96 = 64 bit \n python APD.py -extract -i [input.txt] -db [database] --begin=[begin] --end=[end]\n 2.探测\n python APD.py --detectAll --database=[dbname] --threshold=[threshold] --IPv6=[IPv6] ----directory=[dirname] \n python APD.py --detectOne --database [database] --threshold [threshold] --IPv6 [IPv6] ----directory [dirname]\n 3.输出\n python APD.py --output --database=[db] > prefix.txt\n'''\nimport argparse,code,sqlite3,random,json,time,os,subprocess\nhex_list=['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']\ndef get_rawIP(IP):\n # 标准IP -> hex IP\n seglist=IP.split(':')\n if seglist[0]=='':\n seglist.pop(0)\n if seglist[-1]=='':\n seglist.pop()\n sup=8-len(seglist)\n if '' in seglist:\n sup+=1\n ret=[]\n for i in seglist:\n if i=='':\n for j in range(0,sup):\n ret.append('0'*4)\n else:\n ret.append('{:0>4}'.format(i))\n rawIP=''.join(ret)\n assert(len(rawIP)==32)\n return rawIP\ndef get_standardIP(hexIP):\n assert(len(hexIP) == 32)\n return ':'.join([hexIP[i: i + 4] for i in range(0, 32, 4)])\ndef get_standardPrefix(prefix):\n length=len(prefix)\n return ':'.join([prefix[i:i+4] for i in range(0,length,4)])+'::/'+str(length*4)\ndef generateTargets(prefix):\n length=len(prefix)\n comp_len=32-length-1\n # 32=length+1+()\n ret=[]\n for i in range(0,16):\n target=prefix+hex_list[i]\n for _ in xrange(comp_len):\n target+=hex_list[random.randint(0,15)]\n ret.append(target)\n assert(len(target)==32)\n return ret\ndef detectOne(database, threshold, dirname, local_IPv6):\n if not os.path.exists(dirname):\n os.mkdir(dirname)\n connection = sqlite3.connect(database)\n connection.execute('PRAGMA temp_store_directory = \\'{}\\';'.format(os.path.dirname(args.database)))\n #print(connection.execute('PRAGMA temp_store_directory;').fetchone()[0])\n cursor1 = connection.cursor()\n current_bitlength, begin, end = connection.execute('SELECT current_bitlength, begin, end FROM stat LIMIT 1;').fetchone()\n if current_bitlength == end:\n # 从Temp里创建\n tb_source = 'Temp'\n elif current_bitlength >= begin:\n tb_source = 'tb_{}'.format(current_bitlength + 4)\n else:\n print('alread scan all prefixed from {} to {}'.format(begin, end))\n return False\n # tb_dest 前缀, 匹配数量, 响应数量\n tb_dest = 'tb_{}'.format(current_bitlength)\n connection.executescript('DROP TABLE IF EXISTS {};CREATE TABLE {} (prefix TEXT, count INTEGER, response_count INTEGER);'.format(tb_dest, tb_dest))\n # tb_target 扫描IP 前缀 是否响应\n tb_target = 'target_{}'.format(current_bitlength)\n connection.executescript('DROP TABLE IF EXISTS {};CREATE TABLE {} (IP TEXT, prefix TEXT, responsive INTEGER);'.format(tb_target, tb_target))\n #print('current_bitlength {}, tb {}->{}'.format(current_bitlength, tb_source, tb_dest))\n oldprefix, prefix_count = '', 0\n t0 = time.time()\n if tb_source == 'Temp':\n for item in connection.execute('SELECT prefix FROM Temp ORDER BY prefix ASC;'):\n prefix = item[0]\n if oldprefix != prefix: \n if prefix_count >= 1:\n cursor1.execute('INSERT INTO {} VALUES (?, ?, ?);'.format(tb_dest), (oldprefix, prefix_count, 0))\n oldprefix = prefix\n prefix_count = 1\n else:\n prefix_count += 1\n if prefix_count >= 1:\n cursor1.execute('INSERT INTO {} VALUES (?, ?, ?);'.format(tb_dest), (oldprefix, prefix_count, 0))\n #print('create tbdest use {} seconds'.format(time.time() - t0))\n t0 = time.time()\n cursor1.execute('CREATE INDEX {} ON {}(prefix);'.format(tb_dest+'index', tb_dest))\n #print('create index use {} seconds'.format(time.time() - t0))\n else:\n # already sorted\n isAliased = True\n for item in connection.execute('SELECT prefix, count, response_count FROM {};'.format(tb_source)):\n prefix, add_count, response_count = item[0][:current_bitlength / 4], item[1], item[2]\n # 非别名\n if (response_count >= 0 and response_count < 16) or (response_count == -1): \n isAliased = False\n if oldprefix != prefix:\n if prefix_count >= 1:\n # 需要扫描\n if isAliased:\n cursor1.execute('INSERT INTO {} VALUES (?, ?, ?);'.format(tb_dest), (oldprefix, prefix_count, 0))\n else:\n cursor1.execute('INSERT INTO {} VALUES (?, ?, ?);'.format(tb_dest), (oldprefix, prefix_count, -1))\n oldprefix = prefix\n prefix_count = add_count\n if response_count == 16:\n isAliased = True\n else:\n prefix_count += add_count\n if prefix_count >= 1:\n # 需要扫描\n if isAliased:\n cursor1.execute('INSERT INTO {} VALUES (?, ?, ?);'.format(tb_dest), (oldprefix, prefix_count, 0))\n else:\n cursor1.execute('INSERT INTO {} VALUES (?, ?, ?);'.format(tb_dest), (oldprefix, prefix_count, -1))\n #print('create tbdest use {} seconds'.format(time.time() - t0))\n t0 = time.time()\n cursor1.execute('CREATE INDEX {} ON {}(prefix);'.format(tb_dest+'index', tb_dest))\n #print('create index use {} seconds'.format(time.time() - t0))\n #print('creating new table use {} seconds'.format(time.time() - t0))\n target_filename = '{}/target-{}.txt'.format(dirname, current_bitlength)\n result_filename = '{}/result-{}.txt'.format(dirname, current_bitlength)\n filecount = 0\n t0 = time.time()\n with open(target_filename, 'w') as f:\n for item in connection.execute('SELECT prefix, count, response_count FROM {};'.format(tb_dest)):\n prefix, count, response_count = item[0], item[1], item[2]\n if response_count == 0:\n if count >= threshold:\n targets = generateTargets(prefix)\n for target in targets:\n standardIP = get_standardIP(target)\n connection.execute('INSERT INTO {} VALUES (?, ?, ?);'.format(tb_target), (target, prefix, 0))\n f.write(standardIP + '\\n')\n filecount += 1\n else:\n connection.execute('UPDATE {} SET response_count = -2 WHERE prefix = ?;'.format(tb_dest), (prefix,))\n #print('writing to target_file use {} seconds'.format(time.time() - t0))\n if filecount == 0:\n print('skip at {}'.format(current_bitlength))\n else:\n t0 = time.time()\n cursor1.execute('CREATE INDEX {} ON {}(IP);'.format(tb_target+'index', tb_target))\n #print('create index on targets.IP use {} seconds'.format(time.time() - t0))\n command = 'sudo zmap --ipv6-target-file={} --ipv6-source-ip={} -M icmp6_echoscan -f saddr,daddr,ipid,ttl,timestamp_str -O json -o {}'.format(target_filename, local_IPv6, result_filename)\n t0 = time.time()\n p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n returncode = p.poll()\n while returncode is None:\n line = p.stdout.readline()\n returncode = p.poll()\n line = line.strip()\n #print(line)\n print('zmap scanning {}, store result in {},use {} seconds'.format(target_filename, result_filename, time.time() - t0))\n t0 = time.time()\n for line in open(result_filename, 'r'):\n responsive_IP=json.loads(line)['saddr']\n raw_IP=get_rawIP(responsive_IP)\n prefix=connection.execute('select prefix from {} where IP=?;'.format(tb_target),(raw_IP,)).fetchone()[0]\n connection.execute('update {} set responsive=1 where IP=?;'.format(tb_target),(raw_IP,))\n connection.execute('update {} set response_count=response_count+1 where prefix=?;'.format(tb_dest),(prefix,))\n for prefix_ in connection.execute('select prefix from {} where response_count=16;'.format(tb_dest)):\n cursor1.execute('INSERT INTO AliasedPrefixes VALUES (?);', (prefix_[0],))\n connection.execute('UPDATE stat SET current_bitlength = current_bitlength - 4;')\n connection.commit()\n connection.close()\n return True\ndef test(database):\n connection=sqlite3.connect(database)\n connection.execute('PRAGMA temp_store_directory = \\'{}\\';'.format(os.path.dirname(database)))\n t0=time.time()\n f=open('test.t','w')\n count = 0\n for item in connection.execute('SELECT prefix FROM Temp ORDER BY prefix ASC;'):\n f.write(item[0][0])\n count += 1\n if count % 1000000 == 0:\n print('{} use {} seconds'.format(count, time.time() - t0))\n f.close()\n print('{} use {} seconds'.format(count, time.time() - t0))\n connection.commit()\n connection.close()\n exit(0)\ndef extract(input, database, begin, end):\n # 统计 prefix, count, 0\n t0,IP_count=time.time(),0\n begin_hex, end_hex = begin / 4, end / 4\n connection=sqlite3.connect(database)\n connection.execute('PRAGMA temp_store_directory = \\'{}\\';'.format(os.path.dirname(database)))\n print(connection.execute('PRAGMA temp_store_directory;').fetchone()[0])\n connection.executescript('DROP TABLE IF EXISTS stat;create table stat (current_bitlength INTEGER, IP_count INTEGER, begin INTEGER, end INTEGER, threshold INTEGER);')\n connection.executescript('DROP TABLE IF EXISTS Temp; CREATE TABLE Temp (prefix TEXT);')\n connection.executescript('DROP TABLE IF EXISTS AliasedPrefixes; CREATE TABLE AliasedPrefixes (prefix TEXT);')\n c1,c2=connection.cursor(),connection.cursor()\n batches, max_count = [], 10000000\n for line in open(input):\n if line and line[0]!='#':\n IP=line.strip()\n raw_IP=get_rawIP(IP)\n #assert(len(raw_IP) == 32)\n IP_count+=1\n if IP_count%1000000==0:\n print('{} {} seconds'.format(IP_count, time.time()-t0))\n prefix = raw_IP[:end_hex]\n batches.append((prefix, ))\n if len(batches) >= max_count:\n c1.executemany('INSERT INTO Temp VALUES (?);', batches)\n batches = []\n c1.executemany('INSERT INTO Temp VALUES (?);', batches)\n t0 = time.time()\n c1.execute('CREATE INDEX Temp_Index ON Temp(prefix);')\n print('create index use {} seconds'.format(time.time() - t0))\n connection.execute('INSERT INTO stat values (?, ?, ?, ?, ?);', (end, IP_count, begin, end, 0))\n connection.commit()\n connection.close()\nif __name__=='__main__':\n parse=argparse.ArgumentParser()\n parse.add_argument('--extract', action='store_true', help='extract prefix to db file')\n parse.add_argument('--test', action='store_true', help='do some test.')\n parse.add_argument('--detectOne', action='store_true', help='after extract')\n parse.add_argument('--detectAll', action='store_true', help='after extract')\n parse.add_argument('--output', action='store_true', help='print aliased prefix')\n parse.add_argument('--input','-i',type=str,help='input IPv6 addresses. # to comment \\\\n to split. or dbfile or prefix file')\n parse.add_argument('--database','-db',type=str,help='output database name')\n parse.add_argument('--directory','-tempdir',type=str,help='output directory name')\n parse.add_argument('--IPv6','-IP',type=str,help='local IPv6 address')\n parse.add_argument('--threshold','-t',default=100,type=int,help='threshold, min prefix count')\n parse.add_argument('--begin','-b',default=32,type=int,help='prefix range')\n parse.add_argument('--end','-e',default=96,type=int,help='prefix range')\n args=parse.parse_args()\n\n if args.detectOne:\n detectOne(args.database, args.threshold, args.directory, args.IPv6)\n elif args.detectAll:\n while detectOne(args.database, args.threshold, args.directory, args.IPv6):\n #print('')\n pass\n elif args.extract:\n extract(args.input, args.database, args.begin, args.end)\n elif args.output:\n # 输出别名前缀\n connection=sqlite3.connect(args.database)\n for item in connection.execute('SELECT prefix FROM AliasedPrefixes;'):\n print(get_standardPrefix(item[0]))\n connection.close()\n elif args.test:\n test(args.database)","sub_path":"APD.py","file_name":"APD.py","file_ext":"py","file_size_in_byte":12629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"388250935","text":"import random\r\n\r\nmatriz = []\r\nlinhas = int(input(\"Informe o numero de linhas: \"))\r\ncolunas = int(input(\"Informe o numero de colunas: \"))\r\n\r\nfor i in range(linhas):\r\n sublista = []\r\n for j in range(colunas):\r\n n = random.randint(1,100)\r\n sublista.append(n)\r\n matriz.append(sublista)\r\n\r\nfor i in range(linhas):\r\n print(matriz[i])","sub_path":"AULAS/ipc-20151-aula20/leituraMatriz.py","file_name":"leituraMatriz.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"465485893","text":"class TFunc:\n\tdef __init__(self, nombre, tipo, varEnt, varDec, varCuadrado, varRect, varCirc, varLin, varEstr, varBool, varEntTemp, varDecTemp, varCuadradoTemp, varRectTemp, varCircTemp, varLinTemp, varEstrTemp, varBoolTemp, cuadruploInicial, arrVar, arrParam):\n\t\tself.nombre = nombre\n\t\tself.tipo = tipo\n\t\tself.varEnt = varEnt\n\t\tself.varDec = varDec\n\t\tself.varCuadrado = varCuadrado\n\t\tself.varRect = varRect\n\t\tself.varCirc = varCirc\n\t\tself.varLin = varLin\n\t\tself.varEstr = varEstr\n\t\tself.varBool = varBool\n\t\tself.varEntTemp = varEntTemp\n\t\tself.varDecTemp = varDecTemp\n\t\tself.varCuadradoTemp = varCuadradoTemp\n\t\tself.varRectTemp = varRectTemp\n\t\tself.varCircTemp = varCircTemp\n\t\tself.varLinTemp = varLinTemp\n\t\tself.varEstrTemp = varEstrTemp\n\t\tself.varBoolTemp = varBoolTemp\n\t\tself.cuadruploInicial = cuadruploInicial\n\t\tself.arrVar = []\n\t\tself.arrParam = []","sub_path":"TFunc.py","file_name":"TFunc.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"199812277","text":"\n\nfrom xai.brain.wordbase.nouns._sunset import _SUNSET\n\n#calss header\nclass _SUNSETS(_SUNSET, ):\n\tdef __init__(self,): \n\t\t_SUNSET.__init__(self)\n\t\tself.name = \"SUNSETS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"sunset\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_sunsets.py","file_name":"_sunsets.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"613025894","text":"import requests\nimport json\nimport pprint\nimport sys\nimport logging\nimport vyos2\n\nimport perms\n\n\n\ndef get_firewall_rulenumber(hostname, firewall, rulenumber):\n v = vyos2.api (\n hostname= hostname,\n api = \"get\",\n op = \"showConfig\",\n cmd = [\"firewall\", \"name\", firewall, \"rule\", rulenumber],\n description = \"get_firewall_rulenumber\",\n )\n return v\n\n\ndef get_firewall_group(hostname):\n v = vyos2.api (\n hostname= hostname,\n api = \"get\",\n op = \"showConfig\",\n cmd = [\"firewall\", \"group\"],\n description = \"get_firewall_group\",\n )\n return v\n","sub_path":"vycontrol/vyos_common.py","file_name":"vyos_common.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"400283896","text":"import os\n\nfrom setuptools import setup\nfrom string import Template\n\n\ndef read(fname):\n \"\"\"Read a file in the top level directory and return its content.\n \"\"\"\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\n\ntemplate = Template(\"$script = paper_to_git.bin.$script:main\")\nscripts = set(template.substitute(script=script)\n for script in ('paper_git'))\n\nsetup(\n name=\"paper_to_git\",\n version=\"0.1\",\n author=\"Abhilash Raj\",\n author_email=\"raj.abhilash1@gmail.com\",\n description=\"Sync between Dropbox Paper and any git repo.\",\n license=\"MIT\",\n keywords=\"dorpbox-paper git\",\n url=\"https://github.com/maxking/paper-to-git\",\n packages=['paper_to_git'],\n long_description=read('README.md'),\n entry_points={\n 'console_scripts': [\n \"paper-git = paper_to_git.bin.paper_git:main\",\n ],\n },\n classifiers=[\n \"Development Status :: Alpha\",\n \"Topic :: Utilities\",\n \"License :: MIT\",\n ],\n install_requires=[\n 'dropbox',\n 'flufl.lock',\n 'lazr.config',\n 'peewee',\n 'GitPython'\n ]\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"317602903","text":"import os, json, hashlib\nfrom io import BytesIO\nimport requests\nfrom shapely.geometry import Polygon, mapping\nfrom PIL import Image\nfrom flask import Flask, jsonify, request\napp = Flask(__name__)\n\ndef boundary_to_polygon(boundary):\n boundary = boundary + [(p[0] - 1, p[1]) for p in reversed(boundary)]\n polygon = mapping(Polygon(boundary).simplify(1))['coordinates'][0][:-1]\n return polygon\n\nwith open('boundaries_by_hash.json') as fh:\n for i in fh:\n boundaries_by_hash = json.loads(i)\n\n@app.route(\"/predict_single_image\", methods=['POST'])\ndef inference():\n url = request.get_json()['image_url']\n response = requests.get(url)\n image = Image.open(BytesIO(response.content))\n hash = hashlib.md5(image.tobytes()).hexdigest()\n boundary_names = ['ILM (ILM)', 'Inner boundary of RPE (IB_RPE)']\n ilm, inner_rpe = [boundary_to_polygon(boundaries_by_hash[hash][i]) for i in boundary_names]\n predictions = [\n {\n \"class\": \"ILM\",\n \"confidence\": 1,\n \"polygon\": ilm\n },\n {\n \"class\": \"Inner RPE\",\n \"confidence\": 1,\n \"polygon\": inner_rpe\n }\n ]\n return jsonify(predictions)\n\nif __name__ == \"__main__\":\n port = int(os.environ.get(\"PORT\", 5000))\n app.run(host='0.0.0.0', port=port)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"524057856","text":"'''\n Copyright 2019 IBM 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 \n '''\n\nimport os\nfrom sys import exit, exc_info, argv\nimport random\nimport json\nimport requests\n\nclass mySpace(list):\n def sample(self):\n return random.choice(self)\n \nclass ChallengeEnvironment():\n \"\"\"\n This is the class which defines the simple Sequential Decision-making Environment object, and enables either actions or policies to be evaluated.\n \n Attributes:\n _resolution (string): The population size.\n _timeout (int): The time interval in seconds that any job can be polled.\n _realworkercount (int): The number of jobs which can concurrently be active.\n actionDimension (int): The number of elements in the action space.\n policyDimension (int): The number of elements in the policy.\n _baseuri (string): The http endpoint for the task clerk.\n userId (string): The unique user id.\n _experimentCount (int): The experiment budget.\n experimentsRemaining (int): The number of jobs that are remaining in the experiment budget.\n action (list): Temporary data storage for action.\n \n \"\"\"\n\n def __init__(self, baseuri, experimentCount = 105, userID = \"ChallengeUser\", type = \"\", timeout = 0, realworkercount = 1):\n \"\"\"\n The constructor for experiment class.\n \n Parameters:\n baseuri (string): The http endpoint for the task clerk.\n experimentCount (int): The experiment budget (the number of jobs permitted) for this experiment.\n userId (string): A valid userId able to create experiments for a given locationId.\n type (string): The variant of the base environment. May not be valid for all locations.\n timeout (int): The time interval in seconds that any job can be polled.\n realworkercount (int): The number of jobs which can concurrently be active.\n \n Returns:\n None\n \n \"\"\"\n self._realworkercount = realworkercount\n\n self.actionDimension = 2\n self.policyDimension = 5\n self._baseuri = baseuri+\"/sample/\"+type if type is not \"\" else baseuri+\"/sample\"\n self.userId = userID\n self._experimentCount = experimentCount\n self.experimentsRemaining = self._experimentCount\n self._resolution = 0.1\n self.history = []\n self.history1 = []\n self.reset()\n xy = [(round(x*self._resolution,2),round(y*self._resolution,2)) for x in range(0,int(1/self._resolution) +1,1) for y in range(0,int(1/self._resolution) +1,1)]\n self.action_space = mySpace(xy)\n self.observation_space = mySpace([i for i in range(1,self.policyDimension+1)])\n \n def reset(self):\n \"\"\"Resets the state and clears all evidence of past actions.\"\"\"\n self.state = 1\n self.done = False\n self.action = []\n\n def _simplePostAction(self, action):\n \"\"\"\n The helper function to get the reward for a given action.\n \n Parameters:\n action (object): The action to be posted.\n \n Returns:\n reward: The reward associated with the provided action or nan if the job is not complete.\n \n \"\"\"\n rewardUrl = '%s/evaluate/action/'%self._baseuri\n\n try:\n #print(action)\n extended_action = {}\n extended_action['action']=action\n extended_action['old'] = self.action\n extended_action['state'] = self.state\n #print(extended_action)\n response = requests.post(rewardUrl, data = json.dumps(extended_action), headers = {'Content-Type': 'application/json', 'Accept': 'application/json'});\n data = response.json();\n reward = -float(data['data'])\n except Exception as e:\n print(e);\n reward = float('nan')\n return reward\n\n def _simplePostPolicy(self, policy):\n \"\"\"\n The helper function to get the reward for a given policy (sequence of actions).\n \n Parameters:\n policy (object): The policy to be posted.\n \n Returns:\n reward: The episodic reward associated with the provided policy or nan if the job is not complete.\n \n \"\"\"\n rewardUrl = '%s/evaluate/policy/'%self._baseuri\n\n try:\n #print(policy)\n response = requests.post(rewardUrl, data = json.dumps(policy), headers = {'Content-Type': 'application/json', 'Accept': 'application/json'});\n data = response.json();\n reward = -float(data['data'])\n except Exception as e:\n print(e);\n reward = float('nan')\n return reward\n\n def evaluateAction(self, action):\n \"\"\"\n A `gym compliant` method to evaluate an action's utility.\n \n Parameters:\n action (object): The action to be posted.\n \n Raises:\n ValueError\n If Request would exceed the permitted number of Evaluations.\n If the interventions in the actions are not in [0,1].\n If there are not two interventions per action.\n\n Returns:\n unnamed (tuple): The next state, the provided reward, is the next state the terminal state, {}.\n \n \"\"\"\n reward = float(\"nan\")\n print(self.experimentsRemaining, \" Evaluations Remaining\")\n if self.experimentsRemaining <= 0:\n raise ValueError('You have exceeded the permitted number of evaluations')\n\n if any([any((i<0, i>1)) for i in action]):\n raise ValueError('Interventions should be in [0,1]')\n try:\n action = [action[0],action[1]]\n except:\n raise ValueError('Two interventions are required per action')\n \n self.experimentsRemaining -= 1\n\n if ~self.done and self.state <= self.policyDimension:\n reward = self._simplePostAction(action)\n self.action = action\n self.state += 1\n\n if self.state > self.policyDimension: self.done = True\n self.history.append([self.state-1, action[0], action[1], reward])\n return self.state, reward, self.done, {}\n\n def evaluatePolicy(self, data, coverage = 1):\n \"\"\"\n The function to post one or more policies and blocks until evaluated (or abandoned). Evaluations will be performed in parallel and are limited by the realworker count.\n \n Parameters:\n data (object): The policy or policies to be evaluated.\n coverage (float): The minimum portion of the data that must be returned.\n \n Raises:\n ValueError\n If Request would exceed the permitted number of Evaluations.\n If the policies to be evaluated aren't stored in a dictionary or a list of dictionaries.\n If any intervention is not in [0,1]\n \n Returns:\n states: A list containing either the states associated with the provided actions or a list of lists of states if multiple sequences of actions (i.e. multiple policies) were sent for evaluation.\n reward: A list containing either the rewards associated with the provided action or nan if the action is not complete for all actions to be evaluated.\n \n \"\"\"\n print(self.experimentsRemaining, \" Evaluations Remaining\")\n\n from multiprocessing import Pool\n if type(data) is list and all([type(i) is dict for i in data]): #list of policies\n states = []\n for apolicy in data:\n states.append([i for i in apolicy.keys()])\n if any([any((i[0]<0,i[0]>1,i[1]<0,i[1]>1)) for i in [apolicy[k] for k in apolicy]]):\n raise ValueError('All interventions should be in [0,1]')\n self.experimentsRemaining -= len(data)*5\n if self.experimentsRemaining < 0:\n raise ValueError('Request would exceed the permitted number of Evaluations')\n pool = Pool(self._realworkercount)\n result = pool.map(self._simplePostPolicy, data)\n pool.close()\n pool.join()\n self.history1.append([i for i in zip(data,result)])\n elif type(data) is dict:\n self.experimentsRemaining -= 1*5\n if self.experimentsRemaining < 0:\n raise ValueError('Request would exceed the permitted number of Evaluations')\n result = self._simplePostPolicy(data)\n states = [i for i in data.keys()]\n self.history1.append([data,result])\n else:\n raise ValueError('argument should be a policy (dictionary) or a list of policies')\n \n return states, result\n","sub_path":"ushiriki_policy_engine_library/SimpleChallengeEnvironment.py","file_name":"SimpleChallengeEnvironment.py","file_ext":"py","file_size_in_byte":9455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"234684905","text":"## Script (Python) \"unicodeIntersect\"\n##title=Test if a unicode string is in a unicode list\n##bind container=container\n##bind context=context\n##bind namespace=\n##bind script=script\n##bind subpath=traverse_subpath\n##parameters=values, vocab\n\nif vocab is None or len(vocab) == 0:\n return []\n\ndef unicodeEncode(value, site_charset=None):\n # Recursively deal with sequences\n tuplevalue = same_type(value, ())\n if (tuplevalue or same_type(value, [])):\n encoded = [unicodeEncode(v) for v in value]\n if tuplevalue:\n encoded = tuple(encoded)\n return encoded\n\n if not isinstance(value, basestring):\n value = str(value)\n\n if site_charset is None:\n site_charset = context.getCharset()\n\n if same_type(value, ''):\n value = unicode(value, site_charset)\n\n # don't try to catch unicode error here\n # if one occurs, that means the site charset must be changed !\n return value.encode(site_charset)\n\nunicode_vocab = {unicodeEncode(v) for v in vocab}\nunicode_values = [unicodeEncode(v) for v in values]\nreturn [v for v in unicode_values if v not in unicode_vocab]\n","sub_path":"src/mars/skin/skins/mars_skin_custom_templates/unicodeExclude.py","file_name":"unicodeExclude.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"6657024","text":"#!/usr/bin/python3.4\n#note python3 only\nimport readline \nimport xml.dom.minidom\nfrom xml.dom.minidom import parse, parseString\nimport urllib.request \nimport subprocess\nimport highlighter\nimport os\nimport sys \n\n\nclass NNDCParser():\n \n def __init__(self):\n \"\"\"\n feed method is our entry where we start to get the table, and it will\n break down the table row by row, each row will be send to\n 'parse_a_row' to extract the energy, spin, gammas.But we have to deal\n with the last row indiviually.\n \n the data structure\n levels[ level1, level2, level3 ]\n \n level={}\n level['Ex']= float, energy of a level\n level['Ex_err'] = float, error of the enery\n level['ref'] = list, each element is string, ex 'A', 'B' \n level['spin'] = str, \"3/2+\"\n level['lifetime'] = str\n level['lifetime_unit'] = str\n level['lifetime_err'] = str\n level['lifetime_sec'] = float\n \n level['gammas'] = [ gamma1, gamma2, ... ]\n gamma = {}\n gamma['eng'] = float, gamma energy\n gamma['err'] = float, gamma energy err\n gamma['?'] = bool, not certrain\n gamma['I'] = str, relative intensity ( having <50 ..format)\n gamma['I_err'] = str, relative intensity error\n \n level['final_states'] = [ float, float, ...]\n \n one can use print_result method to check the data.\n \n \"\"\"\n self.__levels = []\n self.__col_Dict={}\n self.refs = {}\n pass\n \n def feed(self, content ): \n \"\"\" to extact the each raw from the table, \n and then pasre the data in a row. \"\"\"\n\n # foward the data to the table with levels and gammas\n marker = \"<TABLE cellspacing=1 cellpadding=4 width=800>\"\n idx_tmp = content.find(marker)\n length_tmp = len( marker )\n refs = content[ : idx_tmp ]\n self.__parse_refs( refs )\n content = content[ idx_tmp+length_tmp: ]\n \n # In general, we have multiple rows in the table.\n # only the first row have the close tag \"</tr>\"\n # other row just open tab <tr>\n tag_tr_i = \"<tr\"\n tag_tr_m = \">\"\n tag_tr_f = \"</tr>\"\n \n idx_tr_i = content.find( tag_tr_i ) \n idx_tr_m = content.find( tag_tr_m, idx_tr_i ) \n idx_tr_f = content.find( tag_tr_f, idx_tr_m ) \n \n\n \n # check if we do find the tag.\n go_on = (idx_tr_i != -1 and idx_tr_m != -1 and idx_tr_f != -1 )\n \n # cut the first row off, it is the table header\n # we need to parse the header, the column content is not \n # always in the same order. \n if( go_on ):\n idx2 = idx_tr_f + len( tag_tr_f )\n header = content[ :idx2 ]\n self.__parse_header(header) # header analysis.\n content = content[ idx2: ] # the rest data.\n \n \n \n # the rest rows are having a single <tr> without </tr>\n # so we need to reset the tag_tr_i to '<tr>' from '<tr'\n tag_tr_i = \"<tr>\"\n while ( go_on ):\n # since no </tr> close tag, \n # I can only search for next <tr> as a marker.\n # and let the <tr> .... <tr> ..... structure as our go_on indication.\n # In this way, we will miss the last row.\n # Hence, we have to deal with the last row latter.\n idx1 = content.find( tag_tr_i ) \n idx2 = content.find( tag_tr_i, idx1 + len(tag_tr_i) )\n\n if( idx1 == -1 or idx2 == -1): \n \n go_on = False\n \n else:\n \n aRowData = content[ idx1 + len( tag_tr_i ): idx2 ]\n \n # append the return from parse_a_row to our __levels list. \n self.__levels.append( self.parse_a_row( aRowData ) )\n \n # forward the content to next row. \n content = content[ idx2: ]\n \n #print(\"\\n\", content.replace(\" \",\"\") )# for testing.\n\n \n # deal with the last row. \n tag_tr = \"<tr>\"\n tag_table = \"</table>\"\n idx_tr = content.find( tag_tr )\n idx_table = content.find( tag_table )\n lastRow = content[ idx_tr + len(tag_tr): idx_table ]\n self.__levels.append( self.parse_a_row( lastRow ) )\n #print( lastRow.replace(\" \",\"\") ) \n \n pass \n \n def __parse_refs( self, data ):\n \"to parse a table with 4 columns\"\n \n # take off <table> tag.\n marker1 = \"<table cellspacing=1>\"\n marker2 = \"</table>\"\n idx1 = data.find( marker1 )\n idx2 = data.find( marker2, idx1 )\n data = data[ idx1+len(marker1): idx2 ]\n \n # only first row and last row have </tr> tag.\n tag_tr_i = \"<tr>\"\n tag_tr_f = \"</tr>\"\n go_on = True\n \n while( go_on ):\n idx_tr_i = data.find( tag_tr_i ) \n idx_tr_f = data.find( tag_tr_f, idx_tr_i ) \n \n \n if( idx_tr_i == -1 and idx_tr_f == -1 ):\n go_on = False\n else:\n \n aRow = data[ idx_tr_i + len(tag_tr_i): idx_tr_f ]\n self.__ref_aRow( aRow ) # self.refs will be updated here.\n data = data[ idx_tr_f: ]\n \n pass\n pass\n \n def __ref_aRow(self, data ):\n tag_i = \"<td\"\n tag_f = \"</td>\"\n go_on = True\n \n tmp = []\n \n if( data.find(\"References\") != -1 ): return\n \n while( go_on ):\n idx_i = data.find( tag_i ) \n idx_f = data.find( tag_f, idx_i ) \n \n \n if( idx_i == -1 and idx_f == -1 ):\n go_on = False\n else:\n \n aCol = data[ idx_i + len(tag_i): idx_f ]\n aCol = aCol.replace(\"align=left nowrap>\",\"\")\n aCol = aCol.replace(\"align=center>\",\"\")\n aCol = aCol.replace(\" \",\"\")\n aCol = aCol.replace(\"<sup>\",\"\")\n aCol = aCol.replace(\"</sup>\",\"\")\n aCol = aCol.replace(\"α\",\"a\")\n aCol = aCol.replace(\"β\",\"b\")\n aCol = aCol.replace(\"γ\",\"g\")\n aCol = aCol.replace(\"μ\",\"g\")\n aCol = aCol.replace(\"’\",\"'\")\n tmp.append( aCol )\n \n data = data[ idx_f: ]\n #--------------------------------end of while\n \n # assign data to self.refs\n # note: we have the following structure.\n #[' I', ' 28Si(18O,15O)', ' J', ' 31P(g-,NU)']\n # [' K', ' 31P(n,p)', ' ']\n sizeN = len( tmp )//2 * 2 \n for i in range( 0, sizeN, 2 ):\n self.refs[ tmp[i] ] = tmp[i+1]\n \n \n \n pass\n\n def __parse_header(self, header ):\n \"\"\"\n we have data look like:\n <tr><td class=\"header\">E(level)<br>(keV)</td><td class=\"header\">XREF</td>\n <td class=\"header\">Jπ(level)</td><td class=\"header\"> T<sub>1/2</sub>(level)</td>\n <td class=\"header\">E(γ)<br>(keV)</td><td class=\"header\">I(γ)</td>\n <td class=\"header\">M(γ)</td><td class=\"header\" colspan=2>Final level </td>\n </tr>\n and we have to parse to know which column corresponds to which type of data.\n we assign it into self.\n The data will be stored at self.__col_Dict\n \"\"\"\n tag_tr_i = \"<tr>\"\n tag_tr_f = \"</tr>\"\n idx_tr_i = header.find( tag_tr_i ) \n idx_tr_f = header.find( tag_tr_f, idx_tr_i ) \n \n # remove the outermost <tr> and </tr> tags.\n header = header[ idx_tr_i+len(tag_tr_i) : idx_tr_f ]\n\n # we have two possible tags, with/withoug \"colspan=2\"\n tag_td_i = '<td class=\"header\">'\n tag_td_i2 = '<td class=\"header\" colspan=2>'\n \n tag_td_f = \"</td>\"\n go_on = True\n col = 1\n \n \n while ( go_on ):\n \n # search <td> ... </td> tags.\n idx1A = header.find( tag_td_i ) \n idx1B = header.find( tag_td_i2 ) \n idx2 = header.find( tag_td_f, idx1A + len(tag_td_i) )\n \n if( idx2 == -1): \n \n go_on = False\n \n else:\n \n # to get a column data \n if( idx1A != -1 ):\n aColData = header[ idx1A + len( tag_td_i ): idx2 ]\n \n elif( idx1B != -1 ): \n aColData = header[ idx1B + len( tag_td_i2 ): idx2 ]\n \n \n \n # assign which col to which type of data.\n if( aColData.find('E(level)') != -1 ): self.__col_Dict[ \"Ex\" ] = col \n elif( aColData.find('XREF') != -1 ): self.__col_Dict[ \"XREF\" ] = col \n elif( aColData.find('J&pi') != -1 ): self.__col_Dict[ \"Jpi\" ] = col \n elif( aColData.find('T<sub>1/2</sub>') != -1 ): self.__col_Dict[ \"T\" ] = col \n elif( aColData.find('E(γ)') != -1 ): self.__col_Dict[ \"gamma\"] = col \n elif( aColData.find('I(γ)') != -1 ): self.__col_Dict[ \"I\" ] = col\n elif( aColData.find('M(γ)') != -1 ): self.__col_Dict[ \"M\" ] = col \n elif( aColData.find('Final level') != -1 ): self.__col_Dict[ \"flevel\" ] = col \n else:\n print( aColData )\n \n \n # forward the content to next col. \n header = header[ idx2: ]\n col += 1\n pass\n \n\n\n def parse_a_row(self, aRowData ):\n \"\"\" to parse data in <tr> ... </tr>, which I call a row.\n In a row, we have multiple <td>...</td> tags, which I call cells.\n In some cases, the last row only has the <td> but no </td> tag. \n \"\"\"\n \n # define a dictionary object 'level', and we will return it,\n # which will be appended into self.__levels\n level = {}\n\n level['?'] = False # default, a level is not uncertain. \n Ex_status = True # for excitation energy level\n go_on = True\n col_idx = 0 # for col index.\n\n\n tag_td_i = \"<td\"\n tag_td_m = \">\"\n tag_td_f = \"</td>\"\n \n while ( go_on ):\n idx1 = aRowData.find( tag_td_i ) \n idxm = aRowData.find( tag_td_m, idx1 ) \n idx2 = aRowData.find( tag_td_f, idx1 + len(tag_td_i) + 1 )\n \n if( idx1 == -1 or idx2 == -1): \n \n go_on = False\n # when we cannot find <td> .... </td> structure \n # we will exist the loop.\n \n else:\n \n \n col_idx += 1\n \n # to analyze a cell \n cellData = aRowData[ idxm + 1: idx2 ]\n cellData = cellData.replace( \" \", \"\")\n \n \n # the Ex cell also serves as a filter,\n # only when Ex is ok, we extract the other properties of this level.\n if( \"Ex\" in self.__col_Dict and col_idx == self.__col_Dict[\"Ex\"] ):\n \n \n \n Ex_status = self.check_Ex( cellData ) \n \n \n \n if( Ex_status ):\n level['Ex'], level['Ex_err'] = \\\n self.get_Ex_and_Err( cellData, level['?'] ) \n # Ex, and Ex_err will update through return value,\n # '?' will be update in this place.\n \n \n \n \n if( \"XREF\" in self.__col_Dict and col_idx == self.__col_Dict[\"XREF\"] and Ex_status ):\n level['ref'] = self.__parse_XREF( cellData ) \n \n \n \n if( \"Jpi\" in self.__col_Dict and col_idx == self.__col_Dict[\"Jpi\"] and Ex_status ):\n \n cellData = cellData.replace(\" \",\"\")\n # if( cellData == \"\" ): cellData = \"NA\"\n level['spin'] = cellData\n \n \n if( \"T\" in self.__col_Dict and col_idx == self.__col_Dict[\"T\"] and Ex_status ):\n \n level['lifetime'], level['lifetime_unit'], level['lifetime_err'], \\\n level['lifetime_sec'] \\\n = self.get_lifetime( cellData )\n\n\n \n if( \"gamma\" in self.__col_Dict and col_idx == self.__col_Dict[\"gamma\"] and Ex_status ):\n level['gammas'] = self.get_gammas( cellData ) \n\n\n \n if( \"I\" in self.__col_Dict and col_idx == self.__col_Dict[\"I\"] and Ex_status ):\n self.get_relative_intensity( cellData, level['gammas'] ) \n \n \n\n if( \"flevel\" in self.__col_Dict and col_idx == self.__col_Dict[\"flevel\"] and Ex_status ): \n level['final_states'] = self.get_final_states( cellData )\n pass\n\n aRowData = aRowData[ idx2 + len(tag_td_f) : ]\n \n if(0): print(\"TEST\", col_idx , cellData )\n if(0): print( aRowData )\n \n \n \n \n \n return level\n \n \n def check_Ex(self, Ex_string ):\n \"\"\" we ignore the states from unplaced band head, which Ex_status = False\n \"\"\"\n Ex_status = True\n if( Ex_string[0]==\"(\" and Ex_string[-1]==\")\" ): Ex_status = False\n \n symbols = ( \"A\", \"B\", \"C\", \"D\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\" )\n \n for sym in symbols:\n if( len(Ex_string) == 1 and (Ex_string.find( sym ) != -1) ):\n Ex_status = False\n \n sym = \"+\"+sym\n if( len(Ex_string) > 1 and (Ex_string.find( sym ) != -1) ):\n Ex_status = False\n pass\n\n if( Ex_string.find( \"&ge\" ) != -1 ): Ex_status = False\n if( Ex_string.find( \">\" ) != -1 ): Ex_status = False\n if( Ex_string.find( \"<\" ) != -1 ): Ex_status = False\n if( Ex_string.find( \"SP\" ) != -1 ): Ex_status = False\n if( Ex_string.find( \"Syst.\")!= -1 ): Ex_status = False\n return Ex_status\n \n \n \n \n def get_Ex_and_Err(self, data, uncertain):\n \"\"\" to extract the excitation energy and error from data,\n normally, it has format as 1000 2,\n the second number is uncertainty.\n \"\"\"\n Ex = -1. ; err = -1.\n\n items = data.split(\" \")\n \n # Ex part.\n Ex = items[0]\n Ex = Ex. replace( \"S\", \"\" ) #ex. 6587.40 4 S\n \n # if we have 1000? \n if( Ex[-1] == \"?\" ):\n uncertain = True\n Ex = Ex.replace( \"?\", \"\" )\n \n # if we have ~1000 \n if( Ex.find(\"≈\") != -1 ):\n # remove the approximation sign.\n Ex = Ex. replace( \"≈\", \"\" )\n\n # Ex err part\n if ( len(items) > 1):\n \n # use this condition to make sure we do have uncertainty term.\n # the err has the <i> </i> tags.\n err = items[1]\n err = err.replace(\"<i>\", \"\")\n err = err.replace(\"</i>\", \"\")\n err = err.replace(\"S\", \"\")\n \n if( err[-1]==\"?\" ):\n uncertain = True\n err = err.replace(\"?\", \"\")\n \n \n err = float( err )\n Ex = float ( Ex )\n return Ex, err\n \n def __parse_XREF( self, data ):\n tag_a_i = \"<a\"\n tag_a_m = '\">'\n tag_a_f = \"</a>\"\n go_on = True\n refs = []\n \n while( go_on ):\n\n idx1 = data.find( tag_a_i ) \n idxm = data.find( tag_a_m, idx1 ) \n idx2 = data.find( tag_a_f, idx1 + len(tag_a_i) + 1 )\n \n if( idx1 == -1 or idx2 == -1): \n go_on = False\n else:\n refTemp = data[ idxm+len(tag_a_m): idx2 ]\n refs.append( refTemp )\n \n # to forward \n data = data[ idx2: ]\n pass\n\n return refs\n \n \n\n def __lifetime_to_sec(self, lifetime, unit):\n \"\"\" doing the unit conversion, and make lifetime in unit of second\"\"\"\n if( unit == \"\" ): return 0.\n if( lifetime == \"\" ): return 0. \n if( unit.find(\"eV\") != -1 ): return 0. \n if( lifetime.find(\"<\") != -1 ): return 0.\n \n unit_s = 0.0\n if( unit == \"s\" ): unit_s = 1.\n elif( unit == \"m\" ): unit_s = 1. * 60.\n elif( unit == \"h\" ): unit_s = 1. * 60. * 60.\n elif( unit == \"d\" ): unit_s = 1. * 60. * 60. * 24.\n elif( unit == \"y\" ): unit_s = 1. * 60. * 60. * 24. * 365.\n elif( unit == \"ms\" ): unit_s = 1.E-3\n elif( unit == \"µS\" ): unit_s = 1.E-6\n elif( unit == \"ns\" ): unit_s = 1.E-9\n elif( unit == \"ps\" ): unit_s = 1.E-12\n elif( unit == \"fs\" ): unit_s = 1.E-15\n elif( unit == \"as\" ): unit_s = 1.E-18\n else:\n print( \"TEST\", unit )\n \n \n \n lifetime_sec = 0.0\n try:\n lifetime_sec = float( lifetime )\n except:\n pass\n \n lifetime_sec = lifetime_sec * unit_s\n return lifetime_sec \n pass\n\n\n def get_lifetime(self, data):\n \"\"\"\n note: we can have the following format.\n 157.36 m <i>26</i> <br> % β<sup>-</sup> = 100 <br> \n \"\"\"\n\n # To skip the second raw, such as % p = 99.\n data1 = data.split(\"<br>\")[0]\n \n \n lifetime = \"0.0\"\n lifetime_unit = \"\"\n lifetime_err = \"0.0\"\n\n if( data1.find(\"<\") != -1 or \\\n data1.find(\">\") != -1 or \\\n data1.find(\"≤\") != -1 or \\\n data1.find(\"≥\") != -1 ): \n \n items = data1.split(\" \")\n\n # ['', '<', '5.0', 'ns', '']\n if( len(items) > 1 ):\n lifetime = \"<\" + items[2]\n lifetime_unit = items[3]\n\n elif( data1.find(\"asymp;\") != -1 ): \n \n items = data1.split(\" \")\n \n # ['', '≈', '0.5', 'ns', '']\n if( len(items) > 1 ):\n lifetime = \"<\" + items[2]\n lifetime_unit = items[3]\n\n else:\n items = data1.split(\" \")\n if ( len(items) > 3):\n lifetime = items[1]\n lifetime_unit = items[2]\n lifetime_err = items[3]\n lifetime_err = lifetime_err.replace(\"<i>\", \"\")\n lifetime_err = lifetime_err.replace(\"</i>\", \"\")\n\n if( data1.find(\"%\") != -1 ):\n lifetime = \"0.0\"\n lifetime_unit = \"\"\n lifetime_err = \"0.0\"\n \n \n lifetime_sec = self.__lifetime_to_sec( lifetime, lifetime_unit )\n return lifetime, lifetime_unit, lifetime_err, lifetime_sec \n \n \n \n def get_gammas(self, data):\n \n \"\"\" parse the gamma info, we data looks like: \n 943.2 <i>7</i><br>1694.87 <i>5</i><br>\n it contins multiple gammas.\n \n rare cases:\n 5 <i>Calc.</i>S<br> .... \n \"\"\"\n gamma_infos = []\n \n items = data.split(\"<br>\")\n # the last one is \"\", \n # so I require at least have one gamma.\n if( len(items)>1 ):\n for item in items:\n \n if( item.find(\"Calc\") != -1 ):\n # not include the calculated one.\n pass\n elif( len(item)>1):\n # the len(item) condition is to ignore the last \"\"\n gamma_infos.append( item )\n pass\n pass\n \n \n # now we have a list\n # [ '943.2 <i>7</i>', '1694.87 <i>5</i><br>']\n gammas = []\n \n for gamma_info in gamma_infos:\n gamma = {}\n gamma['?'] = False\n gamma_eng = \"\"\n gamma_err = 0\n \n \n items = gamma_info.split()\n if( len(items) > 1):\n # enery part\n gamma_eng = items[0]\n \n if( gamma_eng[-1] == \"?\" ): \n gamma['?'] = True\n gamma_eng = gamma_eng.replace( \"?\", \"\")\n \n \n \n gamma_err = items[1]\n if( gamma_err[-1] == \"?\"): \n gamma['?'] = True\n gamma_err = gamma_err.replace( \"?\", \"\")\n gamma_err = gamma_err.replace(\"<i>\", \"\")\n gamma_err = gamma_err.replace(\"</i>\", \"\")\n gamma_err = gamma_err.replace( \"S\", \"\")\n \n elif( len(items) == 1):\n \n gamma_eng = items[0]\n gamma_eng = gamma_eng.replace( \"≈\", \"\")\n \n \n if( gamma_eng[-1] == \"?\" or gamma_eng[-1] == \")\" ): \n gamma['?'] = True\n gamma_eng = gamma_eng.replace( \"?\", \"\")\n gamma_eng = gamma_eng.replace( \"(\", \"\")\n gamma_eng = gamma_eng.replace( \")\", \"\")\n \n gamma_eng = gamma_eng.replace( \"S\", \"\") # 0+ --> 0+\n \n gamma_eng = float( gamma_eng )\n gamma_err = float( gamma_err )\n gamma['eng'] = gamma_eng\n gamma['err'] = gamma_err\n gammas.append( gamma )\n \n return gammas\n pass\n \n \n def get_relative_intensity(self, data, gams ):\n \"\"\"\n we have data look likes:\n 100<br>\n 1.01 <i>25</i><br>100 <i>5</i><br>\n 18 <i>4</i><br>22 <i>6</i><br>100 <i>8</i><br>\n 16 <i>6</i><br><3.5<br><3.5<br>100 <i>6</i><br>\n \"\"\"\n \n items = data.split(\"<br>\")\n if len( items ) <= 1: return 0\n if( \"\" in items ): items.remove(\"\")\n if( len(items) != len(gams) ): return 0\n \n \n cnt = 0\n for item in items:\n \n \n \n # ignore the empty one.\n if( item == \"\" ): continue\n if( item.find(\"<i>\") != -1 ):\n things = item.split(\" \")\n \n gams[cnt]['I'] = things[0]\n I_err = things[1]\n I_err = I_err.replace(\"<i>\", \"\")\n I_err = I_err.replace(\"</i>\", \"\")\n gams[cnt]['I_err']= I_err\n \n cnt += 1\n pass\n else:\n \n \n #just single value or with \"<\"\n gams[cnt]['I_err'] = \"\"\n if( item.find(\"<\") != -1 ): \n things = item.split( \"<\" ) \n gams[cnt]['I'] = \"<\" + things[1]\n if(0): print( gams[cnt]['I'] )\n else:\n gams[cnt]['I'] = item.rstrip()\n \n \n cnt += 1\n\n\n \n def get_final_states( self, data ):\n \"\"\"\n we data looks like:\n 2316.93<br>1694.91<br>752.23<br>0<br>\n \"\"\"\n finalSates = []\n items = data.split(\"<br>\")\n \n \n \n # the last term = \"\", so I requre at least 2 items.\n if( len(items)>1 ):\n for item in items:\n # in some case we will empty one.\n if( item != ' ' and len(item) >= 1 ):\n #item = item.replace(\"+X\", \"\")\n #item = item.replace(\"+Y\", \"\")\n #item = item.replace(\"+Z\", \"\")\n item = float(item )\n finalSates.append( item )\n \n return finalSates\n pass\n\n\n def get_levels(self): return self.__levels\n\n def print_levels(self, upperLimt=9999999.0):\n \"\"\"by default, we will print all the levels,\n use upperLimt is in unit of keV. \"\"\"\n\n outStr = \"\"\n \n for level in self.__levels:\n if( level['Ex'] <= upperLimt ):\n if( 'spin' not in level or level['spin'] == \"NA\" ):\n s = \"@lvlE %7.3f \" %(level['Ex'] )\n else:\n s = \"@lvlE %7.3f @spin %s \"\\\n %(level['Ex'], level['spin'] )\n \n outStr += s\n outStr += \"\\n\"\n \n # deal with the final state(s)\n #'final_states' are the states the gammas decay to\n if( 'final_states' in level.keys() and \\\n len(level['final_states'] )>1 ):\n \n gam_cnt = 0 \n for final_state in level['final_states'] :\n Ei = level['Ex']\n Ef = final_state\n gam = level['gammas'][gam_cnt]\n gammaE = gam['eng'] \n s = \"@Ei %8.3f @Ef %8.3f @E %8.3f\" %(Ei, Ef, gammaE) \n \n outStr += s\n outStr += \"\\n\"\n gam_cnt += 1\n\n s = (\"#\" + \"=\"*78) # separation line.\n outStr += s\n outStr += \"\\n\"\n \n print( outStr )\n \n \n \n def reset(self): \n self.__levels = []; \n self.__col_Dict = {}\n self.refs = {}\n \n \n \n \nclass Run():\n '''\n an interface for NNDCParser.\n '''\n def __init__( self, inFile=\"\"):\n \n\n # upper energy limit.\n self.lvlE_limitU = 3000 # -1 = no limit\n\n self.__A_min = 1\n self.__A_max = -1 # -1 = no limit\n self.__A_flag = 0 # 0 = none, 1 = odd, 2 = even\n\n self.__Z_min = 1\n self.__Z_max = -1 # -1 = no limit\n self.__Z_flag = 0 # 0 = none, 1 = odd, 2 = even\n\n self.__N_min = 0\n self.__N_max = -1 # -1 = no limit\n self.__N_flag = 0 # 0 = none, 1 = odd, 2 = even\n\n self.__As = [] # manual selected A\n self.__Zs = [] # manual selected Z\n self.__Ns = [] # manual selected N\n\n \n self.use_lvl_builder = True\n self.show_gam = True\n\n self.__valid_syms = [] # updated at __load_mass16_table\n self.__nuclei_syms = []\n\n # to use mass16.xml as our symbol table.\n # self.__nuclei_table has a structure of [ (), (), (), ]\n # each elment is ( sym, A, Z, N ) \n self.__nuclei_table = self.__load_mass16_table()\n self.nuclei_list = self.__nuclei_table[:]\n \n # reaction energy table, for Sn, Sp ...\n # each element is a dic, key = sym, Sn, Sp, S2n, S2p, Qa\n self.__rec_eng_table = self.__load_mass16_Sn_table() \n \n self.__useRange = True\n \n self.parser = NNDCParser()\n\n while( 1 ):\n self.__process()\n \n\n def __load_mass16_table( self ):\n '''\n we load mass16.xml as our symbol table.\n '''\n try:\n f = open(\"mass16.xml\",\"r\")\n f.close()\n except:\n print( \"Error: cannot open mass16.xml \")\n print( \"Please check the file.\")\n sys.exit(0)\n\n doc = parse( open(\"mass16.xml\") )\n nuclei_table = doc.getElementsByTagName(\"nuclei\")\n\n nuclei_table_new = []\n for nuclei in nuclei_table:\n sym = nuclei.getAttribute('sym')\n A = nuclei.getAttribute('A')\n Z = nuclei.getAttribute('Z')\n\n A = int(A)\n Z = int(Z)\n N = A-Z\n nuclei_table_new.append( (sym, A, Z, N) ) \n self.__valid_syms.append( sym )\n\n\n return nuclei_table_new\n \n\n def __load_mass16_Sn_table( self ):\n '''\n we load mass16_Sn.xml as our reaction energy table.\n '''\n try:\n f = open(\"mass16_Sn.xml\",\"r\")\n f.close()\n except:\n print( \"Error: cannot open mass16_Sn.xml \")\n print( \"Please check the file.\")\n sys.exit(0)\n\n doc = parse( open(\"mass16_Sn.xml\") )\n eng_table = doc.getElementsByTagName(\"nuclei\")\n\n eng_table_new = []\n for nuclei in eng_table:\n sym = nuclei.getAttribute('sym')\n Sn = nuclei.getAttribute('Sn')\n Sp = nuclei.getAttribute('Sp')\n S2n = nuclei.getAttribute('S2n')\n S2p = nuclei.getAttribute('S2p')\n Qa = nuclei.getAttribute('Qa')\n\n try:\n # print ( \"debug\", Sn,\".\" )\n Sn = float(Sn)\n except:\n Sn = \"None\"\n\n try:\n Sp = float(Sp)\n except:\n Sp = \"None\"\n\n\n try:\n S2n = float(S2n)\n except:\n S2n = \"None\"\n\n\n try:\n S2p = float(S2p)\n except:\n S2p = \"None\"\n\n\n try:\n Qa = float(Qa)\n Sa = -Qa\n except:\n Sa = \"None\"\n \n tmp_dic = { 'sym': sym,\\\n 'Sn' : Sn , 'Sp' : Sp,\\\n 'S2n': S2n, 'S2p': S2p,\\\n 'Sa' : Sa }\n eng_table_new.append( tmp_dic ) \n \n return eng_table_new\n \n\n def __get_eng_limits( self, sym_input, \\\n lowE_type, lowE_shift, uppE_type, uppE_shift ):\n '''\n lowE_type and uppE_type are keys.\n when we can found key 'Sn', 'Sp' ... in a nuclei\n then we return good_status = True.\n note: some nuclei don't have Sn value from table.\n '''\n good_status = True\n if( lowE_type == \"gs\" ): E1 = 0.\n if( uppE_type == \"gs\" ): E2 = 0.\n\n for tmp_dic in self.__rec_eng_table:\n sym = tmp_dic['sym']\n\n if( sym == sym_input ):\n if( lowE_type in tmp_dic ):\n E1 = tmp_dic[lowE_type]\n if( E1 == \"None\" ): good_status = False\n if( uppE_type in tmp_dic ):\n E2 = tmp_dic[uppE_type]\n if( E2 == \"None\" ): good_status = False\n \n if( good_status ): \n E1 += lowE_shift\n E2 += uppE_shift\n else: \n E1 = E2= 0\n \n \n\n return E1, E2, good_status \n pass\n\n\n\n def __print_selected_nuclei( self ):\n '''\n (1) print out the selected nuclei_list\n (2) update self.nuclei_list\n '''\n nuclei_list = []\n\n # -----------manual selection -----------\n # if when using manual selection, the range selection\n # will be skip.\n\n \n\n if len( self.__As ) > 0 :\n for nuclei in self.__nuclei_table:\n A = nuclei[1]\n if A in self.__As: \n nuclei_list.append( nuclei )\n else:\n nuclei_list = self.__nuclei_table[:] \n # print( \"debug 1, len = \", len(nuclei_list) ) \n\n\n tmp_list = []\n if len( self.__Zs ) > 0 : \n for nuclei in nuclei_list:\n Z = nuclei[2]\n if Z in self.__Zs: \n tmp_list.append( nuclei )\n nuclei_list = tmp_list[:]\n # print( \"debug 2, len = \", len(nuclei_list) ) \n\n\n tmp_list = []\n if len( self.__Ns ) > 0 : \n for nuclei in nuclei_list:\n N = nuclei[3]\n if N in self.__Ns: \n tmp_list.append( nuclei )\n nuclei_list = tmp_list[:]\n # print( \"debug 3, len = \", len(nuclei_list) ) \n\n\n\n # -----------range selection -----------\n # do A selection\n tmp_list = []\n if( self.__A_max == -1 ):\n # no limit, so we add in all nuclei.\n for nuclei in nuclei_list:\n tmp_list.append( nuclei )\n elif( self.__A_max >= 1 ):\n for nuclei in nuclei_list:\n A = nuclei[1]\n if( A >= self.__A_min and A <= self.__A_max ):\n tmp_list.append( nuclei )\n nuclei_list = tmp_list[:]\n\n # deal with odd/even A\n tmp_list = []\n for nuclei in nuclei_list:\n A = nuclei[1]\n Odd_A = False\n Even_A = False\n if( A % 2 == 1 ): Odd_A = True\n if( A % 2 == 0 ): Even_A = True\n if( self.__A_flag == 1 and Odd_A ):\n tmp_list.append( nuclei )\n elif( self.__A_flag == 2 and Even_A ):\n tmp_list.append( nuclei )\n elif( self.__A_flag == 0 ):\n tmp_list.append( nuclei )\n nuclei_list = tmp_list[:]\n\n\n # do Z selection\n tmp_list = []\n if( self.__Z_max == -1 ):\n # no limit, so we add in all nuclei.\n for nuclei in nuclei_list:\n tmp_list.append( nuclei )\n elif( self.__Z_max >= 1 ):\n for nuclei in nuclei_list:\n Z = nuclei[2]\n if( Z >= self.__Z_min and Z <= self.__Z_max ):\n tmp_list.append( nuclei )\n nuclei_list = tmp_list[:]\n\n # deal with odd/even Z\n tmp_list = []\n for nuclei in nuclei_list:\n Z = nuclei[2]\n Odd_Z = False\n Even_Z = False\n if( Z % 2 == 1 ): Odd_Z = True\n if( Z % 2 == 0 ): Even_Z = True\n if( self.__Z_flag == 1 and Odd_Z ):\n tmp_list.append( nuclei )\n elif( self.__Z_flag == 2 and Even_Z ):\n tmp_list.append( nuclei )\n elif( self.__Z_flag == 0 ):\n tmp_list.append( nuclei )\n nuclei_list = tmp_list[:]\n\n\n\n\n # do N selection\n tmp_list = []\n if( self.__N_max == -1 ):\n # no limit, so we add in all nuclei.\n for nuclei in nuclei_list:\n tmp_list.append( nuclei )\n elif( self.__N_max >= 1 ):\n for nuclei in nuclei_list:\n N = nuclei[3]\n if( N >= self.__N_min and N <= self.__N_max ):\n tmp_list.append( nuclei )\n nuclei_list = tmp_list[:]\n\n # deal with odd/even Z\n tmp_list = []\n for nuclei in nuclei_list:\n N = nuclei[3]\n Odd_N = False\n Even_N = False\n if( N % 2 == 1 ): Odd_N = True\n if( N % 2 == 0 ): Even_N = True\n if( self.__N_flag == 1 and Odd_N ):\n tmp_list.append( nuclei )\n elif( self.__N_flag == 2 and Even_N ):\n tmp_list.append( nuclei )\n elif( self.__N_flag == 0 ):\n tmp_list.append( nuclei )\n nuclei_list = tmp_list[:]\n\n # update \n self.nuclei_list = nuclei_list[:]\n\n # output sting\n outStr = \"\\n %4d nuclei are selected:\\n \"\\\n %len( nuclei_list)\n \n \n\n if len( nuclei_list) > 10:\n # over than 10 items\n\n \n # first 5\n for nuclei in nuclei_list[:5]:\n sym = nuclei[0]\n outStr += \"%5s \" %sym\n outStr += \"...\\n \"\n\n # last 5\n tmp_list = []\n for i in range(5):\n idx = -1*i - 1\n nuclei = nuclei_list[ idx ]\n sym = nuclei[0]\n tmp_list.append( sym)\n \n for x in reversed( tmp_list):\n outStr += \"%5s \" %x\n else:\n # less or equal to 10 items.\n itemp = 0\n for nuclei in nuclei_list[:10]:\n sym = nuclei[0]\n outStr += \"%5s \" %sym\n itemp += 1\n if itemp == 5: outStr += \"\\n \"\n\n\n #=========================================\n # for manual input\n if( not self.__useRange ):\n outStr2 = \"\\n %4d nuclei are selected:\\n \"\\\n %len(self.__nuclei_syms)\n \n if len(self.__nuclei_syms) > 10:\n #first 5\n for sym in self.__nuclei_syms:\n outStr2 += \"%5s \" %sym\n outStr2 += \"...\\n \"\n #last 5\n for i in range(5):\n idx = -1*i - 1\n sym = self.__nuclei_syms[idx]\n outStr2 += \"%5s \" %sym\n else:\n # less or equal to 10 items.\n itemp = 0\n for sym in self.__nuclei_syms[:10]:\n \n outStr2 += \"%5s \" %sym\n itemp += 1\n if itemp == 5: outStr2 += \"\\n \"\n return outStr2 \n\n\n return outStr \n pass\n\n def __set_A_flag( self ):\n opt = input( \"Set A to (0) none, (1) odd, (2) even :\" )\n opt = opt.rstrip()\n opt = opt.lstrip()\n\n if opt == \"0\" :\n self.__A_flag = 0\n elif opt == \"1\" :\n self.__A_flag = 1\n elif opt == \"2\" :\n self.__A_flag = 2\n else:\n self.__A_flag = 0\n\n def __set_Z_flag( self ):\n opt = input( \"Set Z to (0) none, (1) odd, (2) even :\" )\n opt = opt.rstrip()\n opt = opt.lstrip()\n\n if opt == \"0\" :\n self.__Z_flag = 0\n elif opt == \"1\" :\n self.__Z_flag = 1\n elif opt == \"2\" :\n self.__Z_flag = 2\n else:\n self.__Z_flag = 0\n\n def __set_N_flag( self ):\n opt = input( \"Set N to (0) none, (1) odd, (2) even :\" )\n opt = opt.rstrip()\n opt = opt.lstrip()\n\n if opt == \"0\" :\n self.__N_flag = 0\n elif opt == \"1\" :\n self.__N_flag = 1\n elif opt == \"2\" :\n self.__N_flag = 2\n else:\n self.__N_flag = 0\n\n\n def __set_As( self ):\n As = input( \"input numbers (separate by spaces): \")\n As = As.split()\n for item in As:\n item = int( item )\n self.__As.append( item )\n \n # force to skip range selection.\n if( len( self.__As ) > 0 ):\n self.__A_max = -1 # -1 = no limit\n\n pass\n\n def __set_Zs( self ):\n Zs = input( \"input numbers (separate by spaces): \")\n Zs = Zs.split()\n for item in Zs:\n item = int( item )\n self.__Zs.append( item )\n \n # force to skip range selection.\n if( len( self.__Zs ) > 0 ):\n self.__Z_max = -1 # -1 = no limit\n\n pass\n\n def __set_Ns( self ):\n Ns = input( \"input numbers (separate by spaces): \")\n Ns = Ns.split()\n for item in Ns:\n item = int( item )\n self.__Ns.append( item )\n \n # force to skip range selection.\n if( len( self.__Ns ) > 0 ):\n self.__N_max = -1 # -1 = no limit\n\n pass\n\n\n\n def __set_A_selection( self ):\n \n while( 1 ):\n os.system('clear');\n print( \" ->SELECTION SUMMARY->A SELECTION SUBMENU\")\n print( self.__print_status() )\n print( self.__print_selected_nuclei() )\n print(\" --------------------------------\\n\")\n \n \n print( \" (a) add one or more\" )\n print( \" (s) set odd/even \" )\n print( \" (R) Reset A selections\")\n print( \" (X) Done\")\n print( \" Or input two num for A1 and A2 range (separate by spaces) \")\n opt = input( \"\\nYour choice: \" )\n \n if opt.lower() == \"x\": break\n\n elif opt.lower() == \"a\": self.__set_As()\n\n elif opt.lower() == \"s\": self.__set_A_flag()\n\n elif opt.lower() == \"r\" :\n self.__A_min = 1\n self.__A_max = -1 # -1 = no limit\n self.__A_flag = 0 # 0 = none, 1 = odd, 2 = even\n self.__As = []\n \n \n opt = opt.split()\n if len(opt) == 2:\n As = [ int(opt[0]), int(opt[1]) ] \n self.__A_min = min( As )\n self.__A_max = max( As ) \n if self.__A_min < 1 : self.__A_min = 1\n\n\n def __set_Z_selection( self ):\n \n while( 1 ):\n os.system('clear');\n print( \" ->SELECTION SUMMARY->Z SELECTION SUBMENU\")\n print( self.__print_status() )\n print( self.__print_selected_nuclei() )\n print(\" --------------------------------\\n\")\n \n \n print( \" (a) add one or more\" )\n print( \" (s) set odd/even \" )\n print( \" (R) Reset Z selections\")\n print( \" (X) Done\")\n print( \" Or input two num for Z1 and Z2 range (separate by spaces) \")\n opt = input( \"\\nYour choice: \" )\n \n if opt.lower() == \"x\": break\n\n elif opt.lower() == \"a\": self.__set_Zs()\n\n elif opt.lower() == \"s\": self.__set_Z_flag()\n\n elif opt.lower() == \"r\" :\n self.__Z_min = 1\n self.__Z_max = -1 # -1 = no limit\n self.__Z_flag = 0 # 0 = none, 1 = odd, 2 = even\n self.__Zs = []\n \n \n opt = opt.split()\n if len(opt) == 2:\n Zs = [ int(opt[0]), int(opt[1]) ] \n self.__Z_min = min( Zs )\n self.__Z_max = max( Zs ) \n if self.__Z_min < 1 : self.__Z_min = 1\n\n\n def __set_N_selection( self ):\n \n while( 1 ):\n os.system('clear');\n print( \" ->SELECTION SUMMARY->N SELECTION SUBMENU\")\n print( self.__print_status() )\n print( self.__print_selected_nuclei() )\n print(\" --------------------------------\\n\")\n \n \n print( \" (a) add one or more\" )\n print( \" (s) set odd/even \" )\n print( \" (R) Reset N selections\")\n print( \" (X) Done\")\n print( \" Or input two num for N1 and N2 range (separate by spaces) \")\n opt = input( \"\\nYour choice: \" )\n \n if opt.lower() == \"x\": break\n\n elif opt.lower() == \"a\": self.__set_Ns()\n\n elif opt.lower() == \"s\": self.__set_N_flag()\n\n elif opt.lower() == \"r\" :\n self.__N_min = 1\n self.__N_max = -1 # -1 = no limit\n self.__N_flag = 0 # 0 = none, 1 = odd, 2 = even\n self.__Ns = []\n \n \n opt = opt.split()\n if len(opt) == 2:\n Ns = [ int(opt[0]), int(opt[1]) ] \n self.__N_min = min( Ns )\n self.__N_max = max( Ns ) \n if self.__N_min < 1 : self.__N_min = 1\n\n\n\n\n\n\n def __reset_nuclei_selection( self ):\n self.__A_min = 1\n self.__A_max = -1\n self.__A_flag = 0\n\n self.__Z_min = 1\n self.__Z_max = -1\n self.__Z_flag = 0\n\n self.__N_min = 0\n self.__N_max = -1\n self.__N_flag = 0\n\n self.__nuclei_syms = []\n pass\n\n def __print_A_status( self ):\n \n # range selection part\n if self.__A_max < 1:\n sA_selection = \"None\"\n if self.__A_max >= 1:\n sA_selection = \"%3d:%3d\" %(self.__A_min, self.__A_max)\n\n if self.__A_flag == 1: sA_selection += \" odd A\"\n if self.__A_flag == 2: sA_selection += \" even A\"\n sA_selection = \" A1 <= A <= A2 [current %s]\"%(sA_selection)\n\n # manual selection part\n if len(self.__As) > 0:\n sA_selection = \" A = [\"\n for item in self.__As:\n sA_selection += \"%2d, \" %item\n \n # remove the last \", \"\n sA_selection = sA_selection[:-2]\n sA_selection += \" ]\"\n\n return sA_selection\n \n def __print_Z_status( self ):\n \n # range selection part\n if self.__Z_max < 1:\n sZ_selection = \"None\"\n if self.__Z_max >= 1:\n sZ_selection = \"%3d:%3d\" %(self.__Z_min, self.__Z_max)\n \n if self.__Z_flag == 1: sZ_selection += \" odd Z\"\n if self.__Z_flag == 2: sZ_selection += \" even Z\"\n sZ_selection = \" Z1 <= Z <= Z2 [current %s]\"%(sZ_selection)\n \n # manual selection part\n if len(self.__Zs) > 0:\n sZ_selection = \" Z = [\"\n for item in self.__Zs:\n sZ_selection += \"%2d, \" %item\n \n # remove the last \", \"\n sZ_selection = sZ_selection[:-2]\n sZ_selection += \" ]\"\n\n return sZ_selection\n\n def __print_N_status( self ):\n\n # range selection part\n if self.__N_max < 1:\n sN_selection = \"None\"\n if self.__N_max >= 1:\n sN_selection = \"%3d:%3d\" %(self.__N_min, self.__N_max)\n \n if self.__N_flag == 1: sN_selection += \" odd N\"\n if self.__N_flag == 2: sN_selection += \" even N\"\n sN_selection = \" N1 <= N <= N2 [current %s]\"%(sN_selection)\n\n # manual selection part\n if len(self.__Ns) > 0:\n sN_selection = \" N = [\"\n for item in self.__Ns:\n sN_selection += \"%2d, \" %item\n \n # remove the last \", \"\n sN_selection = sN_selection[:-2]\n sN_selection += \" ]\"\n\n return sN_selection\n\n def __print_status( self ):\n strOut = \"\"\n strOut += self.__print_A_status() + \"\\n\"\n strOut += self.__print_Z_status() + \"\\n\"\n strOut += self.__print_N_status() \n \n return strOut\n\n def __print_select_nuclei_menu( self ):\n \n strOut = \" ->SELECTION SUMMARY\\n\" \n strOut += self.__print_status() + \"\\n\"\n strOut += self.__print_selected_nuclei() + \"\\n\"\n strOut += \" --------------------------------\\n\\n\"\n \n strOut += \" (1) select A or set (A1,A2) range\\n\" \n strOut += \" (2) select Z or set (Z1,Z2) range\\n\" \n strOut += \" (3) select N or set (N1,N2) range\\n\" \n strOut += \" \\n\"\n strOut += \" (4) select nuclei symbols \\n\" \n strOut += \" --------------------------------\\n\"\n strOut += \" (R) Reset selections \\n\"\n strOut += \" (X) Done \\n\"\n print( strOut )\n opt = input(\"Your choice: \")\n \n return opt\n \n pass\n\n \n def __set_sym_selection( self ):\n \n print( \"Input symbols ex. 4He 7Li (separate by spaces), and 0 for reset. \")\n # print( \"Only valid symbols will be added.\")\n opt = input( \"Your choice: \" )\n\n if opt == \"0\":\n self.__nuclei_syms = []\n else:\n syms = opt.split()\n for sym in syms:\n if sym in self.__valid_syms:\n self.__nuclei_syms.append( sym )\n pass\n\n def __select_nuclei( self ):\n \n while( 1 ):\n os.system('clear');\n opt = self.__print_select_nuclei_menu()\n\n if opt == \"1\" :\n self.__useRange = True\n self.__nuclei_syms = [] # reset\n self.__set_A_selection()\n \n elif opt == \"2\" :\n self.__useRange = True\n self.__nuclei_syms = [] # reset\n self.__set_Z_selection()\n\n elif opt == \"3\" :\n self.__useRange = True\n self.__nuclei_syms = [] # reset\n self.__set_N_selection()\n\n elif opt == \"4\":\n # disable selection by range.\n # we do manual input.\n self.__useRange = False\n\n # we set the range selection\n self.__A_min = 1\n self.__A_max = -1\n self.__A_flag = 0\n\n self.__Z_min = 1\n self.__Z_max = -1\n self.__Z_flag = 0\n\n self.__N_min = 0\n self.__N_max = -1\n self.__N_flag = 0\n\n self.__set_sym_selection()\n\n elif opt.lower() == 'r' :\n # to reset ALL\n self.__reset_nuclei_selection()\n\n elif opt.lower() == 'x' :\n break\n\n \n pass\n\n def __set_upper_energy_limit( self ):\n limit = input( \"input the upper energy limits in keV (0=none): \" )\n\n \n try:\n fLimit = float( limit )\n self.lvlE_limitU = fLimit\n except:\n self.lvlE_limitU = -1\n\n if limit == \"0\" : self.lvlE_limitU = -1\n\n\n pass\n\n def __set_use_lvl_builder( self ):\n\n opt = input( \"to use lvl_builder? (y/N): \" )\n if opt.lower() == \"n\" or len(opt)==0: self.use_lvl_builder = False\n elif opt.lower() == 'y': self.use_lvl_builder = True\n else: self.use_lvl_builder = False\n\n def __set_show_gam( self ):\n\n opt = input( \"to show gammas? (y/N): \" )\n if opt.lower() == \"n\" or len(opt)==0: self.show_gam = False\n elif opt.lower() == 'y': self.show_gam = True\n else: self.show_gam = False\n\n def __process( self ):\n '''\n it will be use in the while loop at the __init__, served as \n the main function to interact with a user.\n '''\n opt = self.__print_main_menu()\n \n if( opt.lower() == \"1\" ):\n self.__select_nuclei()\n\n elif( opt.lower() == \"2\" ):\n self.__set_upper_energy_limit()\n\n elif( opt.lower() == \"3\" ):\n self.__set_use_lvl_builder()\n\n elif( opt.lower() == \"4\" ):\n self.__set_show_gam()\n\n elif( opt.lower() == \"a1\" ):\n os.system('clear')\n self.__run_plot_lvl_schemes()\n\n elif( opt.lower() == \"a2\" ):\n os.system('clear')\n self.__run_find_reference()\n\n elif( opt.lower() == \"a3\" ):\n os.system('clear')\n self.__run_plot_lvl_schemes_with_JPIs()\n\n elif( opt.lower() == \"a4\" ):\n os.system('clear')\n self.__run_plot_lvl_schemes_with_stateN()\n\n elif( opt.lower() == \"a5\" ):\n os.system('clear')\n self.__run_plot_lvl_schemes_with_rec_eng()\n\n elif( opt.lower() == \"r\" ):\n self.__reset_to_default()\n\n elif( opt.lower() == \"xx\" ):\n sys.exit(1)\n \n def __print_main_menu( self ):\n '''\n print the main menu and then return the option.\n '''\n os.system('clear');\n \n sNucleiList=\"\"\n if( self.__useRange ):\n # selection by range\n if len(self.nuclei_list)== 0 :\n sNucleiList = \"None\"\n else: \n sNucleiList = \"%2d nuclei\" %len(self.nuclei_list)\n else:\n if len(self.__nuclei_syms)== 0 :\n sNucleiList = \"None\"\n elif len(self.__nuclei_syms) > 5 :\n # over 5 terms\n for sym in self.__nuclei_syms[:5] :\n sNucleiList += \"%s \" %sym\n sNucleiList += \"...\"\n else:\n for sym in self.__nuclei_syms :\n sNucleiList += \"%s \" %sym\n\n # energy upper limit.\n if self.lvlE_limitU == -1:\n sLvlE_limitU = \"None\"\n elif self.lvlE_limitU > 0:\n sLvlE_limitU = \"%.f\" %float( self.lvlE_limitU )\n\n # use lvl_builder\n if self.use_lvl_builder:\n sUseLvlBuilder = \"True\"\n else:\n sUseLvlBuilder = \"False\"\n\n # show gam\n if self.show_gam:\n sShow_gam = \"True\"\n else:\n sShow_gam = \"False\"\n\n strOut = \"\\n ~Welcome to NNDC parser~ \\n\"\n strOut += \"\\n (1) Select nuclei [current: %s]\\n\" %sNucleiList \n strOut+=\" (2) upper engergy limit [current: %5s] (keV)\\n\"%(sLvlE_limitU)\n strOut+=\" (3) to use lvl_builder [current: %5s]\\n\" %(sUseLvlBuilder)\n strOut+=\" (4) to show gammas [current: %5s]\" %(sShow_gam)\n strOut+=\"\"\"\n -----------------------------------------------------------\n (a1) plot level schemes \n (a2) plot level schemes with ref selections.\n (a3) plot level schemes with JPi selections\n (a4) plot level schemes with # of states limt\n (a5) plot level schemes with Sn, Sp...limts\n -----------------------------------------------------------\n (R) Reset to default \n (XX) Exit \n\n Your choice: \"\"\" \n \n opt = input( strOut )\n return opt.lower()\n \n def __reset_to_default( self ):\n '''\n reset ALL setting.\n '''\n self.lvlE_limitU = 3000 # -1 = no limit\n\n self.__A_min = 1\n self.__A_max = -1 # -1 = no limit\n self.__A_flag = 0 # 0 = none, 1 = odd, 2 = even\n\n self.__Z_min = 1\n self.__Z_max = -1 # -1 = no limit\n self.__Z_flag = 0 # 0 = none, 1 = odd, 2 = even\n\n self.__N_min = 0\n self.__N_max = -1 # -1 = no limit\n self.__N_flag = 0 # 0 = none, 1 = odd, 2 = even\n\n self.__As = [] # manual selected A\n self.__Zs = [] # manual selected Z\n self.__Ns = [] # manual selected N\n\n \n self.use_lvl_builder = True\n self.show_gam = True\n\n self.__nuclei_syms = []\n self.__useRange = True\n pass\n\n def __get_symbols( self ):\n '''\n organize our selection to a list of symbols for our \n selected nuclei.\n '''\n if len(self.__nuclei_syms) > 0 :\n return self.__nuclei_syms\n elif len(self.nuclei_list) > 0:\n nuclei_list = []\n for nuclei in self.nuclei_list:\n sym = nuclei[0]\n nuclei_list.append( sym )\n return nuclei_list[:] \n else:\n return []\n\n def __check_has_data( self, nucleus ):\n '''\n to check whether we have data or not for a given nucleus at NNDC\n '''\n url=\\\n 'https://www.nndc.bnl.gov/nudat2/getdataset.jsp?nucleus=%s&unc=nds' %nucleus\n \n marker = \"<TABLE cellspacing=1 cellpadding=4 width=800>\" \n \n content =\"\"\n with urllib.request.urlopen( url ) as f:\n content = f.read().decode('utf-8')\n if( content.find(\"Empty dataset\") != -1 or \\\n content.find(marker) == -1 ): \n return (False, \"\")\n else:\n return (True, content )\n \n def __check_JPI( self, cnt_JPIs, JPINs ):\n flag = False\n\n # ie . (cnt_JP1 < JP1N or cnt_JPI2 < JPI2N) )\n # any one of the condition meets, the flag will be True.\n for i in range( len( JPINs ) ):\n if( cnt_JPIs[i] < JPINs[i] ): \n flag = True\n return flag\n\n def __check_ref( self, state_ref, select_list_ref ):\n flag = False\n\n\n # if our select list of ref has an element in state refs\n # then return true.\n for x in select_list_ref:\n x = x.rstrip();\n x = x.lstrip()\n if x in state_ref:\n flag = True\n return flag\n\n def __write_out_results_and_use_lvl_builder( self, outStr, outStr2 ):\n \n with open(\"nndc_result.txt\",\"w\") as f: f.write( outStr )\n \n if( self.use_lvl_builder ):\n with open(\"bandText_file.txt\",\"w\") as f: f.write( outStr2 )\n cmd = \"./lvl_builder.py nndc_result.txt ./demos/NNDC_config.txt \\\n output.agr bandText_file.txt\" \n subprocess.call( cmd, shell=True)\n \n input(\"press any key to continue..\")\n\n\n def __convert_to_lvl( self, levels, lowerLimt, upperLimt, \\\n idx=0, nuclei_N=1, forceNoGam=False ):\n '''\n levels is the object from parser.get_levels()\n upperlimt is an float number \n idx is used for the band location. \n \n For just one nuclei( nuclei_N =1 ), idx doesn't matter.\n '''\n\n outStr = \"\"\n self.levelN_output = 0\n\n # control the bandN\n if( nuclei_N == 1 ): \n # for one nuclei case.\n bandN = \"0_5\" \n else: \n bandN = \"%d\" %idx\n\n \n for level in levels:\n \n if( 'Ex' in level and \\\n level['Ex'] <= upperLimt and \\\n level['Ex'] >= lowerLimt ):\n \n if( 'spin' not in level or level['spin'] == \"\" ):\n s = \"@lvlE %7.3f%02d @bandN %s @color black \"\\\n %(level['Ex'], idx, bandN )\n else:\n s = \"@lvlE %7.3f%02d @bandN %s @color black @spin %s \"\\\n %(level['Ex'], idx, bandN, level['spin'] )\n \n \n outStr += s\n outStr += \"\\n\"\n self.levelN_output += 1\n\n if( forceNoGam ): continue\n\n if( not self.show_gam ): \n s = (\"#\" + \"=\"*78)\n outStr += s + \"\\n\"\n continue\n \n if( ('final_states' in level) and len(level['final_states'] )>0 ):\n #note: 'final_states' are the states a gamma decay to\n gam_cnt = 0 \n for final_state in level['final_states'] :\n Ei = level['Ex']\n Ef = final_state\n gam = level['gammas'][gam_cnt]\n gammaE = gam['eng'] \n s = \"@Ei %6.3f%02d @Ef %6.3f%02d @color blue @I 10 @label %.f\" \\\n %(Ei, idx, Ef, idx, gammaE) \n \n outStr += s + \"\\n\"\n \n gam_cnt += 1\n s = (\"#\" + \"=\"*78)\n outStr += s + \"\\n\" \n return outStr\n\n def __run_find_reference( self ):\n\n print(\" ->FIND REFERENCES\\n\" )\n print( self.__print_selected_nuclei() )\n print(\" --------------------------------\\n\\n\")\n print(\" proton=>p, beta=>b, gamma=>g, alpah=>a...\")\n print(\" Input the sting you want to search in the references. ex. d,p\" )\n opt = input(\"Your choice: \")\n search_string = opt\n\n nuclei_list = self.__get_symbols() \n nuclei_N = len(nuclei_list)\n outStr = \"\"\n \n \n nuclei_found = []\n nuceli_found_refs = []\n \n # lopping\n for idx, nucleus, in zip( range(nuclei_N), nuclei_list ):\n print( \"doing %4s : %d/%d\" %(nucleus, idx+1, nuclei_N ) )\n \n isHaveData, content = self.__check_has_data(nucleus)\n if( not isHaveData ): continue\n\n \n\n # when we have data, then feed the parser data\n self.parser.feed( content )\n \n # get the experiment references which is a dic.\n # { 'A':'ref1', 'B': 'ref2' }\n refs = self.parser.refs\n found_refs = [] \n isFound = False;\n for key in refs.keys():\n ref_content = refs[key]\n if ref_content.find( search_string ) != -1:\n found_refs.append( key )\n isFound = True\n outStr += \"%5s:(%s) %s \\n\" %(nucleus,key, ref_content )\n \n if( isFound ):\n nuclei_found.append( nucleus )\n nuceli_found_refs.append( found_refs )\n \n # reset and go to next nuclei.\n self.parser.reset()\n \n print(\"\")\n print( outStr )\n opt = input(\"plot levels schemes for the states from above refs (y/N): \" )\n \n if opt.lower() == 'y':\n self.__run_plot_lvl_schemes_with_found_refs( nuclei_found, \\\n nuceli_found_refs )\n\n \n pass\n\n def __run_plot_lvl_schemes( self ):\n print(\" ->PLOT LEVEL SCHEMES\\n\" )\n print( self.__print_selected_nuclei() )\n print(\" --------------------------------\\n\\n\")\n\n nuclei_list = self.__get_symbols() \n nuclei_N = len(nuclei_list)\n opt = \"1\"\n if nuclei_N > 5:\n print(\" You have more than 5 nuclei to plot...\" )\n print(\" (1) use first 5 nuclei only (2) to plot ALL \" )\n opt = input(\"Your choice: \")\n\n if opt == \"1\":\n nuclei_list = nuclei_list[:5]\n nuclei_N = len(nuclei_list)\n\n # upper energy limit control\n if self.lvlE_limitU == -1: \n upperLimt = 999999.\n else: upperLimt = self.lvlE_limitU \n\n\n outStr =\"\" \n outStr2 = \"\"\n\n for idx, nucleus in zip( range(nuclei_N), nuclei_list ):\n \n print( \"doing %4s : %d/%d\" %(nucleus, idx+1, nuclei_N ) )\n \n isHaveData, content = self.__check_has_data(nucleus)\n if( not isHaveData ): continue\n \n # when we have data, then feed the parser data\n self.parser.feed( content )\n \n # retrieve data\n levels = self.parser.get_levels()\n \n # collect lvl input data.\n outStr += self.__convert_to_lvl( levels, 0, upperLimt, idx, nuclei_N )\n \n # collect nuclei data for band text\n # here we don't exclude nuclei with 0 level output.\n outStr2 += '%d \\t \"%s\"\\n' %(idx, nucleus ) \n\n\n \n # reset and go to next nuclei.\n self.parser.reset()\n #---------------------------------------- end of for loop\n\n # print( outStr )\n self.__write_out_results_and_use_lvl_builder( outStr, outStr2 )\n\n\n def __run_plot_lvl_schemes_with_JPIs( self):\n print(\" ->PLOT LEVEL SCHEMES WITH SPIN AND PARITY\\n\" )\n print( self.__print_selected_nuclei() )\n print(\" --------------------------------\\n\\n\")\n\n print(\" input the JPi, ex. 2+, or just + (separate by spaces) \")\n opt = input(\"Your Choice : \")\n JPIs = opt.split()\n \n print(\"\")\n print(\" input the minium num for JPi states (separate by spaces)\")\n opt = input(\"Your Choice : \")\n JPINs = []\n for jpi in opt.split():\n jpi = int(jpi)\n JPINs.append( jpi )\n\n\n nuclei_list = self.__get_symbols() \n nuclei_N = len(nuclei_list)\n opt = \"1\"\n if nuclei_N > 5:\n print(\" You have more than 5 nuclei to plot...\" )\n print(\" (1) use first 5 nuclei only (2) to plot ALL \" )\n opt = input(\"Your choice: \")\n\n if opt == \"1\":\n nuclei_list = nuclei_list[:5]\n nuclei_N = len(nuclei_list)\n\n # upper energy limit control\n if self.lvlE_limitU == -1: \n upperLimt = 999999.\n else: upperLimt = self.lvlE_limitU \n\n outStr =\"\" \n outStr2 = \"\"\n\n for idx, nucleus in zip( range(nuclei_N), nuclei_list ):\n \n print( \"doing %4s : %d/%d\" %(nucleus, idx+1, nuclei_N ) )\n \n isHaveData, content = self.__check_has_data(nucleus)\n if( not isHaveData ): continue\n \n # when we have data, then feed the parser data\n self.parser.feed( content )\n \n # retrieve data\n levels = self.parser.get_levels()\n level_N = len( levels )\n \n # collect nuclei data for band text\n outStr2 += '%d \\t \"%s\"\\n' %(idx, nucleus )\n\n # for state counting.\n cnt_JPIs = [ 0 for _ in range( len(JPIs) ) ] \n \n if( nuclei_N == 1 ): \n # for one nuclei case.\n bandN = \"0_5\" \n else: \n bandN = \"%d\" %idx\n\n\n for level in levels : \n s=\"\"\n # Levels\n if( 'Ex' in level and level['Ex'] <= upperLimt and \\\n self.__check_JPI( cnt_JPIs, JPINs ) ):\n \n if( self.show_gam ):\n # when use gam, we need to have full levels.\n s = \"@lvlE %7.3f%02d @bandN %s @spin %s \"\\\n %(level['Ex'], idx, bandN, level['spin'] )\n \n # no spin info case. \n if( 'spin' not in level or level['spin'] == \"\" ):\n s = \"@lvlE %7.3f%02d @bandN %s \" %(level['Ex'], idx, bandN )\n\n # the states that match our JPIs \n for ii in range( len(JPIs) ):\n if( level['spin'].find( JPIs[ii] ) != -1):\n s = \"@lvlE %7.3f%02d @bandN %s @spin %s \"\\\n %(level['Ex'], idx, bandN, level['spin'] )\n cnt_JPIs[ii] += 1\n \n if( len(s)> 0 ): \n outStr += s + \"\\n\" \n\n if( not self.show_gam ): \n if( len(s)> 0 ): \n s = (\"#\" + \"=\"*78)\n outStr += s + \"\\n\"\n continue\n\n # Gammas\n #'final_states' are the states the gammas decay to\n if( 'final_states' in level.keys() and \\\n len(level['final_states'] )>0 ):\n \n gam_cnt = 0 \n for final_state in level['final_states'] :\n Ei = level['Ex']\n Ef = final_state\n \n gam = level['gammas'][gam_cnt]\n gammaE = gam['eng'] \n s = \"@Ei %8.3f%02d @Ef %8.3f%02d @label %8.f @color blue\" \\\n %(Ei, idx, Ef, idx, gammaE) \n if( self.show_gam ): outStr += s + \"\\n\"\n gam_cnt += 1\n\n s = (\"#\" + \"=\"*78) # separation line.\n outStr += s + \"\\n\"\n # reset and go to next nuclei.\n self.parser.reset()\n #---------------------------------------- end of for loop\n\n # print( outStr )\n self.__write_out_results_and_use_lvl_builder( outStr, outStr2 )\n \n\n def __run_plot_lvl_schemes_with_stateN( self ):\n print(\" ->PLOT LEVEL SCHEMES WITH # OF STATES\\n\" )\n print( self.__print_selected_nuclei() )\n print(\" --------------------------------\\n\\n\")\n\n nuclei_list = self.__get_symbols() \n nuclei_N = len(nuclei_list)\n opt = \"1\"\n if nuclei_N > 5:\n print(\" You have more than 5 nuclei to plot...\" )\n print(\" (1) use first 5 nuclei only (2) to plot ALL \" )\n opt = input(\"Your choice: \")\n\n if opt == \"1\":\n nuclei_list = nuclei_list[:5]\n nuclei_N = len(nuclei_list)\n\n stateNs = [] \n print(\" input the # of states for each select nucleus (separate by spaces) \")\n print(\" or one number for all selected nuclei\")\n opt = input(\"Your Choice : \")\n \n opt = opt.split()\n if len(opt) == 1:\n stateNs = [ int(opt[0]) for _ in range( nuclei_N ) ] \n else:\n for stateN in opt:\n stateN = int(stateN)\n stateNs.append( stateN )\n\n # to avoid missing, we fill the last item for missing ones.\n if len(stateNs) < nuclei_N:\n ndiff = nuclei_N - len(stateNs)\n lastItem = stateNs[-1]\n for ii in range( ndiff ):\n stateNs.append( lastItem )\n\n\n # upper energy limit control\n if self.lvlE_limitU == -1: \n upperLimt = 999999.\n else: upperLimt = self.lvlE_limitU \n\n outStr =\"\" \n outStr2 = \"\"\n\n\n for idx, nucleus in zip( range(nuclei_N), nuclei_list ):\n \n print( \"doing %4s : %d/%d\" %(nucleus, idx+1, nuclei_N ) )\n \n isHaveData, content = self.__check_has_data(nucleus)\n if( not isHaveData ): continue\n \n # when we have data, then feed the parser data\n self.parser.feed( content )\n \n # retrieve data\n levels = self.parser.get_levels()\n \n if( nuclei_N == 1 ): \n # for one nuclei case.\n bandN = \"0_5\" \n else: \n bandN = \"%d\" %idx\n \n # collect nuclei data for band text\n outStr2 += '%d \\t \"%s\"\\n' %(idx, nucleus )\n\n # for state counting.\n cnt_stateN = 0\n \n for level in levels : \n s=\"\"\n # Levels\n if( cnt_stateN < stateNs[idx] ):\n \n # to avoid rare abnormal cases.\n if( 'Ex' not in level ): continue\n \n\n cnt_stateN += 1 \n \n if( 'spin' not in level or level['spin'] == \"\" ):\n # no spin info case. \n s = \"@lvlE %7.3f%02d @bandN %s \" %(level['Ex'], idx, bandN )\n else:\n s = \"@lvlE %7.3f%02d @bandN %s @spin %s \"\\\n %(level['Ex'], idx, bandN, level['spin'] )\n \n if( len(s)> 0 ): \n outStr += s + \"\\n\" \n\n if( not self.show_gam ): \n if( len(s)> 0 ): \n s = (\"#\" + \"=\"*78)\n outStr += s + \"\\n\"\n continue\n\n # Gammas\n #'final_states' are the states the gammas decay to\n if( 'final_states' in level.keys() and \\\n len(level['final_states'] )>0 ):\n \n gam_cnt = 0 \n for final_state in level['final_states'] :\n Ei = level['Ex']\n Ef = final_state\n \n gam = level['gammas'][gam_cnt]\n gammaE = gam['eng'] \n s = \"@Ei %8.3f%02d @Ef %8.3f%02d @label %8.f @color blue\" \\\n %(Ei, idx, Ef, idx, gammaE) \n if( self.show_gam ): outStr += s + \"\\n\"\n gam_cnt += 1\n\n s = (\"#\" + \"=\"*78) # separation line.\n outStr += s + \"\\n\"\n # reset and go to next nuclei.\n self.parser.reset()\n #---------------------------------------- end of for loop\n\n # print( outStr )\n \n self.__write_out_results_and_use_lvl_builder( outStr, outStr2 )\n \n def __run_plot_lvl_schemes_with_found_refs( self, \\\n nuclei_found, nuceli_found_refs ):\n '''\n we don't show gammas since we may miss some states\n if we select states from referenes.\n '''\n\n nuclei_list = nuclei_found\n nuclei_N = len(nuclei_list)\n\n \n # control the number of nuclei to plot\n opt = \"1\"\n if nuclei_N > 5:\n print(\" You have more than 5 nuclei to plot...\" )\n print(\" (1) use first 5 nuclei only (2) to plot ALL \" )\n opt = input(\"Your choice: \")\n\n if opt == \"1\":\n nuclei_list = nuclei_list[:5]\n nuclei_N = len(nuclei_list)\n\n # upper energy limit control\n if self.lvlE_limitU == -1: \n upperLimt = 999999.\n else: upperLimt = self.lvlE_limitU \n\n \n outStr = \"\"\n outStr2 = \"\" \n\n for idx, nucleus in zip( range(nuclei_N), nuclei_list ):\n \n print( \"doing %4s : %d/%d\" %(nucleus, idx+1, nuclei_N ) )\n \n isHaveData, content = self.__check_has_data(nucleus)\n self.parser.feed( content )\n \n # retrieve data\n levels = self.parser.get_levels()\n\n # collect nuclei data for band text\n outStr2 += '%d \\t \"%s\"\\n' %(idx, nucleus )\n\n if( nuclei_N == 1 ): \n # for one nuclei case.\n bandN = \"0_5\" \n else: \n bandN = \"%d\" %idx\n\n for level in levels : \n s=\"\"\n \n # Levels\n if( level['Ex'] <= upperLimt and\\\n self.__check_ref( level['ref'], nuceli_found_refs[idx]) ):\n \n if( 'spin' not in level or level['spin'] == \"\" ):\n # no spin info case. \n s = \"@lvlE %7.3f%02d @bandN %s \" %(level['Ex'], idx, bandN )\n else:\n s = \"@lvlE %7.3f%02d @bandN %s @spin %s \"\\\n %(level['Ex'], idx, bandN, level['spin'] )\n \n if( len(s)> 0 ): \n outStr += s + \"\\n\" \n\n \n if( len(s)> 0 ): \n s = (\"#\" + \"=\"*78)\n outStr += s + \"\\n\"\n \n \n \n # reset and go to next nuclei.\n self.parser.reset()\n #---------------------------------------- end of for loop\n\n # print( outStr )\n \n self.__write_out_results_and_use_lvl_builder( outStr, outStr2 )\n\n pass\n\n def __run_plot_lvl_schemes_with_rec_eng( self ):\n print(\" ->PLOT LEVEL SCHEMES WITH REACTION ENERGY LIMTS\\n\" )\n print( self.__print_selected_nuclei() )\n print(\" --------------------------------\\n\\n\")\n\n print(\" gs = ground state energy = 0. [keV] \")\n print(\" Sn = 1 neutron separation energy [keV] \")\n print(\" Sp = 1 protron separation energy [keV]\")\n print(\" S2n = 2 neutron separation energy [keV]\")\n print(\" S2p = 2 protron separation energy [keV]\")\n print(\" Sa = 1 alpha separation energy (Sa = -Qa) \")\n print(\" input format as 'Sn' , 'Sn + 500' \")\n print(\" \")\n\n lowE = input(\"Your lower energy limit : \")\n lowE_shift = 0.\n\n if( lowE.find(\"+\") != -1 ):\n lowE = lowE.split(\"+\")\n lowE_type = lowE[0]\n lowE_type = lowE_type.strip()\n lowE_shift = float( lowE[1] )\n elif( lowE.find(\"-\") != -1 ):\n lowE = lowE.split(\"-\")\n lowE_type = lowE[0]\n lowE_type = lowE_type.strip()\n lowE_shift = -1*float( lowE[1] )\n else:\n lowE_type = lowE\n lowE_type = lowE_type.strip()\n if lowE_type not in ( \"gs\", \"Sn\",\"S2n\", \"Sp\", \"S2p\", \"Sa\" ):\n print( \"%s is invalid input format\" %lowE ) \n input( \"press any key to continue \")\n return\n\n uppE = input(\"Your upper energy limit : \")\n uppE_shift = 0.\n if( uppE.find(\"+\") != -1 ):\n uppE = uppE.split(\"+\")\n uppE_type = uppE[0]\n uppE_type = uppE_type.strip()\n uppE_shift = float( uppE[1] )\n elif( uppE.find(\"-\") != -1 ):\n uppE = uppE.split(\"-\")\n uppE_type = uppE[0]\n uppE_type = uppE_type.strip()\n uppE_shift = -1*float( uppE[1] )\n else:\n uppE_type = uppE\n uppE_type = uppE_type.strip()\n\n if uppE_type not in ( \"gs\", \"Sn\",\"S2n\", \"Sp\", \"S2p\", \"Sa\" ):\n print( \"%s is invalid input format\" %uppE ) \n input( \"press any key to continue \")\n return\n\n # control the number of nuclei to plot.\n nuclei_list = self.__get_symbols() \n nuclei_N = len(nuclei_list)\n opt = \"1\"\n if nuclei_N > 5:\n print(\" You have more than 5 nuclei to plot...\" )\n print(\" (1) use first 5 nuclei only (2) to plot ALL \" )\n opt = input(\"Your choice: \")\n\n if opt == \"1\":\n nuclei_list = nuclei_list[:5]\n nuclei_N = len(nuclei_list)\n \n\n outStr =\"\" \n outStr2 = \"\"\n \n\n for idx, nucleus in zip( range(nuclei_N), nuclei_list ):\n \n \n isHaveData, content = self.__check_has_data(nucleus)\n if( not isHaveData ): continue\n \n # when we have data, then feed the parser data\n self.parser.feed( content )\n \n # retrieve data\n levels = self.parser.get_levels()\n \n # we have to make sure 'Sn', 'Sp'... data exit.\n # good_status = true tell us, we can get these numbers.\n lowerLimt, upperLimt, good_status = \\\n self.__get_eng_limits( nucleus, \\\n lowE_type, lowE_shift, \\\n uppE_type, uppE_shift )\n\n \n if good_status: \n # collect lvl input data.\n outStr += self.__convert_to_lvl( levels, lowerLimt, upperLimt, \\\n idx, nuclei_N, forceNoGam = True )\n \n \n # collect nuclei data for band text\n outStr2 += '%d \\t \"%s\"\\n' %(idx, nucleus ) \n \n # note: if we want to eliminate the text for empty levels.\n # use ==> if( self.levelN_output > 0 ):\n # levelN_output will be update at __convert_to_lvl()\n \n\n print ( \"doing %4s : %2d/%2d energy range = %5.f to %5.f [keV]\" \\\n %(nucleus, idx+1, nuclei_N, lowerLimt, upperLimt ) )\n\n \n # reset and go to next nuclei.\n self.parser.reset()\n #---------------------------------------- end of for loop\n\n \n self.__write_out_results_and_use_lvl_builder( outStr, outStr2 )\n\n\n pass\n\n \n\n \n \n\nif __name__ == '__main__':\n obj = Run()\n\n \n","sub_path":"parseNNDC2.py","file_name":"parseNNDC2.py","file_ext":"py","file_size_in_byte":79337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"255727864","text":"from ursina import *\nfrom ursina.prefabs.first_person_controller import FirstPersonController\n\napp = Ursina()\n#load all the texture\ngrass_texture = load_texture('assets/grass_block.png')\nstone_texture = load_texture('assets/stone_block.png')\nbrick_texture = load_texture('assets/brick_block.png')\ndirt_texture = load_texture('assets/dirt_block.png')\nsky_texture = load_texture('assets/skybox.png')\narm_texture = load_texture('assets/arm_texture.png')\npunch_sound = Audio('assets/assets_punch_sound.wav', loop=False, autoplay=False)\nblock_pick = 1\n\n#Για να μην φαινονται τα fps στη πανω γωνια\nwindow.fps_counter.enable = False\n#για να φυφει το exit button\nwindow.exit_button.visible = False\n\ndef update():\n #για αλλαγη blocks που μπορω να βαλω\n global block_pick\n\n #Στο update methoud για να γινει η κινηση\n if held_keys['left mouse'] or held_keys['right mouse']:\n hand.active()\n else:\n hand.passive()\n #dictionaries\n if held_keys['1']: block_pick = 1\n if held_keys['2']: block_pick = 2\n if held_keys['3']: block_pick = 3\n if held_keys['4']: block_pick = 4\n\nclass Voxel(Button):\n #Η κλαση Voxel ειναι για το πατωμα\n def __init__(self,position=(0, 0, 0), texture=grass_texture):\n super().__init__(\n parent=scene,\n position=position,\n #Η ursina δεν εχει UV MAP αρα θα πρεπει να φτιαξουμε εμεισ ενα αντικειμανο που να εχει ωστε να κανουμε πανω του apply το texture\n model='assets/Grass_block_real',\n origin_y=0.5,\n texture=texture,\n color=color.color(0, 0, random.uniform(0.9, 1)),\n scale=0.5\n )\n #για προσθηκη blocks\n def input(self, key):\n #το input του player\n if self.hovered:\n\n if key=='left mouse down':\n # Εδω για να παιξει ο ηχος\n punch_sound.play()\n #if για να επιλεξουμε ποιο απο τα block θα βαλουμε στο πατωμα\n if block_pick == 1:\n voxel= Voxel(position=self.position+mouse.normal, texture=grass_texture)\n if block_pick == 2:\n voxel= Voxel(position=self.position+mouse.normal, texture=stone_texture)\n if block_pick == 3:\n voxel= Voxel(position=self.position+mouse.normal, texture=brick_texture)\n if block_pick == 4:\n voxel= Voxel(position=self.position+mouse.normal, texture=dirt_texture)\n #καταστροφη blocks\n if key=='right mouse down':\n #Εδω για να παιξει ο ηχοσ οταν σπαμε τα blocks\n punch_sound.play()\n destroy(self)\n\n#Κλασση ουρανου\nclass Sky(Entity):\n def __init__(self):\n super().__init__(\n parent=scene,\n model='sphere',\n texture=sky_texture,\n scale=150,\n #Θελουμε double sided διοτι αν ειμαστε μεσα στο αντικειμενο δεν μπορουμε να το δουμε\n double_sided=True\n )\n\nclass Hand(Entity):\n def __init__(self):\n super().__init__(\n parent=camera.ui,\n #τα custom models εχουν προβλημα\n model='assets/arm_real',\n texture=arm_texture,\n scale=0.2,\n #Τοποθετηση χεριου στην οθονη\n rotation=Vec3(150, -10, 0),\n position=Vec2(0.4, -0.6)\n )\n #τεχνιτο animation του χεριου οταν χτιζει\n #Στο active γινεται η κινηση\n def active(self):\n self.position=Vec2(0.3, -0.5)\n #Στο passive γινεται η επαναφορα\n def passive(self):\n self.position=Vec2(0.4, -0.6)\n\n\n\n#ενθετη for για να χτιστουν τα τουβλακια σε δυο διαστασεις στο πατωμα\nfor z in range(25):\n for x in range(25):\n voxel = Voxel(position=(x, 0, z))\n\n#FPS controlls\nplayer = FirstPersonController()\n#Δημιουργια ουρανου\nsky = Sky()\n#Δημιουργια χεριου\nhand = Hand()\n\napp.run()","sub_path":"REALMINECRAFT.py","file_name":"REALMINECRAFT.py","file_ext":"py","file_size_in_byte":4459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"282510504","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('words', '0001_initial'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='word',\n old_name='speling',\n new_name='spelling',\n ),\n migrations.AddField(\n model_name='word',\n name='translation',\n field=models.CharField(default='EMPTY', max_length=200),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='word',\n name='user',\n field=models.ForeignKey(blank=True, default=0, to=settings.AUTH_USER_MODEL),\n preserve_default=False,\n ),\n ]\n","sub_path":"wsgi/flashcards/words/migrations/0002_auto_20160124_1731.py","file_name":"0002_auto_20160124_1731.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"535537865","text":"import math\r\n\r\ndef digits(inp):\r\n #return list of digits of positive integer inp\r\n goal = []\r\n while inp > 0:\r\n goal.append(inp%10)\r\n inp = int((1/10) * (inp - (inp % 10) ) )\r\n return list(reversed(goal))\r\n\r\ndef buildNumber(digits):\r\n #given a list of digits, build a number having those digits in the correct order\r\n length = len(digits)\r\n value = 0\r\n for i in range(length):\r\n value += (10 ** (length-1-i))*digits[i]\r\n return value\r\n\r\ndef isPalindrome(inp):\r\n #checks if integer inp is a palindrome\r\n if digits(inp) == digits(inp)[::-1]:\r\n return True\r\n return False\r\n\r\ndef step(n):\r\n #given n, return n + reversed(n)\r\n return n + buildNumber(digits(n)[::-1])\r\n\r\ndef test(n):\r\n #if a number n becomes a palindrome in 50 or less iterations of step, return True\r\n temp = n\r\n for i in range(50):\r\n temp = step(temp)\r\n if isPalindrome(temp):\r\n return True\r\n return False\r\n\r\nprint(test(349))\r\nprint(test(4994))\r\n\r\ndef problem55(upper):\r\n counter = 0\r\n for i in range(upper):\r\n if not test(i):\r\n counter +=1\r\n return counter\r\n\r\nprint(problem55(10000))\r\n\r\n#print(problem55Step(349))\r\n","sub_path":"055.py","file_name":"055.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"595514582","text":"class Solution:\n def searchMatrix(self, matrix: [[int]], target: int) -> bool:\n if len(matrix) == 0:\n return False\n\n low = 0\n high = len(matrix) * len(matrix[0]) - 1\n\n while low <= high:\n mid = int((low + high) / 2)\n mid_num = matrix[int(mid / len(matrix[0]))][mid % len(matrix[0])]\n if target < mid_num:\n high = mid - 1\n elif target > mid_num:\n low = mid + 1\n else:\n return True\n return False\n","sub_path":"LeetCode/SearchA2DMatrix_74.py","file_name":"SearchA2DMatrix_74.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"188590939","text":"from sklearn.utils import shuffle\nfrom sklearn.model_selection import StratifiedKFold\nimport numpy as np\nimport os\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n#import torchvision.datasets.mnist\nfrom torchvision import transforms\nimport importlib.machinery\nfrom torch.utils.data import Dataset, DataLoader\nimport argparse\nfrom torch.autograd import Variable\nfrom sklearn.utils import class_weight\nimport PIL\nfrom PIL import Image\nimport pickle\n# import botorch\nfrom functools import partial\nfrom hyperopt import hp, tpe, fmin\n\nprocess_results = importlib.machinery.SourceFileLoader('process_results','../../2.Results/process_results.py').load_module()\n#import process_results\n\nSEED = 42\n\n# Set the random seed manually for reproducibility.\nnp.random.seed(SEED)\ntorch.manual_seed(SEED)\nif torch.cuda.is_available():\n torch.cuda.manual_seed(SEED)\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n#device = torch.device('cpu')\nsoftmax = torch.nn.Softmax(dim=1)\ncriterion = nn.CrossEntropyLoss(ignore_index=-100, reduction=\"mean\")\n\nclass KidneyDataset(torch.utils.data.Dataset):\n\n def __init__(self, dataset, dataset_type, save_file_path):\n self.X = []\n self.y = []\n self.cov = []\n dic = {} \n for key in dataset:\n self.cov.append(key)\n self.y.append(dataset[key]['labels'])\n x = np.zeros((4, 256, 256)) # change this later for single view\n if dataset[key]['left'] is not None:\n x[:2,:,:] = dataset[key]['left']\n if dataset[key]['right'] is not None:\n x[2:,:,:] = dataset[key]['right']\n self.X.append(x)\n \n # dic[key] = {'img': x, 'labels': dataset[key]['labels']}\n self.X = np.array(self.X)\n self.y = np.array(self.y)\n self.cov = np.array(self.cov)\n \n num_1 = 0\n num_0 = 0\n for item in self.y:\n if item[-1] == 1:\n num_1 += 1\n elif item[-1] == 0:\n num_0 += 1\n with open(save_file_path, 'a') as f:\n f.write(\"{}_FUNC:::{} class_0/{} class_1\\n\".format(dataset_type.upper(), num_0, num_1))\n def __getitem__(self, index):\n return self.X[index], self.y[index], self.cov[index]\n\n def __len__(self):\n return len(self.X)\n\ndef get_proba(x):\n pred_prob, pred_label = torch.tensor([]).to(device), torch.tensor([]).to(device)\n try:\n x = torch.stack(x)\n x_softmax = softmax(x)\n pred_prob = x_softmax[:, 1]\n pred_label = torch.argmax(x_softmax, dim=1)\n except:\n pass \n return pred_prob, pred_label\n\ndef get_data_stats(y, label_type, save_path):\n with open(save_path, 'a') as f:\n f.write(\"{}:::{} class_0/{} class_1/{} total\\n\".format(label_type, len(y)-sum(y), sum(y), len(y)))\n\ndef run_test_data(data, data_type):\n pass\ndef train(args, dataset_train, dataset_test, lr, func_weight):\n\n from CNN_multitask_2 import CNN\n\n hyperparams = {'lr': lr,\n 'momentum': args.momentum,\n 'weight_decay': args.weight_decay,\n 'train/test_split': args.split \n }\n\n params = {'batch_size': args.batch_size,\n 'shuffle': True,\n 'num_workers': args.num_workers}\n\n if not os.path.isdir(args.dir):\n os.makedirs(args.dir)\n save_file_path = \"{}/lr-{}_funcweight-{}.txt\".format(args.dir, lr, func_weight)\n f = open(save_file_path, 'a') \n\n val_generator = None\n if args.val:\n train_cov_shuffled = shuffle(sorted(list(dataset_train.keys())), random_state=42)\n val_covs = train_cov_shuffled[int(len(train_cov_shuffled)*0.9):]\n train_covs = train_cov_shuffled[:int(len(train_cov_shuffled)*0.9)]\n \n dataset_val = {key: dataset_train[key] for key in val_covs}\n dataset_train = {key: dataset_train[key] for key in train_covs}\n \n val_set = KidneyDataset(dataset_val, \"val\", save_file_path)\n val_generator = DataLoader(val_set, **params)\n \n training_set = KidneyDataset(dataset_train, \"train\",save_file_path)\n training_generator = DataLoader(training_set, **params)\n \n \n test_set = KidneyDataset(dataset_test, \"test\", save_file_path)\n test_generator = DataLoader(test_set, **params)\n \n \n if args.view != \"siamese\":\n net = CNN(num_views=1, three_channel=False).to(device)\n else:\n net = CNN(num_views=2, three_channel=False).to(device)\n\n net.zero_grad()\n optimizer = torch.optim.SGD(net.parameters(), lr=hyperparams['lr'], momentum=hyperparams['momentum'],\n weight_decay=hyperparams['weight_decay'])\n\n \n best_val_auc = 0\n best_epoch = -1\n for epoch in range(args.max_epochs):\n loss_accum_train, loss_accum_val, loss_accum_test = 0, 0, 0\n\n surgery_targets_train, surgery_pred_prob_train, surgery_pred_label_train = [], [], []\n reflux_targets_train, reflux_pred_prob_train, reflux_pred_label_train = [], [], []\n func_targets_train, func_pred_prob_train, func_pred_label_train = [], [], []\n\n surgery_patient_ID_train, reflux_patient_ID_train, func_patient_ID_train = [], [], []\n\n surgery_targets_val, surgery_pred_prob_val, surgery_pred_label_val = [], [], []\n reflux_targets_val, reflux_pred_prob_val, reflux_pred_label_val = [], [], []\n func_targets_val, func_pred_prob_val, func_pred_label_val = [], [], []\n\n surgery_patient_ID_val, reflux_patient_ID_val, func_patient_ID_val = [], [], []\n\n surgery_targets_test, surgery_pred_prob_test, surgery_pred_label_test = [], [], []\n reflux_targets_test, reflux_pred_prob_test, reflux_pred_label_test = [], [], []\n func_targets_test, func_pred_prob_test, func_pred_label_test = [], [], []\n\n surgery_patient_ID_test, reflux_patient_ID_test, func_patient_ID_test = [], [], []\n\n counter_train, counter_val, counter_test = 0, 0, 0\n \n net.train()\n for batch_idx, (x, y, cov) in enumerate(training_generator):\n optimizer.zero_grad()\n preds = net(x.float().to(device))\n assert len(preds) == 5\n assert len(y) == len(x)\n y = Variable(y.type(torch.LongTensor), requires_grad=False).to(device)\n loss=0\n for i in range(5):\n if i == 4:\n loss += criterion(preds[i], y[:, i])\n else:\n loss += func_weight * criterion(preds[i], y[:, i])\n loss.backward()\n optimizer.step()\n\n pred_surgery, pred_reflux, pred_func = [], [], []\n surg_batch_cov, reflux_batch_cov, func_batch_cov = [], [], []\n y_surgery, y_reflux, y_func = [], [], []\n \n for i in range(len(y)):\n if y[i][0] != -100:\n y_surgery.append(y[i][0].cpu().detach().numpy()); pred_surgery.append(preds[0][i]); surg_batch_cov.append(cov[i])\n if y[i][1] != -100:\n y_surgery.append(y[i][1].cpu().detach().numpy()); pred_surgery.append(preds[1][i]); surg_batch_cov.append(cov[i])\n if y[i][2] != -100:\n y_reflux.append(y[i][2].cpu().detach().numpy()); pred_reflux.append(preds[2][i]); reflux_batch_cov.append(cov[i])\n if y[i][3] != -100:\n y_reflux.append(y[i][3].cpu().detach().numpy()); pred_reflux.append(preds[3][i]); reflux_batch_cov.append(cov[i])\n if y[i][4] != -100:\n y_func.append(y[i][4].cpu().detach().numpy()); pred_func.append(preds[4][i]); func_batch_cov.append(cov[i])\n counter_train += len(pred_surgery) + len(pred_reflux) + len(pred_func)\n loss_accum_train += loss.item() * (len(pred_surgery) + len(pred_reflux) + len(pred_func))\n\n\n surgery_pred_prob, surgery_pred_label = get_proba(pred_surgery)\n reflux_pred_prob, reflux_pred_label = get_proba(pred_reflux)\n func_pred_prob, func_pred_label = get_proba(pred_func) \n\n surgery_pred_prob_train.append(surgery_pred_prob.cpu().detach().numpy())\n surgery_targets_train.append(y_surgery)\n surgery_pred_label_train.append(surgery_pred_label.cpu().detach().numpy())\n surgery_patient_ID_train.extend(surg_batch_cov)\n\n reflux_pred_prob_train.append(reflux_pred_prob.cpu().detach().numpy())\n reflux_targets_train.append(y_reflux)\n reflux_pred_label_train.append(reflux_pred_label.cpu().detach().numpy())\n reflux_patient_ID_train.extend(reflux_batch_cov)\n\n func_pred_prob_train.append(func_pred_prob.cpu().detach().numpy())\n func_targets_train.append(y_func)\n func_pred_label_train.append(func_pred_label.cpu().detach().numpy())\n func_patient_ID_train.extend(func_batch_cov)\n surgery_pred_prob_train = np.concatenate(np.array(surgery_pred_prob_train))\n surgery_targets_train = np.concatenate(np.array(surgery_targets_train))\n surgery_pred_label_train = np.concatenate(np.array(surgery_pred_label_train))\n reflux_pred_prob_train = np.concatenate(reflux_pred_prob_train)\n reflux_targets_train = np.concatenate(reflux_targets_train)\n reflux_pred_label_train = np.concatenate(reflux_pred_label_train)\n func_pred_prob_train = np.concatenate(func_pred_prob_train)\n func_targets_train = np.concatenate(func_targets_train)\n func_pred_label_train = np.concatenate(func_pred_label_train)\n f.write(\"TrainEpoch\\t{}\\tLoss\\t{}\\n\".format(epoch, loss_accum_train/counter_train))\n surgery_results_train = process_results.get_metrics(y_score=surgery_pred_prob_train, y_true=surgery_targets_train, y_pred=surgery_pred_label_train)\n\n f.write('TrainEpoch\\t{}\\tSURGERY\\tAUC\\t{:.6f}\\t'\n 'AUPRC\\t{:.6f}\\tTN\\t{}\\tFP\\t{}\\tFN\\t{}\\tTP\\t{}\\n'.format(epoch,\n surgery_results_train['auc'],\n surgery_results_train['auprc'], surgery_results_train['tn'],\n surgery_results_train['fp'], surgery_results_train['fn'],\n surgery_results_train['tp']))\n reflux_results_train = process_results.get_metrics(y_score=reflux_pred_prob_train,\n y_true=reflux_targets_train,\n y_pred=reflux_pred_label_train)\n\n f.write('TrainEpoch\\t{}\\tREFLUX\\tAUC\\t{:.6f}\\t'\n 'AUPRC\\t{:.6f}\\tTN\\t{}\\tFP\\t{}\\tFN\\t{}\\tTP\\t{}\\n'.format(epoch,\n reflux_results_train['auc'],\n reflux_results_train['auprc'], reflux_results_train['tn'],\n reflux_results_train['fp'], reflux_results_train['fn'],\n reflux_results_train['tp']))\n func_results_train = process_results.get_metrics(y_score=func_pred_prob_train,\n y_true=func_targets_train,\n y_pred=func_pred_label_train)\n\n f.write('TrainEpoch\\t{}\\tFUNC\\tAUC\\t{:.6f}\\t'\n 'AUPRC\\t{:.6f}\\tTN\\t{}\\tFP\\t{}\\tFN\\t{}\\tTP\\t{}\\n'.format(epoch,\n func_results_train['auc'],\n func_results_train['auprc'], func_results_train['tn'],\n func_results_train['fp'], func_results_train['fn'],\n func_results_train['tp']))\n if args.val:\n with torch.no_grad():\n for batch_idx, (x, y, cov) in enumerate(val_generator):\n net.zero_grad()\n net.eval() # 20190619\n optimizer.zero_grad()\n preds = net(x.float().to(device))\n assert len(preds) == 5\n assert len(y) == len(x)\n loss=0\n y = Variable(y.type(torch.LongTensor), requires_grad=False).to(device)\n for i in range(5):\n if i == 4:\n loss += criterion(preds[i], y[:, i])\n else:\n loss += func_weight * criterion(preds[i], y[:, i])\n \n loss_accum_val += loss.item() * (len(y_surgery) + len(y_reflux) + len(y_func))\n \n #loss.backward()\n \n #optimizer.step()\n pred_surgery, pred_reflux, pred_func = [], [], []\n surg_batch_cov, reflux_batch_cov, func_batch_cov = [], [], []\n y_surgery, y_reflux, y_func = [], [], []\n \n for i in range(len(y)):\n if y[i][0] != -100:\n y_surgery.append(y[i][0].cpu().detach().numpy()); pred_surgery.append(preds[0][i]); surg_batch_cov.append(cov[i])\n if y[i][1] != -100:\n y_surgery.append(y[i][1].cpu().detach().numpy()); pred_surgery.append(preds[1][i]); surg_batch_cov.append(cov[i])\n if y[i][2] != -100:\n y_reflux.append(y[i][2].cpu().detach().numpy()); pred_reflux.append(preds[2][i]); reflux_batch_cov.append(cov[i])\n if y[i][3] != -100:\n y_reflux.append(y[i][3].cpu().detach().numpy()); pred_reflux.append(preds[3][i]); reflux_batch_cov.append(cov[i])\n if y[i][4] != -100:\n y_func.append(y[i][4].cpu().detach().numpy()); pred_func.append(preds[4][i]); func_batch_cov.append(cov[i])\n counter_val += len(pred_surgery) + len(pred_reflux) + len(pred_func)\n \n \n surgery_pred_prob, surgery_pred_label = get_proba(pred_surgery)\n reflux_pred_prob, reflux_pred_label = get_proba(pred_reflux)\n func_pred_prob, func_pred_label = get_proba(pred_func)\n \n surgery_pred_prob_val.append(surgery_pred_prob.cpu().detach().numpy())\n surgery_targets_val.append(y_surgery)\n surgery_pred_label_val.append(surgery_pred_label.cpu().detach().numpy())\n surgery_patient_ID_val.extend(surg_batch_cov)\n \n reflux_pred_prob_val.append(reflux_pred_prob.cpu().detach().numpy())\n reflux_targets_val.append(y_reflux)\n reflux_pred_label_val.append(reflux_pred_label.cpu().detach().numpy())\n reflux_patient_ID_val.extend(reflux_batch_cov)\n \n func_pred_prob_val.append(func_pred_prob.cpu().detach().numpy())\n func_targets_val.append(y_func)\n func_pred_label_val.append(func_pred_label.cpu().detach().numpy())\n func_patient_ID_val.extend(func_batch_cov)\n surgery_pred_prob_val = np.concatenate(surgery_pred_prob_val)\n surgery_targets_val = np.concatenate(surgery_targets_val)\n surgery_pred_label_val = np.concatenate(surgery_pred_label_val)\n reflux_pred_prob_val = np.concatenate(reflux_pred_prob_val)\n reflux_targets_val = np.concatenate(reflux_targets_val)\n reflux_pred_label_val = np.concatenate(reflux_pred_label_val)\n func_pred_prob_val = np.concatenate(func_pred_prob_val)\n func_targets_val = np.concatenate(func_targets_val)\n func_pred_label_val = np.concatenate(func_pred_label_val)\n\n \n curr_val_loss= loss_accum_val/counter_val\n f.write(\"ValEpoch\\t{}\\tLoss\\t{}\\n\".format(epoch, curr_val_loss))\n surgery_results_val = process_results.get_metrics(y_score=surgery_pred_prob_val,\n y_true=surgery_targets_val,\n y_pred=surgery_pred_label_val)\n \n f.write('ValEpoch\\t{}\\tSURGERY\\tAUC\\t{:.6f}\\t'\n 'AUPRC\\t{:.6f}\\tTN\\t{}\\tFP\\t{}\\tFN\\t{}\\tTP\\t{}\\n'.format(epoch,\n surgery_results_val['auc'],\n surgery_results_val['auprc'], surgery_results_val['tn'],\n surgery_results_val['fp'], surgery_results_val['fn'],\n surgery_results_val['tp']))\n reflux_results_val = process_results.get_metrics(y_score=reflux_pred_prob_val,\n y_true=reflux_targets_val,\n y_pred=reflux_pred_label_val)\n \n f.write('ValEpoch\\t{}\\tREFLUX\\tAUC\\t{:.6f}\\t'\n 'AUPRC\\t{:.6f}\\tTN\\t{}\\tFP\\t{}\\tFN\\t{}\\tTP\\t{}\\n'.format(epoch,\n reflux_results_val['auc'],\n reflux_results_val['auprc'], reflux_results_val['tn'],\n reflux_results_val['fp'], reflux_results_val['fn'],\n reflux_results_val['tp']))\n func_results_val = process_results.get_metrics(y_score=func_pred_prob_val,\n y_true=func_targets_val,\n y_pred=func_pred_label_val)\n \n f.write('ValEpoch\\t{}\\tFUNC\\tAUC\\t{:.6f}\\t'\n 'AUPRC\\t{:.6f}\\tTN\\t{}\\tFP\\t{}\\tFN\\t{}\\tTP\\t{}\\n'.format(epoch,\n func_results_val['auc'],\n func_results_val['auprc'], func_results_val['tn'],\n func_results_val['fp'], func_results_val['fn'],\n func_results_val['tp']))\n net.eval()\n with torch.no_grad():\n for batch_idx, (x, y, cov) in enumerate(test_generator):\n net.zero_grad()\n net.eval() # 20190619\n optimizer.zero_grad()\n preds = net(x.float().to(device))\n assert len(preds) == 5\n assert len(y) == len(x)\n loss=0\n y = Variable(y.type(torch.LongTensor), requires_grad=False).to(device)\n for i in range(5):\n if i == 4:\n loss += criterion(preds[i], y[:, i])\n else:\n loss += func_weight * criterion(preds[i], y[:, i])\n\n loss_accum_test += loss.item() * (len(y_surgery) + len(y_reflux) + len(y_func))\n\n #loss.backward()\n\n #optimizer.step()\n pred_surgery, pred_reflux, pred_func = [], [], []\n surg_batch_cov, reflux_batch_cov, func_batch_cov = [], [], []\n y_surgery, y_reflux, y_func = [], [], []\n\n for i in range(len(y)):\n if y[i][0] != -100:\n y_surgery.append(y[i][0].cpu().detach().numpy()); pred_surgery.append(preds[0][i]); surg_batch_cov.append(cov[i])\n if y[i][1] != -100:\n y_surgery.append(y[i][1].cpu().detach().numpy()); pred_surgery.append(preds[1][i]); surg_batch_cov.append(cov[i])\n if y[i][2] != -100:\n y_reflux.append(y[i][2].cpu().detach().numpy()); pred_reflux.append(preds[2][i]); reflux_batch_cov.append(cov[i])\n if y[i][3] != -100:\n y_reflux.append(y[i][3].cpu().detach().numpy()); pred_reflux.append(preds[3][i]); reflux_batch_cov.append(cov[i])\n if y[i][4] != -100:\n y_func.append(y[i][4].cpu().detach().numpy()); pred_func.append(preds[4][i]); func_batch_cov.append(cov[i])\n counter_test += len(pred_surgery) + len(pred_reflux) + len(pred_func)\n\n\n surgery_pred_prob, surgery_pred_label = get_proba(pred_surgery)\n reflux_pred_prob, reflux_pred_label = get_proba(pred_reflux)\n func_pred_prob, func_pred_label = get_proba(pred_func)\n\n surgery_pred_prob_test.append(surgery_pred_prob.cpu().detach().numpy())\n surgery_targets_test.append(y_surgery)\n surgery_pred_label_test.append(surgery_pred_label.cpu().detach().numpy())\n surgery_patient_ID_test.extend(surg_batch_cov)\n\n reflux_pred_prob_test.append(reflux_pred_prob.cpu().detach().numpy())\n reflux_targets_test.append(y_reflux)\n reflux_pred_label_test.append(reflux_pred_label.cpu().detach().numpy())\n reflux_patient_ID_test.extend(reflux_batch_cov)\n\n func_pred_prob_test.append(func_pred_prob.cpu().detach().numpy())\n func_targets_test.append(y_func)\n func_pred_label_test.append(func_pred_label.cpu().detach().numpy())\n func_patient_ID_test.extend(func_batch_cov)\n surgery_pred_prob_test = np.concatenate(surgery_pred_prob_test)\n surgery_targets_test = np.concatenate(surgery_targets_test)\n surgery_pred_label_test = np.concatenate(surgery_pred_label_test)\n reflux_pred_prob_test = np.concatenate(reflux_pred_prob_test)\n reflux_targets_test = np.concatenate(reflux_targets_test)\n reflux_pred_label_test = np.concatenate(reflux_pred_label_test)\n func_pred_prob_test = np.concatenate(func_pred_prob_test)\n func_targets_test = np.concatenate(func_targets_test)\n func_pred_label_test = np.concatenate(func_pred_label_test)\n \n f.write(\"TestEpoch\\t{}\\tLoss\\t{}\\n\".format(epoch, loss_accum_test/counter_test))\n\n surgery_results_test = process_results.get_metrics(y_score=surgery_pred_prob_test,\n y_true=surgery_targets_test,\n y_pred=surgery_pred_label_test)\n\n f.write('TestEpoch\\t{}\\tSURGERY\\tAUC\\t{:.6f}\\t'\n 'AUPRC\\t{:.6f}\\tTN\\t{}\\tFP\\t{}\\tFN\\t{}\\tTP\\t{}\\n'.format(epoch,\n surgery_results_test['auc'],\n surgery_results_test['auprc'], surgery_results_test['tn'],\n surgery_results_test['fp'], surgery_results_test['fn'],\n surgery_results_test['tp']))\n reflux_results_test = process_results.get_metrics(y_score=reflux_pred_prob_test,\n y_true=reflux_targets_test,\n y_pred=reflux_pred_label_test)\n\n f.write('TestEpoch\\t{}\\tREFLUX\\tAUC\\t{:.6f}\\t'\n 'AUPRC\\t{:.6f}\\tTN\\t{}\\tFP\\t{}\\tFN\\t{}\\tTP\\t{}\\n'.format(epoch,\n reflux_results_test['auc'],\n reflux_results_test['auprc'], reflux_results_test['tn'],\n reflux_results_test['fp'], reflux_results_test['fn'],\n reflux_results_test['tp']))\n func_results_test = process_results.get_metrics(y_score=func_pred_prob_test,\n y_true=func_targets_test,\n y_pred=func_pred_label_test)\n\n f.write('TestEpoch\\t{}\\tFUNC\\tAUC\\t{:.6f}\\t'\n 'AUPRC\\t{:.6f}\\tTN\\t{}\\tFP\\t{}\\tFN\\t{}\\tTP\\t{}\\n'.format(epoch,\n func_results_test['auc'],\n func_results_test['auprc'], func_results_test['tn'],\n func_results_test['fp'], func_results_test['fn'],\n func_results_test['tp']))\n\n \n if func_results_val['auc'] > 0:\n if func_results_val['auc'] > best_val_auc:\n best_val_auc = func_results_val['auc']\n best_epoch = epoch\n checkpoint = {'epoch': epoch,\n 'loss': loss,\n 'hyperparams': hyperparams,\n 'args': args,\n 'model_state_dict': net.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'loss_train': loss_accum_train / counter_train,\n 'surgery_results_train': surgery_results_train,\n 'reflux_results_train': reflux_results_train,\n 'func_results_train': func_results_train,\n 'surgery_pred_prob_train': surgery_pred_prob_train,\n 'reflux_pred_prob_train': reflux_pred_prob_train,\n 'func_pred_prob_train': func_pred_prob_train,\n 'surgery_targets_train': surgery_targets_train,\n 'reflux_targets_train': reflux_targets_train,\n 'func_targets_train': func_targets_train,\n 'surgery_patient_ID_train': surgery_patient_ID_train,\n 'reflux_patient_ID_train': reflux_patient_ID_train,\n 'func_patient_ID_train': func_patient_ID_train,\n 'loss_test': loss_accum_test / counter_test,\n 'surgery_results_test': surgery_results_test,\n 'reflux_results_test': reflux_results_test,\n 'func_results_test': func_results_test,\n 'surgery_pred_prob_test': surgery_pred_prob_test,\n 'reflux_pred_prob_test': reflux_pred_prob_test,\n 'func_pred_prob_test': func_pred_prob_test,\n 'surgery_targets_test': surgery_targets_test,\n 'reflux_targets_test': reflux_targets_test,\n 'func_targets_test': func_targets_test,\n 'surgery_patient_ID_test': surgery_patient_ID_test,\n 'reflux_patient_ID_test': reflux_patient_ID_test,\n 'func_patient_ID_test': func_patient_ID_test}\n if args.val:\n checkpoint['loss_val'] = loss_accum_val / counter_val; checkpoint['surgery_results_val'] = surgery_results_val; checkpoint['reflux_results_val'] = reflux_results_val; \n checkpoint['func_results_val'] = func_results_val; checkpoint['surgery_pred_prob_val'] = surgery_pred_prob_val; checkpoint['reflux_pred_prob_val'] = reflux_pred_prob_val; \n checkpoint['func_pred_prob_val'] = func_pred_prob_val; checkpoint['surgery_targets_val'] = surgery_targets_val; checkpoint['reflux_targets_val'] = reflux_targets_val; \n checkpoint['func_targets_val'] = func_targets_val; checkpoint['surgery_patient_ID_val'] = surgery_patient_ID_val; checkpoint['reflux_patient_ID_val'] = reflux_patient_ID_val; \n checkpoint['func_patient_ID_val'] = func_patient_ID_val\n if not os.path.isdir(args.dir):\n os.makedirs(args.dir)\n path_to_checkpoint = \"{}/checkpoint_lr-{}_funcweight-{}.pth\".format(args.dir, lr, func_weight)\n torch.save(checkpoint, path_to_checkpoint)\n \n \n f.close()\n return best_val_auc, best_epoch\n \ndef train_model(space, data):\n \n lr = space[0]\n func_weight = space[1]\n save_file_path = \"{}/lr-{}_funcweight-{}.txt\".format(data['args'].dir, lr, func_weight)\n with open(save_file_path, 'a') as f:\n f.write(\"LR:::{}\\tFUNC_WEIGHT:::{}\\n\".format(lr, func_weight))\n args = data['args']\n data_train = data['data_train']\n data_test = data['data_test']\n best_val, best_epoch = train(args, data_train, data_test, lr, func_weight)\n with open(save_file_path, 'a') as f:\n f.write(\"BEST_VAL_AUC:::{}\\tBEST_EPOCH:::{}\\n\".format(best_val, best_epoch))\n if not os.path.isdir(data['args'].dir):\n os.makedirs(data['args'].dir)\n with open(\"{}/global_stats.txt\".format(data['args'].dir), 'a') as fhandle:\n fhandle.write(\"lr\\t{}\\tfuncweight\\t{}\\tbest_epoch\\t{}\\tbest_auc\\t{}\\n\".format(lr, func_weight, best_epoch, best_val))\n return best_val\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--max_epochs', default=35, type=int, help=\"Number of epochs\")\n parser.add_argument('--batch_size', default=64, type=int, help=\"Batch size\")\n parser.add_argument('--lr', default=0.001, type=float, help=\"Learning rate\")\n parser.add_argument('--momentum', default=0.9, type=float, help=\"Momentum\")\n parser.add_argument(\"--weight_decay\", default=5e-4, type=float, help=\"Weight decay\")\n parser.add_argument(\"--num_workers\", default=1, type=int, help=\"Number of CPU workers\")\n parser.add_argument(\"--dir\", default=\"./\", help=\"Directory to save model checkpoints to\")\n parser.add_argument(\"--contrast\", default=1, type=int, help=\"Image contrast to train on\")\n parser.add_argument(\"--view\", default=\"siamese\", help=\"siamese, sag, trans\")\n parser.add_argument(\"--checkpoint\", default=\"\", help=\"Path to load pretrained model checkpoint from\")\n parser.add_argument(\"--split\", default=0.7, type=float, help=\"proportion of dataset to use as training\")\n parser.add_argument(\"--bottom_cut\", default=0.0, type=float, help=\"proportion of dataset to cut from bottom\")\n parser.add_argument(\"--etiology\", default=\"B\", help=\"O (obstruction), R (reflux), B (both)\")\n parser.add_argument(\"--hydro_only\", action=\"store_true\")\n parser.add_argument(\"--output_dim\", default=256, type=int, help=\"output dim for last linear layer\")\n parser.add_argument(\"--datafile\", default=\"../../0.Preprocess/preprocessed_images_20190617.pickle\", help=\"File containing pandas dataframe with images stored as numpy array\")\n parser.add_argument(\"--gender\", default=None, type=str, help=\"choose from 'male' and 'female'\")\n parser.add_argument(\"--val\", action=\"store_true\", help=\"run validation set\")\n args = parser.parse_args()\n if not os.path.isdir(args.dir):\n os.makedirs(args.dir)\n save_file_path = \"{}/global_stats.txt\".format(args.dir)\n with open(save_file_path, 'w') as f:\n f.write(\"ARGS\" + '\\t' + str(args) + '\\n')\n \n load_dataset_surgery = importlib.machinery.SourceFileLoader('load_dataset','../../0.Preprocess/load_dataset.py').load_module()\n #import load_dataset as load_dataset_surgery\n train_X_surg, train_y_surg, train_cov_surg, test_X_surg, test_y_surg, test_cov_surg = load_dataset_surgery.load_dataset(views_to_get=\"siamese\", pickle_file=args.datafile, contrast=args.contrast, split=args.split, get_cov=True)\n load_dataset_vur = importlib.machinery.SourceFileLoader('load_dataset','../../0.Preprocess/load_dataset_vur.py').load_module()\n #import load_dataset_vur\n train_X_reflux, train_y_reflux, train_cov_reflux, test_X_reflux, test_y_reflux, test_cov_reflux = load_dataset_vur.load_dataset(views_to_get=\"siamese\", pickle_file=\"../../0.Preprocess/vur_images_256_20200422.pickle\", image_dim=256, contrast=args.contrast, split=args.split, get_cov=True)\n \n load_dataset_func = importlib.machinery.SourceFileLoader('load_dataset','../../0.Preprocess/load_dataset_func.py').load_module()\n #import load_dataset_func\n train_X_func, train_y_func, train_cov_func, test_X_func, test_y_func, test_cov_func = load_dataset_func.load_dataset(views_to_get=\"siamese\", pickle_file=\"../../0.Preprocess/func_images_256_20200422.pickle\", image_dim=256, contrast=args.contrast, split=args.split, get_cov=True)\n train_y_func = [1 if item >=0.6 or item <= 0.4 else 0 for item in train_y_func]\n test_y_func = [1 if item >=0.6 or item <= 0.4 else 0 for item in test_y_func] \n\n get_data_stats(train_y_surg, \"SURG_TRAIN\", save_file_path)\n get_data_stats(test_y_surg, \"SURG_TEST\", save_file_path)\n get_data_stats(train_y_reflux, \"REFLUX_TRAIN\", save_file_path)\n get_data_stats(test_y_reflux, \"REFLUX_TEST\", save_file_path)\n get_data_stats(train_y_func, \"FUNC_TRAIN\", save_file_path)\n get_data_stats(test_y_func, \"FUNC_TEST\", save_file_path)\n with open(save_file_path, 'a') as f:\n f.write(\"-----------------------------------\\n\")\n\n train_X = []\n train_y = []\n train_cov = []\n \n for i in range(len(train_cov_surg)):\n train_cov_surg[i] = \"_\".join(train_cov_surg[i].split(\"_\")[:5])\n for i in range(len(train_cov_reflux)):\n item_ = train_cov_reflux[i].split(\"_\")[:-1]\n item_[0], item_[1] = str(float(item_[0])), str(float(item_[1]))\n item_ = \"_\".join(item_)\n train_cov_reflux[i] = item_\n train_cov_reflux[i] = \"_\".join(train_cov_reflux[i].split(\"_\")[:5])\n for i in range(len(train_cov_func)):\n train_cov_func[i] = \"_\".join(train_cov_func[i].split(\"_\")[:5])\n \n\n dataset_train = {}\n for i in range(len(train_cov_surg)):\n trunc_id = \"_\".join(train_cov_surg[i].split(\"_\")[:4]) \n if trunc_id not in dataset_train:\n dataset_train[trunc_id] = {'left': None, 'right': None, 'labels': [-100, -100, -100, -100, -100]}\n if \"Left\" in train_cov_surg[i]:\n dataset_train[trunc_id]['left'], dataset_train[trunc_id]['labels'][0] = train_X_surg[i], train_y_surg[i]\n elif \"Right\" in train_cov_surg[i]:\n dataset_train[trunc_id]['right'], dataset_train[trunc_id]['labels'][1] = train_X_surg[i], train_y_surg[i]\n for i in range(len(train_cov_reflux)):\n trunc_id = \"_\".join(train_cov_reflux[i].split(\"_\")[:4])\n if trunc_id not in dataset_train:\n dataset_train[trunc_id] = {'left': None, 'right': None, 'labels': [-100, -100, -100, -100, -100]}\n if \"Left\" in train_cov_reflux[i]:\n if dataset_train[trunc_id]['left'] is None: dataset_train[trunc_id]['left'] = train_X_reflux[i]\n dataset_train[trunc_id]['labels'][2] = train_y_reflux[i]\n elif \"Right\" in train_cov_reflux[i]:\n if dataset_train[trunc_id]['right'] is None: dataset_train[trunc_id]['right'] = train_X_reflux[i]\n dataset_train[trunc_id]['labels'][3] = train_y_reflux[i]\n for i in range(len(train_cov_func)):\n trunc_id = \"_\".join(train_cov_func[i].split(\"_\")[:4])\n if trunc_id not in dataset_train:\n dataset_train[trunc_id] = {'left': None, 'right': None, 'labels': [-100, -100, -100, -100, -100]}\n dataset_train[trunc_id]['left'], dataset_train[trunc_id]['right'] = train_X_func[i][:2], train_X_func[i][2:]\n dataset_train[trunc_id]['labels'][4] = train_y_func[i]\n\n\n test_X = []\n test_y = []\n test_cov = []\n \n for i in range(len(test_cov_surg)):\n test_cov_surg[i] = \"_\".join(test_cov_surg[i].split(\"_\")[:5])\n for i in range(len(test_cov_reflux)):\n item_ = test_cov_reflux[i].split(\"_\")[:-1]\n item_[0], item_[1] = str(float(item_[0])), str(float(item_[1]))\n item_ = \"_\".join(item_)\n test_cov_reflux[i] = item_\n test_cov_reflux[i] = \"_\".join(test_cov_reflux[i].split(\"_\")[:5])\n for i in range(len(test_cov_func)):\n test_cov_func[i] = \"_\".join(test_cov_func[i].split(\"_\")[:5])\n\n\n dataset_test = {}\n for i in range(len(test_cov_surg)):\n trunc_id = \"_\".join(test_cov_surg[i].split(\"_\")[:4])\n if trunc_id not in dataset_test:\n dataset_test[trunc_id] = {'left': None, 'right': None, 'labels': [-100, -100, -100, -100, -100]}\n if \"Left\" in test_cov_surg[i]:\n dataset_test[trunc_id]['left'], dataset_test[trunc_id]['labels'][0] = test_X_surg[i], test_y_surg[i]\n elif \"Right\" in test_cov_surg[i]:\n dataset_test[trunc_id]['right'], dataset_test[trunc_id]['labels'][1] = test_X_surg[i], test_y_surg[i]\n for i in range(len(test_cov_reflux)):\n trunc_id = \"_\".join(test_cov_reflux[i].split(\"_\")[:4])\n if trunc_id not in dataset_test:\n dataset_test[trunc_id] = {'left': None, 'right': None, 'labels': [-100, -100, -100, -100, -100]}\n if \"Left\" in test_cov_reflux[i]:\n if dataset_test[trunc_id]['left'] is None: dataset_test[trunc_id]['left'] = test_X_reflux[i]\n dataset_test[trunc_id]['labels'][2] = test_y_reflux[i]\n elif \"Right\" in test_cov_reflux[i]:\n if dataset_test[trunc_id]['right'] is None: dataset_test[trunc_id]['right'] = test_X_reflux[i]\n dataset_test[trunc_id]['labels'][3] = test_y_reflux[i]\n for i in range(len(test_cov_func)):\n trunc_id = \"_\".join(test_cov_func[i].split(\"_\")[:4])\n if trunc_id not in dataset_test:\n dataset_test[trunc_id] = {'left': None, 'right': None, 'labels': [-100, -100, -100, -100, -100]}\n dataset_test[trunc_id]['left'], dataset_test[trunc_id]['right'] = test_X_func[i][:2,:,:], test_X_func[i][2:,:,:]\n dataset_test[trunc_id]['labels'][4] = test_y_func[i]\n\n\n data = {'args': args,\n 'data_train': dataset_train,\n 'data_test': dataset_test}\n\n space=[hp.uniform('lr', 0.001, 0.01),\n hp.uniform('func_loss', 0.001, 1)]\n\n fmin_objective = partial(train_model, data=data)\n\n best = fmin(fn=fmin_objective,\n space=space,\n algo=tpe.suggest,\n max_evals=1000,\n show_progressbar=True,\n verbose=True,\n rstate=np.random.RandomState(42))\n\n train_model(args, dataset_train, dataset_test, max_epochs)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"1.Models/multitask/train_network_multitask_v2_bayesopt.py","file_name":"train_network_multitask_v2_bayesopt.py","file_ext":"py","file_size_in_byte":38896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"319098354","text":"import requests\n\n\nclass Scraper:\n def __init__(self):\n \"\"\"\n initial object\n \"\"\"\n self.HTTP_ACCESS_OK = 200\n self.BASE_URL = 'https://gensun.org/list_ja_female'\n\n def scrape_actress_data(self, url):\n \"\"\"\n scraping actress data and return response\n \"\"\"\n ret_data = None\n\n response = requests.get(url)\n\n if self.HTTP_ACCESS_OK == response.status_code:\n ret_data = response\n return ret_data\n","sub_path":"request_manager.py","file_name":"request_manager.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"176398294","text":"#!/usr/bin/env python\n\n# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"This application demonstrates speech transcription using the\nGoogle Cloud API.\n\nUsage Examples:\n python beta_snippets.py \\\n transcription gs://python-docs-samples-tests/video/googlework_short.mp4\n\"\"\"\n\nimport argparse\n\nfrom google.cloud import videointelligence_v1p1beta1 as videointelligence\n\n\n# [START video_speech_transcription]\ndef speech_transcription(input_uri):\n \"\"\"Transcribe speech from a video stored on GCS.\"\"\"\n video_client = videointelligence.VideoIntelligenceServiceClient()\n\n features = [videointelligence.enums.Feature.SPEECH_TRANSCRIPTION]\n\n config = videointelligence.types.SpeechTranscriptionConfig(\n language_code='en-US')\n video_context = videointelligence.types.VideoContext(\n speech_transcription_config=config)\n\n operation = video_client.annotate_video(\n input_uri, features=features,\n video_context=video_context)\n\n print('\\nProcessing video for speech transcription.')\n\n result = operation.result(timeout=180)\n\n # There is only one annotation_result since only\n # one video is processed.\n annotation_results = result.annotation_results[0]\n speech_transcription = annotation_results.speech_transcriptions[0]\n alternative = speech_transcription.alternatives[0]\n\n print('Transcript: {}'.format(alternative.transcript))\n print('Confidence: {}\\n'.format(alternative.confidence))\n\n print('Word level information:')\n for word_info in alternative.words:\n word = word_info.word\n start_time = word_info.start_time\n end_time = word_info.end_time\n print('\\t{}s - {}s: {}'.format(\n start_time.seconds + start_time.nanos * 1e-9,\n end_time.seconds + end_time.nanos * 1e-9,\n word))\n# [END video_speech_transcription]\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n subparsers = parser.add_subparsers(dest='command')\n\n speech_transcription_parser = subparsers.add_parser(\n 'transcription', help=speech_transcription.__doc__)\n speech_transcription_parser.add_argument('gcs_uri')\n\n args = parser.parse_args()\n\n if args.command == 'transcription':\n speech_transcription(args.gcs_uri)\n","sub_path":"video/cloud-client/analyze/beta_snippets.py","file_name":"beta_snippets.py","file_ext":"py","file_size_in_byte":2898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"426920189","text":"import numpy as np \nimport matplotlib.pyplot as plt \nimport os.path\n\ninput_dir = \"../figures/bilfil\"\nfiles = {\n \"unfiltered\": \"\",\n \"classical\": \"_classical\",\n \"adaptive\": \"_adaptive\"\n }\nfname = \"bilfil_stripes_816x64_uint16{}.raw\"\n\nl0, l1 = 220, 300\ny = 31\nx = np.arange(l0,l1)\n\nfig = plt.figure()\nfor name,suffix in files.items():\n img = np.fromfile(os.path.join(input_dir, fname.format(suffix)),\n dtype=np.uint16).reshape((64,816))\n plt.plot(x, img[y, l0:l1], label=name)\n #plt.plot(x, np.mean(img, axis=0)[l0:l1], label=name)\n\nplt.legend(loc=\"best\")\nplt.grid(True)\nplt.show()\n","sub_path":"scripts/bilfil_comparison_stripes.py","file_name":"bilfil_comparison_stripes.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"483898096","text":"#!/usr/bin/env python3\nfrom benchmark_utils import *\nimport subprocess\nsub_program, time_f, memory_f, num_func_f = get_arg()\nif memory_f:\n subprocess.run(sub_program)\n mem_use = get_memory_use()\n print('Memory usage:', mem_use, 'kB')\n\nelif num_func_f:\n get_num_funcs(sub_program[0])\n\nelif time_f:\n subprocess.run(sub_program)\n run_time = get_run_time()\n print('Run-time:', run_time, 's')\n","sub_path":"04Thebench/benchmarking.py","file_name":"benchmarking.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"589651759","text":"# -*- coding: utf-8 -*-\n###################################################################################\n# Added to enable code completion in IDE's.\nif 0:\n from gluon import * # @UnusedWildImport\n from gluon import db,auth,request\n import gluon\n global auth; auth = gluon.tools.Auth()\n from applications.baadal.models import * # @UnusedWildImport\n###################################################################################\nfrom helper import is_moderator, is_faculty, get_vm_template_config\nfrom auth_user import fetch_ldap_user, create_or_update_user\n\ndef get_my_pending_vm():\n vms = db(db.vm_data.status.belongs(VM_STATUS_REQUESTED, VM_STATUS_VERIFIED) \n & (db.vm_data.requester_id==auth.user.id)).select(db.vm_data.ALL)\n\n return get_pending_vm_list(vms)\n\n\ndef get_my_hosted_vm():\n vms = db((db.vm_data.status > VM_STATUS_APPROVED) \n & (db.vm_data.id==db.user_vm_map.vm_id) \n & (db.user_vm_map.user_id==auth.user.id)).select(db.vm_data.ALL)\n\n return get_hosted_vm_list(vms)\n\n#Create configuration dropdowns\ndef get_configuration_elem(form):\n \n xmldoc = get_vm_template_config() # Read vm_template_config.xml\n itemlist = xmldoc.getElementsByTagName('template')\n _id=0 #for default configurations set, select box id will be configuration_0 \n for item in itemlist:\n if item.attributes['default'].value != 'true': #if not default, get the id \n _id=item.attributes['id'].value\n select=SELECT(_name='configuration_'+str(_id)) # create HTML select with name as configuration_id\n cfglist = item.getElementsByTagName('config')\n i=0\n for cfg in cfglist:\n #Create HTML options and insert into select\n select.insert(i,OPTION(cfg.attributes['display'].value,_value=cfg.attributes['value'].value))\n i+=1\n \n #Create HTML tr, and insert label and select box\n config_elem = TR(LABEL('Configuration:'),select,TD(),_id='config_row__'+str(_id))\n form[0].insert(2,config_elem)#insert tr element in the form\n\n# Gets CPU, RAM and HDD information on the basis of template selected.\ndef set_configuration_elem(form):\n\n configVal = form.vars.configuration_0 #Default configuration dropdown\n template = form.vars.template_id\n \n # if configuration specific to selected template is available\n if eval('form.vars.configuration_'+str(template)) != None:\n configVal = eval('form.vars.configuration_'+str(template))\n\n configVal = configVal.split(',')\n \n form.vars.vCPU = int(configVal[0])\n form.vars.RAM = int(configVal[1])*1024\n form.vars.HDD = int(configVal[2])\n if form.vars.extra_HDD == None:\n form.vars.extra_HDD = 0\n\n\ndef validate_approver(form):\n faculty_user = request.post_vars.user_name\n faculty_user_name = request.post_vars.faculty_user\n \n if(faculty_user != ''):\n faculty_info = get_user_info(faculty_user, [FACULTY])\n if faculty_info[1] == faculty_user_name:\n form.vars.owner_id = faculty_info[0]\n form.vars.status = VM_STATUS_REQUESTED\n return\n \n faculty_info = get_user_info(faculty_user_name, [FACULTY])\n if faculty_info != None:\n form.vars.owner_id = faculty_info[0]\n form.vars.status = VM_STATUS_REQUESTED\n else:\n form.errors.faculty_user='Faculty Approver Username is not valid'\n\n\ndef request_vm_validation(form):\n set_configuration_elem(form)\n if not(is_moderator() | is_faculty()):\n validate_approver(form)\n else:\n form.vars.owner_id = auth.user.id\n form.vars.status = VM_STATUS_VERIFIED\n \n form.vars.requester_id = auth.user.id\n\n\ndef add_faculty_approver(form):\n\n _input=INPUT(_name='faculty_user',_id='faculty_user') # create INPUT\n _link = TD(A('Verify', _href='#',_onclick='verify_faculty()'))\n faculty_elem = TR(LABEL('Faculty Approver:'),_input,_link,_id='faculty_row')\n form[0].insert(-1,faculty_elem)#insert tr element in the form\n\n\ndef get_request_vm_form():\n \n form_fields = ['vm_name','template_id','extra_HDD','purpose']\n form_labels = {'vm_name':'Name of VM','extra_HDD':'Optional Additional Harddisk(GB)','template_id':'Template Image','purpose':'Purpose of this VM'}\n\n form =SQLFORM(db.vm_data, fields = form_fields, labels = form_labels, hidden=dict(user_name=''))\n get_configuration_elem(form) # Create dropdowns for configuration\n\n if not(is_moderator() | is_faculty()):\n add_faculty_approver(form)\n \n return form\n\n\ndef get_user_info(username, roles):\n user_query = db((db.user.username == username) \n & (db.user.id == db.user_membership.user_id)\n & (db.user_membership.group_id == db.user_group.id)\n & (db.user_group.role.belongs(roles)))\n user = user_query.select().first()\n # If user not present in DB\n if not user:\n if current.auth_type == 'ldap':\n user_info = fetch_ldap_user(username)\n if user_info:\n if [obj for obj in roles if obj in user_info['roles']]:\n create_or_update_user(user_info, False)\n user = user_query.select().first()\n \n if user:\n return (user.user.id, (user.user.first_name + ' ' + user.user.last_name))\t\n\n\ndef get_my_task_list(task_status, task_num):\n task_query = db((db.task_queue_event.status == task_status) \n & (db.task_queue_event.vm_id == db.vm_data.id) \n & (db.vm_data.requester_id==auth.user.id))\n\n events = task_query.select(db.task_queue_event.ALL, orderby = ~db.task_queue_event.start_time, limitby=(0,task_num))\n\n return get_task_list(events)\n\n \ndef get_vm_config(vm_id):\n\n vminfo = get_vm_info(vm_id)\n \n vm_info_map = {'id' : str(vminfo.id),\n 'name' : str(vminfo.vm_name),\n 'hdd' : str(vminfo.HDD),\n 'extrahdd' : str(vminfo.extra_HDD),\n 'ram' : str(vminfo.RAM),\n 'vcpus' : str(vminfo.vCPU),\n 'status' : str(vminfo.status),\n 'ostype' : 'Linux',\n 'purpose' : str(vminfo.purpose),\n 'totalcost' : str(vminfo.total_cost),\n 'currentrunlevel' : str(vminfo.current_run_level)}\n\n if is_moderator():\n vm_info_map.update({'host' : str(vminfo.host_id),\n 'vnc' : str(vminfo.vnc_port)})\n\n return vm_info_map \n \n \ndef get_vm_user_list(vm_id) :\t\t\n vm_users = db((vm_id == db.user_vm_map.vm_id) & (db.user_vm_map.user_id == db.user.id)).select(db.user.ALL)\n user_id_lst = []\n for vm_user in vm_users:\n user_id_lst.append(vm_user)\n return user_id_lst\n\ndef check_snapshot_limit(vm_id):\n snapshots = len(db(db.snapshot.vm_id == vm_id).select())\n logger.debug(\"No of snapshots are \" + str(snapshots))\n if snapshots < SNAPSHOTTING_LIMIT:\n return True\n else:\n return False\n\n","sub_path":"baadalinstallation/baadal/models/user_model.py","file_name":"user_model.py","file_ext":"py","file_size_in_byte":7086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"101561406","text":"import sys, os\nimport argparse\nimport numpy as np \nimport pandas as pd\nimport json\nfrom sklearn.model_selection import GridSearchCV, cross_validate, ShuffleSplit, StratifiedShuffleSplit\nfrom sklearn.metrics import (roc_curve, accuracy_score, log_loss, \n balanced_accuracy_score, confusion_matrix, \n roc_auc_score, make_scorer, average_precision_score)\nfrom yattag import Doc\nimport matplotlib.pyplot as plt\n# DEFAULT_PROJECT_REPO = os.path.sep.join(__file__.split(os.path.sep)[:-2])\n# PROJECT_REPO_DIR = os.path.abspath(\n# os.environ.get('PROJECT_REPO_DIR', DEFAULT_PROJECT_REPO))\nPROJECT_REPO_DIR = os.path.abspath(os.path.join(__file__, '../../../'))\nsys.path.append(os.path.join(PROJECT_REPO_DIR, 'src', 'rnn'))\nsys.path.append(os.path.join(PROJECT_REPO_DIR, 'src', 'PC-VAE'))\n\nfrom dataset_loader import TidySequentialDataCSVLoader\nfrom feature_transformation import (parse_id_cols, parse_feature_cols)\nfrom utils import load_data_dict_json\nfrom joblib import dump\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nimport glob\nfrom numpy.random import RandomState\nfrom pcvae.datasets.toy import toy_line, custom_dataset\nfrom pcvae.models.hmm import HMM\nfrom pcvae.datasets.base import dataset, real_dataset, classification_dataset, make_dataset\nfrom sklearn.model_selection import train_test_split\nfrom pcvae.util.optimizers import get_optimizer\nfrom sklearn.linear_model import LogisticRegression\nimport tensorflow as tf\nimport numpy.ma as ma\nfrom sklearn.cluster import KMeans\n\n# def standardize_data_for_pchmm(X_train, y_train, X_test, y_test):\ndef convert_to_categorical(y):\n C = len(np.unique(y))\n N = len(y)\n y_cat = np.zeros((N, C))\n y_cat[:, 0] = (y==0)*1.0\n y_cat[:, 1] = (y==1)*1.0\n \n return y_cat\n\ndef save_loss_plots(model, save_file, data_dict):\n model_hist = model.history.history\n epochs = range(len(model_hist['loss']))\n hmm_model_loss = model_hist['hmm_model_loss']\n predictor_loss = model_hist['predictor_loss']\n model_hist['epochs'] = epochs\n model_hist['n_train'] = len(data_dict['train'][1])\n model_hist['n_valid'] = len(data_dict['valid'][1])\n model_hist['n_test'] = len(data_dict['test'][1])\n model_hist_df = pd.DataFrame(model_hist)\n \n # save to file\n model_hist_df.to_csv(save_file, index=False)\n print('Training plots saved to %s'%save_file)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='pchmm fitting')\n parser.add_argument('--outcome_col_name', type=str, required=True)\n parser.add_argument('--train_csv_files', type=str, required=True)\n parser.add_argument('--test_csv_files', type=str, required=True)\n parser.add_argument('--data_dict_files', type=str, required=True)\n parser.add_argument('--valid_csv_files', type=str, default=None)\n parser.add_argument('--imputation_strategy', type=str, default=\"no_imp\")\n parser.add_argument('--batch_size', type=int, default=1024,\n help='Number of sequences per minibatch')\n parser.add_argument('--epochs', type=int, default=50,\n help='Number of epochs')\n parser.add_argument('--lr', type=float, default=0.0005,\n help='Learning rate for the optimizer')\n parser.add_argument('--init_strategy', type=str, default='kmeans')\n parser.add_argument('--seed', type=int, default=1111,\n help='random seed')\n parser.add_argument('--lamb', type=int, default=100,\n help='Langrange multiplier')\n parser.add_argument('--validation_size', type=float, default=0.15,\n help='validation split size')\n parser.add_argument('--n_states', type=int, default=0.15,\n help='number of HMM states')\n parser.add_argument('--perc_labelled', type=int, default=0.15,\n help='percentage of labelled examples')\n parser.add_argument('--output_dir', type=str, default=None, \n help='directory where trained model and loss curves over epochs are saved')\n parser.add_argument('--output_filename_prefix', type=str, default=None, \n help='prefix for the training history jsons and trained classifier')\n args = parser.parse_args()\n\n rs = RandomState(args.seed)\n\n x_train_csv_filename, y_train_csv_filename = args.train_csv_files.split(',')\n x_test_csv_filename, y_test_csv_filename = args.test_csv_files.split(',')\n x_valid_csv_filename, y_valid_csv_filename = args.valid_csv_files.split(',')\n x_dict, y_dict = args.data_dict_files.split(',')\n x_data_dict = load_data_dict_json(x_dict)\n \n # get the id and feature columns\n id_cols = parse_id_cols(x_data_dict)\n feature_cols = parse_feature_cols(x_data_dict)\n \n \n x_train_df = pd.read_csv(x_train_csv_filename)\n x_test_df = pd.read_csv(x_test_csv_filename)\n y_train_df = pd.read_csv(y_train_csv_filename)\n y_test_df = pd.read_csv(y_test_csv_filename)\n x_valid_df = pd.read_csv(x_valid_csv_filename)\n y_valid_df = pd.read_csv(y_valid_csv_filename)\n \n \n # impute values\n imputation_strategy = args.imputation_strategy\n \n if imputation_strategy=='ffill':\n print('Imputing missing values by strategy : %s'%imputation_strategy)\n x_train_df = x_train_df.groupby(id_cols).apply(lambda x: x.fillna(method='pad')).copy()\n x_valid_df = x_valid_df.groupby(id_cols).apply(lambda x: x.fillna(method='pad')).copy()\n x_test_df = x_test_df.groupby(id_cols).apply(lambda x: x.fillna(method='pad')).copy()\n\n for feature_col in feature_cols:\n x_train_df[feature_col].fillna(x_train_df[feature_col].mean(), inplace=True)\n\n # impute population mean of training set to test set\n x_valid_df[feature_col].fillna(x_train_df[feature_col].mean(), inplace=True)\n x_test_df[feature_col].fillna(x_train_df[feature_col].mean(), inplace=True)\n elif imputation_strategy=='mean':\n print('Imputing missing values by strategy : %s'%imputation_strategy)\n for feature_col in feature_cols:\n x_train_df[feature_col].fillna(x_train_df[feature_col].mean(), inplace=True)\n\n # impute population mean of training set to test set\n x_valid_df[feature_col].fillna(x_train_df[feature_col].mean(), inplace=True)\n x_test_df[feature_col].fillna(x_train_df[feature_col].mean(), inplace=True)\n elif imputation_strategy=='no_imp':\n print('Missing values not imputed')\n \n \n \n # extract data into NxTxF \n train_vitals = TidySequentialDataCSVLoader(\n x_csv_path=x_train_df,\n y_csv_path=y_train_df,\n x_col_names=feature_cols,\n idx_col_names=id_cols,\n y_col_name=args.outcome_col_name,\n y_label_type='per_sequence'\n )\n\n test_vitals = TidySequentialDataCSVLoader(\n x_csv_path=x_test_df,\n y_csv_path=y_test_df,\n x_col_names=feature_cols,\n idx_col_names=id_cols,\n y_col_name=args.outcome_col_name,\n y_label_type='per_sequence'\n )\n \n \n valid_vitals = TidySequentialDataCSVLoader(\n x_csv_path=x_valid_df,\n y_csv_path=y_valid_df,\n x_col_names=feature_cols,\n idx_col_names=id_cols,\n y_col_name=args.outcome_col_name,\n y_label_type='per_sequence'\n )\n \n X_train, y_train = train_vitals.get_batch_data(batch_id=0)\n X_test, y_test = test_vitals.get_batch_data(batch_id=0)\n X_val, y_val = valid_vitals.get_batch_data(batch_id=0)\n \n del train_vitals, test_vitals, valid_vitals\n N,T,F = X_train.shape\n \n \n print('number of data points : %d\\nnumber of time points : %s\\nnumber of features : %s\\n'%(N,T,F))\n \n \n # mask labels in training set and validation set as per user provided %perc_labelled\n N_tr = len(X_train)\n N_va = len(X_val)\n N_te = len(X_test)\n \n state_id = 41\n rnd_state = np.random.RandomState(state_id)\n n_unlabelled_tr = int((1-(args.perc_labelled)/100)*N_tr)\n unlabelled_inds_tr = rnd_state.permutation(N_tr)[:n_unlabelled_tr]\n y_train = y_train.astype(np.float32)\n y_train[unlabelled_inds_tr] = np.nan \n \n rnd_state = np.random.RandomState(state_id)\n n_unlabelled_va = int((1-(args.perc_labelled)/100)*N_va)\n unlabelled_inds_va = rnd_state.permutation(N_va)[:n_unlabelled_va]\n y_val = y_val.astype(np.float32)\n y_val[unlabelled_inds_va] = np.nan \n \n rnd_state = np.random.RandomState(state_id)\n n_unlabelled_te = int((1-(args.perc_labelled)/100)*N_te)\n unlabelled_inds_te = rnd_state.permutation(N_te)[:n_unlabelled_te]\n y_test = y_test.astype(np.float32)\n y_test[unlabelled_inds_te] = np.nan \n \n X_train = np.expand_dims(X_train, 1)\n X_val = np.expand_dims(X_val, 1)\n X_test = np.expand_dims(X_test, 1)\n \n # standardize data for PC-HMM\n key_list = ['train', 'valid', 'test']\n data_dict = dict.fromkeys(key_list)\n data_dict['train'] = (X_train, y_train)\n data_dict['valid'] = (X_val, y_val)\n data_dict['test'] = (X_test, y_test)\n \n # get the init means and covariances of the observation distribution by clustering\n# print('Initializing cluster means with kmeans...')\n prng = np.random.RandomState(args.seed)\n n_init = 15000\n init_inds = prng.permutation(N)[:n_init]# select random samples from training set\n X_flat = X_train[:n_init].reshape(n_init*T, X_train.shape[-1])# flatten across time\n X_flat = np.where(np.isnan(X_flat), ma.array(X_flat, mask=np.isnan(X_flat)).mean(axis=0), X_flat)\n \n # get cluster means\n n_states = args.n_states\n if args.init_strategy=='kmeans':\n print('Initializing cluster means with kmeans...')\n # get cluster means\n kmeans = KMeans(n_clusters=n_states, n_init=10).fit(X_flat)\n init_means = kmeans.cluster_centers_\n\n # get cluster covariance in each cluster\n init_covs = np.stack([np.zeros(F) for i in range(n_states)])\n elif args.init_strategy=='uniform':\n print('Initializing cluster means with random init...')\n percentile_ranges_F2 = np.percentile(X_flat, [1, 99], axis=0).T\n init_means = np.zeros((n_states, F))\n for f in range(F):\n low=percentile_ranges_F2[f, 0]\n high=percentile_ranges_F2[f, 1]\n if low==high:\n high=low+1\n init_means[:,f] = prng.uniform(low=low, \n high=high, \n size=args.n_states)\n init_covs = np.stack([np.zeros(F) for i in range(n_states)])\n \n# # get cluster covariance in each cluster\n# init_covs = np.stack([np.zeros(F) for i in range(n_states)])\n \n # train model\n optimizer = get_optimizer('adam', lr = args.lr)\n\n # draw the initial probabilities from dirichlet distribution\n prng = np.random.RandomState(args.seed)\n init_state_probas = prng.dirichlet(5*np.ones(n_states))\n\n model = HMM(\n states=n_states, \n lam=args.lamb, \n prior_weight=0.01,\n observation_dist='NormalWithMissing',\n observation_initializer=dict(loc=init_means, \n scale=init_covs),\n initial_state_alpha=1.,\n initial_state_initializer=np.log(init_state_probas),\n transition_alpha=1.,\n transition_initializer=None, optimizer=optimizer)\n \n \n data = custom_dataset(data_dict=data_dict)\n data.batch_size = args.batch_size\n model.build(data) \n \n # set the regression coefficients of the model\n eta_weights = np.zeros((n_states, 2)) \n \n # set the initial etas as the weights from logistic regression classifier with average beliefs as features \n x_train,y_train = data.train().numpy()\n \n pos_inds = np.where(y_train[:,1]==1)[0]\n neg_inds = np.where(y_train[:,0]==1)[0]\n \n x_pos = x_train[pos_inds]\n y_pos = y_train[pos_inds]\n x_neg = x_train[neg_inds]\n y_neg = y_train[neg_inds]\n \n # get their belief states of the positive and negative sequences\n z_pos = model.hmm_model.predict(x_pos)\n z_neg = model.hmm_model.predict(x_neg)\n \n # print the average belief states across time\n beliefs_pos = z_pos.mean(axis=1)\n beliefs_neg = z_neg.mean(axis=1)\n \n \n # perform logistic regression with belief states as features for these positive and negative samples\n print('Performing Logistic Regression on initial belief states to get the initial eta coefficients...')\n logistic = LogisticRegression(solver='lbfgs', random_state = 42)\n penalty = ['l2']\n C = [1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1e0, 1e2, 1e3, 1e4, 1e5]\n hyperparameters = dict(C=C, penalty=penalty)\n classifier = GridSearchCV(logistic, hyperparameters, cv=5, verbose=10, scoring = 'roc_auc')\n \n X_tr = np.vstack([beliefs_pos, beliefs_neg])\n y_tr = np.vstack([y_pos, y_neg])\n cv = classifier.fit(X_tr, y_tr[:,1])\n \n # get the logistic regression coefficients. These are the optimal eta coefficients.\n lr_weights = cv.best_estimator_.coef_\n \n # set the K logistic regression weights as K x 2 eta coefficients\n opt_eta_weights = np.vstack([np.zeros_like(lr_weights), lr_weights]).T\n \n # set the intercept of the eta coefficients\n opt_eta_intercept = np.asarray([0, cv.best_estimator_.intercept_[0]])\n init_etas = [opt_eta_weights, opt_eta_intercept]\n model._predictor.set_weights(init_etas)\n \n \n model.fit(data, steps_per_epoch=1, epochs=100, batch_size=args.batch_size, lr=args.lr,\n initial_weights=model.model.get_weights())\n \n # evaluate on test set\n# x_train, y_train = data.train().numpy()\n z_train = model.hmm_model.predict(x_train)\n y_train_pred_proba = model._predictor.predict(z_train)\n labelled_inds_tr = ~np.isnan(y_train[:,0])\n train_roc_auc = roc_auc_score(y_train[labelled_inds_tr], y_train_pred_proba[labelled_inds_tr])\n train_auprc = average_precision_score(y_train[labelled_inds_tr], y_train_pred_proba[labelled_inds_tr])\n print('ROC AUC on train : %.4f'%train_roc_auc)\n print('AUPRC on train : %.4f'%train_auprc)\n \n \n # evaluate on valid set\n x_valid, y_valid = data.valid().numpy()\n z_valid = model.hmm_model.predict(x_valid)\n y_valid_pred_proba = model._predictor.predict(z_valid)\n labelled_inds_va = ~np.isnan(y_valid[:,0])\n valid_roc_auc = roc_auc_score(y_valid[labelled_inds_va], y_valid_pred_proba[labelled_inds_va])\n valid_auprc = average_precision_score(y_valid[labelled_inds_va], y_valid_pred_proba[labelled_inds_va])\n print('ROC AUC on valid : %.4f'%valid_roc_auc)\n print('AUPRC on valid : %.4f'%valid_auprc)\n \n \n # evaluate on test set\n x_test, y_test = data.test().numpy()\n z_test = model.hmm_model.predict(x_test)\n y_test_pred_proba = model._predictor.predict(z_test)\n labelled_inds_te = ~np.isnan(y_test[:,0])\n test_roc_auc = roc_auc_score(y_test[labelled_inds_te], y_test_pred_proba[labelled_inds_te])\n test_auprc = average_precision_score(y_test[labelled_inds_te], y_test_pred_proba[labelled_inds_te])\n print('ROC AUC on test : %.4f'%test_roc_auc)\n print('AUPRC on test : %.4f'%test_auprc)\n \n # get the parameters of the fit distribution\n mu_all = model.hmm_model(x_train[:10]).observation_distribution.distribution.mean().numpy()\n try:\n cov_all = model.hmm_model(x_train[:10]).observation_distribution.distribution.covariance().numpy()\n except:\n cov_all = model.hmm_model(x_train[:10]).observation_distribution.distribution.scale.numpy()\n \n eta_all = np.vstack(model._predictor.get_weights())\n \n mu_params_file = os.path.join(args.output_dir, args.output_filename_prefix+'-fit-mu.npy')\n cov_params_file = os.path.join(args.output_dir, args.output_filename_prefix+'-fit-cov.npy')\n eta_params_file = os.path.join(args.output_dir, args.output_filename_prefix+'-fit-eta.npy')\n np.save(mu_params_file, mu_all)\n np.save(cov_params_file, cov_all)\n np.save(eta_params_file, eta_all)\n \n # save the loss plots of the model\n save_file = os.path.join(args.output_dir, args.output_filename_prefix+'.csv')\n save_loss_plots(model, save_file, data_dict)\n \n # save the model\n model_filename = os.path.join(args.output_dir, args.output_filename_prefix+'-weights.h5')\n model.model.save_weights(model_filename, save_format='h5')\n \n \n # save some additional performance \n perf_save_file = os.path.join(args.output_dir, 'final_perf_'+args.output_filename_prefix+'.csv')\n model_perf_df = pd.DataFrame([{'train_AUPRC' : train_auprc, \n 'valid_AUPRC' : valid_auprc, \n 'test_AUPRC' : test_auprc}])\n \n \n model_perf_df.to_csv(perf_save_file, index=False)\n \n \n# if __name__ == '__main__':\n# main()\n \n '''\n Debugging code\n \n from sklearn.linear_model import LogisticRegression\n # get 10 positive and 10 negative sequences\n pos_inds = np.where(y[:,1]==1)[0]\n neg_inds = np.where(y[:,0]==1)[0]\n \n x_pos = x[pos_inds]\n y_pos = y[pos_inds]\n x_neg = x[neg_inds]\n y_neg = y[neg_inds]\n \n # get their belief states of the positive and negative sequences\n z_pos = model.hmm_model.predict(x_pos)\n z_neg = model.hmm_model.predict(x_neg)\n \n # print the average belief states across time\n beliefs_pos = z_pos.mean(axis=1)\n beliefs_neg = z_neg.mean(axis=1)\n \n # perform logistic regression with belief states as features for these positive and negative samples\n \n logistic = LogisticRegression(solver='lbfgs', random_state = 42)\n \n \n penalty = ['l2']\n C = [1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1e0, 1e2, 1e3, 1e4]\n hyperparameters = dict(C=C, penalty=penalty)\n classifier = GridSearchCV(logistic, hyperparameters, cv=5, verbose=10, scoring = 'roc_auc')\n \n X_tr = np.vstack([beliefs_pos, beliefs_neg])\n y_tr = np.vstack([y_pos, y_neg])\n cv = classifier.fit(X_tr, y_tr[:,1])\n \n # get the logistic regression coefficients. These are the optimal eta coefficients.\n lr_weights = cv.best_estimator_.coef_\n \n # plot the log probas from of a few negative and positive samples using the logistic regression estimates \n n=50\n x_pos = x[pos_inds[:n]]\n y_pos = y[pos_inds[:n]]\n x_neg = x[neg_inds[:n]]\n y_neg = y[neg_inds[:n]]\n\n # get their belief states of the positive and negative sequences\n z_pos = model.hmm_model.predict(x_pos)\n z_neg = model.hmm_model.predict(x_neg)\n\n # print the average belief states across time\n beliefs_pos = z_pos.mean(axis=1)\n beliefs_neg = z_neg.mean(axis=1)\n \n X_eval = np.vstack([beliefs_pos, beliefs_neg])\n predict_probas = cv.predict_log_proba(X_eval)\n predict_probas_pos = predict_probas[:n, 1]\n predict_probas_neg = predict_probas[n:, 1]\n \n f, axs = plt.subplots(1,1, figsize=(5, 5))\n axs.plot(np.zeros_like(predict_probas_neg), predict_probas_neg, '.')\n axs.plot(np.ones_like(predict_probas_pos), predict_probas_pos, '.')\n axs.set_ylabel('log p(y=1)')\n axs.set_xticks([0, 1])\n axs.set_xticklabels(['50 negative samples', '50 positive samples'])\n f.savefig('predicted_proba_viz_post_lr.png')\n \n # plot some negative sequences that have a high log p(y=1)\n outcast_inds = np.where(predict_probas_neg>-3)\n x_neg_outcasts = x_neg(outcast_inds)\n f, ax = plt.subplots(figsize=(15, 5))\n ax.scatter(x_neg_outcasts[:, :, :, 0], x_neg_outcasts[:, :, :, 1], s=2, marker='x')\n ax.set_xlim([-5, 50])\n ax.set_ylim([-5, 5])\n fontsize=10\n ax.set_ylabel('Temperature_1 (deg C)', fontsize=fontsize)\n ax.set_xlabel('Temperature_0 (deg C)', fontsize = fontsize)\n ax.set_title('negative sequences with log p(y=1)>-3')\n f.savefig('x_outcasts.png')\n \n ###### Converting logistic regression weights to etas\n # set the lr weights as initial etas\n opt_eta_weights = np.vstack([np.zeros_like(lr_weights), lr_weights]).T\n init_etas[0] = opt_eta_weights\n model._predictor.set_weights(init_etas)\n \n # print the predicted probabilities of class 0 and class 1\n y_pred_pos = model._predictor(z_pos).distribution.logits.numpy()\n y_pred_neg = model._predictor(z_neg).distribution.logits.numpy()\n \n # the 2 lines above is the same as \n y_pred_pos = np.matmul(beliefs_pos, opt_eta_weights)+opt_eta_intercept\n y_pred_neg = np.matmul(beliefs_neg, opt_eta_weights)+opt_eta_intercept\n \n \n # plot the log p(y=1) for the negative and positive samples\n y1_pos = expit(y_pred_pos[:,1])\n y1_neg = expit(y_pred_neg[:,1])\n f, axs = plt.subplots(1,1, figsize=(5, 5))\n axs.plot(np.zeros_like(y1_neg), y1_neg, '.')\n axs.plot(np.ones_like(y1_pos), y1_pos, '.')\n axs.set_ylabel('p(y=1)')\n axs.set_xticks([0, 1])\n axs.set_xticklabels(['50 negative samples', '50 positive samples'])\n f.savefig('predicted_proba_viz.png')\n ''' \n \n\n","sub_path":"src/PC-HMM/main_mimic_semi_supervised_old.py","file_name":"main_mimic_semi_supervised_old.py","file_ext":"py","file_size_in_byte":21214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"408446190","text":"import sc2\nfrom sc2 import run_game, maps, Race, Difficulty\nfrom sc2.player import Bot, Computer\nfrom sc2.constants import UnitTypeId as unitType\nimport random\n\nPROBE = unitType.PROBE\nNEXUS = unitType.NEXUS\nPYLON = unitType.PYLON\nASSIMILATOR = unitType.ASSIMILATOR\nGATEWAY = unitType.GATEWAY\nCYBERNATICSCORE = unitType.CYBERNETICSCORE\nSTALKER = unitType.STALKER\nZEALOT = unitType.ZEALOT\n\nclass SpartaBot(sc2.BotAI):\n async def on_step(self, iteration):\n await self.distribute_workers()\n await self.build_workers()\n await self.build_pylons()\n await self.build_assimilators()\n #await self.expand()\n await self.build_offensive_buildings()\n await self.build_offensive_force()\n await self.attack()\n\n async def build_workers(self):\n for nexus in self.units(NEXUS).ready.noqueue:\n if self.can_afford(PROBE):\n await self.do(nexus.train(PROBE))\n\n async def build_pylons(self):\n if self.supply_left < 5 and not self.already_pending(PYLON):\n nexuses = self.units(NEXUS).ready\n if nexuses.exists:\n if self.can_afford(PYLON):\n await self.build(PYLON, near=nexuses.first)\n\n async def build_assimilators(self):\n for nexus in self.units(NEXUS).ready:\n vaspenes = self.state.vespene_geyser.closer_than(25.0, nexus)\n for vaspene in vaspenes:\n if not self.can_afford(ASSIMILATOR):\n break;\n if not self.units(ASSIMILATOR).closer_than(1.0,vaspene):\n worker = self.select_build_worker(vaspene.position)\n if worker is None:\n break;\n await self.do(worker.build(ASSIMILATOR, vaspene))\n\n async def expand(self):\n if self.units(NEXUS).amount < 3 and self.can_afford(NEXUS):\n await self.expand_now()\n\n async def build_offensive_buildings(self):\n if self.units(PYLON).ready.exists:\n pylon = self.units(PYLON).ready.random\n\n if self.units(GATEWAY).ready.exists and not self.units(CYBERNATICSCORE):\n if self.can_afford(CYBERNATICSCORE) and not self.already_pending(CYBERNATICSCORE):\n await self.build(CYBERNATICSCORE, near=pylon)\n\n elif len(self.units(GATEWAY)) < 3:\n if self.can_afford(GATEWAY) and not self.already_pending(GATEWAY):\n await self.build(GATEWAY,near=pylon)\n\n async def build_offensive_force(self):\n for gw in self.units(GATEWAY).ready.noqueue:\n if self.can_afford(STALKER) and not self.already_pending(STALKER):\n await self.do(gw.train(STALKER))\n\n def find_target(self,state):\n if len(self.known_enemy_units) > 0:\n return random.choice(self.known_enemy_units)\n elif len(self.known_enemy_structures) > 0:\n return random.choice(self.known_enemy_structures)\n else:\n return self.enemy_start_locations[0]\n\n async def attack(self):\n if self.units(STALKER).amount > 15:\n for s in self.units(STALKER).idle:\n await self.do(s.attack(self.find_target(self.state)))\n\n if self.units(STALKER).amount > 5:\n if len(self.known_enemy_units) > 0:\n for s in self.units(STALKER).idle:\n await self.do(s.attack(random.choice(self.known_enemy_units)))\n\nrun_game(maps.get(\"AbyssalReefLE\"),\n [Bot(Race.Protoss, SpartaBot()),\n Computer(Race.Terran, Difficulty.Easy)], realtime=False)\n","sub_path":"Bot.py","file_name":"Bot.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"366404250","text":"\"\"\"\nReproducing the experiment of section 6.1 \"Representative Power of Normalizing Flows\" from [1]_ (figure 3).\nThis experiment visually demonstrates that normalizing flows can successfully transform a simple \ninitial approximate distribution q_0(z) to much better approximate some known non-Gaussian bivariate \ndistribution p(z).\nThe known target distributions are specified using energy functions U(z) (table 1 from [1]_).\np(z) = \\frac{1}{Z} e^{-U(z)}, where Z is the unknown partition function (normalization constant); \nthat is, p(z) \\prop e^{-U(z)}.\nSteps\n-----\n1. Generate samples from initial distribution z0 ~ q_0(z) = N(z; \\mu, \\sigma^2 I).\n Here \\mu and \\sigma can either be fixed to something \"reasonable\", or estimated as follows.\n Draw auxillary random variable \\eps from standard normal distribution\n \\eps ~ N(0, I)\n and apply linear normalizing flow transformation f(\\eps) = \\mu + \\sigma \\eps, reparameterizing \n \\sigma = e^{1/2*log_var} to ensure \\sigma > 0, then jointly optimize {mu, log_var} together \n with the other normalizing flow parameters (see below).\n2. Transform the initial samples z_0 through K normalizing flow transforms, from which we obtain the \n transformed approximate distribution q_K(z),\n log q_K(z) = log q_0(z) - sum_{k=1}^K log det |J_k|\n where J_k is the Jacobian of the k-th (invertible) normalizing flow transform.\n E.g. for planar flows,\n log q_K(z) = log q_0(z) - sum_{k=1}^K log |1 + u_k^T \\psi_k(z_{k-1})|\n where each flow includes model parameters \\lambda = {w, u, b}.\n3. Jointly optimize all model parameters by minimizing KL-divergence between the approxmate distribution q_K(z)\n and the true distribution p(z).\n loss = KL[q_K(z)||p(z)] = E_{z_K~q_K(z)} [log q_K(z_K) - log p(z_K)]\n = E_{z_K~q_K(z)} [(log q_0(z_0) - sum_k log det |J_k|) - (-U(z_K) - log(Z))]\n = E_{z_0~q_0(z)} [log q_0(z_0) - sum_k log det |J_k| + U(f_1(f_2(..f_K(z_0)))) + log(Z)]\n Here the partition function Z is independent of z_0 and model parameters, so we can ignore it for the optimization\n \\frac{\\partial}{\\partial params} loss \\prop \\frac{\\partial}{\\partial params} E_{z_0~q_0(z)} [log q0(z0) - sum_k log det |J_k| + U(z_K)]\nReferences\n----------\n .. [1] Jimenez Rezende, D., Mohamed, S., \"Variational Inference with Normalizing Flows\", \n Proceedings of the 32nd International Conference on Machine Learning, 2015.\n\"\"\"\nfrom __future__ import division\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport theano\nimport theano.tensor as T\nimport lasagne\nfrom parmesan.distributions import log_stdnormal, log_normal2\nfrom parmesan.layers import NormalizingPlanarFlowLayer, ListIndexLayer\n\n# TODO\n# - why doesn't 3rd column plot work (should show qK(z) but instead shows q0(z))? not using Theano / Lasagne correctly? some mistake?\n# - draw hyperplane w^T+b = 0 (line in this case) for mode='planar'\n# - during training print E[log p(zK)], E[log qK(zK)] = E[q0(z0) - sum log dot J]\n# - now everything uses shape (batch_size*iw_samples, ndim); would be nice to reshape to (batch_size, iw_samples, ndim) like in iw_vae_normflow.py, \n# although in this case there's no practical difference in the result as we aren't using any actual data\n\n# config\nmode = 'linear' # 'linear' or 'planar'\n# mode = 'planar' # 'linear' or 'planar'\nnorm_p_z = True # for mode='linear' only\nuse_annealed_loss = False # annealed free energy, see paper\nnflows = 2\nbatch_size = 100\nif mode == 'linear':\n nparam_updates = 20000\nelif mode == 'planar':\n nparam_updates = 100000#500000\nreport_every = 1000\nnepochs = nparam_updates // report_every # total num. of 'epochs'\nlr = 1.0e-5\nmomentum = 0.9\niw_samples = 1 # number of samples for Monte Carlo approximation of expectation over q0(z)\n # note: because we aren't using any actual data in this case, this has the same effect as multiplying batch_size\n\nclass NormalizingLinearFlowLayer(lasagne.layers.Layer):\n \"\"\"\n Normalizing flow layer with transform f(z) = mu + sigma*z.\n \n Ensures constraint sigma > 0, by reparameterizing it as log_var.\n This flow transformation is not very powerful as a general transformation, \n it is mainly intended for testing purposes.\n \"\"\"\n def __init__(self, incoming,\n mu=lasagne.init.Normal(),\n log_var=lasagne.init.Normal(), **kwargs):\n super(NormalizingLinearFlowLayer, self).__init__(incoming, **kwargs)\n \n ndim = int(np.prod(self.input_shape[1:]))\n \n self.mu = self.add_param(mu, (ndim,), name=\"mu\")\n self.log_var = self.add_param(log_var, (ndim,), name=\"log_var\")\n \n def get_output_shape_for(self, input_shape):\n return input_shape\n \n def get_output_for(self, input, **kwargs):\n z = input\n sigma = T.exp(0.5*self.log_var)\n f_z = self.mu + sigma*z\n logdet_jacobian = T.sum(0.5*self.log_var)\n return [f_z, logdet_jacobian]\n\ndef U_z(z):\n \"\"\"Test energy function U(z).\"\"\"\n if mode == 'linear':\n import math\n if norm_p_z:\n # normalized; in this case KL divergence should be >= 0,\n # at least if batch_size*iw_samples is sufficiently large to have a good Monte Carlo approximation of expectation\n c = - 0.5 * math.log(2*math.pi)\n else:\n # not normalized; in this case KL divergence may be negative (or never reach a value close to zero)\n c = 0\n mu = np.array([0.7, -1.5]).astype(theano.config.floatX)\n log_var = np.log(np.array([2.3, 0.3])).astype(theano.config.floatX)\n log_p = c - log_var/2 - (z - mu)**2 / (2*T.exp(log_var))\n return -T.sum(log_p, axis=1)\n elif mode == 'planar':\n z1 = z[:, 0]\n z2 = z[:, 1]\n return 0.5*((T.sqrt(z1**2 + z2**2) - 2)/0.4)**2 - T.log(T.exp(-0.5*((z1 - 2)/0.6)**2) + T.exp(-0.5*((z1 + 2)/0.6)**2))\n\ndef evaluate_bivariate_pdf(p_z, range, npoints, z_sym=None):\n \"\"\"Evaluate (possibly unnormalized) pdf over a meshgrid.\"\"\"\n side = np.linspace(range[0], range[1], npoints)\n z1, z2 = np.meshgrid(side, side)\n z = np.hstack([z1.reshape(-1, 1), z2.reshape(-1, 1)])\n\n if not z_sym:\n z_sym = T.matrix('z')\n p_z_ = p_z(z_sym)\n else:\n p_z_ = p_z\n\n p_z_fun = theano.function([z_sym], [p_z_], allow_input_downcast=True)\n \n return z1, z2, p_z_fun(z)[0].reshape((npoints, npoints))\n\ndef evaluate_bivariate_pdf_no_comp(p_z_fun, range, npoints):\n side = np.linspace(range[0], range[1], npoints)\n z1, z2 = np.meshgrid(side, side)\n z = np.hstack([z1.reshape(-1, 1), z2.reshape(-1, 1)])\n return z1, z2, p_z_fun(z)[0].reshape((npoints, npoints))\n\n# main script\nnp.random.seed(1234)\n\nz0 = T.matrix('z0')\n\nl_in = lasagne.layers.InputLayer((None, 2), input_var=z0)\n\nif mode == 'linear':\n l_nf = NormalizingLinearFlowLayer(l_in, name='NF')\n l_zk = ListIndexLayer(l_nf, index=0)\n l_logdet_J_list = [ListIndexLayer(l_nf, index=1)]\nelif mode == 'planar':\n l_logdet_J_list = []\n l_zk = l_in\n # ->\n # also learn initial mapping form standard gaussian to gaussian with mean and diagonal covariance\n #l_nf = NormalizingLinearFlowLayer(l_zk, name='NF_0')\n #l_zk = ListIndexLayer(l_nf, index=0)\n #l_logdet_J_list += [ListIndexLayer(l_nf, index=1)]\n # <-\n for k in xrange(nflows):\n l_nf = NormalizingPlanarFlowLayer(l_zk, name='NF_{:d}'.format(1+k))\n l_zk = ListIndexLayer(l_nf, index=0)\n l_logdet_J_list += [ListIndexLayer(l_nf, index=1)]\n\ntrain_out = lasagne.layers.get_output([l_zk] + l_logdet_J_list, z0, deterministic=False)\nzK = train_out[0]\nlogdet_J_list = train_out[1:]\n\n# loss function\nlog_q0_z0 = log_stdnormal(z0).sum(axis=1)\n\nsum_logdet_J = 0\nfor logdet_J_k in logdet_J_list:\n sum_logdet_J += logdet_J_k\nlog_qK_zK = log_q0_z0 - sum_logdet_J\n\nif use_annealed_loss:\n iteration = theano.shared(0)\n beta_t = T.minimum(1, 0.01 + iteration/10000) # inverse temperature that goes from 0.01 to 1 after 10000 iterations\n # XXX: an 'iteration' is a parameter update, right?\n kl = T.mean(log_qK_zK + beta_t*U_z(zK), axis=0)\nelse:\n kl = T.mean(log_qK_zK + U_z(zK), axis=0)\n\nloss = kl\n\n# updates\nparams = lasagne.layers.get_all_params([l_zk], trainable=True)\n\nprint('Trainable parameters:')\nfor p in params:\n print(' {}: {}'.format(p, p.get_value().shape if p.get_value().shape != () else 'scalar'))\n\ngrads = T.grad(loss, params)\n\nupdates_rmsprop = lasagne.updates.rmsprop(grads, params, learning_rate=lr)\nupdates = lasagne.updates.apply_momentum(updates_rmsprop, params, momentum=momentum)\n#updates = lasagne.updates.adam(grads, params, learning_rate=0.0001)\n\nif use_annealed_loss:\n updates[iteration] = iteration + 1\n\n# compile\nprint('Compiling...')\ntrain_model = theano.function([z0], [loss], updates=updates, allow_input_downcast=True)\n\n# train\nprint('Training...')\nlosses = []\nepoch = 0\nassert nparam_updates % report_every == 0, 'should be integer multiple'\nfor k in xrange(nparam_updates):\n z0_ = np.random.normal(size=(batch_size*iw_samples, 2))\n\n loss = train_model(z0_)[0]\n losses += [loss]\n\n if (1+k) % report_every == 0:\n print('{:d}/{:d}: loss = {:.6f}'.format(1+epoch, nepochs, np.mean(losses)))\n\n if any(np.isnan(losses)):\n print('NaN loss, aborting...')\n break\n\n for p in params:\n print(' {}:\\t{}'.format(p, p.get_value()))\n\n losses = []\n epoch += 1\n\n\n# plot\nfig = plt.figure()\n \nax = plt.subplot(1, 4, 1, aspect='equal')\nz1, z2, phat_z = evaluate_bivariate_pdf(lambda z: T.exp(-U_z(z)), range=(-4, 4), npoints=200)\nplt.pcolormesh(z1, z2, phat_z)\nax.get_xaxis().set_ticks([])\nax.get_yaxis().set_ticks([])\nax.invert_yaxis()\nax.set_title('$p(z)$')\n\nax = plt.subplot(1, 4, 2, aspect='equal')\nz1, z2, q0_z0 = evaluate_bivariate_pdf(T.exp(log_q0_z0), range=(-4, 4), npoints=200, z_sym=z0)\nplt.pcolormesh(z1, z2, q0_z0)\nax.get_xaxis().set_ticks([])\nax.get_yaxis().set_ticks([])\nax.invert_yaxis()\nax.set_title('$q_0(z)$')\n\nax = plt.subplot(1, 4, 3, aspect='equal')\n# get transformed distribution qK(z) directly\n# XXX: doesn't work (ie. shows the un-transformed distribution q0_z0 instead)\nqK_zK = T.exp(log_qK_zK)\nprint('\\nComputational graph before optimization:')\ntheano.printing.debugprint(qK_zK)\nprint('')\neval_model1 = theano.function([z0], [qK_zK], allow_input_downcast=True)\nprint('\\nComputational graph after optimization:')\ntheano.printing.debugprint(eval_model1.maker.fgraph.outputs[0])\nprint('')\nz1, z2, qK_zK_ = evaluate_bivariate_pdf_no_comp(eval_model1, range=(-4, 4), npoints=200)\nax.pcolormesh(z1, z2, qK_zK_)\nax.get_xaxis().set_ticks([])\nax.get_yaxis().set_ticks([])\nax.invert_yaxis()\nax.set_title('$q_K(z)$')\n\nax = plt.subplot(1, 4, 4, aspect='equal')\n# get samples zK ~ qK(z) and plot those\n# XXX: this DOES work\neval_model2 = theano.function([z0], [zK], allow_input_downcast=True)\nN = 1000000 # take many samples; but will still look a little 'spotty'\nz0_ = np.random.normal(size=(N, 2))\nzK_ = eval_model2(z0_)[0]\nax.hist2d(zK_[:, 0], zK_[:, 1], range=[[-4, 4], [-4, 4]], bins=200)\nax.get_xaxis().set_ticks([])\nax.get_yaxis().set_ticks([])\nax.invert_yaxis()\nax.set_title('$z_K \\sim q_K(z)$')\n\nfig.tight_layout()\n\nplt.show()\n\nprint('Done :)')","sub_path":"code/NF/nf6_1.py","file_name":"nf6_1.py","file_ext":"py","file_size_in_byte":11372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"299590450","text":"import os\nimport math\nimport re\nimport numpy as np\nimport random\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import PorterStemmer\nfrom nltk.stem import WordNetLemmatizer\n\nclass Utility(object):\n\n doc_path = './data/bbc/'\n classes = ['politics', 'sport', 'tech', 'trump', 'business', 'entertainment']\n\n porter = PorterStemmer()\n lemmatizer = WordNetLemmatizer()\n\n def __init__(self):\n pass\n\n def train_test_split(self, file_list, train_split=0.7):\n '''\n Split file list into train and test list\n '''\n #random.shuffle(file_list)\n cut_point = int(len(file_list) * train_split)\n \n train = file_list[:cut_point]\n test = file_list[cut_point:]\n\n return train, test\n\n def train_test_docs(self):\n\n train_docs = {}\n test_docs = {}\n for class_ in self.classes:\n docs = [d for d in os.listdir(os.path.join(self.doc_path, class_))]\n split_docs = self.train_test_split(docs)\n train_docs[class_] = split_docs[0] #[:10]\n test_docs[class_] = split_docs[1] #[:5]\n\n return train_docs, test_docs\n\n def load_class_docs(self, dataset_docs):\n \"\"\"Load documents\n \"\"\"\n dataset_class = []\n dataset_articles = []\n dataset_docs_names = []\n\n for class_ in dataset_docs:\n \n for doc in dataset_docs[class_]: #[:5]:\n\n file_handle = open(os.path.join(self.doc_path, class_, doc))\n doc_text = file_handle.read()\n dataset_class.append(class_)\n dataset_articles.append(doc_text) #self.clean_words(doc_text))\n dataset_docs_names.append(class_ + doc.split(\".\")[0])\n \n return np.asarray(dataset_class), np.asarray(dataset_docs_names), np.asarray(dataset_articles)\n \n def vector_fit_transform(self, docs):\n\n vocabulary = [word for article in docs for word in article]\n self.vocabulary = list(set(vocabulary))\n\n doc_vectors = []\n for article in docs:\n doc_v = np.array([self.tf_idf(word, article, docs)\n for word in vocabulary])\n #doc_v = np.array([self.freq(word, article) for word in self.vocabulary])\n doc_vectors.append(doc_v)\n\n return np.array(doc_vectors)\n \n def vector_transform(self, docs):\n \n doc_vectors = []\n for article in docs:\n doc_v = np.array([self.tf_idf(word, article, docs)\n for word in self.vocabulary])\n #doc_v = np.array([self.freq(word, article) for word in self.vocabulary])\n doc_vectors.append(doc_v)\n\n return np.array(doc_vectors)\n\n def clean_words(self, words):\n \"\"\"Clean up words i.e. remove symbols, lowercase, remove stop words and lemmatize\n \"\"\"\n\n lettered_words = re.sub(\"[^a-zA-Z]\", \" \", words)\n lowercase_words = lettered_words.lower().split() # TODO: [:10] # Shorten words\n lowercase_words = lowercase_words\n\n stop_words = set(stopwords.words(\"english\"))\n\n lemmatized_words = [self.lemmatizer.lemmatize(\n w) for w in lowercase_words if not w in stop_words]\n stemmed_words = [self.porter.stem(w) for w in lemmatized_words]\n\n return stemmed_words\n\n def freq(self, word, doc):\n return doc.count(word)\n \n def word_count(self, doc):\n return len(doc)\n \n def tf(self, word, doc):\n return math.log10(1 + self.freq(word, doc))\n \n \n def num_docs_containing(self, word, list_of_docs):\n count = 0\n for document in list_of_docs:\n if self.freq(word, document) > 0:\n count += 1\n \n return count\n \n def idf(self, word, list_of_docs):\n df = self.num_docs_containing(word, list_of_docs)\n \n if df == 0:\n return 0\n return math.log10(len(list_of_docs) / float(df))\n \n \n def tf_idf(self, word, doc, list_of_docs):\n return (self.tf(word, doc) * self.idf(word, list_of_docs))\n","sub_path":"Project4/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"24876982","text":"#-*- coding: utf-8 -*-\n'''\n:maintainer: Nicolas Herbaut\n:maturity: 20150910\n:requires: none\n:platform: all\n'''\n\nimport yaml\nimport os\nimport requests\nimport random\n\n__virtualname__ = 'pman'\n\nPARITY_PILLAR=\"/srv/pillar/parity.sls\"\n\ndef get_local_ip():\n res=\"http://%s:8540\"%(__salt__[\"mine.get\"](__grains__[\"id\"],\"datapath_ip\")[__grains__[\"id\"]][0])\n \n return res\n\ndef parity_in_top_pillar_gard():\n with open(\"/srv/pillar/top.sls\",\"r+\") as target:\n top=yaml.load(target.read())\n states=top[\"base\"][\"*\"]\n if \"parity\" not in states:\n states.append(\"parity\")\n target.seek(0)\n yaml.dump(top,target)\n target.truncate()\n\ndef file_exists_guard(f=PARITY_PILLAR):\n if(not os.path.exists(PARITY_PILLAR)):\n with open(PARITY_PILLAR,\"w\") as target:\n print(\"creating \" + PARITY_PILLAR + \" file \")\n\n\ndef create_user_account(*args, **kwargs):\n\n grains_id=__grains__[\"id\"]\n \n \n count=int(__pillar__[\"parity\"][\"client_count\"])\n \n signatures=[]\n for i in range(0,count):\n \n passphrase=\"user \"+grains_id+\" \"+str(i)\n payload = {\n \"method\": \"parity_newAccountFromPhrase\",\n \"params\": [passphrase,grains_id],\n \"jsonrpc\": \"2.0\",\n \"id\": 0,\n }\n try:\n response = requests.post(get_local_ip(), json=payload)\n response=response.json()\n account_signature = response[\"result\"]\n set_account_meta(account_signature[2:],\"role\",\"user\")\n set_account_meta(account_signature[2:],\"passphrase\",passphrase)\n signatures.append(account_signature)\n except:\n break\n\n return signatures\n\n\n \n\n\n\ndef create_authority_account(*args, **kwargs):\n\n grains_id=__grains__[\"id\"]\n\n\n # Example echo method\n\n\n\n\n payload = {\n \"method\": \"parity_newAccountFromPhrase\",\n \"params\": [grains_id,grains_id],\n \"jsonrpc\": \"2.0\",\n \"id\": 0,\n }\n try:\n response = requests.post(get_local_ip(), json=payload)\n response=response.json()\n account_signature = response[\"result\"]\n set_account_meta(account_signature[2:],\"role\",\"authority\")\n return account_signature\n except:\n return\n\n \n\n\ndef create_account(passphrase,passphrase_recover,role,*args, **kwargs):\n\n grains_id=__grains__[\"id\"]\n\n # Example echo method\n payload = {\n \"method\": \"parity_newAccountFromPhrase\",\n \"params\": [passphrase,passphrase_recover],\n \"jsonrpc\": \"2.0\",\n \"id\": 0,\n }\n\n try:\n response = requests.post(get_local_ip(), json=payload)\n response=response.json()\n account_signature = response[\"result\"]\n set_account_meta(account_signature[2:],\"role\",role)\n\n\n return account_signature\n except:\n return\n\n\ndef list_accounts(*args, **kwargs):\n payload = {\n \"method\": \"parity_allAccountsInfo\",\n \"params\": [],\n \"jsonrpc\": \"2.0\",\n \"id\": 1,\n }\n try:\n response = requests.post(get_local_ip(), json=payload).json()\n return [k for k in response[\"result\"].keys()]\n except:\n return\n\n\ndef list_accounts_details(*args, **kwargs):\n payload = {\n \"method\": \"parity_allAccountsInfo\",\n \"params\": [],\n \"jsonrpc\": \"2.0\",\n \"id\": 1,\n }\n try:\n response = requests.post(get_local_ip(), json=payload).json()\n return response\n except Exception as e :\n return \"failed to contact server\"\n\n \n\n\ndef set_account_name(*args,**kwargs):\n account,name = args[0], args[1]\n payload = {\n \"method\": \"parity_setAccountName\",\n #that because salt somehow convert the 32 byte hex to an integer...\n \"params\": [\"0x\"+account,name],\n \"jsonrpc\": \"2.0\",\n \"id\": 1,\n }\n try:\n response = requests.post(get_local_ip(), json=payload)\n return response.json()\n except:\n return\n\ndef set_account_meta(account,key,value,*args,**kwargs):\n\n payload = {\n \"method\": \"parity_allAccountsInfo\",\n \"params\": [],\n \"jsonrpc\": \"2.0\",\n \"id\": 1,\n }\n\n previous_meta = eval(requests.post(get_local_ip(), json=payload).json()[\"result\"][\"0x\"+account][\"meta\"])\n\n previous_meta[key]=value\n\n meta=(\"%s\"%str(previous_meta)).replace(\"'\",'\"')\n\n payload = {\n \"method\": \"parity_setAccountMeta\",\n #that because salt somehow convert the 32 byte hex to an integer...\n #\"params\": [\"0x\"+account,\"%s\"%str(previous_meta)],\n \"params\": [\"0x\"+account,meta],\n \n \"jsonrpc\": \"2.0\",\n \"id\": 1,\n }\n\n print(payload)\n try:\n response = requests.post(get_local_ip(), json=payload)\n print(\"@@@@@@@@@@@@@@@@@\")\n print(response)\n print(\"@@@@@@@@@@@@@@@@@\")\n return previous_meta\n except Exception as e:\n print(\"*********************\")\n print(res)\n print(\"****************\")\n return\n\ndef get_accounts_by_name(name,*args,**kwargs):\n payload = {\n \"method\": \"parity_allAccountsInfo\",\n \"params\": [],\n \"jsonrpc\": \"2.0\",\n \"id\": 1,\n }\n\n try:\n response = requests.post(get_local_ip(), json=payload).json()\n return [k for (k,v) in response.items() if v[\"name\"]==name]\n except:\n return\n\n \n \n\n\ndef get_accounts_by_meta(key,value,*args,**kwargs):\n payload = {\n \"method\": \"parity_allAccountsInfo\",\n \"params\": [],\n \"jsonrpc\": \"2.0\",\n \"id\": 1,\n }\n\n try:\n response = requests.post(get_local_ip(), json=payload).json()[\"result\"]\n\n return [k for (k,v) in response.items() if eval(v[\"meta\"]).get(key,\"\")==value]\n except:\n return \n\ndef get_enode(*args,**kwargs):\n payload = {\n \"method\": \"parity_enode\",\n \"params\": [],\n \"jsonrpc\": \"2.0\",\n \"id\": 1,\n }\n try:\n response= requests.post(get_local_ip(), json=payload).json()[\"result\"]\n return response\n except:\n return\n\n\n\ndef register_addReservedPeer(*args,**kwargs):\n \n print(__salt__[\"mine.get\"](\"*\",\"parity_enode\").items())\n for k,v in __salt__[\"mine.get\"](\"*\",\"parity_enode\").items():\n if k!=__grains__[\"id\"]:\n try:\n payload = {\n \"method\": \"parity_addReservedPeer\",\n \"params\": [v],\n \"jsonrpc\": \"2.0\",\n \"id\": 0,\n }\n print(payload)\n response= requests.post(get_local_ip(), json=payload).json()\n print(response)\n except:\n return False\n return True\n\n \n \n\n ","sub_path":"hyperledger-fabric-cluster-stack/salt/_modules/paritymanager.py","file_name":"paritymanager.py","file_ext":"py","file_size_in_byte":6541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"290117161","text":"from app.functions import *\n\n\napp.registerEvent(counting_server)\n\n\n# Drop down menus at top left #\napp.addMenuList('File', GUIVar.fileMenuList, menu_press)\napp.addMenuList('Options', ['Update'], menu_press)\n\nprint('creating tabs for server')\n# Tabbed Frame that holds the whole GUI #\nwith app.tabbedFrame('Tabs'):\n app.setBg(GUIConfig.appBgColor)\n\n # Setup tab #\n with app.tab('Setup'):\n app.setBg(GUIConfig.appBgColor)\n with app.frame('Presets', row=0, column=0):\n app.setSticky('new')\n app.setBg(GUIConfig.appBgColor)\n app.addLabel('timestamp',\n datetime.datetime.now().strftime(\"%a, %b %d, '%y\\n %I:%M:%S %p\"))\n # app.addOptionBox('Area: ', ['Select'] + GUIVar.areas)\n # app.setOptionBoxChangeFunction('Area: ', enable_sched_select)\n app.addLabelOptionBox('Shift: ', GUIVar.shifts)\n app.addLabelOptionBox('Schedule: ', GUIVar.scheduleTypes)\n app.setOptionBoxChangeFunction('Shift: ', change_schedule_box_options)\n app.setOptionBoxChangeFunction('Schedule: ', determine_time_file)\n app.setOptionBox('Shift: ', shift_guesser())\n with app.frame('info', row=2, column=0):\n app.setBg(GUIConfig.appBgColor)\n # app.addButton('Set', set_kpi, row=3, column=0, colspan=2)\n # app.addButton('Recalculate', recalculate, row=4, column=0, colspan=2)\n app.addLabel('totalTimeLabel', 'Total Available Time', row=3, column=0)\n app.addLabel('totalTime', Var.available_time, row=4, column=0)\n app.addLabel('taktLabel2', 'Takt', row=3, column=1)\n app.addLabel('takt2', 0, row=4, column=1)\n with app.labelFrame('Demand', row=1, column=0):\n app.setBg(GUIConfig.appBgColor)\n app.setSticky('w')\n app.addLabelNumericEntry('demand', row=0, column=0, colspan=2)\n app.setEntry('demand', 0)\n app.setLabel('demand', 'Demand: ')\n with app.labelFrame('demandIncrementFrame', row=0, column=2, rowspan=2, hideTitle=True):\n app.setSticky('ew')\n app.setBg(GUIConfig.appBgColor)\n inc = GUIVar.demandIncrements\n for i in range(len(inc)):\n app.addButton('%02dUPDemand' % int(inc[i]), demand_set, row=0, column=i + 1)\n app.addButton('%02dDNDemand' % int(inc[i]), demand_set, row=1, column=i + 1)\n app.setButton('%02dUPDemand' % int(inc[i]), '+%s' % inc[i])\n app.setButton('%02dDNDemand' % int(inc[i]), '-%s' % inc[i])\n with app.labelFrame('Plan Cycle Time', row=0, column=1, rowspan=3, hideTitle=True):\n app.setSticky('n')\n app.addLabel('plan_cycle_label', 'Plan Cycle Time')\n app.addButtons(['tct_up1', 'tct_up5'], set_tct)\n app.setButton('tct_up1', \"+1\")\n app.setButton('tct_up5', \"+5\")\n app.addLabel('plan_cycle', 60)\n app.addButtons(['tct_dn1', 'tct_dn5'], set_tct)\n app.setButton('tct_dn1', \"-1\")\n app.setButton('tct_dn5', \"-5\")\n app.addButton('log_tct', log_tct)\n app.setButton('log_tct', 'Set PCT on all timers')\n app.addButton('remove_tct', log_tct)\n app.setButton('remove_tct', 'Remove PCT from all timers')\n with app.tab('Schedule'):\n app.setBg(GUIConfig.appBgColor)\n with app.frame('Parameters', row=0, column=1, rowspan=3):\n app.setSticky('new')\n app.setBg(GUIConfig.appBgColor)\n # with app.frame('Shift', colspan=4):\n # app.addLabel('start-end', 'time-time', 0, 0)\n # app.addLabel('start-endTotal', 'Total Seconds', 0, 1)\n # # app.addLabel('start-endPercent', 'Percent', 1, 0)\n for block in range(1, 5):\n with app.labelFrame('%s Block' % GUIVar.ordinalList[block], row=1, column=block-1):\n app.setSticky('new')\n app.setLabelFrameAnchor('%s Block' % GUIVar.ordinalList[block], 'n')\n app.addLabel('block%s' % block, 'time-time', 0, 0)\n app.addLabel('block%sTotal' % block, 'Seconds', 1, 0)\n # app.addLabel('block%sPercent' % block, 'Percent', 2, 0)\n with app.frame('Meta', row=0, column=2):\n app.setSticky('new')\n app.setBg(GUIConfig.appBgColor)\n app.addOptionBox('Area', ['Ace Post Leach', 'Brickyard', 'Talladega'])\n app.setOptionBoxChangeFunction('Area', set_area)\n app.setOptionBox('Area', c['Var']['Area'])\nprint('done with creating layout at %s seconds' % (datetime.datetime.now()-Var.time_open).total_seconds())\nread_time_file(shift=Var.shift, name=Var.sched.name)\n\nwith app.subWindow('New Schedule', modal=True, transient=True):\n app.addLabel('saveDialog', 'Save New Schedule', row=0, column=0, colspan=5)\n app.addEntry('newScheduleName', row=1, column=2, colspan=3)\n app.addMessage('Fake', 'Fake Message Here', row=2, column=2, colspan=3)\n\napp.setBg(GUIConfig.appBgColor)\n","sub_path":"app/layout_server.py","file_name":"layout_server.py","file_ext":"py","file_size_in_byte":5144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"509127037","text":"# -*- coding: utf-8 -*-\n\n#COMECE AQUI ABAIXO\na=[]\ndef crescente(lista):\n for i in range (0,n,1):\n while lista[i]<lista[i+1]:\n return 'S'\n else:\n return 'N'\n\nn= int(input('Digite a quantidade abaixo: '))\nfor i in range (0,n,1):\n a.append(int(input('Digite o numero%d: ' %(i+1))))\nprint (crescente(a))\n\n","sub_path":"moodledata/vpl_data/380/usersdata/311/96979/submittedfiles/principal.py","file_name":"principal.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"630533983","text":"import argparse\r\nimport sys\r\n\r\nfrom slanitsch.ue02_RSA.encryption import keygen, encrypt, decrypt\r\n\r\nsys.path.insert(0, \"../../..\")\r\n\r\n\"\"\"\r\nErweiterte Ausgabe, ja oder nein\r\n\"\"\"\r\nverbosity = False\r\n\r\n\"\"\"\r\nArgumente mit Typen und ob sie optional sind\r\n\"\"\"\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument(\"-v\", \"--verbosity\", help=\"increase output verbosity\", action=\"store_true\")\r\nparser.add_argument(\"-o\", \"--outputfile\", help=\"file to write output into\", type=str)\r\ngroup = parser.add_mutually_exclusive_group(required=True)\r\ngroup.add_argument(\"-k\", \"--keygen\", help=\"generate new keys with the given length\", type=int)\r\ngroup.add_argument(\"-e\", \"--encrypt\", help=\"encrypt file\", type=str)\r\ngroup.add_argument(\"-d\", \"--decrypt\", help=\"decrypt file\", type=str)\r\n\r\nargs = parser.parse_args()\r\n\r\n\"\"\"\r\nWenn das verbosity Argument im Aufruf vorhanden ist wird die erweiterte Ausgabe angemacht\r\n\"\"\"\r\nif args.verbosity:\r\n print(\"verbosity turned on\")\r\n verbosity = True\r\n\r\n\"\"\"\r\nSchlüsselgeneration durch -k mit optionaler Angabe des Fields für den Key\r\nStandardfile für Keys: keys.txt\r\n\"\"\"\r\nif args.keygen:\r\n if args.outputfile:\r\n print(args.outputfile)\r\n keygen(args.keygen, verbosity, args.outputfile, )\r\n else:\r\n keygen(args.keygen, verbosity)\r\n\r\n\"\"\"\r\nVerschlüsselung eines Files mit optionaler Angabe des Destinationfiles\r\nStandardfile für den Output der Encryption: encrypted.txt\r\n\"\"\"\r\nif args.encrypt:\r\n if args.outputfile:\r\n encrypt(args.encrypt, args.outputfile, verbosity)\r\n else:\r\n encrypt(args.encrypt, \"encrypted.txt\", verbosity)\r\n\r\n\"\"\"\r\nEntschlüsselt ein File mit optionaler Angabe des Destinationfiles\r\nStandardfile für den Output der Decryption: ergebnis.txt\r\n\"\"\"\r\nif args.decrypt:\r\n if args.outputfile:\r\n decrypt(args.decrypt, args.outputfile, verbosity)\r\n else:\r\n decrypt(args.decrypt, \"ergebnis.txt\", verbosity)","sub_path":"ue02_RSA/rsa.py","file_name":"rsa.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"286526117","text":"\"\"\"\nsession 依赖cookie\n\"\"\"\nfrom flask import Flask, session, request\n\n\"\"\"\n每次重新设置的session加密后产生不一样的session字符串序列。\n\"\"\"\n\napp = Flask(__name__)\napp.secret_key = \"tanglaoer\"\n\n@app.route('/')\ndef index():\n\tuser_id = session['user_id']\n\tuser_name = session['user_name']\n\treturn \"index\"\n\n@app.route('/login')\ndef login():\n\t\"\"\"写入session\"\"\"\n\tsession['user_id'] = \"1\"\n\tsession['user_name'] = \"laowang\"\n\treturn \"success\"\n\n\n@app.route('/logout')\ndef logout():\n\t\"\"\"注销\"\"\"\n\n\tsession.pop('user_id', None) # 如果不提供None,没有则报错。\n\tsession.clear()\n\treturn \"logout\"\n\nif __name__ == '__main__':\n\tapp.run(debug=True)","sub_path":"demo013.py","file_name":"demo013.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"450329724","text":"#!/usr/bin/python\n#-*-coding:utf-8-*\n\"\"\"\n第 i 个人的体重为 people[i],每艘船可以承载的最大重量为 limit。\n每艘船最多可同时载两人,但条件是这些人的重量之和最多为 limit。\n返回载到每一个人所需的最小船数。(保证每个人都能被船载)。\n\n输入:people = [1,2], limit = 3\n输出:1\n解释:1 艘船载 (1, 2)\n\n输入:people = [3,2,2,1], limit = 3\n输出:3\n解释:3 艘船分别载 (1, 2), (2) 和 (3)\n\n思路 (双指针法)\n如果最重的人可以与最轻的人共用一艘船,那么就这样安排。否则,最重的人无法与任何人配对,\n那么他们将自己独自乘一艘船。这么做的原因是,如果最轻的人可以与任何人配对,那么他们也\n可以与最重的人配对。\nceshiyixia\n\"\"\"\nclass Solution(object):\n class Solution(object):\n def numRescueBoats(self, people, limit):\n people.sort() # 升序# reverse=True降序,默认是升序(reverse=False)\n i, j = 0, len(people) - 1\n ans = 0\n while i <= j:\n ans += 1\n # 只有最小和最大组合不超过限制最小的索引值才加\n if people[i] + people[j] <= limit:\n i += 1\n j -= 1\n return ans\n\n\n\n\n\n\n\n","sub_path":"save_boat.py","file_name":"save_boat.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"310530184","text":"\"\"\" jupyter addin shows starttime, elapsedtime; sounds alert on cell finish\r\n\"\"\"\r\nimport time\r\nfrom IPython.core.magics.execution import _format_time\r\nfrom IPython.display import display as d\r\nfrom IPython.display import Audio\r\nfrom IPython.core.display import HTML\r\nimport numpy as np\r\nimport logging as log\r\n\r\ndef alert():\r\n \"\"\" makes sound on client using javascript (works with remote server) \"\"\" \r\n framerate = 44100\r\n duration=.05\r\n freq=300\r\n t = np.linspace(0,duration,framerate*duration)\r\n data = np.sin(2*np.pi*freq*t)\r\n d(Audio(data,rate=framerate, autoplay=True))\r\n hide_audio()\r\n \r\ndef hide_audio():\r\n \"\"\" hide the audio control \"\"\"\r\n d(HTML(\"<style>audio{display:none}</style>\"))\r\n\r\ndef s(line, cell=None):\r\n '''Skips execution of the current line/cell.'''\r\n pass\r\n\r\nclass Cell(object):\r\n \"\"\" action cell events \"\"\"\r\n\r\n def __init__(self):\r\n self.start_time = None\r\n\r\n def pre_run_cell(self):\r\n log.info(\"starting\")\r\n self.start_time = time.time()\r\n\r\n def post_run_cell(self): \r\n # show the elapsed time\r\n if self.start_time:\r\n diff = time.time() - self.start_time\r\n print('time: %s' % _format_time(diff))\r\n \r\n # alert finish if more than 30 seconds \r\n if diff > 30:\r\n alert()\r\n self.start_time = None\r\n \r\ncell = Cell()\r\n\r\ndef load_ipython_extension(ip):\r\n hide_audio()\r\n ip.events.register('pre_run_cell', cell.pre_run_cell)\r\n ip.events.register('post_run_cell', cell.post_run_cell)\r\n ip.register_magic_function(s, 'line_cell')\r\n\r\ndef unload_ipython_extension(ip):\r\n ip.events.unregister('pre_run_cell', cell.pre_run_cell)\r\n ip.events.unregister('post_run_cell', cell.post_run_cell)\r\n del ip.magics_manager.magics['cell']['skip']","sub_path":"kaggle/pack-kaggle/lib/python3.6/site-packages/cellevents.py","file_name":"cellevents.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"181482587","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\n\ndef createANDsave_plot(flame,roi,experiment, frame, image, heights, projection,\n depths):\n \"\"\"\n Creates a plot that includes the flame, its contour, height and depth and\n saves it.\n This is used for evaluating the performance of the algorithm.\n \n Parameters:\n ----------\n flame: contour of the flame\n np.ndarray\n \n roi: region of the image\n np.ndarray \n \n experiment: name of the experiment\n str\n \n frame: number of the frame currently being analysed\n int\n \n image: image currently being analysed\n np.ndarray\n \n (height_top, height_bottom): tupple with top and bottom flame heights in pixels\n tuple\n \n projection: projection of the top of the flame outwards\n float\n \n (depth_below, depth_topdoor, depth_above): tupple with flame depths in pixels\n tuple\n \n Returns:\n -------\n None\n \"\"\"\n \n height_top, height_bottom = np.round(heights, 2)\n projection = np.round(projection, 2)\n depth_below, depth_topdoor, depth_above = np.round(depths, 2)\n\n fig, ax = plt.subplots(1, 1, figsize=(16,9))\n fig.tight_layout()\n \n # add note that includes flame heights, projection and depths on each frame\n ax.text(200, 400, \n (f\"Top flame height = {height_top} m \\nBottom flame heigh\"\n f\"t = {height_bottom} m \\nTop flame projection = {projection}\"\n f\" m\\nDepth 0.5 m below = {depth_below} m \\nDepth top of doo\"\n f\"r = {depth_topdoor} m \\nDepth 0.5 m above = {depth_above} m\"), \n fontsize=18, bbox=dict(facecolor=\"red\", alpha=0.5), ma=\"left\",\n ha=\"left\")\n \n # draw flame contour\n if cv2.contourArea(flame) > 4500:\n cv2.drawContours(roi,[flame],0, (51,255,51),4)\n\n ellipse = cv2.fitEllipse(flame)\n cv2.ellipse(roi, ellipse, (0,255,0),3)\n\n ax.imshow(image)\n\n plt.savefig(f\"{experiment}_frames_processed/{frame}.png\")\n plt.close(fig)\n \n return None\n","sub_path":"analysis/video_analysis/contourplot_createANDsave.py","file_name":"contourplot_createANDsave.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"479048572","text":"import cv2\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter import filedialog\nfrom PIL import Image,ImageTk\nimport os\nimport time\nimport pyautogui\nimport re\nimport pickle\nimport shutil\nfrom tkinter import messagebox\nimport numpy as np\nimport csv\n\n\n\n\nroot = Tk()\nroot.title(\"Flossify\")\nroot.config(bg='skyblue')\nv=0\nval=0\n\ntemp=[]\ndata=[]\n\n\n\n\n#catagory index variable\nvar = IntVar()\n#catgory name varible from text entry \ngp=StringVar()\n#frame slide variable\nslider=IntVar()\n#from frame variable\nfrom_frame = IntVar()\n#to_frame variable\n\n\nafter =IntVar()\n\n\n\nto_frame = IntVar()\n\n#path textentry variable\npaath = StringVar()\n\n#output folder path variable\noutput_path = StringVar()\n\n#final frame variable\nfframe = IntVar()\n\nfirst_frame = IntVar()\n\n#annotation checkbox variable\ncheck = IntVar()\n\n#video conver option checkbox variable\nfull = IntVar()\n\n\nxthreshold = IntVar()\n\nythreshold = IntVar()\n\n\nstep = IntVar()\n\ndenseflag = IntVar()\n\n\nclassvar = StringVar()\n\n\nfile_path = StringVar()\n\nspeed = 1\nentry=[]\nradio=[]\nbutton=[]\nclasses=[]\njstep = 1\nloaded = 0\n\n\nclassfile = []\n\ncurrentframe = 0\nfinalframe = 0\npath = ''\n\n\ni=2\nj=0\nf=0\nt=100\n\ndef add_radiobutton(catagory='',vble=None,fn=None,ROW=0,COLUMN=0,ROWSPAN=1,COLUMNSPAN=1,PADX=0,PADY=0,bgg=None):\n\tglobal val\n\tval+=1\n\tx=Radiobutton(root,text=catagory,indicatoron=0,width=30,command=fn,variable=vble,value=val,bg=bgg)\n\tx.grid(row=ROW,column=COLUMN,rowspan=ROWSPAN,padx=PADX,pady=PADY)\n\treturn x\n\n\ndef add_listbox(hgt=10,wdt=20,mode=SINGLE,x1=0,y1=0,PADX=0,PADY=0):\n\tx=Listbox(root,height=hgt,width=wdt,selectmode=mode)\n\tx.place(x=x1,y=y1,height=wdt,width=hgt)\n\treturn x\n\ndef add_slider(vble=None,orientation=HORIZONTAL,fn = None,frm=0,to=0,wdt=10,lnth=100,x1=0,y1=0):\n\tx=Scale(root,orient=orientation,width=wdt,length=lnth,variable=vble,command=fn,from_=frm,to=to)\n\tx.place(x=x1,y=y1,height=wdt,width=lnth)\n\treturn x \n\n\n\ndef add_textentry(vble,ROW=0,COLUMN=0,ROWSPAN=1,COLUMNSPAN=1,PADX=0,PADY=0):\n\tx=(Entry(root,textvariable=vble))\n\tx.grid(row=ROW,column=COLUMN,rowspan=ROWSPAN,padx=PADX,pady=PADY)\n\treturn x\n\n\ndef add_checkbox(lble,vble,cmd=None,ROW=0,COLUMN=0,ROWSPAN=1,COLUMNSPAN=1,PADX=0,PADY=0):\n\tx=(Checkbutton(root,text=lble,variable=vble,onvalue=1,offvalue=0,command=cmd,height=1,width=20))\n\tx.grid(row=ROW,column=COLUMN,rowspan=ROWSPAN,padx=PADX,pady=PADY)\n\treturn x\n\ndef add_button(labl,fn,ROW=0,COLUMN=0,ROWSPAN=1,COLUMNSPAN=1,PADX=0,PADY=0):\n\tx=(Button(root,text=labl,command=fn))\n\tx.grid(row=ROW,column=COLUMN,rowspan=ROWSPAN,padx=PADX,pady=PADY)\n\treturn x\n\ndef sort_dir(data):\n\tconvert=lambda text:int(text) if text.isdigit() else text.lower()\n\tak=lambda key:[convert(c) for c in re.split('([0-9]+)',key)]\n\treturn sorted(data,key=ak)\n\n\n\ndef add_menu():\n\n\tmenu=Menu(root)\n\n\tfilemenu=Menu(menu,tearoff=0)\n\n\t#filemenu.add_command(label=\"Load frames\",command=load_frames)\n\t#filemenu.add_command(label=\"Convert video\",command=video_to_frame)\n\tfilemenu.add_command(label=\"Load video\",command=load_video)\n\n\n\tfilemenu.add_separator()\n\n\tfilemenu.add_command(label=\"Exit\",command=exitfun)\n\n\tmenu.add_cascade(label='File',menu=filemenu)\n\n\n\n\tedit=Menu(menu,tearoff=0)\n\n\t#edit.add_command(label=\"Create folders\",command=None)\n\tedit.add_command(label=\"Load table and create folder\",command=None)\n\tedit.add_command(label=\"Speed up\",command=increasevideospeed)\n\tedit.add_command(label=\"Slow down\",command=deccreasevideospeed)\n\n\t\n\n\tmenu.add_cascade(label='Annotation',menu=edit)\n\n\thlp=Menu(menu,tearoff=0)\n\n\tmenu.add_cascade(label='Help',menu=hlp)\n\n\tAbout=Menu(menu,tearoff=0)\n\n\tmenu.add_cascade(label='About',menu=About)\n\n\troot.config(menu=menu)\n\ndef exitfun():\n\n\tcv2.destroyAllWindows()\n\texit()\n\n'''\ndef load_frames():\n\n\tglobal path,finalframe,s,classfile\n\n\n\tpath = paath.get()\n\n\titems=[]\n\n\n\terrorbox.delete('1.0',END)\n\terrorbox.delete('2.0',END) #line.column\n\n\n\tif os.path.exists(path) :\n\n\n\n\t\tif full.get() :\n\n\t\t\terrorbox.insert(END,\"Loading whole directory .................\")\n\n\t\t\titems = sort_dir(os.listdir(path))\n\n\n\t\t\tfinalframe = len(items) - 1\n\t\t\n\t\telse:\n\n\t\t\tcf=first_frame.get()\n\n\t\t\tfinalframe = fframe.get()\n\n\t\t\terrorbox.insert(END,\"Loading\"+str(finalframe)+\"frames .................\")\n\n\n\t\t\titems = (sort_dir(os.listdir(path))[cf:cf+finalframe])\n\n\n\n\t\tfor i in range(len(items)):\n\n\t\t\tl.insert(i,items[i])\n\n\t\tfor i in range(finalframe+1):\n\t\t\tclassfile.append(-1)\n\n\t\ts=add_slider(vble=slider,fn = slide,frm=0,to=finalframe,wdt=40,lnth=490,x1=305,y1=530)\n\n\t\terrorbox.insert('2.0','\\nsuccess')\n\n\t\tshow()\n\n\telse :\n\t\terrorbox.delete('1.0',END)\n\n\t\terrorbox.insert('1.0',\"error : invalid path\")\n'''\n\ndef load_video():\n\n\tglobal path,finalframe,s,classfile,currentframe,fffirst,cap,loaded\n\n\n\tpath = file_path.get()\n\n\titems=[]\n\n\n\tif os.path.exists(path) :\n\n\t\tcap = cv2.VideoCapture(path)\n\n\t\tif full.get() :\n\n\t\t\tcf = 0\n\n\t\t\tfinalframe = int(cap.get(7))-1\n\n\n\t\t\tfor i in range(finalframe+1):\n\n\t\t\t\tl.insert(i,i)\n\n\t\t\n\t\telse:\n\n\t\t\tcf=first_frame.get()\n\n\t\t\tif cf + fframe.get() < cap.get(7) :\n\n\t\t\t\tfinalframe = cf + fframe.get() -1\n\n\t\t\telse :\n\t\t\t\tmessagebox.showerror(\"error\",\"frame index out of range\")\n\t\t\t\treturn\n\n\n\t\t\tfor i in range(finalframe-cf+1):\n\n\t\t\t\tl.insert(i,i+cf)\n\n\n\t\t\t#errorbox.insert(END,\"Loading\"+str(finalframe)+\"frames .................\")\n\n\n\t\t\t#items = (sort_dir(os.listdir(path))[cf:cf+finalframe])\n\n\t\tcurrentframe = cf\n\n\t\tfffirst = cf\n\n\t\tfor i in range(cf,finalframe+1):\n\t\t\tclassfile.append(0)\n\n\t\t#print(classfile)\n\t\tloaded = 1\n\n\t\ts=Scale(root,orient=HORIZONTAL,width=10,length=490,variable=slider,command=slide,from_=cf,to=finalframe)\n\t\ts.grid(row=20,column=0,columnspan=5,rowspan=2)\n\t\ts.config(bg='yellow')\n\t\n\t\tcv2.destroyAllWindows()\n\n\t\tcv2.namedWindow(\"frame\")\n\t\tcv2.moveWindow(\"frame\",300,250)\n\n\t\tshow()\n\n\n\n\telse :\n\t\terrorbox.delete('1.0',END)\n\n\t\terrorbox.insert('1.0',\"error : invalid path\")\n\n\t\t\n\n'''\n\ndef video_to_frame():\n\n\tp = file_path.get()\n\n\n\terrorbox.delete('1.0',END)\n\terrorbox.delete('2.0',END) #line.column\n\n\topath = output_path.get()\n\n\tif os.path.isfile(p) == False :\n\t\terrorbox.insert('1.0',\"error : invalid source file\")\n\t\treturn\n\n\tif os.path.exists(opath) == False :\n\n\t\terrorbox.insert('1.0',\"creating destination directory...........\")\n\n\t\tos.mkdir(opath)\n\n\t\terrorbox.insert('2.0',\"\\nsuccess\")\n\n\tcap = cv2.VideoCapture(p)\n\n\tif full.get() == 0:\n\n\t\tcf=first_frame.get()\n\n\t\tff = fframe.get()\n\n\t\tentry[3].delete(0,END)\n\n\t\tentry[3].insert(0,\" No. of frames \")\n\n\t\tret = 1\n\n\t\ttemp=0\n\n\t\terrorbox.insert('3.0',\"\\nconverting\"+str(ff)+\"frames...........\")\n\n\t\twhile temp < cf and ret:\n\n\t\t\tret , frame =cap.read()\n\n\t\t\ttemp += 1\n\n\t\tret = 1\n\n\t\tff = ff + cf\n\n\t\twhile (cf < ff) and ret:\n\n\t\t\tret , frame =cap.read()\n\n\t\t\tfilename = opath+'/'+str(cf)+'.jpg'\n\n\t\t\tcv2.imwrite(filename,frame)\n\n\t\t\tcf+=1\n\t\t\n\n\telse :\n\n\t\terrorbox.insert('3.0',\"\\nconverting whole video into frames...........\")\n\n\t\tcf = 1\n\n\t\tsuccess = 1\n\n\t\twhile success:\n\n\t\t\tsuccess , frame =cap.read()\n\n\t\t\tfilename = opath+'/'+str(cf)+'.jpg'\n\n\t\t\tcv2.imwrite(filename,frame)\n\n\t\t\tcf +=1\n\n\terrorbox.insert(END,\"\\ndone\")\n\n\tcap.release()\n\n'''\n\ndef increasevideospeed():\n\tglobal speed\n\tif speed > 0:\n\t\tspeed -= 1\n\tif loaded == 1:\n\t\tdshow()\n\ndef deccreasevideospeed():\n\tglobal speed\n\tif speed < 20:\n\t\tspeed += 1\n\tif loaded == 1:\n\t\tdshow()\ndef create_class():\n\tglobal radio,classes,i,j\n\n\terrorbox.delete('1.0',END)\n\terrorbox.delete('2.0',END) #line.column\n\tif gp.get()=='':\n\t\terrorbox.insert(END,\"error : enter valid class name\")\n\t\tprint(\"error:enter valid string\")\n\t\tmessagebox.showerror('ERROR','enter valid class name')\n\t\tif loaded == 1:\n\t\t\tdshow()\n\t\treturn\n\n\tclasses.append(gp.get())\n\tradio.append(add_radiobutton(gp.get(),var,present,i,5,bgg='lightpink'))\n\tentry[0].delete(first=0,last=END)\n\ti+=1\n\n\terrorbox.insert(END,\"new class :\"+str(gp.get())+\"created\")\n\tif loaded == 1:\n\t\tdshow()\n\nflag=1\t\n\n\n\ndef present():\n\tglobal classfile,currentframe\n\tif len(classfile)<1:\n\t\tif loaded == 1:\n\t\t\tdshow()\n\t\treturn\n\tclassfile[currentframe-fffirst] = var.get()\n\tl.delete(currentframe-fffirst)\n\tl.insert(currentframe-fffirst,str(currentframe)+'---'+str(var.get()))\n\tif loaded == 1:\n\t\tdshow()\n\n\n'''\n\ndef videoplay():\n\t\n\tglobal currentframe,finalframe,path,flag,speed\n\n\terrorbox.delete('1.0',END)\n\tif os.path.exists(path) == False:\n\t\terrorbox.insert(END,\"error : inavalid path or frames not loaded\")\n\t\treturn\n\tx =sort_dir(os.listdir(path))\n\n\tflag=1\n\tcv2.destroyAllWindows()\t\n\tcf = currentframe\n\tt1 = time.time()\n\n\terrorbox.insert(END,\"playing video\")\n\t\n\twhile (currentframe < finalframe):\n\t\t\t\n\t\t\tfm =os.path.join(path,x[currentframe])\n\t\t\tframe = cv2.imread(fm)\n\t\t\tcv2.imshow(\"frame\",frame)\n\t\t\tcv2.setMouseCallback('frame',rect)\n\t\t\tl.activate(currentframe)\n\t\t\ts.set(currentframe)\n\t\t\tcurrentframe += 1\n\t\t\tif flag==0:\n\t\t\t\tbreak\n\n\t\t\tfor j in range(speed):\n\t\t\t\tcv2.waitKey(1)\n\tt2 = time.time()\n\n\tif check.get():\n\t\terrorbox.insert(END,\"\\nannotating....\")\n\t\tfor i in range(cf,currentframe+1):\n\t\t\tclassfile[i] = var.get()\n\t\terrorbox.insert(END,\"done\")\n\n\tif t2-t1 !=0 and currentframe - cf != 0:\n\n\t\tspd = (currentframe-cf)/(t2-t1)\n\n\t\terrorbox.insert(END,\"\\n\"+str(spd)+\"fps\")\n\n\t\tprint(spd,\"fps\")\n\n'''\n\n\nccf = 0\n\ndef videoplay():\n\t\n\tglobal ccf,currentframe,finalframe,path,flag,speed\n\n\terrorbox.delete('1.0',END)\n\tif os.path.exists(path) == False:\n\t\terrorbox.insert(END,\"error : inavalid path \")\n\t\tmessagebox.showerror(\"error\",\"video not loaded\")\n\t\tif loaded == 1:\n\t\t\tdshow()\n\t\treturn\n\n\tflag=1\n\tcv2.destroyAllWindows()\t\n\tcf = currentframe\n\tccf = cf\n\tt1 = time.time()\n\n\terrorbox.insert(END,\"playing video\")\n\t\n\twhile (currentframe+jstep <= finalframe):\n\n\t\t\tshow()\n\t\t\t\n\t\t\tcv2.setMouseCallback('frame',rect)\n\n\t\t\tl.activate(currentframe-fffirst)\n\t\t\ts.set(currentframe)\n\t\t\tcurrentframe += jstep\n\t\t\tif flag==0:\n\t\t\t\tbreak\n\n\t\t\tfor j in range(speed):\n\t\t\t\tcv2.waitKey(1)\n\n\tif flag==0 and (currentframe < (finalframe-100)) and (currentframe > 100):\n\t\tprint(\"dense flow\")\n\t\tdense()\n\n\n\n\tcv2.destroyAllWindows()\n\tshow()\n\n\tl.activate(currentframe-fffirst)\n\ts.set(currentframe)\n\n\tt2 = time.time()\n\n\tif check.get():\n\t\t\n\t\tif after.get() == 0:\n\t\t\terrorbox.insert(END,\"\\nannotating....\")\n\n\n\t\t\tfor i in range(cf,currentframe+1):\n\t\t\t\tclassfile[i-fffirst] = var.get()\n\t\t\t\t#l.delete(i-fffirst)\n\t\t\t\t#l.insert(i-fffirst,str(i)+'---'+str(var.get()))\n\n\n\t\t\terrorbox.insert(END,\"done\")\n\n\tif t2-t1 !=0 and currentframe - cf != 0:\n\n\t\tspd = (currentframe-cf)/(t2-t1)\n\n\t\terrorbox.insert(END,\"\\n\"+str(spd)+\"fps\")\n\n\t\tprint(spd,\"fps\")\n\n\ndef post():\n\tglobal ccf,currentframe,finalframe,path,flag,speed\n\terrorbox.insert(END,\"\\nannotating....\")\n\n\n\n\tfor i in range(ccf,currentframe+1):\n\t\tclassfile[i-fffirst] = var.get()\n\t\tl.delete(i-fffirst)\n\t\tl.insert(i-fffirst,str(i)+'---'+str(var.get()))\n\n\n\terrorbox.insert(END,\"done\")\n\n\tif loaded == 1:\n\t\tdshow()\n\n\ndef next_image():\n\tglobal currentframe,finalframe,path\n\n\terrorbox.delete('1.0',END)\n\n\tif os.path.exists(path) == False:\n\t\tmessagebox.showerror(\"error\",\"video not loaded\")\n\t\tif loaded == 1:\n\t\t\tdshow()\n\t\treturn\n\n\tcf = currentframe\n\n\tif currentframe+jstep <= finalframe :\n\n\t\tcurrentframe+=jstep\n\n\telse:\n\t\terrorbox.insert(END,\"no next image to show\")\n\n\tif check.get():\n\n\t\tfor i in range(cf,currentframe+1):\n\t\t\tclassfile[i-fffirst] = var.get()\n\t\t\t#l.delete(i-fffirst)\n\t\t\t#l.insert(i-fffirst,str(i)+'---'+str(var.get()))\n\n\tcv2.destroyAllWindows()\n\tl.activate(currentframe)\n\ts.set(currentframe)\n\tshow()\n\n\ndef prev_image():\n\tglobal currentframe,finalframe,path\n\t\n\terrorbox.delete('1.0',END)\n\t\n\t\t\n\tcf = currentframe\t\n\n\tif os.path.exists(path) == False:\n\t\tmessagebox.showerror(\"error\",\"video not loaded\")\n\t\tif loaded == 1:\n\t\t\tdshow()\n\t\treturn\n\tif currentframe-jstep >= fffirst :\n\t\tcurrentframe -= jstep\n\n\telse :\n\t\terrorbox.insert(END,\"no previous image to show\")\n\n\n\tif check.get():\n\t\tfor i in range(currentframe,cf):\n\t\t\tclassfile[i-fffirst] = var.get()\n\t\t\t#l.delete(i-fffirst)\n\t\t\t#l.insert(i-fffirst,str(i)+'---'+str(var.get()))\n\n\n\n\tcv2.destroyAllWindows()\n\tl.activate(currentframe)\n\ts.set(currentframe)\n\tshow()\n\n\n\n\n\ndef fromtoannotate():\n\tglobal c\n\terrorbox.delete('1.0',END)\n\tx = from_frame.get()\n\ty = to_frame.get()\n\tc = var.get()\n\n\tif x < fffirst or y > finalframe:\n\t\tmessagebox.showerror(\"error\",\"index out of range\")\n\t\tprint('error')\n\t\tif loaded == 1:\n\t\t\tdshow()\n\t\treturn\n\n\tentry[1].delete(first=0,last=END)\n\tentry[2].delete(first=0,last=END)\n\tentry[1].insert(0,0)\n\tentry[2].insert(0,0)\n\n\terrorbox.insert(END,\"Annotating...............\")\n\n\tfor i in range(x-fffirst,y-fffirst+1):\n\t\tclassfile[i] = c\n\t\t#l.delete(i)\n\t\t#l.insert(i,str(i+fffirst)+\"---\"+str(c))\n\n\terrorbox.insert(END,\"\\ndone\")\n\tif loaded == 1:\n\t\tdshow()\n\ndef listboxfn(event):\n\tglobal currentframe\n\tcurrentframe = l.curselection()[0]+fffirst\n\tl.activate(currentframe)\n\ts.set(currentframe)\n\tif loaded == 1:\n\t\tdshow()\n\ndef show():\n\tglobal cap\n\tcap.set(1,currentframe)\n\tret,frame = cap.read()\n\t#(500,281)\n\tframe = cv2.resize(frame,(750,422),interpolation = cv2.INTER_AREA)\n\t#cv2.putText(frame,str(currentframe),(20,20),cv2.FONT_HERSHEY_SIMPLEX,2,255)\n\tcv2.imshow(\"frame\",frame)\n\ndef dshow():\n\n\tcv2.destroyAllWindows()\n\tshow()\n\n\ndef slide(x=None):\n\t\n\tglobal currentframe,finalframe,path\n\tcv2.destroyAllWindows()\n\tcurrentframe = (slider.get())\n\tl.activate(currentframe)\n\tshow()\n\ndef rect(event,x,y,flags,param):\n\tglobal xy,i,flag\n\tif event==cv2.EVENT_LBUTTONDOWN:\n\t\terrorbox.insert(END,\"\\nPaused\")\n\t\tflag=0\n\ndef cleartext1(event):\n\tipth = filedialog.askdirectory()\n\tentry[4].delete(0,END)\n\tentry[4].insert(0,ipth)\n\tif loaded == 1:\n\t\tdshow()\n\ndef cleartext2(event):\n\t\n\tipth = filedialog.askdirectory()\n\tentry[5].delete(0,END)\n\tentry[5].insert(0,ipth)\n\tif loaded == 1:\n\t\tdshow()\n\n\ndef load(event):\n\t\n\tipth = filedialog.askopenfilename(initialdir = '/',title = \"select file\",filetypes = ((\"pickle\",'.pkl'),('all files','*.*')))\n\tentry[-1].delete(0,END)\n\tentry[-1].insert(0,ipth)\n\tif loaded == 1:\n\t\tdshow()\n\n\ndef cleartext3(event):\n\tipth = filedialog.askopenfilename(initialdir = '/',title = \"select file\",filetypes = ((\"video\",'*.*'),('all files','*.*')))\n\tentry[6].delete(0,END)\n\tentry[6].insert(0,ipth)\n\tif loaded == 1:\n\t\tdshow()\n\n\n\ndef cleartext4(event):\n\tentry[3].delete(0,END)\n\tentry[3].insert(0,0)\n\t#if loaded == 1:\n\t#\tdshow()\n\ndef printclass():\n\tprint(classes)\n\tif loaded == 1:\n\t\tdshow()\n\n\ndef pause():\n\tglobal flag\n\tflag=0\n\n\n\n\ndef writefile():\n\tglobal classfile,classes\n\tdest = output_path.get()\n\tif os.path.exists(dest) == False:\n\t\tmessagebox.showerror(\"error\",\"path not given\")\n\t\tif loaded == 1:\n\t\t\tdshow()\n\t\treturn\n\terrorbox.delete('1.0',END)\n\tprint(\"writing...\")\n\terrorbox.insert(END,\"\\nwriting file\")\n\tif os.path.exists(dest+'/classified.pkl') == False:\n\t\tfile = open(dest+'/classified.pkl','wb')\n\telse:\n\t\tfile = open(dest+'/classified.pkl','ab')\n\n\tpickle.dump(classfile,file)\n\tfile.close()\n\tfile = open(dest+'/classes.pkl','wb')\n\tpickle.dump(classes,file)\n\tfile.close()\n\n\tcsvclass = []\n\n\n\tfor i in range(len(classfile)):\n\t\tcsvclass.append([i+fffirst,classfile[i]])\n\t\tif classfile[i] >= 1:\n\t\t\tcsvclass[i].append(classes[classfile[i]-1])\n\n\n\n\tcsvfile=open(dest+'/classifiedcsv.csv','w')\n\twriter = csv.writer(csvfile)\n\twriter.writerows(csvclass)\n\tcsvfile.close()\n\terrorbox.insert(END,\"\\ndone\")\n\n\n\n\tprint(\"done\")\n\tif loaded == 1:\n\t\tdshow()\n\n\n\ndef jump():\n\tglobal jstep\n\tjstep = step.get()\n\tif loaded == 1:\n\t\tdshow() \n'''\ndef createfolder():\n\tglobal path,classfile,classes\n\n\terrorbox.delete('1.0',END)\n\n\tdest = output_path.get()\n\n\tfor folder in classes :\n\t\tif os.path.exists(dest+'/'+folder) == False:\n\t\t\tos.mkdir(dest+'/'+folder)\n\t\telse :\n\t\t\tshutil.rmtree(dest+'/'+folder)\n\t\t\tos.mkdir(dest+'/'+folder)\n\n\titems = sort_dir(os.listdir(path))\n\n\terrorbox.insert(END,\"\\ncopying to specific folders........\")\n\tfor i in range(len(classfile)) :\n\t\tif classfile[i] > 0 :\n\t\t\t#print(classes[classfile[i]])\n\t\t\t#print(items[i])\n\t\t\tshutil.copy(path+'/'+items[i],dest+'/'+classes[classfile[i]-1])\n\terrorbox.insert(END,\"\\ndone\")\n\tprint(\"donnnneeeee\")\n\t'''\n'''\ndef load_create():\n\n\tdest = output_path.get()\n\tpth = paath.get()\n\ttable = open(pth,'rb')\n\tx=pickle.load(table)\n\tfile.close()\n\n\tpth = paath.get()\n\ttable = open(pth,'rb')\n\tclss=pickle.load(table)\n\tfile.close()\n\n\n\n\tfor folder in clss :\n\t\tif os.path.exists(dest+'/'+folder) == False:\n\t\t\tos.mkdir(dest+'/'+folder)\n\t\telse :\n\t\t\tshutil.rmtree(dest+'/'+folder)\n\t\t\tos.mkdir(dest+'/'+folder)\n\n\titems = sort_dir(os.listdir(fromaddress))\n\n\tfor i in range(len(x)) :\n\t\tif x[i] > 0 :\n\t\t\t#print(classes[classfile[i]])\n\t\t\t#print(items[i])\n\t\t\tshutil.copy(pth+'/'+items[i],dest+'/'+clss[x[i]-1])\n\tprint(\"donnnneeeee\")\n\n'''\n\n\ndef load_class():\n\tglobal entry,radio,classes,i,j\n\tdest = classvar.get()\n\tprint(dest)\n\tfile = open(dest,'rb')\n\ty=pickle.load(file)\n\tfile.close()\n\n\tprint(y)\n\n\n\terrorbox.delete('1.0',END)\n\terrorbox.delete('2.0',END) #line.column\n\n\tfor cls in y:\n\n\t\tclasses.append(cls)\n\t\tradio.append(add_radiobutton(cls,var,present,i,5,bgg='lightpink'))\n\t\ti+=1\n\t\terrorbox.insert(END,\"new class :\"+str(gp.get())+\"created\")\n\n\tif loaded == 1:\n\t\tdshow()\ndef ifdshow(event=None):\n\tif loaded==1:\n\t\tdshow()\n\n\n\ndenserunflag = 0\ndenseframe = 0\nhigh = 0\nList = None\nsug=0\ndef suggest():\n\tglobal ccf,sug\n\tccf = currentframe\n\tsug = 1\n\tdense()\n\t#denserunflag = 1\n\ndef dense():\n\treturn\n\t'''\n global sug,cap,currentframe,denserunflag,denseframe,high,List,flag\n denseframe = currentframe\n entry[1].delete(0,END)\n if sug == 0:\n\t entry[1].insert(0,ccf)\n else:\n \tsug=1\n \tentry[1].insert(0,currentframe)\n print(denseflag)\n if denseflag.get() :\n denserunflag = 1\n errorbox.insert('1.0',\"\\nWait.....\\n\")\n \n x=currentframe\n if x-100<fffirst:\n \tx1=x\n else:\n\t x1=x-100\n if x+100 > finalframe:\n \ty1=x\n else:\n\t y1=x+100\n count=x1\n cap.set(1,x1)\n ret, frame1 = cap.read()\n prvs = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)\n \n while(count<y1):\n ret, frame2 = cap.read()\n next1 = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY)\n \n flow = cv2.calcOpticalFlowFarneback(prvs,next1, None, 0.5, 3, 15, 3, 5, 1.2, 0)\n a=flow[0]\n a=np.sum(np.square(a))\n b=flow[1]\n b=np.sum(np.square(b))\n z=np.sqrt(a+b)\n data.append([count,z])\n print(count)\n #cv2.imshow('frame1',frame1)\n #k = cv2.waitKey(30) & 0xff\n #if k == 27:\n # break\n prvs = next1\n count+=1\n List = [data[f][1] for f in range(len(data))]\n high=List.index(max(List))\n print(high)\n cap.set(1,data[high][0])\n currentframe = data[high][0]\n ret, frame1 = cap.read()\n cv2.destroyAllWindows()\n cv2.imshow('frame',frame1)\n l.activate(currentframe-fffirst)\n s.set(currentframe)\n entry[2].delete(0,END)\n entry[2].insert(0,currentframe)\n'''\n\n\n\ndef left():\n global currentframe,high,List,temp,cap,denserunflag\n if denseflag.get() and denserunflag == 1:\n if(high!=0):\n temp=[List[f] for f in range(0,high)]\n high=temp.index(max(temp))\n high=List.index(temp[high])\n print(data[high][0])\n cap.set(1,data[high][0])\n currentframe = data[high][0]\n ret, frame1 = cap.read()\n l.activate(currentframe-fffirst)\n s.set(currentframe)\n entry[2].delete(0,END)\n entry[2].insert(0,currentframe)\n cv2.destroyAllWindows()\n cv2.imshow('frame',frame1)\n else:\n print(\"Go right\")\n else :\n print(\"Check mark optical flow\")\n ifdshow()\n\ndef right():\n\n global high,List,cap,currentframe\n print(denserunflag,denseflag)\n if denseflag.get() and denserunflag == 1:\n if(high!=199):\n temp=[List[f] for f in range(high+1,200)]\n high=temp.index(max(temp))\n high=List.index(temp[high])\n print(data[high][0])\n cap.set(1,data[high][0])\n currentframe = data[high][0]\n ret, frame1 = cap.read()\n l.activate(currentframe-fffirst)\n s.set(currentframe)\n entry[2].delete(0,END)\n entry[2].insert(0,currentframe)\n \n else:\n print(\"Go left\")\n else :\n print(\"Check mark optical flow\")\n ifdshow()\n\n\ndef reject():\n\tglobal denserunflag,currentframe,denseframe\n\tif denserunflag == 1:\n\t\tdenserunflag = 0\n\t\tcurrentframe = denseframe\n\t\tentry[1].delete(0,END)\n\t\tentry[1].insert(0,0)\n\t\tentry[2].delete(0,END)\n\t\tentry[2].insert(0,0)\n\t\t\n\tifdshow()\n\ndef ok():\n\tglobal denserunflag,currentframe,denseframe\n\tif denserunflag == 1:\n\t\tdenserunflag = 0\n\t\tentry[2].delete(0,END)\n\t\tentry[1].delete(0,END)\n\t\tentry[1].insert(0,0)\n\t\tentry[2].insert(0,0)\n\tifdshow()\n\n\n\nadd_menu()\nadd_radiobutton('No. of frames',ROW=0,COLUMN=0)\n#e1=add_radiobutton('No. of frames',ROW=6,COLUMN=5)\nadd_radiobutton('from',ROW=0,COLUMN=1)\nadd_radiobutton(ROW=0,COLUMN=2)\nadd_radiobutton('to',ROW=0,COLUMN=3)\nadd_radiobutton(ROW=0,COLUMN=4)\nadd_radiobutton(\"Class/catagory\",ROW=0,COLUMN=5)\nadd_radiobutton(ROW=0,COLUMN=6)\nadd_radiobutton(ROW=0,COLUMN=7)\nadd_radiobutton(ROW=0,COLUMN=8)\n\nfor k in range(40):\n\tadd_radiobutton(ROW=k,COLUMN=9)\n\nval=0\n\nr1=Radiobutton(root,text=\"None\",indicatoron=0,width=30,command=present,variable=var,value=0,bg=\"lightpink\")\nr1.grid(row=1,column=5)\nerrorbox = Text(root,height=3)\nerrorbox.grid(row=24,column=1,rowspan=3,columnspan=3)\nerrorbox.bind(\"<Button-1>\",ifdshow)\nerrorbox.insert('1.0',\"initializing..............\")\n\nbutton.append(add_button(\" Add class \",create_class,5,4))\nbutton.append(add_button(\" >> \",next_image,22,3))\nbutton.append(add_button(\" << \",prev_image,22,1))\nbutton.append(add_button(\" play \",videoplay,22,2))\n#button.append(add_button(\" predict \",None,23,1))\nbutton.append(add_button(\" Load video \",load_video,11,4))\n#button.append(add_button(\"printclass\",printclass,1,1))\n#class text entry\nentry.append(add_textentry(gp,6,4))\n\nentry.append(add_textentry(from_frame,1,1))\nentry.append(add_textentry(to_frame,1,3))\n\nbutton.append(add_button(\" catagorise \",fromtoannotate,1,2))\n\n#l = add_listbox(hgt=190,wdt=520,x1=10,y1=140)\n\nl=Listbox(root,height=32,width=29,selectmode=SINGLE)\n#l.place(relx=0.01,rely=0.2,height=520,width=190)\nl.grid(row=0,column=0,rowspan = 32)\n#sy = Scrollbar()\n\n#sy.grid(row=0,column=0,rowspan = 50,sticky=E)\n#sy.config(command = l.yview)\n#l.config(yscrollcommand = sy.set)\nl.bind(\"<Button-1>\",listboxfn) \n\nadd_checkbox(lble = 'annotate',vble = check ,cmd = dshow ,ROW=23,COLUMN=2)\n\nadd_checkbox(lble = 'post annotate',vble = after ,cmd = dshow ,ROW=24,COLUMN=4)\n\nadd_checkbox(lble = 'full load',vble = full ,ROW=4,COLUMN=0)\n\nadd_checkbox(lble = 'optical flow',vble = denseflag ,ROW=4,COLUMN=2)\n\nbutton.append(add_button(\" left \",left,4,1))\nbutton.append(add_button(\" right \",right,4,3))\n\nbutton.append(add_button(\" refresh \",ok,5,1))\nbutton.append(add_button(\" refresh \",reject,5,3))\nbutton.append(add_button(\" suggest \",suggest,5,2))\n\n#button.append(add_button(\" write file \",writefile,3,4))\nb1=Button(root,text='writefile',command=writefile)\nb1.grid(row=1,column=4)\nb1.config(bg='yellow')\n\n#b2=Button(root,text='create folders',command=createfolder)\n#b2.grid(row=2,column=4)\n\nl1=ttk.Label(root,text=\"input file\")\nl1.grid(row=9,column=4)\nl1.bind(\"<Button-1>\",ifdshow)\nl2=ttk.Label(root,text=\"output directory\")\nl2.grid(row=7,column=4)\nl2.bind(\"<Button-1>\",ifdshow)\n\n#l3=ttk.Label(root,text=\"input directory\")\n#l3.grid(row=4,column=4)\n\nl4=ttk.Label(root,text=\"No. of frames\")\nl4.grid(row=0,column=0)\nl4.bind(\"<Button-1>\",ifdshow)\n\nl5=ttk.Label(root,text=\"From frame\")\nl5.grid(row=2,column=0)\nl5.bind(\"<Button-1>\",ifdshow)\n\nentry.append(add_textentry(fframe,1,0))\n#entry[3].insert(0,'')\nentry[3].bind(\"<Button-1>\",cleartext4)\n#entry.append(add_textentry(paath,5,4))\n#entry[4].bind(\"<Button-1>\",cleartext1)\nentry.append(0)\nentry.append(add_textentry(output_path,8,4))\nentry[5].bind(\"<Button-1>\",cleartext2)\nentry.append(add_textentry(file_path,10,4))\nentry[6].bind(\"<Button-1>\",cleartext3)\nentry.append(add_textentry(first_frame,3,0))\n\nerrorbox.insert(END,\"\\ndone\")\n\n\n'''\nbutton.append(add_button(\"sparse optical flow\",sflow,15,4))\nentry.append(add_textentry(xthreshold,17,4))\nentry.append(add_textentry(ythreshold,19,4))\nl5=ttk.Label(root,text=\"x-threshold\")\nl5.grid(row=16,column=4)\n\nl7=ttk.Label(root,text=\"y-threshold\")\nl7.grid(row=18,column=4)\n'''\n\n#button.append(add_button(\"dense optical flow\",None,16,4))\nbutton.append(add_button(\"jump steps\",jump,20,4))\n\nentry.append(add_textentry(step,21,4))\nentry[-1].delete(0,END)\nentry[-1].insert(0,1)\n\nbutton.append(add_button(\"annotate\",post,23,4))\n\nbutton.append(add_button(\"Load class\",load_class,3,4))\n\nentry.append(add_textentry(classvar,4,4))\nentry[-1].bind(\"<Button-1>\",load)\n\n#errorbox.insert('3.0',\"abcdefgk\")\n#errorbox.delete('1.0',END)\nfor b in button:\n\tb.config(bg='yellow')\n\n#button.append(add_button(\" create folders \",None,4,4))\n#x=Scale(root,orient=HORIZONTAL,width=40,length=490,variable=slider,command=slide,from_=0,to=400)\n#x.place(x=305,y=530,height=40,width=490)\nroot.geometry('1320x670+0+0')\nroot.mainloop()","sub_path":"w.py","file_name":"w.py","file_ext":"py","file_size_in_byte":25013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"48995630","text":"from .. import datasets\nfrom . import scorers\nfrom . import models\nfrom . import methods\nfrom .. import __version__\nimport numpy as np\nimport sklearn\nimport os\nimport pickle\nimport sys\nimport time\nimport subprocess\nfrom multiprocessing import Pool\nimport itertools\nfrom shap.benchmark.methods import linear_regress, tree_regress, deep_regress\n\nall_scorers = [\n \"runtime\",\n \"local_accuracy\",\n \"consistency_guarantees\",\n \"mask_keep_positive\",\n \"mask_keep_negative\",\n \"keep_positive\",\n \"keep_negative\",\n \"batch_keep_absolute_r2\",\n \"mask_remove_positive\",\n \"mask_remove_negative\",\n \"remove_positive\",\n \"remove_negative\",\n \"batch_remove_absolute_r2\"\n]\n\n_experiments = []\n_experiments += [[\"corrgroups60\", \"lasso\", m, s] for s in all_scorers for m in linear_regress]\n_experiments += [[\"corrgroups60\", \"ridge\", m, s] for s in all_scorers for m in linear_regress]\n_experiments += [[\"corrgroups60\", \"decision_tree\", m, s] for s in all_scorers for m in tree_regress]\n_experiments += [[\"corrgroups60\", \"random_forest\", m, s] for s in all_scorers for m in tree_regress]\n_experiments += [[\"corrgroups60\", \"gbm\", m, s] for s in all_scorers for m in tree_regress]\n_experiments += [[\"corrgroups60\", \"ffnn\", m, s] for s in all_scorers for m in deep_regress]\n\ndef experiments(dataset=None, model=None, method=None, scorer=None):\n for experiment in _experiments:\n if dataset is not None and dataset != experiment[0]:\n continue\n if model is not None and model != experiment[1]:\n continue\n if method is not None and method != experiment[2]:\n continue\n if scorer is not None and scorer != experiment[3]:\n continue\n yield experiment\n\ndef run_experiment(experiment, use_cache=True, cache_dir=\"/tmp\"):\n dataset_name, model_name, method_name, scorer_name = experiment\n\n # see if we have a cached version\n cache_id = \"v\" + \"__\".join([__version__, dataset_name, model_name, method_name, scorer_name])\n cache_file = os.path.join(cache_dir, cache_id + \".pickle\")\n if use_cache and os.path.isfile(cache_file):\n with open(cache_file, \"rb\") as f:\n #print(cache_id.replace(\"__\", \" \") + \" ...loaded from cache.\")\n return pickle.load(f)\n\n # compute the scores\n print(cache_id.replace(\"__\", \" \") + \" ...\")\n sys.stdout.flush()\n start = time.time()\n X,y = getattr(datasets, dataset_name)()\n score = getattr(scorers, scorer_name)(\n X, y,\n getattr(models, dataset_name+\"__\"+model_name),\n method_name\n )\n print(\"...took %f seconds.\\n\" % (time.time() - start))\n\n # cache the scores\n with open(cache_file, \"wb\") as f:\n pickle.dump(score, f)\n\n return score\n \n\ndef run_experiments_helper(args):\n experiment, cache_dir = args\n return run_experiment(experiment, cache_dir=cache_dir)\n\ndef run_experiments(dataset=None, model=None, method=None, scorer=None, cache_dir=\"/tmp\", nworkers=1):\n experiments_arr = list(experiments(dataset=dataset, model=model, method=method, scorer=scorer))\n if nworkers == 1:\n out = list(map(run_experiments_helper, zip(experiments_arr, itertools.repeat(cache_dir))))\n else:\n with Pool(nworkers) as pool:\n out = pool.map(run_experiments_helper, zip(experiments_arr, itertools.repeat(cache_dir)))\n return list(zip(experiments_arr, out))","sub_path":"shap/benchmark/experiments.py","file_name":"experiments.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"639076714","text":"import http.server\nimport sys\nimport threading\nfrom robots.common.download import get_file_extension_only_by_headers, TDownloadedFile, \\\n DEFAULT_HTML_EXTENSION, TDownloadEnv\n\nHTTP_HEAD_REQUESTS_COUNT = 0\nHTTP_GET_REQUESTS_COUNT = 0\n\n\nclass THttpServer(http.server.BaseHTTPRequestHandler):\n\n def build_headers(self):\n self.send_response(200)\n self.send_header(\"Content-type\", \"application/octet-stream\")\n self.send_header(\"Content-Disposition\", 'attachment;filename = \"wrong_name.doc\"')\n self.end_headers()\n\n def do_GET(self):\n global HTTP_GET_REQUESTS_COUNT\n HTTP_GET_REQUESTS_COUNT += 1\n self.build_headers()\n self.wfile.write(\"<html> aaaaaaa </html>\".encode(\"latin\"))\n\n\n\n def do_HEAD(self):\n global HTTP_HEAD_REQUESTS_COUNT\n HTTP_HEAD_REQUESTS_COUNT += 1\n self.build_headers()\n\n\nHTTP_SERVER = None\ndef start_server(host, port):\n global HTTP_SERVER\n HTTP_SERVER = http.server.HTTPServer((host, int(port)), THttpServer)\n HTTP_SERVER.serve_forever()\n\n\nif __name__ == '__main__':\n TDownloadEnv.clear_cache_folder()\n web_addr = sys.argv[1]\n host, port = web_addr.split(\":\")\n server_thread = threading.Thread(target=start_server, args=(host, port))\n server_thread.start()\n url = web_addr +\"/somepath\"\n wrong_extension = get_file_extension_only_by_headers(url)\n assert wrong_extension == \".doc\" # see minvr.ru for this error\n downloaded_file = TDownloadedFile(url)\n right_extension = downloaded_file.file_extension #read file contents to determine it's type\n assert right_extension == DEFAULT_HTML_EXTENSION\n HTTP_SERVER.shutdown()\n assert HTTP_GET_REQUESTS_COUNT == 1\n assert HTTP_HEAD_REQUESTS_COUNT == 1\n","sub_path":"tools/robots/dlrobot/tests/content_type/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"282918203","text":"from module.modules import *\nfrom module.modules_base import *\nfrom colorama import Fore, Style, init\nfrom papa_pg import *\n\ninit()\nhead = 'term;dep\\n'\nout = head\nprint(f'{Fore.CYAN} Dep: From To\\n')\nchoise = input(' -> ')\n\nif ' ' in choise:\n start, finish = choise.split(' ')\n start, finish = int(start), int(finish) + 1\nelse:\n start = int(choise)\n finish = start + 1\n\nfor x in range(start, finish):\n dep, term = str(x), str(x*10+1)\n out += term + ';' + dep + '\\n'\n\np_green('\\n' + out + '\\n')\ntext_to_file(out, IN_DATA_PATH + 'otbor.csv')\nmk_vsyo_zapros()\n\ninsert_all_otbor()\n","sub_path":"add_otbor.py","file_name":"add_otbor.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"595141581","text":"import argparse\nfrom operator import itemgetter\nfrom file_handler import FileHandler\nfrom website_searcher import WebsiteParser\n\n\n# here is where we start\ndef main():\n # parsing arguments passed when calling script\n parser = argparse.ArgumentParser(description=\"Choosing input and output file with addresses\")\n parser.add_argument('websites_file', help=\"type input file\", type=str)\n parser.add_argument('counted_websites', help=\"type output file\", type=str)\n\n arg = parser.parse_args()\n\n # initialization of a file\n file_handler = FileHandler(arg.counted_websites)\n # get list of websites\n websites = file_handler.read_file(arg.websites_file)\n\n website = WebsiteParser()\n websites_info = website.manage_websites(websites)\n\n # sort list of websites by value of tag_num\n websites_info = sorted(websites_info, key=itemgetter('tag_num'), reverse=True)\n\n file_handler.make_output_file(websites_info)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"buttonz-counter.py","file_name":"buttonz-counter.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"641396262","text":"import collections\n\nfrom lmath import FloatToInteger\nfrom lvalue import LuaValue, LUATYPE, LuaNil\n\n\nclass LuaDict(collections.Mapping):\n def __init__(self):\n self.map = {}\n\n def __setitem__(self, key, value):\n if not isinstance(key, LuaValue):\n raise TypeError('key must be instance of LuaValue')\n if not isinstance(value, LuaValue):\n raise TypeError('value must be instance of LuaValue')\n if key.typeOf() is LUATYPE.LUA_TSTRING.value:\n self.map[key.value] = value\n else:\n self.map[key] = value\n\n def __getitem__(self, item):\n if item.typeOf() is LUATYPE.LUA_TSTRING.value:\n item = item.value\n return self.map.get(item,LuaNil())\n\n def __iter__(self):\n return iter(self.map)\n\n def __len__(self):\n return len(self.map)\n\n\nclass LuaArray(collections.MutableSequence):\n def __init__(self):\n self.arr = []\n\n def __delitem__(self, key):\n del self.arr[key]\n\n def __getitem__(self, item):\n return self.arr[item]\n\n def __len__(self):\n return len(self.arr)\n\n def __setitem__(self, key, value):\n LuaArray.assertValue(value)\n self.arr[key] = value\n\n def insert(self, index, value):\n LuaArray.assertValue(value)\n self.arr.insert(index, value)\n\n @staticmethod\n def assertValue(value):\n if not isinstance(value, LuaValue):\n raise TypeError('value must be instance of LuaValue')\n\n\nclass LuaTable(LuaValue):\n LFIELDS_PER_FLUSH = 50\n\n def __init__(self, narr: int, nrec: int):\n super().__init__(LUATYPE.LUA_TTABLE.value, self)\n if narr > 0:\n self.arr = LuaArray()\n if nrec > 0:\n self.map = LuaDict()\n\n def get(self, key: LuaValue) -> LuaValue:\n \"\"\"\n if key is int or can be convert to int,get value from array\n :param key:\n :return:\n \"\"\"\n key = self.floatToInteger(key)\n if type(key.value) is int and (1 <= key.value <= len(self.arr)):\n return self.arr[key.value - 1]\n return self.map.get(key)\n\n def put(self, key, value):\n key = self.floatToInteger(key)\n if type(key.value) is int and key.value >= 1:\n if not hasattr(self,'arr'):\n self.arr = LuaArray()\n if key.value <= len(self.arr):\n self.arr[key.value - 1] = value\n if key.value == len(self.arr) and value.value is None:\n self.shrinkArray()\n return\n if key.value == len(self.arr) + 1:\n if hasattr(self, 'map'):\n del self.map[key]\n if value.value is not None:\n self.arr.append(value)\n self.expandArray()\n return\n if value.value is not None:\n if not hasattr(self, 'map'):\n self.map = LuaDict()\n self.map[key] = value\n else:\n del self.map[key]\n\n def floatToInteger(self, key):\n \"\"\"\n if key is float,try convert to int\n :param key:\n :return:\n \"\"\"\n if key.typeOf() is LUATYPE.LUA_TNUMBER.value:\n if type(key.value) is float:\n keytoint, convert = FloatToInteger(key.value)\n if convert:\n key.value = keytoint\n return key\n return key\n\n def shrinkArray(self):\n for i in range(len(self.arr) - 1, -1, -1):\n if self.arr[i].value is None:\n self.arr.pop()\n\n def expandArray(self):\n \"\"\"\n move item in map to arr\n :return:\n \"\"\"\n idx = len(self.arr) + 1\n if hasattr(self, 'map'):\n for i in self.map.keys():\n if int(i.value) is idx:\n self.arr.append(self.map[i])\n del self.map[i]\n idx += 1\n else:\n break\n\n def len(self) -> int:\n return len(self.arr)\n","sub_path":"ltable.py","file_name":"ltable.py","file_ext":"py","file_size_in_byte":4051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"516515742","text":"\"\"\"\r\nAll data models for Media Store\r\n\"\"\"\r\n\r\nfrom django.db import models\r\n# from django.db.models import prefetch_related\r\n#from django.contrib.admin.models import LogEntry\r\nfrom django.contrib.auth.models import Group, User\r\nfrom django.core.validators import MaxValueValidator, MinValueValidator\r\nfrom django.core.mail import send_mail, EmailMessage\r\nfrom django.core.exceptions import ValidationError\r\nfrom django.contrib import messages\r\nfrom django.forms import ModelForm, ModelChoiceField\r\nfrom django.template import Context\r\nfrom django.db.models.signals import pre_save, post_save\r\nfrom django.dispatch import receiver\r\nfrom django.template.loader import render_to_string\r\nfrom django_auth_ldap.backend import LDAPBackend\r\nfrom django.shortcuts import redirect\r\nimport decimal\r\nfrom datetime import datetime, date, timedelta\r\nfrom dateutil import relativedelta\r\nfrom djrichtextfield.models import RichTextField\r\nfrom tinymce import models as tinymce_models\r\n\r\n# Create your models here.\r\n\r\nclass ActiveDepartmentManager(models.Manager):\r\n def get_queryset(self):\r\n return super(ActiveDepartmentManager, self).get_queryset().filter(active=True)\r\n\r\nclass Department(models.Model):\r\n department_name = models.CharField(max_length=100)\r\n number = models.CharField(unique=True, max_length=10)\r\n account_code = models.IntegerField(null=True, blank=True) #I don't think this is necessary, not used anywhere except admin.py ~FIX~\r\n is_shared_resource = models.BooleanField(default=False)\r\n active = models.BooleanField(default=True)\r\n department_manager = models.ForeignKey(User, related_name='dept_manager', blank=True, null=True)\r\n\r\n objects = ActiveDepartmentManager()\r\n all_objects = models.Manager()\r\n\r\n def __str__(self):\r\n if self.department_name == 'Group Leader/Lab Head' and self.department_manager:\r\n return self.number + \" \" + self.department_manager.user_profile.name()\r\n else:\r\n return self.number + \" \" + self.department_name\r\n\r\n class Meta:\r\n ordering = ('number',)\r\n\r\nclass UserProfile(models.Model):\r\n user = models.OneToOneField(User, related_name='user_profile')\r\n department = models.ForeignKey(Department, blank=True, null=True)\r\n hhmi_project_id = models.CharField(max_length=30, blank=True, null=True) #needed for visitor projects\r\n employee_id = models.CharField(max_length=20, blank=True, null=True)\r\n email_address = models.CharField(max_length=255, blank=True, null=True)\r\n first_name = models.CharField(max_length=30, blank=True, null=True)\r\n last_name = models.CharField(max_length=30, blank=True, null=True)\r\n manager = models.ForeignKey(User, related_name='user_manager', blank=True, null=True, on_delete=models.SET_NULL) #needed for human-readable department drop-down\r\n is_manager = models.BooleanField(default=False) #do we need? Yes, for manager priveleges (viewing all orders within dept)\r\n is_active = models.BooleanField(default=False)\r\n is_janelia = models.BooleanField(default=False)\r\n is_visitor = models.BooleanField(default=False)\r\n is_privileged = models.BooleanField(default=False)\r\n\r\n# this is used to prevent updates from workday overriding the values that have\r\n# been altered in ResourceMatrix. We need to do this for people who are in the\r\n# wrong department for billing. eg: Pat Rivlin is in \"093417 Fly Brain Imaging EM\"\r\n# but she should be billed to \"093093 Electron Microscopy\". This could be dangerous\r\n# and we should probably limit which fields are ignored to department.\r\n skip_updates = models.BooleanField(default=False)\r\n offboard_date = models.DateField(blank=True, null=True)\r\n\r\n def name(self):\r\n return self.last_name + \", \" + self.first_name\r\n\r\n\r\n def __str__(self):\r\n return str(self.user)\r\n\r\n def department_id_list(self):\r\n deparment_ids = [dept.id for dept in self.alt_departments.all()]\r\n deparment_ids.append(self.department_id)\r\n return deparment_ids\r\n\r\n def manager_name(self):\r\n if self.manager:\r\n return ' '.join([self.manager.first_name, self.manager.last_name])\r\n return ''\r\n\r\n def has_job_privileges(self):\r\n return (self.user.is_superuser or\r\n (self.is_manager and self.department.number == '093098'))\r\n\r\n#assign barcode info to employee name\r\n def data_text_search(self):\r\n if self.employee_id:\r\n if 'J' in self.employee_id:\r\n return ';' + (self.employee_id.replace('J', '9')) + '01?' + ' ' + self.first_name + ' ' + self.last_name\r\n return ';' + self.employee_id + '01?' + ' ' + self.first_name + ' ' + self.last_name\r\n return self.first_name + ' ' + self.last_name\r\n\r\nclass UserFullName(User):\r\n class Meta:\r\n proxy = True\r\n \r\n def __str__(self):\r\n return self.get_full_name()\r\n\r\nclass Vendor(models.Model):\r\n email_address = models.CharField(max_length=225, blank=True, null=True)\r\n company = models.CharField(max_length=50, blank=True, null=True)\r\n contact = models.CharField(max_length=100, blank=True, null=True)\r\n notes_ven = models.CharField(max_length=500, blank=True, null=True)\r\n active = models.BooleanField(default=True)\r\n\r\n def __str__(self):\r\n return self.company\r\n\r\nMEDIA_CHOICES = (\r\n #('','---------'),\r\n ('Agar','Agar'),\r\n ('Antibiotics','Antibiotics'),\r\n ('BDSC', 'Fly Food - BDSC'),\r\n ('Cornmeal Food','Fly Food - Cornmeal'),\r\n ('Dextrose Food','Fly Food - Dextrose'),\r\n ('Power Food','Fly Food - Power'),\r\n ('Wurzburg Food','Fly Food - Wurzburg'),\r\n ('Liquid Media','Liquid Media'),\r\n ('Miscellaneous','Miscellaneous'),\r\n ('Solutions & Buffers','Solutions & Buffers'),\r\n ('Sylgard','Sylgard'),\r\n)\r\n\r\nclass Inventory(models.Model):\r\n\r\n BOOL_CHOICES = ((True, 'Yes'), (False, 'No'))\r\n class Meta:\r\n verbose_name_plural = 'Inventory'\r\n\r\n inventory_text = models.CharField(max_length=75)\r\n product = models.CharField(max_length=40, blank=True, null=True)\r\n media_type = models.CharField(max_length=30, blank=True, null=True, choices=MEDIA_CHOICES)\r\n cost = models.DecimalField(max_digits=5, decimal_places=2, default=0)\r\n container = models.CharField(max_length=50, blank=True, null=True)\r\n volume = models.CharField(max_length=15, blank=True, null=True)\r\n date_created = models.DateField(auto_now_add=True, blank=True, null=True)\r\n notes_inv = models.CharField(max_length=500, blank=True, null=True)\r\n vendor = models.ForeignKey(Vendor, blank=True, null=True)\r\n date_modified = models.DateField(auto_now_add=True, blank=True, null=True)\r\n deposit = models.IntegerField(default=0, blank=True,null=True)\r\n minimum_amt = models.IntegerField(blank=True, null=True)\r\n withdrawal = models.IntegerField(default=0, blank=True, null=True)\r\n# current_amt = deposit - withdrawal\r\n active = models.BooleanField(default=True, choices=BOOL_CHOICES)\r\n\r\n\r\n def __unicode__(self):\r\n return self.inventory_text\r\n\r\n def __str__(self):\r\n return self.inventory_text\r\n\r\n def list_media_type(self):\r\n return self.media_type\r\n\r\nclass OrderManager(models.Manager):\r\n def preferred_order(self, *args, **kwargs):\r\n \"\"\"Sort patterns by preferred order of Y then -- then N\"\"\"\r\n orders = self.get_queryset().filter(*args, **kwargs)\r\n orders = orders.annotate( custom_order=\r\n models.Case( \r\n models.When(status='Submitted', then=models.Value(0)),\r\n models.When(status='In Progress', then=models.Value(1)),\r\n models.When(status='Complete', then=models.Value(2)),\r\n models.When(status='Billed', then=models.Value(3)),\r\n models.When(status='Problem', then=models.Value(4)),\r\n models.When(status='Canceled', then=models.Value(5)),\r\n models.When(status='Auto', then=models.Value(6)),\r\n default=models.Value(7),\r\n output_field=models.IntegerField(), )\r\n ).order_by('custom_order', 'date_recurring_stop')\r\n return orders\r\n\r\nclass Order(models.Model):\r\n #model field choices, extracted for easy reference\r\n STATUS_CHOICES = (\r\n ('Submitted', 'Submitted'),\r\n ('In Progress', 'In Progress'),\r\n ('Complete', 'Complete'),\r\n ('Billed', 'Billed'),\r\n ('Problem', 'Problem'),\r\n ('Canceled', 'Canceled'),\r\n ('Auto', 'Auto'),\r\n )\r\n LOCATION_CHOICES = (\r\n ('1E.372', '1E.372 (21C)'),\r\n ('2W.225', '2W.225 (4C)'),\r\n ('2W.227', '2W.227 (4C)'),\r\n ('2W.263', '2W.263 (4C)'),\r\n ('2W.265', '2W.265 (4C)'),\r\n ('2C.225', '2C.225 (4C)'),\r\n ('2C.227', '2C.227 (4C)'),\r\n ('2C.267', '2C.267 (4C)'),\r\n ('2C.277', '2C.277 (4C)'),\r\n ('2C ambient', 'Near 2C.243 (21C)'),\r\n ('2E.231', '2E.231 (4C)'),\r\n ('2E.233', '2E.233 (18C)'),\r\n ('2E.267', '2E.267 (4C)'),\r\n ('2E.336.1', 'Robot Room (21C)'),\r\n ('3W.228', '3W.228 (4C)'),\r\n ('3W ambient', ' Near 3W.248 (21C)'),\r\n ('3W.266', '3W.266 (4C)'),\r\n ('3C.226', '3C.226 (4C)'),\r\n ('3C.229', '3C.229 (18C)'),\r\n ('3C.265', '3C.265 (4C)'),\r\n ('3C.267', '3C.267 (4C)'),\r\n ('3C ambient', 'Near 3C.289 (21C)'),\r\n ('3E.265', '3E.265 (18C)'),\r\n ('3E.267', '3E.267 (4C)'),\r\n )\r\n WEEK_CHOICES = (\r\n ('1', 'every week'),\r\n ('2', 'every 2 weeks'),\r\n ('3', 'every 3 weeks'),\r\n ('4', 'once a month'),\r\n )\r\n def user_directory_path(instance, filename):\r\n # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>\r\n return 'user_{0}/{1}'.format(instance.user.UserFullName, filename)\r\n\r\n BOOL_CHOICES = ((True, 'Yes'), (False, 'No'))\r\n #had to make null to migrate CHANGE LATER\r\n notes_order = models.CharField(max_length=500, blank=True, null=True) \r\n submitter = models.ForeignKey(User, related_name='submitter', null=True) #submitting order\r\n requester = models.ForeignKey(User, related_name='requester', null=True) #only use when billing other person\r\n project_code = models.ForeignKey(UserProfile, related_name='pcode', null=True, blank=True)\r\n department = models.ForeignKey(Department, blank=False, null=False)\r\n special_instructions = models.TextField(blank=True) #recording request.user\r\n date_created = models.DateField(auto_now_add=True)\r\n date_modified = models.DateField(auto_now=True, blank=True, null=True)\r\n date_submitted = models.DateField(blank=True, null=True) #is this the same as date_created? ~FIX~\r\n date_complete = models.DateField(blank=True, null=True)\r\n date_billed = models.DateField(blank=True, null=True)\r\n is_recurring = models.BooleanField(default=False)\r\n #had to set a default to migrate\r\n date_recurring_start = models.DateField(default=datetime.now, blank=True, null=True)\r\n date_recurring_stop = models.DateField(blank=True, null=True)\r\n location = models.CharField(max_length=30, blank=False, null=False, choices=LOCATION_CHOICES)\r\n status = models.CharField(max_length=30, blank=False, null=False, default='Submitted', choices=STATUS_CHOICES)\r\n doc = models.FileField(null=True, blank=True) # upload_to=user_directory_path\r\n # doc = models.FileField(upload_to='/groups/sciserv/home/coffmans', null=True, blank=True)\r\n days_since_bill = models.IntegerField(blank=True, null=True) #delete when i get the chance (after work) ~FIX~\r\n weeks = models.CharField(max_length=30, blank=True, null=True, choices=WEEK_CHOICES)\r\n due_date = models.DateField(blank=True, null=True) #Might have to change datefield to charfield?\r\n objects = OrderManager()\r\n is_changed = models.BooleanField(default=False)\r\n \r\n\r\n def already_billed(self):\r\n if self.date_billed:\r\n return True\r\n return False\r\n\r\n def order_total(self):\r\n total = 0\r\n list = self.orderline_set.all()\r\n for line in list:\r\n total += line.total()\r\n return total\r\n\r\n def __unicode__(self):\r\n return 'Order for %s on %s (%s)' % (self.user, self.date_complete or self.date_submitted or self.date_created, self.status)\r\n\r\n def is_closed(self):\r\n return self.status.name == 'Complete'\r\n ##DO WE NEED THIS?? ~FIX~\r\n\r\nclass OrderLine(models.Model):\r\n order = models.ForeignKey(Order, blank=False, null=False)\r\n # description = models.TextField(blank=True) #Where is this being used??~FIX~\r\n inventory = models.ForeignKey(Inventory, blank=False, null=False)\r\n qty = models.DecimalField(\r\n max_digits=10, decimal_places=2, blank=False, null=False)\r\n # unit = models.CharField(max_length=30, blank=True,\r\n # null=True) # DO WE NEED THIS?? this was considered container but we don't need that within the orderline\r\n # shouldn't this be the same as Inventory cost? do we need it? \r\n line_cost = models.DecimalField(\r\n max_digits=10, decimal_places=2, blank=False, null=False)\r\n\r\n def total(self):\r\n total = 0.00\r\n if self.inventory.cost and self.qty:\r\n total = round(decimal.Decimal(str(self.qty))*decimal.Decimal(str(self.inventory.cost)),2)\r\n return decimal.Decimal(total)\r\n\r\n\r\n class Meta:\r\n verbose_name_plural = 'order lines'\r\n\r\n def __unicode__(self):\r\n return u'%s' % self.pk\r\n\r\n def clean(self):\r\n # Don't allow draft entries to have a pub_date.\r\n try:\r\n self.inventory\r\n except Inventory.DoesNotExist:\r\n raise ValidationError(\r\n {'inventory': ('Please select an inventory item.')})\r\n if self.total() <= decimal.Decimal(0):\r\n raise ValidationError('Order line must have quantity and cost > 0')\r\n \r\n\r\nclass Announcements(models.Model):\r\n text = tinymce_models.HTMLField()\r\n show = models.BooleanField(default=False)\r\n\r\n\r\nclass Bottles_Vials(models.Model):\r\n ITEM_CHOICES = (\r\n ('1245', 'Bottles'),\r\n ('1263', 'Vials'),\r\n ) \r\n\r\n item = models.ForeignKey(Inventory, blank=True, null=True)\r\n amnt = models.DecimalField(\r\n max_digits=10, decimal_places=2, blank=False, null=False)\r\n\r\n\r\nORDER_VAR = 'o'\r\nORDER_TYPE_VAR = 'ot'\r\n\r\nclass SortHeaders(models.Model):\r\n \"\"\"\r\n Handles generation of an argument for the Django ORM's\r\n ``order_by`` method and generation of table headers which reflect\r\n the currently selected sort, based on defined table headers with\r\n matching sort criteria.\r\n\r\n Based in part on the Django Admin application's ``ChangeList``\r\n functionality.\r\n \"\"\"\r\n def __init__(self, request, headers, default_order_field=None,\r\n default_order_type='asc', additional_params=None):\r\n \"\"\"\r\n request\r\n The request currently being processed - the current sort\r\n order field and type are determined based on GET\r\n parameters.\r\n\r\n headers\r\n A list of two-tuples of header text and matching ordering\r\n criteria for use with the Django ORM's ``order_by``\r\n method. A criterion of ``None`` indicates that a header\r\n is not sortable.\r\n\r\n default_order_field\r\n The index of the header definition to be used for default\r\n ordering and when an invalid or non-sortable header is\r\n specified in GET parameters. If not specified, the index\r\n of the first sortable header will be used.\r\n\r\n default_order_type\r\n The default type of ordering used - must be one of\r\n ``'asc`` or ``'desc'``.\r\n\r\n additional_params:\r\n Query parameters which should always appear in sort links,\r\n specified as a dictionary mapping parameter names to\r\n values. For example, this might contain the current page\r\n number if you're sorting a paginated list of items.\r\n \"\"\"\r\n if default_order_field is None:\r\n for i, (header, query_lookup) in enumerate(headers):\r\n if query_lookup is not None:\r\n default_order_field = i\r\n break\r\n if default_order_field is None:\r\n raise AttributeError('No default_order_field was specified and none of the header definitions given were sortable.')\r\n if default_order_type not in ('asc', 'desc'):\r\n raise AttributeError('If given, default_order_type must be one of \\'asc\\' or \\'desc\\'.')\r\n if additional_params is None: additional_params = {}\r\n\r\n self.header_defs = headers\r\n self.additional_params = additional_params\r\n self.order_field, self.order_type = default_order_field, default_order_type\r\n\r\n # Determine order field and order type for the current request\r\n params = dict(request.GET.items())\r\n if ORDER_VAR in params:\r\n try:\r\n new_order_field = int(params[ORDER_VAR])\r\n if headers[new_order_field][1] is not None:\r\n self.order_field = new_order_field\r\n except (IndexError, ValueError):\r\n pass # Use the default\r\n if ORDER_TYPE_VAR in params and params[ORDER_TYPE_VAR] in ('asc', 'desc'):\r\n self.order_type = params[ORDER_TYPE_VAR]\r\n\r\n def headers(self):\r\n \"\"\"\r\n Generates dicts containing header and sort link details for\r\n all defined headers.\r\n \"\"\"\r\n for i, (header, order_criterion) in enumerate(self.header_defs):\r\n th_classes = []\r\n new_order_type = 'asc'\r\n if i == self.order_field:\r\n th_classes.append('sorted %sending' % self.order_type)\r\n new_order_type = {'asc': 'desc', 'desc': 'asc'}[self.order_type]\r\n yield {\r\n 'text': header,\r\n 'sortable': order_criterion is not None,\r\n 'url': self.get_query_string({ORDER_VAR: i, ORDER_TYPE_VAR: new_order_type}),\r\n 'class_attr': (th_classes and '%s' % ' '.join(th_classes) or 'unsorted'),\r\n }\r\n\r\n def get_query_string(self, params):\r\n \"\"\"\r\n Creates a query string from the given dictionary of\r\n parameters, including any additonal parameters which should\r\n always be present.\r\n \"\"\"\r\n params.update(self.additional_params)\r\n return '?%s' % '&'.join(['%s=%s' % (param, value) \\\r\n for param, value in params.items()])\r\n\r\n def get_order_by(self):\r\n \"\"\"\r\n Creates an ordering criterion based on the current order\r\n field and order type, for use with the Django ORM's\r\n ``order_by`` method.\r\n \"\"\"\r\n return '%s%s' % (\r\n self.order_type == 'desc' and '-' or '',\r\n self.header_defs[self.order_field][1],\r\n )\r\n\r\n@receiver(pre_save, sender=Order)\r\ndef status_email(sender, instance, *args, **kwargs): \r\n if instance.status == 'Complete': \r\n \r\n if instance.is_recurring == True and date.today() < instance.date_recurring_stop:\r\n order = Order.objects.get(pk=instance.id)\r\n orderlines = OrderLine.objects.filter(order=instance.id)\r\n order.special_instructions = instance.id # = duplicated\r\n instance.date_complete = date.today()\r\n # if Order.objects.filter(special_instructions=instance.id).exists()==False:\r\n # if special_instructions is duplicated:\r\n #somehow stop save? maybe order_formset.save(commit=false) and then finish in view?\r\n #else:\r\n order.id = None\r\n order.pk = None\r\n order.status = 'Submitted'\r\n order.date_billed = None \r\n order.date_submitted = date.today()\r\n order.save()\r\n for ol in orderlines:\r\n ol.pk = None\r\n ol.order = order\r\n ol.save()\r\n order.refresh_from_db() \r\n \r\n\r\n\r\n if instance.notes_order == 'Signout':\r\n print('nothing')\r\n else:\r\n domain = 'http://mediastore.int.janelia.org' #NOT BEST SOLUTION ~FIX~ but needed to work with OSX/iOS because otherwise apple will add weird stuff to the URL and user can't open\r\n context = Context({\r\n 'id': instance.id,\r\n 'location': instance.location,\r\n 'domain': domain,\r\n }) \r\n m_plain = render_to_string('complete_email.txt', context.flatten())\r\n m_html = render_to_string('complete_email.html', context.flatten())\r\n\r\n send_mail(\r\n 'MediaStore Order #{0} Complete'.format(instance.id),\r\n m_plain,\r\n 'mediafacility@janelia.hhmi.org',\r\n [instance.requester.user_profile.email_address, instance.submitter.user_profile.email_address], \r\n fail_silently=False,\r\n html_message=m_html,\r\n )\r\n\r\n \r\n elif instance.status == 'Submitted' and instance.notes_order == 'Signout Remainder':\r\n instance.status = 'Complete'\r\n\r\n elif instance.status == 'Billed':\r\n today = date.today()\r\n nextbill = datetime.strptime(str(today.year) + '-' + str(today.month) + '-' + '25','%Y-%m-%d' ).date()\r\n lastbill = datetime.strptime(str(today.year) + '-' + str(today.month) + '-' + '25','%Y-%m-%d' ).date() + relativedelta.relativedelta(months=-1)\r\n\r\n if today >= nextbill:\r\n nextbill = datetime.strptime(str(today.year) + '-' + str(today.month) + '-' + '25','%Y-%m-%d' ).date() + relativedelta.relativedelta(months=1)\r\n lastbill = datetime.strptime(str(today.year) + '-' + str(today.month) + '-' + '25','%Y-%m-%d' ).date()\r\n\r\n instance.date_billed = today\r\n instance.days_since_bill = (today-lastbill).days\r\n\r\n #elif instance.status == 'Canceled':\r\n #DO WE NEED TO SEND AN EMAIL FOR CANCELED? PROBLEM? WOULD THESE EMAILS BE SENT BEFORE? ~FIX~\r\n \r\n #move this to view, maybe have to save(commit=False) to get start_date?\r\n if instance.is_recurring:\r\n if date.today() <= instance.date_recurring_start:\r\n instance.due_date = instance.date_recurring_start - timedelta(days=instance.date_recurring_start.weekday())\r\n else:\r\n if instance.weeks == '1':\r\n first_date = date.today() + timedelta(days=7)\r\n instance.due_date = first_date - timedelta(days=first_date.weekday())\r\n elif instance.weeks == '2':\r\n first_date = date.today() + timedelta(days=14)\r\n instance.due_date = first_date - timedelta(days=first_date.weekday())\r\n elif instance.weeks == '3':\r\n first_date = date.today() + timedelta(days=21)\r\n instance.due_date = first_date - timedelta(days=first_date.weekday()) \r\n elif instance.weeks == '4':\r\n first_date = date.today() + timedelta(days=28)\r\n instance.due_date = first_date - timedelta(days=first_date.weekday())\r\n\r\n\r\nclass ProjectModelChoiceField(ModelChoiceField):\r\n def label_from_instance(self, obj):\r\n return obj.hhmi_project_id + ' ' + obj.name()\r\n\r\n\r\n","sub_path":"store/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":23360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"653411140","text":"class Solution:\n # @param X : list of integers\n # @param Y : list of integers\n # Points are represented by (X[i], Y[i])\n # @return an integer\n def coverPoints(self, X, Y):\n d = 0\n for i in xrange(len(X)-1):\n p1 = (X[i], Y[i])\n p2 = (X[i+1], Y[i+1])\n d += max((abs(p1[0]-p2[0]), abs(p1[1]-p2[1])))\n return d\n\nprint (Solution().coverPoints([1,10], [1,4]))\n","sub_path":"arrays/min_step_in_infinity_grid.py","file_name":"min_step_in_infinity_grid.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"171593575","text":"import random\r\n#Autor: Jose Eduardo Mendez Verdejo 10/Marzo/19\r\n#Entradas: una matriz de 15 x 12 elementos numericos\r\n#Salidas: el numero menor de la matriz, la suma de sus primeras 5 filas y la suma de las 5 ultimas columnas\r\n#Proceso: se obtiene una matriz de 15 x 12, se busca el elementos menor, se suman las 5 primeras filas y las\r\n#\t\t ultimas 5 columnas.\r\n\r\n\r\n#----- Se obtiene la matriz -----\r\ndef generarMatriz(matriz):\r\n\r\n\tfor i in range(0,15):\r\n\t\tfor j in range(0,12):\r\n\r\n\t\t\t#se generan los elementos de forma aleatoria en un rango de 0 a 999\r\n\t\t\tmatriz[i][j] = random.randrange(0,1000) #para ingreso manual \" int(input(\"ingrese un numero: \")) \"\r\n\r\n#----- Se busca el elemento menor -----\r\ndef menorMatriz(matriz):\r\n\ttrono = 99999 #se asiga a una variable un valor mas grande para realizar la comparacion\r\n\t\r\n\tfor i in range(0,15):\r\n\t\tfor j in range(0,12):\r\n\t\t\t\r\n\t\t\t#si un numero es menor al trono se remplaza\r\n\t\t\tif(matriz[i][j] < trono):\r\n\t\t\t\ttrono = matriz[i][j]\r\n\r\n\treturn trono\t\t\t\r\n\r\n#----- Se suman las 5 filas -----\r\ndef sumaFilas(matriz,n):\r\n\r\n\tsumador = 0\r\n\r\n\tfor i in range(0,5):\r\n\t\tfor j in range(0,n):\r\n\t\t\tsumador += matriz[i][j]\r\n\r\n\treturn sumador\t\t\t\r\n\r\n#----- Se suman las 5 columnas -----\r\ndef sumaColumnas(matriz,n):\r\n\t\r\n\tsumador = 0\r\n\r\n\tfor i in range(0,15):\r\n\t\tfor j in range(n-5,n):\r\n\t\t\tsumador += matriz[i][j]\r\n\r\n\treturn sumador\t\r\n\r\n\r\nmatriz = []\r\nn = 12\r\n\r\nfor i in range (0,15):\r\n\tmatriz.append([0] * n)\r\n\r\n\r\ngenerarMatriz(matriz)\r\nmenor = menorMatriz(matriz)\r\nsumaF = sumaFilas(matriz,n)\r\nsumaC = sumaColumnas(matriz,n)\r\n\r\n#se imprime la matriz para verificar datos\r\nfor i in range(0,15):\r\n\tprint(matriz[i])\r\n\r\nprint(\"numero menor es: \",menor)\r\nprint(\"suma total de las 5 filas es: \",sumaF)\r\nprint(\"suma total de las ultimas 5 columnas es: \",sumaC)\r\n\r\n\"\"\"\r\nAutor QA:Jimmy Nathan Ojeda Arana\r\nEntradas: Se generan al azar\r\nSalidas: El numero menor de la matriz, la suma de sus primeras 5 filas y la suma de las 5 ultimas columnas\r\nProceso: Hace el proceso y da las salidas correctamente \r\n\"\"\"\r\n","sub_path":"Unidad 4-Arreglos/ejercicio1.py","file_name":"ejercicio1.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"401760332","text":"from FiddleCaster.Admin.utils import get_config\nfrom flask_admin.contrib.sqla import ModelView\nfrom flask_admin import form\nfrom flask import url_for\nfrom jinja2 import Markup\n\nconfig = get_config('config')\n\n\nclass UserView(ModelView):\n pass\n\n\nclass GuitarView(ModelView):\n pass\n\n\nclass ImageView(ModelView):\n\n def _list_thumbnail(view, context, model, name):\n if not model.path:\n return ''\n\n return Markup('<img src=\"%s\">' % url_for('static',\n filename=form.thumbgen_filename(model.path)))\n\n column_formatters = {\n 'path': _list_thumbnail\n }\n\n form_overrides = {\n 'path': form.ImageUploadField\n }\n\n form_args = {\n 'path': {\n 'label': 'Image',\n 'thumbnail_size': (100, 100, True),\n 'base_path': config.MEDIA_PATH,\n 'allow_overwrite': False\n }\n }\n\n\nclass SoundView(ModelView):\n form_overrides = {\n 'path': form.FileUploadField\n }\n\n form_args = {\n 'path': {\n 'label': 'Sound',\n 'base_path': config.MEDIA_PATH,\n 'allow_overwrite': False,\n 'allowed_extensions': ['wav', 'mp3', 'mp4']\n }\n }\n","sub_path":"Admin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"235823819","text":"import torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom src.aspect_category_model.capsnet import CapsuleNetwork\n\nclass RecurrentCapsuleNetwork(CapsuleNetwork):\n\n def __init__(self, embedding, aspect_embedding, num_layers, bidirectional, capsule_size, dropout, num_categories):\n super(RecurrentCapsuleNetwork, self).__init__(\n embedding=embedding,\n aspect_embedding=aspect_embedding,\n hidden_size=embedding.embedding_dim * (2 if bidirectional else 1),\n capsule_size=capsule_size,\n dropout=dropout,\n num_categories=num_categories\n )\n embed_size = embedding.embedding_dim\n self.rnn = nn.GRU(\n input_size=embed_size * 2,\n hidden_size=embed_size,\n num_layers=num_layers,\n bidirectional=bidirectional,\n batch_first=True\n )\n self.bidirectional = bidirectional\n\n def _sentence_encode(self, sentence, aspect, mask=None):\n batch_size, time_step, embed_size = sentence.size()\n aspect_aware_sentence = torch.cat((\n sentence, aspect.unsqueeze(1).expand(batch_size, time_step, embed_size)\n ), dim=-1)\n output, _ = self.rnn(aspect_aware_sentence)\n if self.bidirectional:\n sentence = sentence.unsqueeze(-1).expand(batch_size, time_step, embed_size, 2)\n sentence = sentence.contiguous().view(batch_size, time_step, embed_size * 2)\n output = output + sentence\n output = F.dropout(output, p=self.dropout, training=self.training)\n return output","sub_path":"src/aspect_category_model/recurrent_capsnet.py","file_name":"recurrent_capsnet.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"539964005","text":"import numpy as np\n\n\nclass PLSA(object):\n def __init__(self, N, Z):\n self.N = N\n self.X = N.shape[0]\n self.Y = N.shape[1]\n self.Z = Z\n\n # P(z)\n self.Pz = np.random.rand(self.Z)\n # P(x|z)\n self.Px_z = np.random.rand(self.Z, self.X)\n # P(y|z)\n self.Py_z = np.random.rand(self.Z, self.Y)\n\n # 正規化\n self.Pz /= np.sum(self.Pz)\n self.Px_z /= np.sum(self.Px_z, axis=1)[:, None]\n self.Py_z /= np.sum(self.Py_z, axis=1)[:, None]\n\n def train(self, k=200, t=1.0e-7):\n '''\n 対数尤度が収束するまでEステップとMステップを繰り返す\n '''\n prev_llh = 100000\n for i in range(k):\n self.em_algorithm()\n llh = self.llh()\n\n if abs((llh - prev_llh) / prev_llh) < t:\n break\n\n prev_llh = llh\n\n def em_algorithm(self):\n '''\n EMアルゴリズム\n P(z), P(x|z), P(y|z)の更新\n '''\n tmp = self.N / np.einsum('k,ki,kj->ij', self.Pz, self.Px_z, self.Py_z)\n tmp[np.isnan(tmp)] = 0\n tmp[np.isinf(tmp)] = 0\n\n Pz = np.einsum('ij,k,ki,kj->k', tmp, self.Pz, self.Px_z, self.Py_z)\n Px_z = np.einsum('ij,k,ki,kj->ki', tmp, self.Pz, self.Px_z, self.Py_z)\n Py_z = np.einsum('ij,k,ki,kj->kj', tmp, self.Pz, self.Px_z, self.Py_z)\n\n self.Pz = Pz / np.sum(Pz)\n self.Px_z = Px_z / np.sum(Px_z, axis=1)[:, None]\n self.Py_z = Py_z / np.sum(Py_z, axis=1)[:, None]\n\n def llh(self):\n '''\n 対数尤度\n '''\n Pxy = np.einsum('k,ki,kj->ij', self.Pz, self.Px_z, self.Py_z)\n Pxy /= np.sum(Pxy)\n lPxy = np.log(Pxy)\n lPxy[np.isinf(lPxy)] = -1000\n\n return np.sum(self.N * lPxy)","sub_path":"plsa/example/plsa2.py","file_name":"plsa2.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"193966576","text":"import streamlit as st\r\nfrom sqlite3 import *\r\ndef app():\r\n \r\n st.title('Delete')\r\n con = connect('myTable.db')\r\n cur = con.cursor()\r\n \r\n number_plate2 = st.text_input('Input your Car Number plate:')\r\n if(st.button(\"Submit\")):\r\n \r\n cur.execute(\"\"\"DELETE FROM CAR WHERE number_plate=?;\"\"\",(number_plate2,)) \r\n cur.execute(\"\"\"SELECT * FROM CAR;\"\"\") \r\n #st.markdown(\"Enter a Valid Entry\\n\")\r\n \r\n \r\n rows = cur.fetchall()\r\n for row in rows:\r\n st.markdown(row)\r\n \r\n \r\n con.commit()\r\n con.close()\r\n \r\n","sub_path":"DBMS Projects/Delete.py","file_name":"Delete.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"36116842","text":"\nfrom django.urls import path , include\nfrom . import api\n\nfrom. import views\n\napp_name = 'product'\n\n\nurlpatterns = [\n path('', views.home_view),\n path('products/' ,views.all_product) , \n path('add_product/' , views.product_form) ,\n\n path('my_product',views.my_product, name='my_product'),\n\n\n \n \n path('my_product/delete_product/<str:pk>' , views.DeleteProduct , name='delete'),\n path('my_product/edit_product/<str:pk>' , views.UpdateProduct , name='update'),\n path('<slug:slug>' , views.single_product , name='single_product'), \n\n ##api\n path('api/products' , api.products_api , name='productsapi') ,\n path('api/products/<str:pk>' , api.product_detail_api , name='productdetailapi') ,\n\n ##api v2\n path('api/v2/products/<str:pk>' , api.ProductDetail.as_view() , name='ProductDetailApi') ,\n path('api/v2/products' , api.ListVCreat.as_view() , name='ListVCreat') ,\n \n\n \n\n\n]","sub_path":"product/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"437307242","text":"import pygame # All the front end\nimport time # For delay, sleep, etc\nfrom sys import exit # for exit()\n\n\nfrom Cards import Card, cards\nfrom network import Network # Custom network class\nfrom multiprocessing.connection import Client # Multiprocessing client\n\n\npygame.init()\n\nwidth = 1000\nheight = 1000\nwindow = pygame.display.set_mode((width, height))\npygame.display.set_caption(\"UNO Client\")\n\nclass Button:\n def __init__(self, text, color, x, y):\n self.text = text\n self.color = color\n self.x = x\n self.y = y\n self.width = 150\n self.height = 80\n\n def draw(self, win):\n pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height))\n font = pygame.font.SysFont(\"Merriweather\", 40)\n text = font.render(str(self.text), 1, (255,255,255))\n win.blit(text, (self.x + round(self.width/2) - round(text.get_width()/2), self.y + round(self.height/2) - round(text.get_height()/2)))\n\n def click(self, pos):\n x1 = pos[0]\n y1 = pos[1]\n if self.x <= x1 <= self.x + self.width and self.y <= y1 <= self.y + self.height:\n return True\n else:\n return False\n\n# Basically a button, just based on a card instead of on text and color\nclass OnScreenCard(Button):\n\n def __init__(self, card: Card, x, y):\n self.card = card\n self.color = card.color\n self.text = str(card.number)\n self.x = x\n self.y = y\n self.width = 60\n self.height = 110\n\nonScreenCards = list()\ndrawButton = Button(\"Draw 1\", (242, 51, 150), 500, 350)\nendTurnButton = Button(\"End Turn\", (242, 51, 150), 500, 450)\n\ndef redrawWindow(win, game, player):\n \"\"\"\n Redraws pygame window based on the current state of the game\n \"\"\"\n\n global onScreenCards\n\n win.fill((255,255,255))\n\n if not(game.connected()):\n font = pygame.font.SysFont(\"comicsans\", 80)\n text = font.render(\"Waiting for Player...\", 1, (255,0,0), True)\n\n win.blit(text, (int(width/2 - text.get_width()/2), int(height/2 - text.get_height()/2)))\n\n else:\n\n # Draw topmost card on screen\n topCard = OnScreenCard(game.lastMove, 300, 500)\n topCard.draw(win)\n\n # Draw the \"Draw 1\" button on screen\n drawButton.draw(win)\n\n # Draw the \"End turn\" button on screen\n endTurnButton.draw(win)\n\n if game.turn == player:\n # Player's turn turn\n font = pygame.font.SysFont(\"comicsans\", 60)\n text = font.render(\"Your Move\", 1, (0, 255,255))\n win.blit(text, (50, 50))\n\n else:\n\n font = pygame.font.SysFont(\"comicsans\", 60)\n text = font.render(\"Opponent\\'s Move\", 1, (0, 255,255))\n win.blit(text, (50, 50))\n\n # Draw all cards\n XPosition = 50\n YPosition = 200\n\n updatedCards = []\n \n if player == 0:\n cardsToDraw = game.p1Cards\n else:\n cardsToDraw = game.p2Cards\n\n for playableCard in cardsToDraw:\n nextCard = OnScreenCard(playableCard, XPosition, YPosition)\n XPosition += 100\n nextCard.draw(win)\n updatedCards.append(nextCard)\n\n onScreenCards = updatedCards\n\n\n pygame.display.update()\n\n\ndef checkMove(move: Card, game) -> bool:\n \"\"\"\n Checks if the player's move was valid and returns a bool\n @Return: Bool indicating whether or not the move was valid.\n \"\"\"\n lastMove = game.lastMove\n\n if move.number == lastMove.number:\n return True\n\n elif move.color == lastMove.color: \n return True\n\n elif move.wild: \n return True\n\n return False\n\n\ndef main():\n run = True\n global onScreenCards\n\n clock = pygame.time.Clock()\n n = Network()\n player = n.getPlayerNumber()\n pygame.time.delay(50)\n \n while run:\n try:\n game = n.send(\"get\", \"C\")\n except:\n run = False\n print(\"Connection lost.\")\n break\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n exit()\n run = False\n \n if event.type == pygame.MOUSEBUTTONDOWN:\n # Only handle this event if the player is on turn.\n if game.turn == player:\n pos = pygame.mouse.get_pos()\n\n if drawButton.click(pos) and game.connected():\n game = n.send(\"draw\", \"C\")\n\n if endTurnButton.click(pos) and game.connected():\n game = n.send(\"end\", \"C\")\n\n for drawnCard in onScreenCards:\n if drawnCard.click(pos) and game.connected():\n if checkMove(drawnCard.card, game):\n try:\n # Send move\n n.send(\"move\", \"C\")\n n.send(drawnCard.card, \"M\")\n\n except EOFError as e:\n print(\"EOF recd.\")\n pass\n\n clock.tick(10)\n redrawWindow(window, game, player)\n\nmain()","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":5243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"250978378","text":"\"\"\"\r\n Find details about upcoming local concerts.\r\n\r\n Build playlists on Spotify and keep them up to date with upcoming concert schedule.\r\n\"\"\"\r\nimport re\r\nimport os\r\nimport pdb\r\n\r\nfrom datetime import date\r\nimport pandas as pd\r\n\r\n\r\nfrom requests import Session\r\nfrom bs4 import BeautifulSoup\r\n\r\nimport spotipy\r\nimport spotipy.util as util\r\n\r\nclass AuthorizationError(Exception):\r\n pass\r\nclass ConcertNotFoundError(Exception):\r\n \"\"\"City Not supported.\"\"\"\r\n pass\r\nclass ArtistNotFoundError(Exception):\r\n pass\r\n\r\nclass Manager:\r\n \"\"\"\"\"\"\r\n def __init__(self, **kwargs):\r\n \"\"\r\n\r\n self.today = date.today()\r\n self.session = None\r\n # super().__init__(**kwargs)\r\n\r\n \r\n def start_session(self):\r\n \"\"\"\r\n Create Session object\r\n\r\n \"\"\"\r\n\r\n self.session = Session()\r\n return self\r\n\r\n def get_response(self, url, **kwargs):\r\n \" Return response from website\"\r\n \r\n if self.session is not None:\r\n try:\r\n return self.session.get(url, **kwargs)\r\n except Exception as e:\r\n raise e\r\n \r\n def record_data(self, data):\r\n \"Return dataframe from dictionary of collected data.\"\r\n # Where, When, Who, How Much?\r\n # Columns: Venue, Showtime, Artist, Price\r\n\r\n self.df = pd.DataFrame(data)\r\n return self\r\n\r\n def keep_time(self):\r\n \"Remove all entries from before today's date.\"\r\n # TODO\r\n # Make sure self.df.ShowTime.toordinal() < self.today.toordinal()\r\n self.df[self.df.ShowTime < self.today]\r\n return self\r\n\r\nclass ConcertManager(Manager):\r\n \"\"\" Reporter, Tracker \"\"\"\r\n\r\n headers = {\r\n 'user-agent': (\r\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'\r\n 'AppleWebKit/537.36 (KHTML, like Gecko)'\r\n 'Chrome/68.0.3440.106 Safari/537.36')}\r\n\r\n# Existing Concert Sources\r\n links = {\r\n 'Athens': 'http://www.flagpole.com/events/live-music',\r\n 'Music Midtown': 'https://www.musicmidtown.com/lineup/interactive/'}\r\n\r\n def __init__(self, concert=None, **kwargs):\r\n\r\n self.url = None\r\n self.soup = None\r\n self.response = None\r\n self.concert = concert\r\n\r\n try:\r\n self.url = self.links[concert]\r\n except Exception as e:\r\n raise ConcertNotFoundError(e)\r\n\r\n super().__init__(**kwargs)\r\n \r\n def start_session(self):\r\n\r\n super().start_session()\r\n self.session.headers.update(self.headers)\r\n return self\r\n\r\n def get_response(self):\r\n\r\n params = {'stream':True}\r\n # self.response = self.session.get(\r\n # self.url, headers=self.headers, stream=True)\r\n \r\n self.response = super().get_response(self.url, **params)\r\n\r\n def get_concert_soup(self):\r\n\r\n if hasattr(self, 'response'):\r\n self.soup = BeautifulSoup(self.response.content, 'lxml')\r\n return self\r\n else:\r\n return None\r\n \r\n def athens_concerts(self):\r\n \"Return Dictionary of upcoming concerts in Athens, GA\"\r\n\r\n events = self.soup.find(class_='event-list').findAll('h2')\r\n concert_dict = {}\r\n for e in events:\r\n date = e.text\r\n event_count = e.findNext('p')\r\n concert_dict[date]= {'Event Count':event_count.text}\r\n venues = e.findNext('ul').findAll('h4')\r\n \r\n for v in venues:\r\n info = v.findNext('p')\r\n bands = info.fetchNextSiblings()\r\n names = [each.strong.text.replace('\\xa0', '')\r\n for each in bands if each.strong]\r\n concert_dict[date][v.text] = {'Info':info.text, 'Artists':names}\r\n\r\n return concert_dict\r\n\r\n\r\n# @midtown\r\n# def search(self, search_func):\r\n# self.artists = {\r\n# ' '.join(each.text.split())\r\n# for each in self.soup.findAll(class_=search_func)}\r\n\r\n# def __repr__(self):\r\n# return f\"ConcertManager({self.url})\"\r\n\r\n# def __str__(self):\r\n# return f\"ConcertManager({self.url})\"\r\n\r\n# def midtown(f):\r\n\r\n# def wrapper(*args, **kwargs):\r\n# search = re.compile('c-lineup__caption-text js-view-details'\r\n# ' js-lineup__caption-text ')\r\n\r\n# return f(search)\r\n\r\n# return wrapper\r\n\r\n# def athens(func):\r\n\r\n# def wrapper(self):\r\n# search = re.compile(\"\")\r\n\r\n# def str_func(soup_tag):\r\n# return ' '.join(soup_tag.text.split())\r\n\r\n# return func(self, str_func, search)\r\n\r\n# return wrapper\r\n\r\nclass PlaylistManager(Manager):\r\n \"\"\"Judge, Sorter\r\n \"\"\"\r\n\r\n username = os.environ['SPOTIPY_USERNAME']\r\n client_id = os.environ['SPOTIPY_CLIENT_ID']\r\n client_secret = os.environ['SPOTIPY_CLIENT_SECRET']\r\n redirect_uri = os.environ['SPOTIPY_REDIRECT_URI']\r\n # scope = os.environ['SPOTIPY_SCOPE']\r\n scope = 'playlist-read-private playlist-modify-private'\r\n\r\n def __init__(self, artists=None, **kwargs):\r\n\r\n self.artists = artists\r\n self.sp = None\r\n self.token = None\r\n self.usr_playlists = None\r\n self.artist_ids = None\r\n self.ply_id = None\r\n\r\n super().__init__(**kwargs)\r\n\r\n# Use cached_token if available\r\n def authenticate_spotify(self):\r\n\r\n self.token = util.prompt_for_user_token(\r\n self.username, self.scope, self.client_id,\r\n self.client_secret, self.redirect_uri)\r\n if self.token is not None:\r\n self.sp = spotipy.Spotify(\r\n auth=self.token, requests_session=self.session)\r\n return self\r\n else:\r\n raise(AuthorizationError(self.token))\r\n\r\n def get_playlists(self):\r\n\r\n self.usr_playlists = self.sp.current_user_playlists(limit=50)\r\n return self\r\n\r\n def get_playlist_id(self, name=None):\r\n\r\n for each in self.usr_playlists['items']:\r\n if each['name'] == name:\r\n self.ply_id = self.get_uri(each[\"uri\"])\r\n return self\r\n\r\n def get_artist_ids(self):\r\n\r\n self.artist_ids = [\r\n self.find_artist_info('artist', each)['artists']['items'][0]['uri']\r\n for each in self.artists]\r\n return self\r\n\r\n# spotipy.client.SpotifyException: http status: 400, code:-1 - https://api.spotify.com/v1/search?q=artist%3AThe+Revivalists&limit=10&offset=0&type=type\r\n def find_artist_info(self, category, item):\r\n\r\n kwargs = {'q': f'{category}: {item}', 'type': category}\r\n return self.catch(self.sp.search, kwargs)\r\n\r\n def check_for_duplicate(self):\r\n pass\r\n\r\n def get_top_tracks(self, num_songs=10):\r\n for each in self.artist_ids:\r\n results = self.sp.artist_top_tracks(each)\r\n uris = {\r\n self.get_uri(each['uri'])\r\n for each in results['tracks'][:num_songs]}\r\n return uris\r\n\r\n # @top_tracks\r\n def add_tracks(self, uris):\r\n\r\n self.sp.user_playlist_add_tracks(self.username, self.ply_id, uris)\r\n\r\n def get_album(self):\r\n pass\r\n\r\n def clear_playlist(self, sp, user, playlist_id=None):\r\n playlist_tracks = sp.user_playlist_tracks(user, playlist_id)\r\n sp.user_playlist_remove_all_occurrences_of_tracks(\r\n user, playlist_id, playlist_tracks, snapshot_id=None)\r\n\r\n def catch(self, func, kwargs, handle=None):\r\n try:\r\n return func(**kwargs)\r\n except Exception as e:\r\n return handle(e)\r\n\r\n def get_uri(self, string):\r\n str_list = string.split(':')\r\n return str_list[-1]\r\n\r\n\r\n# def main():\r\n# print('Test')\r\n# # band_link = 'https://www.musicmidtown.com/lineup/interactive/'\r\n# # new_concerts = ConcertManager(url=band_link).get_concert_html()\r\n# # new_concerts.get_concert_soup().search()\r\n\r\n# # ply_manager = PlaylistManager(new_concerts)\r\n# # pdb.set_trace()\r\n# # ply_manager.authenticate_spotify()\r\n# # ply_manager.get_playlists()\r\n# # ply_manager.get_playlist_id(\"Music Midtown 2018\")\r\n# # ply_manager.get_artist_ids()\r\n# # ply_manager.add_top_five_songs()\r\n\r\n\r\n# if __name__ == '__main__':\r\n# main()\r\n","sub_path":"PlaylistBuilder.py","file_name":"PlaylistBuilder.py","file_ext":"py","file_size_in_byte":8262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"163371503","text":"__author__ = 'zaxlct'\n__date__ = '2017/4/2 下午5:40'\n\nfrom .models import UserFavorite, UserMessage, UserQinziyou, UserZutuanyou\nfrom .models import UserHotel,UserSpot,UserSchedule\n\nimport xadmin\n\n\n# 用户收藏\nclass UserFavoriteAdmin:\n list_display = ['user', 'data_tag', 'fav_type', 'add_time']\n search_fields = ['user', 'fav_id', 'fav_type']\n list_filter = ['user', 'fav_id', 'fav_type', 'add_time']\n\n\n\n\n# 用户消息\nclass UserMessageAdmin:\n list_display = ['user', 'message', 'has_read', 'add_time']\n search_fields = ['user', 'message', 'has_read']\n # 这里的 user 不是 ForeignKey ,具体请看 models.py\n list_filter = ['user', 'message', 'has_read', 'add_time']\n\n\n\nclass UserHotelAdmin:\n list_display = ['user', 'hotel','add_time']\n search_fields = ['user', 'hotel',]\n list_filter = ['user', 'hotel', 'add_time']\n\n\nclass UserSpotAdmin:\n list_display = ['user', 'spot', 'add_time']\n search_fields = ['user', 'spot']\n list_filter = ['user', 'add_time']\n\n\nclass UserScheduleAdmin:\n list_display = ['user', 'schedule', 'add_time']\n search_fields = ['user', 'schedule']\n list_filter = ['user', 'schedule', 'add_time']\n\nclass UserQinziyouAdmin:\n list_display = ['user', 'qinziyou', 'add_time']\n search_fields = ['user', 'qinziyou']\n list_filter = ['user', 'qinziyou', 'add_time']\n\nclass UserZutuanyouAdmin:\n list_display = ['user', 'zutuanyou', 'add_time']\n search_fields = ['user', 'zutuanyou']\n list_filter = ['user', 'zutuanyou', 'add_time']\n\nxadmin.site.register(UserFavorite, UserFavoriteAdmin)\nxadmin.site.register(UserMessage, UserMessageAdmin)\n\n\nxadmin.site.register(UserSchedule, UserScheduleAdmin)\nxadmin.site.register(UserSpot, UserSpotAdmin)\nxadmin.site.register(UserHotel, UserHotelAdmin)\n\nxadmin.site.register(UserQinziyou, UserQinziyouAdmin)\nxadmin.site.register(UserZutuanyou, UserZutuanyouAdmin)","sub_path":"apps/operation/adminx.py","file_name":"adminx.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"134442942","text":"# Global imports\nimport random\n\n# Local imports\nfrom gameLogger import log\nfrom cellClass import cell\nfrom chunkClass import chunk\nfrom areaClass import area\n\n# At the moment the world consists of:\n# 25 | Areas\n# 2,875 | Chunks\n# 1,207,500 | Tiles\n\nclass world():\n\tdef __init__(self, width = 5, height = 5,cityNames=[\"cityNameHere\"]):\n\t\tself.seed = random.random()\n\t\tself.width = width\n\t\tself.height = height\n\t\tself.wMap = []\n\t\tself.indicator = (0,0)\n\n\t\tfor x in range(0,width):\n\t\t\tcolumn = []\n\t\t\tfor y in range(0,height):\n\t\t\t\tcolumn.append(area(23,5,\" \",cityNames))\n\t\t\tself.wMap.append(column)\n\t\tlog(\"Initiated the world.\")\n\n\tdef update(self,player):\n\t\tself.indicator = (player.wx, player.wy)\n\t\tself.wMap[player.wx][player.wy].update(player)\n\n\n\t# Future update...\n\tdef getArea(self,player):\n\t\trandom.seed(self.seed)\n\n\tdef draw(self,window):\n\t\txi = 0\n\t\tfor x in self.wMap:\n\t\t\tyi = 0\n\t\t\tfor y in x:\n\t\t\t\twindow.addstr(yi + 1, xi + 1, y.icon)\n\t\t\t\tyi += 1\n\t\t\txi += 1\n\t\twindow.addstr(self.indicator[1] + 1, self.indicator[0] + 1, \"@\")","sub_path":"worldClass.py","file_name":"worldClass.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"133139557","text":"#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\n# Copyright 2019 Eddie Antonio Santos <easantos@ualberta.ca>\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 gzip\nimport re\nimport shutil\nimport subprocess\nfrom collections import defaultdict\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import (Callable, Dict, FrozenSet, Iterable, Iterator, List, Set,\n Tuple, Union, Optional)\n\nfrom .data import Arc, StateID\nfrom .parse import FSTParse, parse_text\nfrom .symbol import Epsilon, Grapheme, MultiCharacterSymbol, Symbol\n\n# Type aliases\nPathLike = Union[str, Path] # similar to Python 3.6's os.PathLike\nRawTransduction = Tuple[Symbol, ...]\n# Gets a Symbol from an arc. func(arc: Arc) -> Symbol\nSymbolFromArc = Callable[[Arc], Symbol]\n# An analysis is a tuple of strings.\nAnalyses = Iterable[Tuple[str, ...]]\n# An Hfstol analysis is always a string, the concatenated version of <Analyses>\nHfstolAnalyses = Tuple[str, ...]\n\n\nclass OutOfAlphabetError(Exception):\n \"\"\"\n Raised when an input string contains a character outside of the input\n alphabet.\n \"\"\"\n\n\nclass FstType(Enum):\n FOMA = 0\n HFSTOL = 1\n\n\nclass FST:\n \"\"\"\n A finite-state transducer that can convert between one string and a set of\n output strings.\n \"\"\"\n\n def __init__(self, parse: Optional[FSTParse] = None, hfstol_file_path: Optional[PathLike] = None,\n hfstol_exe_path: Optional[PathLike] = None) -> None:\n\n if parse is not None:\n self.initial_state = min(parse.states)\n self.accepting_states = frozenset(parse.accepting_states)\n\n self.str2symbol = {\n str(sym): sym for sym in parse.sigma.values()\n if sym.is_graphical_symbol\n }\n\n # Prepare a regular expression to symbolify all input.\n # Ensure the longest symbols are first, so that they are match first\n # by the regular expresion.\n symbols = sorted(self.str2symbol.keys(), key=len, reverse=True)\n self.symbol_pattern = re.compile(\n '|'.join(re.escape(entry) for entry in symbols)\n )\n\n self.arcs_from = defaultdict(set) # type: Dict[StateID, Set[Arc]]\n for arc in parse.arcs:\n self.arcs_from[arc.state].add(arc)\n self._fst_type = FstType.FOMA\n else: # hfstol_file_path is not none\n self._hfstol_file_path = hfstol_file_path\n self._hfstol_exe_path = hfstol_exe_path\n self._fst_type = FstType.HFSTOL\n\n def analyze(self, surface_form: str) -> Union[Analyses, HfstolAnalyses]:\n \"\"\"\n Given a surface form or a collection of surface forms, this yields all possible analyses in the FST.\n Note if .hfstol file is used, analysis will be concatenatd. eg. 'eat+V' instead of ('eat', '+V')\n \"\"\"\n if self._fst_type is FstType.FOMA:\n try:\n symbols = list(self.to_symbols(surface_form))\n except OutOfAlphabetError:\n return\n analyses = self._transduce(symbols, get_input_label=lambda arc: arc.lower,\n get_output_label=lambda arc: arc.upper)\n for analysis in analyses:\n yield tuple(self._format_transduction(analysis))\n else: # FstType.HFSTOL\n for analysis in tuple(self._call_hfstol([surface_form]))[0]:\n yield analysis\n\n def _call_hfstol(self, inputs: Iterable[str]) -> Iterable[HfstolAnalyses]:\n \"\"\"\n call hfstol, parse the result and yield from the results\n \"\"\"\n\n # hfst-optimized-lookup expects each analysis on a separate line:\n lines = \"\\n\".join(inputs).encode(\"UTF-8\")\n\n status = subprocess.run(\n [\n str(self._hfstol_exe_path),\n \"--quiet\",\n \"--pipe-mode\",\n str(self._hfstol_file_path),\n ],\n input=lines,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=False,\n )\n\n old_input = None\n res_buffer = [] # type: List[str]\n for line in status.stdout.decode(\"UTF-8\").splitlines():\n # Remove extraneous whitespace.\n line = line.strip()\n # Skip empty lines.\n if not line:\n continue\n\n # Each line will be in this form:\n # <original_input>\\t<res>\n # e.g. in the case of analyzer file\n # nôhkominân nôhkom+N+A+D+Px1Pl+Sg\n # e.g. in the case of generator file\n # nôhkom+N+A+D+Px1Pl+Sg nôhkominân\n # If the hfstol can't compute, the transduction will have +?:\n # e.g.,\n # sadijfijfe\tsadijfijfe\t+?\n original_input, res, *rest = line.split(\"\\t\")\n\n if old_input is not None and original_input != old_input:\n yield tuple(res_buffer)\n res_buffer = []\n if '+?' not in rest and '+?' not in res:\n res_buffer.append(res)\n old_input = original_input\n yield tuple(res_buffer)\n\n def analyze_in_bulk(self, surface_forms: Iterable[str]) -> Iterable[Union[Analyses, HfstolAnalyses]]:\n \"\"\"\n Analyze a multiple of word forms at once.\n \"\"\"\n if self._fst_type is FstType.FOMA:\n for surface_form in surface_forms:\n yield self.analyze(surface_form)\n else:\n yield from self._call_hfstol(surface_forms)\n\n def generate(self, analysis: str) -> Iterable[str]:\n \"\"\"\n Given an analysis, this yields all possible surface forms in the FST.\n \"\"\"\n if self._fst_type is FstType.FOMA:\n try:\n symbols = list(self.to_symbols(analysis))\n except OutOfAlphabetError:\n return\n forms = self._transduce(symbols, get_input_label=lambda arc: arc.upper,\n get_output_label=lambda arc: arc.lower)\n for transduction in forms:\n yield ''.join(str(symbol) for symbol in transduction\n if symbol is not Epsilon)\n else:\n for generated in tuple(self._call_hfstol([analysis]))[0]:\n yield generated\n\n def generate_in_bulk(self, analyses: Iterable[str]) -> Iterable[Iterable[str]]:\n \"\"\"\n generate a bunch at once\n \"\"\"\n if self._fst_type is FstType.FOMA:\n for analysis in analyses:\n yield self.generate(analysis)\n else:\n yield from self._call_hfstol(analyses)\n\n def to_symbols(self, surface_form: str) -> Iterable[Symbol]:\n \"\"\"\n Tokenizes a form into symbols.\n \"\"\"\n text = surface_form\n while text:\n match = self.symbol_pattern.match(text)\n if not match:\n raise OutOfAlphabetError(\"Cannot symbolify form: \" + repr(surface_form))\n # Convert to a symbol\n yield self.str2symbol[match.group(0)]\n text = text[match.end():]\n\n @classmethod\n def from_file(cls, fst_file_path: PathLike, labels: str = \"normal\") -> 'FST':\n \"\"\"\n Read the FST as output by FOMA.\n\n `labels` can be one of:\n - \"normal\" (default): surface form is LOWER label: apply up to\n analyze, apply down to generate; use this if you are following the\n conventions of \"Finite State Morphology\" by Beesley & Karttunen.\n - \"invert\": surface form is UPPER label: apply down to analyze, and\n apply up to generate; HFST usually produces FSTs in this style, so\n try to invert FSTs that aren't working using labels=\"normal\".\n - \"hfstol\": specify this if you supply a .hfstol file, let hfst-optimized-look up decide the direction.\n \"\"\"\n\n if 'hfstol' in labels:\n\n hfstol_exe_path = shutil.which(\"hfst-optimized-lookup\")\n if hfstol_exe_path is None:\n raise ImportError(\n \"hfst-optimized-lookup is not installed.\\n\"\n \"Please install the HFST suite on your system \"\n \"before using hfstol.\\n\"\n \"See: https://github.com/hfst/hfst#installation\"\n )\n return FST(hfstol_file_path=fst_file_path, hfstol_exe_path=hfstol_exe_path)\n else: # .fomabin\n\n with gzip.open(str(fst_file_path), 'rt', encoding='UTF-8') as text_file:\n return cls.from_text(text_file.read(), labels=labels)\n\n @classmethod\n def from_text(cls, att_text: str, labels='normal') -> 'FST':\n \"\"\"\n Parse the fomabin in the text format (un-gzip'd).\n \"\"\"\n parse = parse_text(att_text, invert_labels=True if labels == 'invert' else False)\n return FST(parse)\n\n def _transduce(self, symbols: List[Symbol],\n get_input_label: SymbolFromArc, get_output_label: SymbolFromArc):\n yield from Transducer(initial_state=self.initial_state,\n symbols=symbols,\n arcs_from=self.arcs_from,\n accepting_states=self.accepting_states,\n get_input_label=get_input_label, get_output_label=get_output_label)\n\n def _format_transduction(self, transduction: Iterable[Symbol]) -> Iterable[str]:\n \"\"\"\n Formats the transduction by making a few assumptions:\n\n - Adjacent graphemes should be concatenated\n - Multi-character symbols should stand alone (e.g., +Pl)\n - Epsilons are never emitted in the output\n \"\"\"\n\n current_lemma = ''\n for symbol in transduction:\n if symbol is Epsilon:\n # Skip epsilons\n continue\n elif isinstance(symbol, MultiCharacterSymbol):\n # We've seen a previous sequence of graphemes.\n # Output it and reset!\n if current_lemma:\n yield current_lemma\n current_lemma = ''\n yield str(symbol)\n else:\n # This MUST be a grapheme. Concatenated it to the output.\n assert isinstance(symbol, Grapheme)\n current_lemma += str(symbol)\n\n # We may some graphemes remaining. Output them!\n if current_lemma:\n yield current_lemma\n\n\nclass Transducer(Iterable[RawTransduction]):\n \"\"\"\n Does a single transduction\n \"\"\"\n\n def __init__(\n self,\n initial_state: StateID,\n symbols: Iterable[Symbol],\n get_input_label: SymbolFromArc,\n get_output_label: SymbolFromArc,\n accepting_states: FrozenSet[StateID],\n arcs_from: Dict[StateID, Set[Arc]],\n ) -> None:\n self.initial_state = initial_state\n self.symbols = list(symbols)\n self.get_input_label = get_input_label\n self.get_output_label = get_output_label\n self.accepting_states = accepting_states\n self.arcs_from = arcs_from\n\n def __iter__(self) -> Iterator[RawTransduction]:\n yield from self._accept(self.initial_state, [], [{}])\n\n def _accept(\n self,\n state: StateID,\n transduction: List[Symbol],\n flag_stack: List[Dict[str, str]]\n ) -> Iterable[RawTransduction]:\n # TODO: Handle a maximum transduction depth, for cyclic FSTs.\n if state in self.accepting_states:\n if len(self.symbols) > 0:\n return\n yield tuple(transduction)\n\n for arc in self.arcs_from[state]:\n input_label = self.get_input_label(arc)\n\n if input_label is Epsilon:\n # Transduce WITHOUT consuming input\n transduction.append(self.get_output_label(arc))\n yield from self._accept(arc.destination, transduction, flag_stack)\n transduction.pop()\n elif len(self.symbols) > 0 and input_label == self.symbols[0]:\n # Transduce, consuming the symbol as a label\n transduction.append(self.get_output_label(arc))\n consumed = self.symbols.pop(0)\n yield from self._accept(arc.destination, transduction, flag_stack)\n self.symbols.insert(0, consumed)\n transduction.pop()\n elif input_label.is_flag_diacritic:\n # Evaluate flag diacritic\n flag = input_label\n flags = flag_stack[-1]\n if flag.test(flags): # type: ignore\n next_flags = flags.copy()\n flag.apply(next_flags) # type: ignore\n # Transduce WITHOUT consuming input OR emitting output\n # label (output should be the flag again).\n assert input_label == self.get_output_label(arc), (\n 'Arc does not have flags on both labels ' + repr(arc)\n )\n yield from self._accept(arc.destination, transduction,\n flag_stack + [next_flags])\n","sub_path":"fst_lookup/fst.py","file_name":"fst.py","file_ext":"py","file_size_in_byte":13725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"45711523","text":"# -*- coding:utf-8 -*-\n\n# psyco est un module basé sur les techniques de \"compilation à la volée\"\n# et permet ainsi d'accélérer l'exécution des programmes.\ntry:\n import psyco\n psyco.full() \nexcept:\n pass\n\nfrom random import randrange\nfrom time import time\n\nc_s = 0\nc_f = 0\nc_r = 0\n\ndef tirageAleatoire(taille,rang=30):\n \"\"\"retourne un tableau de taille entiers dont les valeurs\n sont tirées aléatoirement dans l'intervalle [0,rang-1]\"\"\"\n res=[0]*taille\n for i in range(taille):\n res[i]=randrange(rang)\n return res\n\n########################### TRI RAPIDE ###########################\n\ndef partition(tableau,g,d):\n \"partition du tableau dans l'intervalle [g,d]\"\n global c_r\n pivot=tableau[g]\n courg=g+1 \n courd=d \n while True:\n while courg<d and tableau[courg]<=pivot:\n c_r += 1\n courg=courg+1\n while tableau[courd]>pivot:\n c_r += 1\n courd=courd-1\n if courg < courd:\n tableau[courg],tableau[courd]=tableau[courd],tableau[courg]\n else:\n tableau[g],tableau[courd]=tableau[courd],tableau[g]\n return courd\n\ndef triRapide(tableau,g,d):\n \"tri du tableau dans l'intervalle [g,d], donc tri de tableau[g:d+1]\"\n if g<d:\n i=randrange(g,d+1)\n tableau[g],tableau[i]=tableau[i],tableau[g]\n m=partition(tableau,g,d)\n triRapide(tableau,g,m-1)\n triRapide(tableau,m+1,d)\n\nprint(\"Un exemple d'execution de triRapide:\"); print\nL=[5,3,4,7,4,1]; print(\"la liste initiale:\", L)\nprint\ntriRapide(L,0,5); print(\"la meme liste, mais triee:\", L)\n\n########################## TRI SELECTION #########################\n\n## 1) Ecrire la fonction TriSelection\n\ndef triSelection(tableau):\n global c_s\n\n for done in range(len(tableau)):\n min = tableau[done]\n for i in range(done, len(tableau)):\n c_s += 1\n if tableau[i] < min:\n min = i\n temp = tableau[done]\n tableau[done] = tableau[min]\n tableau[min] = temp\n return tableau\n\n\n########################## TRI FUSION #########################\n\n## 2) Ecrire la fonction fusion\n\ndef fusion(tab1,tab2):\n \"\"\" retourne le tableau résultant de la fusion\n des deux tableaux triés tab1 et tab2 \"\"\"\n \n res=[]\n # à compléter\n i,j=0,0\n global c_f\n\n while not (i == len(tab1) and j == len(tab2)):\n if i == len(tab1): #liste 1 finie\n res.append(tab2[j])\n j += 1\n elif j == len(tab2):#liste 2 finie\n res.append(tab1[i])\n i += 1\n else:\n c_f += 1\n if tab1[i] <= tab2[j]:\n res.append(tab1[i])\n i += 1\n else:\n res.append(tab2[j])\n j += 1\n return res\n\n\ndef triFusion(tableau,g,d):\n if g<d:\n m=(g+d)//2\n triFusion(tableau,g,m)\n triFusion(tableau,m+1,d)\n tableau[g:d+1]=fusion(tableau[g:m+1],tableau[m+1:d+1])\n\n\n########################## TEST ######################### \n\n## 3) Tester les temps d'exécution des différents tris\n## pour différentes tailles: 10, 100, 1000,\n## et, si on peut: 10 000, 100 000, 1 000 0000\n \ndef test(n):\n monTab=tirageAleatoire(n,n)\n print(\"*\"*20); print(\"taille = \"),; print(n)\n tonTab=monTab[:]\n\n global c_r\n global c_f\n global c_s\n\n c_r = 0\n\n t1=time()\n triRapide(tonTab,0,len(tonTab)-1)\n t2=time()\n print(\"temps du tri rapide: \"); print(t2-t1)\n print(\"nb comparaisons:\", c_r)\n\n c_s = 0\n\n t1=time()\n triSelection(tonTab)\n t2=time()\n print(\"temps du tri selection: \"); print(t2-t1)\n print(\"nb comparaisons:\", c_s)\n\n c_f = 0\n\n t1=time()\n triFusion(tonTab,0,len(tonTab)-1)\n t2=time()\n print(\"temps du tri fusion: \"); print(t2-t1)\n print(\"nb comparaisons:\", c_f)\n\n\nfor el in [10,100,1000,10000,100000,1000000]:\n\n test(el)\n\n\n## 4) Pour chacun des tris, introduire une variable compteur (globale)\n## pour compter le nombre de comparaisons entre paires d'éléments du tableau.\n##\n## Pour chacun des tris, répondre à la question suivante:\n## Quand on multiplie la taille par 10, par combien est multiplié le temps? le nombre de comparaisons?\n\n# selection: n*10 => O(s) = n²/2\n# = (10*n)²/2 = 100n²/2\n# multiplier n par 10 reviens a ralentir = 100 * O(selection)\n\n# fusion : n*10 => O(f) = nlog(n) => (10n)log(10n)\n# = (10n)*(log(n)+log(10))\n# = 10nlog(n) + 10nlog(10)\n# = 10( nlog(n) + nlog(10))\n# multiplier n par 10 reviens a ralentir ~= 10 * O(fusion) + nlog(10)\n\n# pareil pour le rapide : n*10 => O(r) = (n+10)log(n+10)\n# = (10n)*(log(n)+log(10))\n# = 10nlog(n) + 10nlog(10)\n# = 10( nlog(n) + nlog(10))\n# multiplier n par 10 reviens a ralentir ~= 10 * O(rapide) + nlog(10)\n\n\n# le temps augmente autant que le nombre de comparaisons pour le selection\n# mais pas pour le fusion et le rapide qui ont d'autres étapes plus complexes\n# le fusion, le rapide est legerement plus lent que le fusion a cause des\n# iterations pour trouver les pivots.\n\n\n# questions\n# 1) ( n**2 )/2\n\n# 2) (n/2)**2+n => n²/4 +n => n * ( n/4 +1)\n\n","sub_path":"TP_Algo/tp3Complexite.py","file_name":"tp3Complexite.py","file_ext":"py","file_size_in_byte":5185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"310631436","text":"\"\"\"Script to create a txt description of the collection.\n\"\"\"\n\nfrom pathlib import Path\n\nfrom .book import Book, Serie\nfrom .standard import book_size\n\ntxt_dir = Path(\"zztxt\")\n\n\ndef book_to_txt(book, level):\n \"\"\"Convert a single book to text paragraph\n\n Args:\n book (Book): book object\n level (int): sublevel\n\n Returns:\n (str)\n \"\"\"\n print(\"\\t\", book)\n\n # create book name\n if len(book.number) > 0:\n name = book.number\n else:\n name = \"\"\n\n if len(book.title) > 0:\n if len(name) > 0:\n name = f\"{name} - {book.title}\"\n else:\n name = book.title\n\n # find book size in Mo\n bs = book_size(book)\n\n return \"\\t\" * level + f\"{name} ({book.language})({bs:.1f} Mo)\"\n\n\ndef serie_to_txt(name, serie, level):\n \"\"\"Convert a serie into text paragraph\n\n Args:\n name (str): name of book\n serie (Serie): set of book\n level (int): sublevel\n\n Returns:\n (str)\n \"\"\"\n txt = [\"\\t\" * level + f\"{name}:\"]\n\n for name in sorted(serie.subseries.keys()):\n txt.append(serie_to_txt(name, serie.subseries[name], level + 1))\n\n books = [(str(book), book) for book in serie.books]\n for name, book in sorted(books):\n txt.append(book_to_txt(book, level + 1))\n\n return \"\\n\".join(txt)\n\n\ndef main():\n ##################################################\n #\n print(\"create directories\")\n #\n ##################################################\n if not txt_dir.exists():\n txt_dir.mkdir()\n\n ##################################################\n #\n print(\"write txt\")\n #\n ##################################################\n for dirname in \"0abcdefghijklmnopqrstuvwxyz\":\n dir_pth = Path(dirname)\n\n # sort by serie\n top = Serie()\n\n for pth in dir_pth.glob(\"*.cbz\"):\n book = Book(pth)\n if len(book.serie) == 0:\n # single issue\n top.subseries[book.title] = book\n else:\n # serie, may be recursive with sub series\n gr = book.serie.split(\" - \")\n ser = top\n for name in gr:\n try:\n ser = ser.subseries[name]\n except KeyError:\n ser.subseries[name] = Serie()\n ser = ser.subseries[name]\n\n ser.books.append(book)\n\n # write book list\n body = [\"<DIRECTORY>\"]\n\n for name in sorted(top.subseries.keys()):\n print(name)\n serie = top.subseries[name]\n if isinstance(serie, Book):\n frag = book_to_txt(serie, 0)\n else:\n frag = serie_to_txt(name, serie, 0)\n body.append(frag)\n\n body.append(\"</DIRECTORY>\")\n\n # create txt file\n txt_pth = txt_dir / f\"dir_{dirname}.txt\"\n with open(str(txt_pth), 'w') as f:\n f.write(\"\\n\".join(body))\n","sub_path":"src/fman/cb/txt_translator.py","file_name":"txt_translator.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"459950707","text":"### Neural Network \r\n### by Yuliya Akchurina \r\n#LSL\r\n\"\"\"This script takes the png images stored in 3 different folders with_mask, without_mask, incorrect_mask \r\nas an input to the Neural Network.\r\nConvolutional Neural Network is commented out to prevent overloading the system by running both NN and CNN.\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nimport cv2\r\nimport random\r\nimport tensorflow as tf\r\nfrom tensorflow.keras.models import Sequential\r\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Flatten\r\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import classification_report\r\n\r\nfrom imblearn.over_sampling import RandomOverSampler \r\n\r\n###Path to image folders split by label\r\nimg_data_dir = './balanced images'\r\ndata_with_mask = './images/mask'\r\ndata_without_mask = './images/no_mask'\r\ndata_incorrect_mask = './images/incorrect_mask'\r\n\r\ndata_path = {'mask':data_with_mask, 'no_mask':data_without_mask, 'incorrect_mask':data_incorrect_mask}\r\n\r\nclass_names = ['mask', 'no_mask', 'incorrect_mask']\r\n\r\n'''\r\n###show one image of the dataset \r\nfor className in class_names: \r\n path = os.path.join(img_data_dir,className) # create path to the images\r\n for img in os.listdir(path): # iterate over each image\r\n img_array = cv2.imread(os.path.join(path,img)) # in color \r\n plt.imshow(img_array) # graph it in color \r\n plt.show() \r\n\r\n break # to show only one image \r\n break \r\n\r\n\r\n#print(img_array)\r\n#print(img_array.shape)\r\n'''\r\n###resize images to be the same size \r\nimg_height = 256\r\nimg_width = 256\r\n'''\r\n### show image\r\nnew_array = cv2.resize(img_array, (img_height, img_width))\r\nplt.imshow(new_array, cmap='gray')\r\nplt.show()\r\n'''\r\ntraining_data = []\r\n\r\n### Create training dataset\r\ndef create_training_data():\r\n for className in class_names: \r\n\r\n path = os.path.join(img_data_dir,className) \r\n class_num = class_names.index(className) # get the classification (0,1,2). 0=with_mask 1=without_mask, 2=incorrect_mask\r\n \r\n for img in os.listdir(path):\r\n try: \r\n img_array = cv2.imread(os.path.join(path,img)) #keep colors\r\n new_array = cv2.resize(img_array, (img_height, img_width)) # resize \r\n training_data.append([new_array, class_num]) # add to training data\r\n except Exception as e: \r\n pass\r\n\r\ncreate_training_data()\r\n#print(f'Training data size {len(training_data)}')\r\n\r\nrandom.shuffle(training_data) # shuffle dataset\r\n\r\n#Create model\r\nX = [] #features\r\ny = [] #labels\r\n\r\nfor features,label in training_data:\r\n X.append(features)\r\n y.append(label)\r\n\r\n#print(X[0].reshape(-1, img_height, img_width, 3)) #color\r\nX = np.array(X).reshape(-1, img_height, img_width, 3) # 3 for color\r\ny = np.array(y) \r\n\r\n##Normalize by dividing pixel values by 255 and convert dtype into float32\r\ndef normalize_img(image):\r\n return tf.cast(image, tf.float32)/255.0\r\n\r\nX_norm = normalize_img(X)\r\n\r\nX_norm=np.array(X_norm)\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X_norm, y, test_size=0.2, random_state=1)\r\n### Neural Network \r\nbatch=64\r\nepochs=10\r\nvalidation_split=0.2\r\n\r\n\r\nmodel_NN = tf.keras.models.Sequential([\r\n tf.keras.layers.Flatten(input_shape=(img_height, img_width,3)),\r\n tf.keras.layers.Dense(64, activation = 'relu'),\r\n tf.keras.layers.Dense(128, activation = 'softmax'),\r\n tf.keras.layers.Dense(3)])\r\n\r\nmodel_NN.compile(optimizer = 'adam', loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits = True), metrics = ['accuracy'])\r\nhistory = model_NN.fit(X_train, y_train, batch_size=batch, epochs=epochs, validation_data=(X_test,y_test))\r\n\r\n### obtain results\r\ntrain_loss, train_accuracy = model_NN.evaluate(X_train, y_train, verbose = 2)\r\nprint(f'Training Accuracy {train_accuracy}')\r\n\r\n\r\n\r\n\r\npreds= model_NN.predict(X_test)\r\ny_pred = []\r\nfor p in preds:\r\n y_pred.append(np.argmax(p))\r\nprint(y_pred[0])\r\nprint('\\n')\r\nprint(classification_report(y_true=y_test, y_pred=y_pred,target_names=class_names))\r\n\r\nacc = history.history['accuracy']\r\nval_acc = history.history['val_accuracy']\r\n\r\nloss = history.history['loss']\r\nval_loss = history.history['val_loss']\r\n\r\nepochs_range = range(epochs)\r\n\r\nplt.figure(figsize=(8, 8))\r\nplt.subplot(2, 1, 1)\r\nplt.plot(epochs_range, acc, label='Training Accuracy')\r\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\r\nplt.legend(loc='lower right')\r\nplt.title('Training and Validation Accuracy')\r\n\r\nplt.subplot(2, 1, 2)\r\nplt.plot(epochs_range, loss, label='Training Loss')\r\nplt.plot(epochs_range, val_loss, label='Validation Loss')\r\nplt.legend(loc='upper right')\r\nplt.title('Training and Validation Loss')\r\nplt.show()\r\n\r\n'''\r\n### Commented out CNN to prevent running. Takes a very long time to run. \r\n### CNN build model \r\nbatch=32\r\nepochs=3\r\nvalidation_split=0.3\r\n\r\nmodel = Sequential()\r\nmodel.add(Conv2D(256, (3, 3), input_shape=X.shape[1:]))\r\nmodel.add(Activation('relu'))\r\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\r\nmodel.add(Conv2D(256, (3, 3)))\r\nmodel.add(Activation('relu'))\r\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\r\nmodel.add(Flatten()) \r\nmodel.add(Dense(64))\r\nmodel.add(Dense(3))\r\nmodel.add(Activation('softmax'))\r\n\r\n#model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\r\nmodel.compile(loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer='adam', metrics=['accuracy'])\r\nmodel.fit(X_norm, y, batch_size=batch, epochs=epochs, validation_split=validation_split) \r\n\r\n'''\r\n","sub_path":"NN balanced.py","file_name":"NN balanced.py","file_ext":"py","file_size_in_byte":5630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"503931577","text":"entree_facile = ([9, 0, 6, 4, 0, 5, 0, 8, 0],\n [0, 7, 2, 0, 0, 0, 0, 4, 1],\n [3, 4, 0, 0, 0, 2, 0, 0, 0],\n [0, 0, 4, 1, 6, 0, 3, 0, 0],\n [7, 0, 1, 0, 4, 0, 9, 0, 2],\n [0, 0, 5, 0, 3, 7, 4, 0, 0],\n [0, 0, 0, 7, 0, 0, 0, 2, 9],\n [8, 2, 0, 0, 0, 0, 1, 7, 0],\n [0, 5, 0, 9, 0, 6, 8, 0, 4])\n\nentree_moyen = ([0, 0, 0, 0, 0, 0, 9, 1, 8],\n [9, 8, 4, 0, 7, 0, 0, 0, 0],\n [0, 2, 0, 3, 9, 0, 0, 0, 0],\n [3, 0, 0, 0, 8, 7, 0, 9, 6],\n [6, 0, 5, 0, 0, 0, 4, 0, 0],\n [8, 0, 0, 0, 3, 6, 0, 5, 1],\n [0, 1, 0, 2, 6, 0, 0, 0, 0],\n [4, 3, 8, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 1, 4, 9],)\n\nentree_expert = ([7, 1, 0, 0, 0, 0, 0, 3, 0],\n [0, 0, 0, 8, 0, 9, 0, 0, 1],\n [0, 0, 0, 0, 0, 0, 7, 0, 5],\n [0, 0, 4, 0, 8, 3, 0, 0, 0],\n [0, 0, 6, 0, 0, 0, 0, 1, 2],\n [0, 0, 9, 0, 5, 2, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 4, 0, 6],\n [0, 0, 0, 2, 0, 5, 0, 0, 8],\n [3, 2, 0, 0, 0, 0, 0, 5, 0])\n\nimport copy\nimport argparse\nimport pickle\nfrom collections import Counter\nimport pandas as pd\n\nclass Carre():\n @staticmethod\n def Localise(i,j):\n adresse = {}\n if i < 3:\n adresse = {0, 1 ,2 }\n elif i < 6:\n adresse = {3, 4 ,5 } \n else:\n adresse = {6, 7 ,8 } \n if j < 3 :\n return adresse.intersection({0, 3, 6})\n if j < 6 :\n return adresse.intersection({1, 4, 7})\n return adresse.intersection({2, 5, 8}) \n\n\nclass Grille:\n def __init__(self, pgrille):\n self.grille = list(pgrille) \n self.etat = 0\n\n def get_ligne(self, nb):\n return self.grille[nb]\n\n def get_colonne(self, nb):\n col =[] \n for i in range(9): \n col.append(self.grille[i][nb]) \n return col \n\n def get_carre(self, nb):\n col =[] \n \n if nb in [0,1,2] :\n for i in range(3): \n col += self.get_ligne(i)[0+(3*nb) :3 + (3*nb) ]\n if nb in [3,4,5] :\n for i in range(3,6): \n col += self.get_ligne(i)[0+(3*(nb-3)) :3 + (3*(nb-3))] \n if nb in [6,7,8] :\n for i in range(6,9): \n col += self.get_ligne(i)[0+(3*(nb-6)) :3 + (3*(nb-6))] \n return col\n\n def get_set_ligne(self, nb):\n return(set(self.get_ligne(nb)) - {0}) \n\n def get_set_colonne(self, nb):\n return(set(self.get_colonne(nb))- {0} ) \n\n def get_set_carre(self, nb):\n return(set(self.get_carre(nb)) - {0} )\n\n def affiche(self):\n for i in range(9):\n if i % 3 == 0:\n print(' ') \n for j in range(9) :\n if j %3 == 0:\n print(' ',end ='') \n print(self.grille[i][j],end='')\n print(' ') \n\n \nfrom collections.abc import MutableSequence\n\nclass Grilles(MutableSequence):\n def __init__(self, pgrille):\n self.grille = [pgrille] \n super().__init__()\n\n def __getitem__(self, i):\n return self.grille[i]\n\n def __len__(self):\n return len(self.grille)\n\n def __setitem__(self,i, valeur):\n self.grille[i] = valeur\n\n def __delitem__(self, index):\n del self.grille[index]\n\n def insert(self, index, value):\n self.grille.insert(index, value)\n\n\nGrilles.register(list)\n\n\nclass Resolve:\n def __init__(self, histo, etat):\n self.grille_depart = copy.deepcopy(histo[etat])\n self.univers_possible ={}\n\n def coup_simple(self):\n '''on balaye la ligne et la colonne puis le cube'''\n cpcoup = 0\n #\n for i in range(9):\n for j in range(9):\n if self.grille_depart.grille[i][j] == 0: \n possible = set(range(1,10))\n possible = possible - self.grille_depart.get_set_ligne(i)\n possible = possible - set(self.grille_depart.get_set_colonne(j))\n ab = Carre.Localise(i,j)\n cube= ab.pop()\n possible = possible - set(self.grille_depart.get_set_carre(cube))\n \n self.univers_possible[(cube,i,j)] = possible \n if len(possible) == 1:\n nb = possible.pop()\n print(f\"Ligne : {i+1} Colonne : {j+1}: mettre : {nb}\")\n cpcoup +=1\n self.majlignecolonne(i, j,nb, cube )\n print('coup simple:', cpcoup) \n return(cpcoup)\n\n def _helper_search(self, cube, nb):\n for item, valeur in self.univers_possible.items():\n if item[0] == cube :\n if nb in valeur:\n return (item[1], item[2]) \n return None \n \n def _helper_reduction(self, cube,compteur):\n cube = cube\n lst_ajouer = []\n for nb, quant in compteur.items():\n if quant == 1 :\n l,c =self. _helper_search(cube, nb) \n lst_ajouer.append((cube, l, c, nb) )\n return lst_ajouer \n\n def combo(self):\n a = b = 0\n a =self.coup_simple()\n if a == 0:\n b = self.reduction_carre()\n if a == 0 and b == 0: \n return False\n return True\n \n def reduction_carre(self):\n ''' on travaille sur le cube'''\n reduc = {}\n listajouer =[]\n for i, messet in self.univers_possible.items():\n cle = i[0]\n if cle in reduc:\n reduc[cle].append(list(messet))\n else:\n reduc[cle] = [list(messet)]\n for i in reduc:\n if len(reduc[i]) > 0 :\n compt = Counter()\n for lst in reduc[i]:\n compt.update(lst)\n a = self._helper_reduction(i,compt)\n if len(a) > 0:\n listajouer.extend([*a])\n \n for item in listajouer:\n print(f\"Ligne : {item[1]+1} Colonne : {item[2]+1}: mettre : {item[3]}\")\n self.majlignecolonne(item[1],item[2], item[3], item[0])\n print('coup par reduction:',len(listajouer)) \n print('-------------------------------------------------')\n return(len(listajouer)) \n\n def majlignecolonne(self, i, j , nb, cube ):\n self.grille_depart.grille[i][j] = nb\n \n def etat_suivant(self):\n return self.grille_depart\n\n### --- Main -------###\n### chargement du fichier pickle des grilles \n\nlist_totale =[]\ntry:\n with open('mypicklefile', 'rb') as pers:\n list_totale = pickle.load(pers)\n#print(list_totale)\nexcept:\n pass\n \n### gestion des options \n \nparser = argparse.ArgumentParser(description='Resolveur de sudoku en mode algorithmique')\nparser.add_argument('--grille','-g', metavar='facile|moyen|expert',choices=('facile', 'moyen', 'expert'),\n default= 'facile',\n help='le type de grille à résoudre: facile - moyen - expert')\n\nargs = parser.parse_args()\n#print(args) \nmagrille = vars()['entree_' + args.grille] \n\nmagrille = list_totale[-1][1]\n### hack pour charger un etat specifique\n\nmagrille = ([[8, 6, 0, 9, 5, 7, 3, 2, 1], [1, 9, 5, 4, 2, 3, 7, 6, 8], [7, 3, 4, 6, 1, 0, 5, 9, 0],\n [4, 7, 1, 2, 3, 8, 0, 5, 6], [9, 8, 6, 1, 4, 5, 2, 3, 7], [3, 5, 2, 7, 6, 9, 1, 8, 4],\n [5, 1, 8, 3, 9, 4, 6, 7, 2], [0, 2, 7, 5, 0, 1, 8, 4, 3], [6, 4, 3, 8, 7, 2, 9, 1, 5]\n])\n### modifications pour lire une grille etat initial\npath = \"../../../\"\ndata = pd.read_csv(path+\"sudoku.csv\")\ntry:\n data_pd = pd.DataFrame({\"quizzes\":data[\"quizzes\"],\"solutions\":data[\"solutions\"]})\nexcept:\n pass\n\n\ngrille = Grille(magrille)\nhistogrille = Grilles(grille)\nhistogrille[0].affiche()\nencours = True\ncp = 0\nwhile encours ==True:\n cp +=1\n moteur = Resolve(histogrille,-1)\n encours = moteur.combo() \n histogrille.append(moteur.etat_suivant())\n histogrille[-1].affiche()\n print(histogrille[-1].grille)\nprint(f\"resolu en {cp} cycles\")\n","sub_path":"Python/sudoku_dl1.py","file_name":"sudoku_dl1.py","file_ext":"py","file_size_in_byte":8332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"323594545","text":"# -*- coding: utf-8 -*-\n\nfrom random import Random\nimport scrapy\nfrom urllib import parse as urlparse\nfrom scrapy.http import Request\nfrom ScrapyDemo.items import (\n AntdAsideNavItem, AntdComponentDetailItem, CustomItemLoader)\n\n\nrandom_ins = Random()\n\n\nclass AntDesignAsideSpider(scrapy.Spider):\n name = 'ant_design_aside'\n allowed_domains = ['ant.design']\n start_urls = ['https://ant.design/docs/react/introduce-cn']\n\n def parse(self, response):\n post_nodes = response.css('#Components\\$Menu .ant-menu-item-group')\n\n for post_node in post_nodes:\n primary_title = post_node.css(\n '.ant-menu-item-group-title::text').extract_first('')\n secondary_nodes = post_node.css(\n '.ant-menu-item-group-list>.ant-menu-item')\n for secondary_node in secondary_nodes:\n secondary_key = secondary_node.css(\n 'a::attr(href)').extract_first('')\n secondary_name = secondary_node.css(\n 'a>span:first-child::text').extract_first('')\n secondary_title = secondary_node.css(\n 'span.chinese::text').extract_first('')\n yield Request(\n url=urlparse.urljoin(response.url, secondary_key),\n meta={\n 'primary_title': primary_title,\n 'secondary_title': secondary_title,\n 'secondary_name': secondary_name,\n 'secondary_key': secondary_key\n },\n callback=self.parse_block\n )\n\n def parse_block(self, response):\n primary_title = response.meta.get('primary_title', '')\n secondary_title = response.meta.get('secondary_title', '')\n secondary_name = response.meta.get('secondary_name', '')\n secondary_key = response.meta.get('secondary_key', '')\n\n post_nodes = response.css('#demo-toc>li')\n\n for post_node in post_nodes:\n # aside_nav_item = AntdAsideNavItem()\n # item_loader = CustomItemLoader(\n # item=aside_nav_item,\n # selector=post_node\n # )\n # item_loader.add_value('primary_title', primary_title)\n # item_loader.add_value('secondary_title', secondary_title)\n # item_loader.add_value('secondary_name', secondary_name)\n # item_loader.add_value('secondary_key', secondary_key)\n # aside_nav_item = item_loader.load_item()\n # yield aside_nav_item\n\n detail_id = post_node.css('a::attr(href)').extract_first('')\n name = post_node.css('a::text').extract_first('')\n if not detail_id:\n return\n css_str = detail_id + '>.code-box-meta>.code-box-description'\n detail_block = response.css(css_str)\n\n component_detail_item = AntdComponentDetailItem()\n component_loader = CustomItemLoader(\n item=component_detail_item,\n selector=post_node\n )\n component_loader.add_value('name', name)\n component_loader.add_value(\n 'easy_to_use', random_ins.randint(1, 99))\n component_loader.add_value('key', detail_id.replace('#', '', 1))\n component_loader.add_value('category_name', secondary_name)\n least_title = detail_block.css(' div *::text').extract()\n component_loader.add_value(\n 'desc', ''.join([str(i) for i in least_title]))\n component_detail_item = component_loader.load_item()\n yield component_detail_item\n","sub_path":"ScrapyDemo/spiders/ant_design_aside.py","file_name":"ant_design_aside.py","file_ext":"py","file_size_in_byte":3666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"31298727","text":"#coding=utf-8\nfrom frame.PageOfPublic import PageOfPublic\n\nclass PageOfStudent(PageOfPublic):\n\n def inputSubjects(self,subjects):\n id=\"\"\n tmps = subjects.split(\",\")\n\n for tmp in tmps:\n if tmp==\"少儿创意画\":\n id=\"paint001\"\n elif tmp==\"线描写生\":\n id = \"paint002\"\n elif tmp==\"素描\":\n id = \"paint003\"\n elif tmp==\"硬笔书法\":\n id = \"calligraphy001\"\n elif tmp==\"毛笔书法\":\n id = \"calligraphy002\"\n elif tmp==\"中国舞\":\n id = \"dance001\"\n elif tmp==\"拉丁舞\":\n id = \"dance002\"\n elif tmp==\"街舞\":\n id = \"dance003\"\n elif tmp==\"跆拳道\":\n id = \"sport001\"\n elif tmp==\"午托\":\n id = \"care001\"\n elif tmp==\"晚托\":\n id=\"care002\"\n self.click(id,tmp+\"的复选框\")\n\n\n\n ####新建学生####\n def createStudent(self):\n if self.lastStepIsPass():\n try:\n\n #得到参数\n name = self.getPar('姓名')\n nick = self.getPar('昵称')\n sex = self.getPar('性别')\n birthday = self.getPar(\"生日\")\n guardian = self.getPar('家长')\n subjects = self.getPar('科目')\n mobile = self.getPar('手机')\n rank = self.getPar(\"客户等级\")\n\n\n\n\n self.click('create', '新建按钮')\n\n if(None!=name):\n self.input('fullname','姓名输入框',name)\n\n if( None!=nick ):\n self.input(\"nickname\",\"昵称输入框\",nick)\n\n if(None!=sex):\n if( \"男\"==sex ):\n xpath=\"//input[@name='sex' and @value='1']\"\n else:\n xpath = \"//input[@name='sex' and @value='0']\"\n self.click(xpath,\"性别选择\"+sex)\n if( None!= birthday):\n self.editAttr(\"birthday\",\"生日输入框\",\"type\",\"text\")\n self.input(\"birthday\",\"生日输入框\",birthday)\n if( None!=guardian ):\n self.input(\"guardian\",\"家长输入框\",guardian)\n\n if( None!= subjects):\n self.inputSubjects(subjects)\n\n if(None!=mobile):\n self.input(\"mobile\",\"手机输入框\",mobile)\n\n if(None!=rank):\n self.selectByText(\"rank\",\"客户等级\",rank)\n\n self.sleep(1)\n\n self.click(\"save\",\"保存按钮\")\n self.sleep(3)\n self.alertAccept()\n\n self.sleep(1)\n self.back()\n self.sleep(3)\n\n self.click(\"end\",\"最后一页按钮\")\n\n self.sleep(4)\n\n\n xx= self.getText( \"//div[@id='result']//tbody/tr[last()]/td[@field='fullname']\",\"最后一行的姓名\")\n print(xx)\n if( name!= xx):\n raise Exception(\"没有在最后一页的最后一行找到刚刚输入的学生\")\n\n\n\n except Exception as e :\n self.setFailed(e)\n","sub_path":"CaseManager/bin/Debug/输出/PythonSelenium2/src/testPage/zmy/PageOfStudent.py","file_name":"PageOfStudent.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"507242787","text":"from pprint import pprint\nfrom visdom import Visdom\nimport pathlib\nimport json\nimport sys\nimport matplotlib.pyplot as plt\n\ndef download_env(env):\n vis = Visdom('http://logserver.duckdns.org', port=5010)\n data = vis.get_window_data(env=env)\n d = json.loads(data)\n \n test_acc_avg = []\n\n for key in d:\n try:\n #1 for MR 0 for UMICH\n x = list(d[key][\"content\"][\"data\"][1][\"x\"])\n y = list(d[key][\"content\"][\"data\"][1][\"y\"]) \n if 'test-acc-avg' in key:\n test_acc_avg = (x,y)\n\n except:\n pass \n\n\n return test_acc_avg\n\nif __name__ == \"__main__\":\n source = [ \"SS_bjornhox_04-07-18_14:32_UMICH_W2V_sim_0.0_8821\",\n \"SS_bjornhox_02-07-18_09:24_UMICH_w2v_0.37_df48\", \n \"SS_bjornhox_02-07-18_09:24_UMICH_w2v_0.39_d60d\", \n \"SS_bjornhox_19-07-18_16:02_UMICH_w2v_0.42_bd01\", \n \"SS_bjornhox_03-07-18_14:22_UMICH_UMICH_BASELINE_12cf\"]\n\n\n path = './results/'\n\n pathlib.Path(path).mkdir(parents=True, exist_ok=True)\n\n test_acc_avg_full = []\n \n legend = [\"0.0\", \"0.37\", \"0.39\", \"0.42\", \"random\"]\n\n for i in range(0, len(source)): \n env = source[i]\n res = download_env(env)\n test_acc_avg_full.append(res)\n\n plt.figure(1)\n plt.axis([0,250,50,100])\n plt.subplot(111)\n\n plt.xlabel(\"Amount of labeled data\")\n plt.ylabel(\"% accuracy\")\n\n for line in test_acc_avg_full: \n line[0].insert(0,0)\n line[1].insert(0,50)\n # plt.plot(*line) \n\n \n plt.plot(*test_acc_avg_full[0], color='#ff7f0e') #\n plt.plot(*test_acc_avg_full[1], dashes=[4, 2], color='#9467bd') #\n plt.plot(*test_acc_avg_full[2], color='#1f77b4') #\n plt.plot(*test_acc_avg_full[3], dashes=[6, 2], color='#17becf')#\n plt.plot(*test_acc_avg_full[4], color='#2ca02c')#\n\n plt.legend(legend,\n loc='lower right')\n plt.savefig('results/W2V/W2V_UMICH2.png' , dpi=600)\n # plt.show()\n","sub_path":"selection_strategies/download_graphs/W2V/W2V_sim_umich.py","file_name":"W2V_sim_umich.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"586428553","text":"import os\n\nfrom lxml import html\nimport pylibmc\nimport requests\n\nmc = None\ntry:\n servers = os.environ.get('MEMCACHIER_SERVERS', '').split(',')\n user = os.environ.get('MEMCACHIER_USERNAME', '')\n passwd = os.environ.get('MEMCACHIER_PASSWORD', '')\n if servers and user and passwd:\n mc = pylibmc.Client(servers, binary=True,\n username=user, password=passwd)\nexcept:\n mc = None\n\ndef get_courts(root, marker_name):\n marker_anchors = root.xpath('//a[@name=\"%s\"]' % marker_name)\n for marker in marker_anchors:\n court = None\n court_link = None\n for sibling in marker.itersiblings():\n if (court and sibling.tag == 'a' and\n 'courtinfo' in sibling.get('href')):\n yield {\n 'court': court,\n 'court_link': court_link,\n 'info_link': sibling.get('href')\n }\n court = None\n elif not court and sibling.tag == 'a':\n court = sibling.text\n court_link = sibling.get('href')\n\ndef get_all_courts(force=False):\n all_courts = None\n if mc:\n all_courts = mc.get('all_courts')\n if all_courts and not force:\n return all_courts\n\n COURT_MARKERS = (('U.S. Courts of Appeals', 'APCTS'),\n ('U.S. District Courts', 'DCCTS'),\n ('U.S. Bankruptcy Courts', 'BKCTS'))\n\n resp = requests.get('https://www.pacer.gov/psco/cgi-bin/links.pl')\n root = html.fromstring(resp.text)\n\n all_courts = {}\n\n for name, marker in COURT_MARKERS:\n all_courts[name] = {'id': marker, 'courts': []}\n for info in get_courts(root, marker):\n info_resp = requests.get(info['info_link'])\n info_root = html.fromstring(info_resp.text)\n \n software_td = info_root.xpath(\n '//td[contains(text(), \"Software Version\")]')[0]\n software_version = software_td.getnext().text\n info['software_version'] = software_version\n \n go_live_td = info_root.xpath(\n '//td[contains(text(), \"ECF Go Live Date\")]')[0]\n software_go_live = go_live_td.getnext().text\n info['software_go_live'] = software_go_live\n \n all_courts[name]['courts'].append(info)\n \n if mc:\n mc.set('all_courts', all_courts)\n return all_courts\n\nif __name__ == '__main__':\n import json\n import sys\n\n force = False\n if len(sys.argv) == 2 and sys.argv[1] == '-f':\n force = True\n\n print(json.dumps(get_all_courts(force=force)))\n\n","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"}